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 "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/sockets.h"
44 #include "qemu/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
52 #include "qemu/throttle.h"
53 #include "block/throttle-groups.h"
55 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
56 "\n" QEMU_COPYRIGHT "\n"
58 typedef struct img_cmd_t
{
60 int (*handler
)(int argc
, char **argv
);
65 OPTION_BACKING_CHAIN
= 257,
67 OPTION_IMAGE_OPTS
= 259,
69 OPTION_FLUSH_INTERVAL
= 261,
70 OPTION_NO_DRAIN
= 262,
71 OPTION_TARGET_IMAGE_OPTS
= 263,
73 OPTION_PREALLOCATION
= 265,
76 OPTION_TARGET_IS_ZERO
= 268,
87 typedef enum OutputFormat
{
92 /* Default to cache=writeback as data integrity is not important for qemu-img */
93 #define BDRV_DEFAULT_CACHE "writeback"
95 static void format_print(void *opaque
, const char *name
)
100 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
105 error_vreport(fmt
, ap
);
108 error_printf("Try 'qemu-img --help' for more information\n");
112 static void QEMU_NORETURN
missing_argument(const char *option
)
114 error_exit("missing argument for option '%s'", option
);
117 static void QEMU_NORETURN
unrecognized_option(const char *option
)
119 error_exit("unrecognized option '%s'", option
);
122 /* Please keep in synch with docs/tools/qemu-img.rst */
123 static void QEMU_NORETURN
help(void)
125 const char *help_msg
=
127 "usage: qemu-img [standard options] command [command options]\n"
128 "QEMU disk image utility\n"
130 " '-h', '--help' display this help and exit\n"
131 " '-V', '--version' output version information and exit\n"
132 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
133 " specify tracing options\n"
136 #define DEF(option, callback, arg_string) \
138 #include "qemu-img-cmds.h"
141 "Command parameters:\n"
142 " 'filename' is a disk image filename\n"
143 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
144 " manual page for a description of the object properties. The most common\n"
145 " object type is a 'secret', which is used to supply passwords and/or\n"
146 " encryption keys.\n"
147 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
148 " 'cache' is the cache mode used to write the output disk image, the valid\n"
149 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
150 " 'directsync' and 'unsafe' (default for convert)\n"
151 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
152 " options are the same as for the 'cache' option\n"
153 " 'size' is the disk image size in bytes. Optional suffixes\n"
154 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
155 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
156 " supported. 'b' is ignored.\n"
157 " 'output_filename' is the destination disk image filename\n"
158 " 'output_fmt' is the destination format\n"
159 " 'options' is a comma separated list of format specific options in a\n"
160 " name=value format. Use -o ? for an overview of the options supported by the\n"
162 " 'snapshot_param' is param used for internal snapshot, format\n"
163 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
165 " '-c' indicates that target image must be compressed (qcow format only)\n"
166 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
167 " new backing file match exactly. The image doesn't need a working\n"
168 " backing file before rebasing in this case (useful for renaming the\n"
169 " backing file). For image creation, allow creating without attempting\n"
170 " to open the backing file.\n"
171 " '-h' with or without a command shows this help and lists the supported formats\n"
172 " '-p' show progress of command (only certain commands)\n"
173 " '-q' use Quiet mode - do not print any output (except errors)\n"
174 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
175 " contain only zeros for qemu-img to create a sparse image during\n"
176 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
177 " unallocated or zero sectors, and the destination image will always be\n"
179 " '--output' takes the format in which the output must be done (human or json)\n"
180 " '-n' skips the target volume creation (useful if the volume is created\n"
181 " prior to running qemu-img)\n"
183 "Parameters to bitmap subcommand:\n"
184 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
185 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
186 " or '--merge source'\n"
187 " '-g granularity' sets the granularity for '--add' actions\n"
188 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
189 " bitmaps from an alternative file\n"
191 "Parameters to check subcommand:\n"
192 " '-r' tries to repair any inconsistencies that are found during the check.\n"
193 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
194 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
195 " hiding corruption that has already occurred.\n"
197 "Parameters to convert subcommand:\n"
198 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
199 " '-m' specifies how many coroutines work in parallel during the convert\n"
200 " process (defaults to 8)\n"
201 " '-W' allow to write to the target out of order rather than sequential\n"
203 "Parameters to snapshot subcommand:\n"
204 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
205 " '-a' applies a snapshot (revert disk to saved state)\n"
206 " '-c' creates a snapshot\n"
207 " '-d' deletes a snapshot\n"
208 " '-l' lists all snapshots in the given image\n"
210 "Parameters to compare subcommand:\n"
211 " '-f' first image format\n"
212 " '-F' second image format\n"
213 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
215 "Parameters to dd subcommand:\n"
216 " 'bs=BYTES' read and write up to BYTES bytes at a time "
218 " 'count=N' copy only N input blocks\n"
219 " 'if=FILE' read from FILE\n"
220 " 'of=FILE' write to FILE\n"
221 " 'skip=N' skip N bs-sized blocks at the start of input\n";
223 printf("%s\nSupported formats:", help_msg
);
224 bdrv_iterate_format(format_print
, NULL
, false);
225 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
229 static QemuOptsList qemu_object_opts
= {
231 .implied_opt_name
= "qom-type",
232 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
238 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
240 if (user_creatable_print_help(type
, opts
)) {
247 * Is @optarg safe for accumulate_options()?
248 * It is when multiple of them can be joined together separated by ','.
249 * To make that work, @optarg must not start with ',' (or else a
250 * separating ',' preceding it gets escaped), and it must not end with
251 * an odd number of ',' (or else a separating ',' following it gets
252 * escaped), or be empty (or else a separating ',' preceding it can
253 * escape a separating ',' following it).
256 static bool is_valid_option_list(const char *optarg
)
258 size_t len
= strlen(optarg
);
261 if (!optarg
[0] || optarg
[0] == ',') {
265 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
274 static int accumulate_options(char **options
, char *optarg
)
278 if (!is_valid_option_list(optarg
)) {
279 error_report("Invalid option list: %s", optarg
);
284 *options
= g_strdup(optarg
);
286 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
288 *options
= new_options
;
293 static QemuOptsList qemu_source_opts
= {
295 .implied_opt_name
= "file",
296 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
302 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
308 ret
= vprintf(fmt
, args
);
315 static int print_block_option_help(const char *filename
, const char *fmt
)
317 BlockDriver
*drv
, *proto_drv
;
318 QemuOptsList
*create_opts
= NULL
;
319 Error
*local_err
= NULL
;
321 /* Find driver and parse its options */
322 drv
= bdrv_find_format(fmt
);
324 error_report("Unknown file format '%s'", fmt
);
328 if (!drv
->create_opts
) {
329 error_report("Format driver '%s' does not support image creation", fmt
);
333 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
335 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
337 error_report_err(local_err
);
338 qemu_opts_free(create_opts
);
341 if (!proto_drv
->create_opts
) {
342 error_report("Protocol driver '%s' does not support image creation",
343 proto_drv
->format_name
);
344 qemu_opts_free(create_opts
);
347 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
351 printf("Supported options:\n");
353 printf("Supported %s options:\n", fmt
);
355 qemu_opts_print_help(create_opts
, false);
356 qemu_opts_free(create_opts
);
360 "The protocol level may support further options.\n"
361 "Specify the target filename to include those options.\n");
368 static BlockBackend
*img_open_opts(const char *optstr
,
369 QemuOpts
*opts
, int flags
, bool writethrough
,
370 bool quiet
, bool force_share
)
373 Error
*local_err
= NULL
;
375 options
= qemu_opts_to_qdict(opts
, NULL
);
377 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
378 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
379 error_report("--force-share/-U conflicts with image options");
380 qobject_unref(options
);
383 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
385 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
387 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
390 blk_set_enable_write_cache(blk
, !writethrough
);
395 static BlockBackend
*img_open_file(const char *filename
,
397 const char *fmt
, int flags
,
398 bool writethrough
, bool quiet
,
402 Error
*local_err
= NULL
;
405 options
= qdict_new();
408 qdict_put_str(options
, "driver", fmt
);
412 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
414 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
416 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
419 blk_set_enable_write_cache(blk
, !writethrough
);
425 static int img_add_key_secrets(void *opaque
,
426 const char *name
, const char *value
,
429 QDict
*options
= opaque
;
431 if (g_str_has_suffix(name
, "key-secret")) {
432 qdict_put_str(options
, name
, value
);
439 static BlockBackend
*img_open(bool image_opts
,
440 const char *filename
,
441 const char *fmt
, int flags
, bool writethrough
,
442 bool quiet
, bool force_share
)
448 error_report("--image-opts and --format are mutually exclusive");
451 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
456 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
459 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
466 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
467 const char *base_filename
,
468 const char *base_fmt
)
471 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
473 error_report("Backing file not supported for file format '%s'",
479 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
480 error_report("Backing file format not supported for file "
488 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
494 err
= qemu_strtosz(value
, NULL
, &res
);
495 if (err
< 0 && err
!= -ERANGE
) {
496 error_report("Invalid %s specified. You may use "
497 "k, M, G, T, P or E suffixes for", name
);
498 error_report("kilobytes, megabytes, gigabytes, terabytes, "
499 "petabytes and exabytes.");
502 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
503 error_report("Invalid %s specified. Must be between %" PRId64
504 " and %" PRId64
".", name
, min
, max
);
510 static int64_t cvtnum(const char *name
, const char *value
)
512 return cvtnum_full(name
, value
, 0, INT64_MAX
);
515 static int img_create(int argc
, char **argv
)
518 uint64_t img_size
= -1;
519 const char *fmt
= "raw";
520 const char *base_fmt
= NULL
;
521 const char *filename
;
522 const char *base_filename
= NULL
;
523 char *options
= NULL
;
524 Error
*local_err
= NULL
;
529 static const struct option long_options
[] = {
530 {"help", no_argument
, 0, 'h'},
531 {"object", required_argument
, 0, OPTION_OBJECT
},
534 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
541 missing_argument(argv
[optind
- 1]);
544 unrecognized_option(argv
[optind
- 1]);
553 base_filename
= optarg
;
559 if (accumulate_options(&options
, optarg
) < 0) {
567 flags
|= BDRV_O_NO_BACKING
;
569 case OPTION_OBJECT
: {
571 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
580 /* Get the filename */
581 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
582 if (options
&& has_help_option(options
)) {
584 return print_block_option_help(filename
, fmt
);
587 if (optind
>= argc
) {
588 error_exit("Expecting image file name");
592 if (qemu_opts_foreach(&qemu_object_opts
,
593 user_creatable_add_opts_foreach
,
594 qemu_img_object_print_help
, &error_fatal
)) {
598 /* Get image size, if specified */
602 sval
= cvtnum("image size", argv
[optind
++]);
606 img_size
= (uint64_t)sval
;
608 if (optind
!= argc
) {
609 error_exit("Unexpected argument: %s", argv
[optind
]);
612 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
613 options
, img_size
, flags
, quiet
, &local_err
);
615 error_reportf_err(local_err
, "%s: ", filename
);
627 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
631 Visitor
*v
= qobject_output_visitor_new(&obj
);
633 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
634 visit_complete(v
, &obj
);
635 str
= qobject_to_json_pretty(obj
, true);
637 qprintf(quiet
, "%s\n", str
->str
);
640 g_string_free(str
, true);
643 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
645 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
646 qprintf(quiet
, "No errors were found on the image.\n");
648 if (check
->corruptions
) {
649 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
650 "Data may be corrupted, or further writes to the image "
657 "\n%" PRId64
" leaked clusters were found on the image.\n"
658 "This means waste of disk space, but no harm to data.\n",
662 if (check
->check_errors
) {
665 " internal errors have occurred during the check.\n",
666 check
->check_errors
);
670 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
671 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
672 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
673 check
->allocated_clusters
, check
->total_clusters
,
674 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
675 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
676 check
->compressed_clusters
* 100.0 /
677 check
->allocated_clusters
);
680 if (check
->image_end_offset
) {
682 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
686 static int collect_image_check(BlockDriverState
*bs
,
688 const char *filename
,
693 BdrvCheckResult result
;
695 ret
= bdrv_check(bs
, &result
, fix
);
700 check
->filename
= g_strdup(filename
);
701 check
->format
= g_strdup(bdrv_get_format_name(bs
));
702 check
->check_errors
= result
.check_errors
;
703 check
->corruptions
= result
.corruptions
;
704 check
->has_corruptions
= result
.corruptions
!= 0;
705 check
->leaks
= result
.leaks
;
706 check
->has_leaks
= result
.leaks
!= 0;
707 check
->corruptions_fixed
= result
.corruptions_fixed
;
708 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
709 check
->leaks_fixed
= result
.leaks_fixed
;
710 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
711 check
->image_end_offset
= result
.image_end_offset
;
712 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
713 check
->total_clusters
= result
.bfi
.total_clusters
;
714 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
715 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
716 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
717 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
718 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
719 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
720 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
726 * Checks an image for consistency. Exit codes:
728 * 0 - Check completed, image is good
729 * 1 - Check not completed because of internal errors
730 * 2 - Check completed, image is corrupted
731 * 3 - Check completed, image has leaked clusters, but is good otherwise
732 * 63 - Checks are not supported by the image format
734 static int img_check(int argc
, char **argv
)
737 OutputFormat output_format
= OFORMAT_HUMAN
;
738 const char *filename
, *fmt
, *output
, *cache
;
740 BlockDriverState
*bs
;
742 int flags
= BDRV_O_CHECK
;
746 bool image_opts
= false;
747 bool force_share
= false;
751 cache
= BDRV_DEFAULT_CACHE
;
754 int option_index
= 0;
755 static const struct option long_options
[] = {
756 {"help", no_argument
, 0, 'h'},
757 {"format", required_argument
, 0, 'f'},
758 {"repair", required_argument
, 0, 'r'},
759 {"output", required_argument
, 0, OPTION_OUTPUT
},
760 {"object", required_argument
, 0, OPTION_OBJECT
},
761 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
762 {"force-share", no_argument
, 0, 'U'},
765 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
766 long_options
, &option_index
);
772 missing_argument(argv
[optind
- 1]);
775 unrecognized_option(argv
[optind
- 1]);
784 flags
|= BDRV_O_RDWR
;
786 if (!strcmp(optarg
, "leaks")) {
787 fix
= BDRV_FIX_LEAKS
;
788 } else if (!strcmp(optarg
, "all")) {
789 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
791 error_exit("Unknown option value for -r "
792 "(expecting 'leaks' or 'all'): %s", optarg
);
807 case OPTION_OBJECT
: {
809 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
815 case OPTION_IMAGE_OPTS
:
820 if (optind
!= argc
- 1) {
821 error_exit("Expecting one image file name");
823 filename
= argv
[optind
++];
825 if (output
&& !strcmp(output
, "json")) {
826 output_format
= OFORMAT_JSON
;
827 } else if (output
&& !strcmp(output
, "human")) {
828 output_format
= OFORMAT_HUMAN
;
830 error_report("--output must be used with human or json as argument.");
834 if (qemu_opts_foreach(&qemu_object_opts
,
835 user_creatable_add_opts_foreach
,
836 qemu_img_object_print_help
, &error_fatal
)) {
840 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
842 error_report("Invalid source cache option: %s", cache
);
846 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
853 check
= g_new0(ImageCheck
, 1);
854 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
856 if (ret
== -ENOTSUP
) {
857 error_report("This image format does not support checks");
862 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
863 int corruptions_fixed
, leaks_fixed
;
864 bool has_leaks_fixed
, has_corruptions_fixed
;
866 leaks_fixed
= check
->leaks_fixed
;
867 has_leaks_fixed
= check
->has_leaks_fixed
;
868 corruptions_fixed
= check
->corruptions_fixed
;
869 has_corruptions_fixed
= check
->has_corruptions_fixed
;
871 if (output_format
== OFORMAT_HUMAN
) {
873 "The following inconsistencies were found and repaired:\n\n"
874 " %" PRId64
" leaked clusters\n"
875 " %" PRId64
" corruptions\n\n"
876 "Double checking the fixed image now...\n",
878 check
->corruptions_fixed
);
881 qapi_free_ImageCheck(check
);
882 check
= g_new0(ImageCheck
, 1);
883 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
885 check
->leaks_fixed
= leaks_fixed
;
886 check
->has_leaks_fixed
= has_leaks_fixed
;
887 check
->corruptions_fixed
= corruptions_fixed
;
888 check
->has_corruptions_fixed
= has_corruptions_fixed
;
892 switch (output_format
) {
894 dump_human_image_check(check
, quiet
);
897 dump_json_image_check(check
, quiet
);
902 if (ret
|| check
->check_errors
) {
904 error_report("Check failed: %s", strerror(-ret
));
906 error_report("Check failed");
912 if (check
->corruptions
) {
914 } else if (check
->leaks
) {
921 qapi_free_ImageCheck(check
);
926 typedef struct CommonBlockJobCBInfo
{
927 BlockDriverState
*bs
;
929 } CommonBlockJobCBInfo
;
931 static void common_block_job_cb(void *opaque
, int ret
)
933 CommonBlockJobCBInfo
*cbi
= opaque
;
936 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
940 static void run_block_job(BlockJob
*job
, Error
**errp
)
942 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
945 aio_context_acquire(aio_context
);
948 float progress
= 0.0f
;
949 aio_poll(aio_context
, true);
950 if (job
->job
.progress
.total
) {
951 progress
= (float)job
->job
.progress
.current
/
952 job
->job
.progress
.total
* 100.f
;
954 qemu_progress_print(progress
, 0);
955 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
957 if (!job_is_completed(&job
->job
)) {
958 ret
= job_complete_sync(&job
->job
, errp
);
962 job_unref(&job
->job
);
963 aio_context_release(aio_context
);
965 /* publish completion progress only when success */
967 qemu_progress_print(100.f
, 0);
971 static int img_commit(int argc
, char **argv
)
974 const char *filename
, *fmt
, *cache
, *base
;
976 BlockDriverState
*bs
, *base_bs
;
978 bool progress
= false, quiet
= false, drop
= false;
980 Error
*local_err
= NULL
;
981 CommonBlockJobCBInfo cbi
;
982 bool image_opts
= false;
983 AioContext
*aio_context
;
984 int64_t rate_limit
= 0;
987 cache
= BDRV_DEFAULT_CACHE
;
990 static const struct option long_options
[] = {
991 {"help", no_argument
, 0, 'h'},
992 {"object", required_argument
, 0, OPTION_OBJECT
},
993 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
996 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
1003 missing_argument(argv
[optind
- 1]);
1006 unrecognized_option(argv
[optind
- 1]);
1032 rate_limit
= cvtnum("rate limit", optarg
);
1033 if (rate_limit
< 0) {
1037 case OPTION_OBJECT
: {
1039 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1045 case OPTION_IMAGE_OPTS
:
1051 /* Progress is not shown in Quiet mode */
1056 if (optind
!= argc
- 1) {
1057 error_exit("Expecting one image file name");
1059 filename
= argv
[optind
++];
1061 if (qemu_opts_foreach(&qemu_object_opts
,
1062 user_creatable_add_opts_foreach
,
1063 qemu_img_object_print_help
, &error_fatal
)) {
1067 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1068 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1070 error_report("Invalid cache option: %s", cache
);
1074 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1081 qemu_progress_init(progress
, 1.f
);
1082 qemu_progress_print(0.f
, 100);
1085 base_bs
= bdrv_find_backing_image(bs
, base
);
1087 error_setg(&local_err
,
1088 "Did not find '%s' in the backing chain of '%s'",
1093 /* This is different from QMP, which by default uses the deepest file in
1094 * the backing chain (i.e., the very base); however, the traditional
1095 * behavior of qemu-img commit is using the immediate backing file. */
1096 base_bs
= bdrv_backing_chain_next(bs
);
1098 error_setg(&local_err
, "Image does not have a backing file");
1103 cbi
= (CommonBlockJobCBInfo
){
1108 aio_context
= bdrv_get_aio_context(bs
);
1109 aio_context_acquire(aio_context
);
1110 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1111 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1112 &cbi
, false, &local_err
);
1113 aio_context_release(aio_context
);
1118 /* When the block job completes, the BlockBackend reference will point to
1119 * the old backing file. In order to avoid that the top image is already
1120 * deleted, so we can still empty it afterwards, increment the reference
1121 * counter here preemptively. */
1126 job
= block_job_get("commit");
1128 run_block_job(job
, &local_err
);
1134 BlockBackend
*old_backing_blk
;
1136 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1138 if (!old_backing_blk
) {
1141 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1142 blk_unref(old_backing_blk
);
1143 if (ret
== -ENOTSUP
) {
1144 error_free(local_err
);
1146 } else if (ret
< 0) {
1157 qemu_progress_end();
1162 error_report_err(local_err
);
1166 qprintf(quiet
, "Image committed.\n");
1171 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1172 * of the first sector boundary within buf where the sector contains a
1173 * non-zero byte. This function is robust to a buffer that is not
1176 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1179 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1181 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1182 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1186 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1193 * Returns true iff the first sector pointed to by 'buf' contains at least
1196 * 'pnum' is set to the number of sectors (including and immediately following
1197 * the first one) that are known to be in the same allocated/unallocated state.
1198 * The function will try to align the end offset to alignment boundaries so
1199 * that the request will at least end aligned and consecutive requests will
1200 * also start at an aligned offset.
1202 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1203 int64_t sector_num
, int alignment
)
1212 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1213 for(i
= 1; i
< n
; i
++) {
1214 buf
+= BDRV_SECTOR_SIZE
;
1215 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1220 tail
= (sector_num
+ i
) & (alignment
- 1);
1222 if (is_zero
&& i
<= tail
) {
1223 /* treat unallocated areas which only consist
1224 * of a small tail as allocated. */
1228 /* align up end offset of allocated areas. */
1229 i
+= alignment
- tail
;
1232 /* align down end offset of zero areas. */
1241 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1242 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1243 * breaking up write requests for only small sparse areas.
1245 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1246 int min
, int64_t sector_num
, int alignment
)
1249 int num_checked
, num_used
;
1255 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1261 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1263 sector_num
+= *pnum
;
1264 num_checked
= num_used
;
1267 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1269 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1271 sector_num
+= *pnum
;
1272 num_checked
+= *pnum
;
1274 num_used
= num_checked
;
1275 } else if (*pnum
>= min
) {
1285 * Compares two buffers sector by sector. Returns 0 if the first
1286 * sector of each buffer matches, non-zero otherwise.
1288 * pnum is set to the sector-aligned size of the buffer prefix that
1289 * has the same matching status as the first sector.
1291 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1292 int64_t bytes
, int64_t *pnum
)
1295 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1299 res
= !!memcmp(buf1
, buf2
, i
);
1301 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1303 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1313 #define IO_BUF_SIZE (2 * MiB)
1316 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1318 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1319 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1320 * failure), and 4 on error (the exit status for read errors), after emitting
1323 * @param blk: BlockBackend for the image
1324 * @param offset: Starting offset to check
1325 * @param bytes: Number of bytes to check
1326 * @param filename: Name of disk file we are checking (logging purpose)
1327 * @param buffer: Allocated buffer for storing read data
1328 * @param quiet: Flag for quiet mode
1330 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1331 int64_t bytes
, const char *filename
,
1332 uint8_t *buffer
, bool quiet
)
1337 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1339 error_report("Error while reading offset %" PRId64
" of %s: %s",
1340 offset
, filename
, strerror(-ret
));
1343 idx
= find_nonzero(buffer
, bytes
);
1345 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1354 * Compares two images. Exit codes:
1356 * 0 - Images are identical
1358 * >1 - Error occurred
1360 static int img_compare(int argc
, char **argv
)
1362 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1363 BlockBackend
*blk1
, *blk2
;
1364 BlockDriverState
*bs1
, *bs2
;
1365 int64_t total_size1
, total_size2
;
1366 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1367 int64_t pnum1
, pnum2
;
1368 int allocated1
, allocated2
;
1369 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1370 bool progress
= false, quiet
= false, strict
= false;
1377 uint64_t progress_base
;
1378 bool image_opts
= false;
1379 bool force_share
= false;
1381 cache
= BDRV_DEFAULT_CACHE
;
1383 static const struct option long_options
[] = {
1384 {"help", no_argument
, 0, 'h'},
1385 {"object", required_argument
, 0, OPTION_OBJECT
},
1386 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1387 {"force-share", no_argument
, 0, 'U'},
1390 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1391 long_options
, NULL
);
1397 missing_argument(argv
[optind
- 1]);
1400 unrecognized_option(argv
[optind
- 1]);
1426 case OPTION_OBJECT
: {
1428 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1435 case OPTION_IMAGE_OPTS
:
1441 /* Progress is not shown in Quiet mode */
1447 if (optind
!= argc
- 2) {
1448 error_exit("Expecting two image file names");
1450 filename1
= argv
[optind
++];
1451 filename2
= argv
[optind
++];
1453 if (qemu_opts_foreach(&qemu_object_opts
,
1454 user_creatable_add_opts_foreach
,
1455 qemu_img_object_print_help
, &error_fatal
)) {
1460 /* Initialize before goto out */
1461 qemu_progress_init(progress
, 2.0);
1464 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1466 error_report("Invalid source cache option: %s", cache
);
1471 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1478 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1487 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1488 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1489 total_size1
= blk_getlength(blk1
);
1490 if (total_size1
< 0) {
1491 error_report("Can't get size of %s: %s",
1492 filename1
, strerror(-total_size1
));
1496 total_size2
= blk_getlength(blk2
);
1497 if (total_size2
< 0) {
1498 error_report("Can't get size of %s: %s",
1499 filename2
, strerror(-total_size2
));
1503 total_size
= MIN(total_size1
, total_size2
);
1504 progress_base
= MAX(total_size1
, total_size2
);
1506 qemu_progress_print(0, 100);
1508 if (strict
&& total_size1
!= total_size2
) {
1510 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1514 while (offset
< total_size
) {
1515 int status1
, status2
;
1517 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1518 total_size1
- offset
, &pnum1
, NULL
,
1522 error_report("Sector allocation test failed for %s", filename1
);
1525 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1527 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1528 total_size2
- offset
, &pnum2
, NULL
,
1532 error_report("Sector allocation test failed for %s", filename2
);
1535 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1537 assert(pnum1
&& pnum2
);
1538 chunk
= MIN(pnum1
, pnum2
);
1541 if (status1
!= status2
) {
1543 qprintf(quiet
, "Strict mode: Offset %" PRId64
1544 " block status mismatch!\n", offset
);
1548 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1550 } else if (allocated1
== allocated2
) {
1554 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1555 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1557 error_report("Error while reading offset %" PRId64
1559 offset
, filename1
, strerror(-ret
));
1563 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1565 error_report("Error while reading offset %" PRId64
1567 offset
, filename2
, strerror(-ret
));
1571 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1572 if (ret
|| pnum
!= chunk
) {
1573 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1574 offset
+ (ret
? 0 : pnum
));
1580 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1582 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1583 filename1
, buf1
, quiet
);
1585 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1586 filename2
, buf1
, quiet
);
1593 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1596 if (total_size1
!= total_size2
) {
1597 BlockBackend
*blk_over
;
1598 const char *filename_over
;
1600 qprintf(quiet
, "Warning: Image size mismatch!\n");
1601 if (total_size1
> total_size2
) {
1603 filename_over
= filename1
;
1606 filename_over
= filename2
;
1609 while (offset
< progress_base
) {
1610 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1611 progress_base
- offset
, &chunk
,
1615 error_report("Sector allocation test failed for %s",
1620 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1621 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1622 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1623 filename_over
, buf1
, quiet
);
1629 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1633 qprintf(quiet
, "Images are identical.\n");
1643 qemu_progress_end();
1648 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1649 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1650 const char *src_node
, const char *src_name
,
1653 BlockDirtyBitmapMergeSource
*merge_src
;
1654 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1656 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1657 merge_src
->type
= QTYPE_QDICT
;
1658 merge_src
->u
.external
.node
= g_strdup(src_node
);
1659 merge_src
->u
.external
.name
= g_strdup(src_name
);
1660 QAPI_LIST_PREPEND(list
, merge_src
);
1661 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1662 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1665 enum ImgConvertBlockStatus
{
1671 #define MAX_COROUTINES 16
1672 #define CONVERT_THROTTLE_GROUP "img_convert"
1674 typedef struct ImgConvertState
{
1676 int64_t *src_sectors
;
1679 int64_t total_sectors
;
1680 int64_t allocated_sectors
;
1681 int64_t allocated_done
;
1684 enum ImgConvertBlockStatus status
;
1685 int64_t sector_next_status
;
1686 BlockBackend
*target
;
1690 bool target_has_backing
;
1691 int64_t target_backing_sectors
; /* negative if unknown */
1698 size_t cluster_sectors
;
1700 long num_coroutines
;
1701 int running_coroutines
;
1702 Coroutine
*co
[MAX_COROUTINES
];
1703 int64_t wait_sector_num
[MAX_COROUTINES
];
1708 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1709 int *src_cur
, int64_t *src_cur_offset
)
1712 *src_cur_offset
= 0;
1713 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1714 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1716 assert(*src_cur
< s
->src_num
);
1720 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1722 int64_t src_cur_offset
;
1723 int ret
, n
, src_cur
;
1724 bool post_backing_zero
= false;
1726 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1728 assert(s
->total_sectors
> sector_num
);
1729 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1731 if (s
->target_backing_sectors
>= 0) {
1732 if (sector_num
>= s
->target_backing_sectors
) {
1733 post_backing_zero
= true;
1734 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1735 /* Split requests around target_backing_sectors (because
1736 * starting from there, zeros are handled differently) */
1737 n
= s
->target_backing_sectors
- sector_num
;
1741 if (s
->sector_next_status
<= sector_num
) {
1742 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1745 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1746 BlockDriverState
*base
;
1748 if (s
->target_has_backing
) {
1749 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1755 count
= n
* BDRV_SECTOR_SIZE
;
1757 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1764 warn_report("error while reading block status at "
1765 "offset %" PRIu64
": %s", offset
,
1768 /* Just try to read the data, then */
1769 ret
= BDRV_BLOCK_DATA
;
1770 count
= BDRV_SECTOR_SIZE
;
1772 /* Retry on a shorter range */
1773 n
= DIV_ROUND_UP(n
, 4);
1776 error_report("error while reading block status at offset "
1777 "%" PRIu64
": %s", offset
, strerror(-ret
));
1783 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1786 * Avoid that s->sector_next_status becomes unaligned to the source
1787 * request alignment and/or cluster size to avoid unnecessary read
1790 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1795 if (ret
& BDRV_BLOCK_ZERO
) {
1796 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1797 } else if (ret
& BDRV_BLOCK_DATA
) {
1798 s
->status
= BLK_DATA
;
1800 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1803 s
->sector_next_status
= sector_num
+ n
;
1806 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1807 if (s
->status
== BLK_DATA
) {
1808 n
= MIN(n
, s
->buf_sectors
);
1811 /* We need to write complete clusters for compressed images, so if an
1812 * unallocated area is shorter than that, we must consider the whole
1813 * cluster allocated. */
1814 if (s
->compressed
) {
1815 if (n
< s
->cluster_sectors
) {
1816 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1817 s
->status
= BLK_DATA
;
1819 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1826 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1827 int nb_sectors
, uint8_t *buf
)
1829 uint64_t single_read_until
= 0;
1832 assert(nb_sectors
<= s
->buf_sectors
);
1833 while (nb_sectors
> 0) {
1836 int64_t bs_sectors
, src_cur_offset
;
1839 /* In the case of compression with multiple source files, we can get a
1840 * nb_sectors that spreads into the next part. So we must be able to
1841 * read across multiple BDSes for one convert_read() call. */
1842 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1843 blk
= s
->src
[src_cur
];
1844 bs_sectors
= s
->src_sectors
[src_cur
];
1846 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1848 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1849 if (single_read_until
> offset
) {
1853 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1857 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1861 warn_report("error while reading offset %" PRIu64
1862 ": %s", offset
, strerror(-ret
));
1864 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1873 buf
+= n
* BDRV_SECTOR_SIZE
;
1880 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1881 int nb_sectors
, uint8_t *buf
,
1882 enum ImgConvertBlockStatus status
)
1886 while (nb_sectors
> 0) {
1888 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1891 case BLK_BACKING_FILE
:
1892 /* If we have a backing file, leave clusters unallocated that are
1893 * unallocated in the source image, so that the backing file is
1894 * visible at the respective offset. */
1895 assert(s
->target_has_backing
);
1899 /* If we're told to keep the target fully allocated (-S 0) or there
1900 * is real non-zero data, we must write it. Otherwise we can treat
1901 * it as zero sectors.
1902 * Compressed clusters need to be written as a whole, so in that
1903 * case we can only save the write if the buffer is completely
1905 if (!s
->min_sparse
||
1907 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1908 sector_num
, s
->alignment
)) ||
1910 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1912 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1913 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1922 if (s
->has_zero_init
) {
1923 assert(!s
->target_has_backing
);
1926 ret
= blk_co_pwrite_zeroes(s
->target
,
1927 sector_num
<< BDRV_SECTOR_BITS
,
1928 n
<< BDRV_SECTOR_BITS
,
1929 BDRV_REQ_MAY_UNMAP
);
1938 buf
+= n
* BDRV_SECTOR_SIZE
;
1944 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1949 while (nb_sectors
> 0) {
1952 int64_t bs_sectors
, src_cur_offset
;
1955 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1956 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1957 blk
= s
->src
[src_cur
];
1958 bs_sectors
= s
->src_sectors
[src_cur
];
1960 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1962 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1963 sector_num
<< BDRV_SECTOR_BITS
,
1964 n
<< BDRV_SECTOR_BITS
, 0, 0);
1975 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1977 ImgConvertState
*s
= opaque
;
1978 uint8_t *buf
= NULL
;
1982 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1983 if (s
->co
[i
] == qemu_coroutine_self()) {
1990 s
->running_coroutines
++;
1991 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1996 enum ImgConvertBlockStatus status
;
1999 qemu_co_mutex_lock(&s
->lock
);
2000 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
2001 qemu_co_mutex_unlock(&s
->lock
);
2004 n
= convert_iteration_sectors(s
, s
->sector_num
);
2006 qemu_co_mutex_unlock(&s
->lock
);
2010 /* save current sector and allocation status to local variables */
2011 sector_num
= s
->sector_num
;
2013 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
2014 n
= MIN(n
, s
->buf_sectors
);
2016 /* increment global sector counter so that other coroutines can
2017 * already continue reading beyond this request */
2019 qemu_co_mutex_unlock(&s
->lock
);
2021 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2022 s
->allocated_done
+= n
;
2023 qemu_progress_print(100.0 * s
->allocated_done
/
2024 s
->allocated_sectors
, 0);
2028 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2029 if (status
== BLK_DATA
&& !copy_range
) {
2030 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2032 error_report("error while reading at byte %lld: %s",
2033 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2036 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2038 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2041 if (s
->wr_in_order
) {
2042 /* keep writes in order */
2043 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2044 s
->wait_sector_num
[index
] = sector_num
;
2045 qemu_coroutine_yield();
2047 s
->wait_sector_num
[index
] = -1;
2050 if (s
->ret
== -EINPROGRESS
) {
2052 ret
= convert_co_copy_range(s
, sector_num
, n
);
2054 s
->copy_range
= false;
2058 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2061 error_report("error while writing at byte %lld: %s",
2062 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2067 if (s
->wr_in_order
) {
2068 /* reenter the coroutine that might have waited
2069 * for this write to complete */
2070 s
->wr_offs
= sector_num
+ n
;
2071 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2072 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2074 * A -> B -> A cannot occur because A has
2075 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2076 * B will never enter A during this time window.
2078 qemu_coroutine_enter(s
->co
[i
]);
2086 s
->co
[index
] = NULL
;
2087 s
->running_coroutines
--;
2088 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2089 /* the convert job finished successfully */
2094 static int convert_do_copy(ImgConvertState
*s
)
2097 int64_t sector_num
= 0;
2099 /* Check whether we have zero initialisation or can get it efficiently */
2100 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2101 !s
->target_has_backing
) {
2102 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2105 /* Allocate buffer for copied data. For compressed images, only one cluster
2106 * can be copied at a time. */
2107 if (s
->compressed
) {
2108 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2109 error_report("invalid cluster size");
2112 s
->buf_sectors
= s
->cluster_sectors
;
2115 while (sector_num
< s
->total_sectors
) {
2116 n
= convert_iteration_sectors(s
, sector_num
);
2120 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2122 s
->allocated_sectors
+= n
;
2128 s
->sector_next_status
= 0;
2129 s
->ret
= -EINPROGRESS
;
2131 qemu_co_mutex_init(&s
->lock
);
2132 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2133 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2134 s
->wait_sector_num
[i
] = -1;
2135 qemu_coroutine_enter(s
->co
[i
]);
2138 while (s
->running_coroutines
) {
2139 main_loop_wait(false);
2142 if (s
->compressed
&& !s
->ret
) {
2143 /* signal EOF to align */
2144 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2153 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2155 BdrvDirtyBitmap
*bm
;
2158 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2161 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2164 name
= bdrv_dirty_bitmap_name(bm
);
2165 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2166 true, bdrv_dirty_bitmap_granularity(bm
),
2168 true, !bdrv_dirty_bitmap_enabled(bm
),
2171 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2175 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2178 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2186 #define MAX_BUF_SECTORS 32768
2188 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2192 throttle_config_init(&cfg
);
2193 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2195 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2196 blk_set_io_limits(blk
, &cfg
);
2199 static int img_convert(int argc
, char **argv
)
2201 int c
, bs_i
, flags
, src_flags
= 0;
2202 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2203 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2204 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2205 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2206 BlockDriverInfo bdi
;
2207 BlockDriverState
*out_bs
;
2208 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2209 QemuOptsList
*create_opts
= NULL
;
2210 QDict
*open_opts
= NULL
;
2211 char *options
= NULL
;
2212 Error
*local_err
= NULL
;
2213 bool writethrough
, src_writethrough
, image_opts
= false,
2214 skip_create
= false, progress
= false, tgt_image_opts
= false;
2215 int64_t ret
= -EINVAL
;
2216 bool force_share
= false;
2217 bool explict_min_sparse
= false;
2218 bool bitmaps
= false;
2219 int64_t rate_limit
= 0;
2221 ImgConvertState s
= (ImgConvertState
) {
2222 /* Need at least 4k of zeros for sparse detection */
2224 .copy_range
= false,
2225 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2226 .wr_in_order
= true,
2227 .num_coroutines
= 8,
2231 static const struct option long_options
[] = {
2232 {"help", no_argument
, 0, 'h'},
2233 {"object", required_argument
, 0, OPTION_OBJECT
},
2234 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2235 {"force-share", no_argument
, 0, 'U'},
2236 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2237 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2238 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2239 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2242 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
2243 long_options
, NULL
);
2249 missing_argument(argv
[optind
- 1]);
2252 unrecognized_option(argv
[optind
- 1]);
2264 out_baseimg
= optarg
;
2267 s
.copy_range
= true;
2270 s
.compressed
= true;
2273 if (accumulate_options(&options
, optarg
) < 0) {
2278 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2279 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2282 error_report("Failed in parsing snapshot param '%s'",
2287 snapshot_name
= optarg
;
2294 sval
= cvtnum("buffer size for sparse output", optarg
);
2297 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2298 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2299 error_report("Invalid buffer size for sparse output specified. "
2300 "Valid sizes are multiples of %llu up to %llu. Select "
2301 "0 to disable sparse detection (fully allocates output).",
2302 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2306 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2307 explict_min_sparse
= true;
2326 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2327 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2328 error_report("Invalid number of coroutines. Allowed number of"
2329 " coroutines is between 1 and %d", MAX_COROUTINES
);
2334 s
.wr_in_order
= false;
2340 rate_limit
= cvtnum("rate limit", optarg
);
2341 if (rate_limit
< 0) {
2345 case OPTION_OBJECT
: {
2346 QemuOpts
*object_opts
;
2347 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2354 case OPTION_IMAGE_OPTS
:
2357 case OPTION_SALVAGE
:
2360 case OPTION_TARGET_IMAGE_OPTS
:
2361 tgt_image_opts
= true;
2363 case OPTION_TARGET_IS_ZERO
:
2365 * The user asserting that the target is blank has the
2366 * same effect as the target driver supporting zero
2369 s
.has_zero_init
= true;
2371 case OPTION_BITMAPS
:
2377 if (!out_fmt
&& !tgt_image_opts
) {
2381 if (qemu_opts_foreach(&qemu_object_opts
,
2382 user_creatable_add_opts_foreach
,
2383 qemu_img_object_print_help
, &error_fatal
)) {
2387 if (s
.compressed
&& s
.copy_range
) {
2388 error_report("Cannot enable copy offloading when -c is used");
2392 if (explict_min_sparse
&& s
.copy_range
) {
2393 error_report("Cannot enable copy offloading when -S is used");
2397 if (s
.copy_range
&& s
.salvage
) {
2398 error_report("Cannot use copy offloading in salvaging mode");
2402 if (tgt_image_opts
&& !skip_create
) {
2403 error_report("--target-image-opts requires use of -n flag");
2407 if (skip_create
&& options
) {
2408 error_report("-o has no effect when skipping image creation");
2412 if (s
.has_zero_init
&& !skip_create
) {
2413 error_report("--target-is-zero requires use of -n flag");
2417 s
.src_num
= argc
- optind
- 1;
2418 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2420 if (options
&& has_help_option(options
)) {
2422 ret
= print_block_option_help(out_filename
, out_fmt
);
2425 error_report("Option help requires a format be specified");
2430 if (s
.src_num
< 1) {
2431 error_report("Must specify image file name");
2435 /* ret is still -EINVAL until here */
2436 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2438 error_report("Invalid source cache option: %s", src_cache
);
2442 /* Initialize before goto out */
2446 qemu_progress_init(progress
, 1.0);
2447 qemu_progress_print(0, 100);
2449 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2450 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2451 s
.src_alignment
= g_new(int, s
.src_num
);
2453 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2454 BlockDriverState
*src_bs
;
2455 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2456 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2462 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2463 if (s
.src_sectors
[bs_i
] < 0) {
2464 error_report("Could not get size of %s: %s",
2465 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2469 src_bs
= blk_bs(s
.src
[bs_i
]);
2470 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2472 if (!bdrv_get_info(src_bs
, &bdi
)) {
2473 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2474 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2476 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2480 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2481 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2482 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2484 } else if (snapshot_name
!= NULL
) {
2485 if (s
.src_num
> 1) {
2486 error_report("No support for concatenating multiple snapshot");
2491 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2495 error_reportf_err(local_err
, "Failed to load snapshot: ");
2501 /* Find driver and parse its options */
2502 drv
= bdrv_find_format(out_fmt
);
2504 error_report("Unknown file format '%s'", out_fmt
);
2509 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2511 error_report_err(local_err
);
2516 if (!drv
->create_opts
) {
2517 error_report("Format driver '%s' does not support image creation",
2523 if (!proto_drv
->create_opts
) {
2524 error_report("Protocol driver '%s' does not support image creation",
2525 proto_drv
->format_name
);
2530 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2531 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2533 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2535 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2536 error_report_err(local_err
);
2542 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2543 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2544 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2550 /* Get backing file name if -o backing_file was used */
2551 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2552 if (out_baseimg_param
) {
2553 out_baseimg
= out_baseimg_param
;
2555 s
.target_has_backing
= (bool) out_baseimg
;
2557 if (s
.has_zero_init
&& s
.target_has_backing
) {
2558 error_report("Cannot use --target-is-zero when the destination "
2559 "image has a backing file");
2563 if (s
.src_num
> 1 && out_baseimg
) {
2564 error_report("Having a backing file for the target makes no sense when "
2565 "concatenating multiple input images");
2570 if (out_baseimg_param
) {
2571 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2572 warn_report("Deprecated use of backing file without explicit "
2577 /* Check if compression is supported */
2580 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2581 const char *encryptfmt
=
2582 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2583 const char *preallocation
=
2584 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2586 if (drv
&& !block_driver_can_compress(drv
)) {
2587 error_report("Compression not supported for this file format");
2592 if (encryption
|| encryptfmt
) {
2593 error_report("Compression and encryption not supported at "
2600 && strcmp(preallocation
, "off"))
2602 error_report("Compression and preallocation not supported at "
2609 /* Determine if bitmaps need copying */
2611 if (s
.src_num
> 1) {
2612 error_report("Copying bitmaps only possible with single source");
2616 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2617 error_report("Source lacks bitmap support");
2624 * The later open call will need any decryption secrets, and
2625 * bdrv_create() will purge "opts", so extract them now before
2629 open_opts
= qdict_new();
2630 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2632 /* Create the new image */
2633 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2635 error_reportf_err(local_err
, "%s: error while converting %s: ",
2636 out_filename
, out_fmt
);
2641 s
.target_is_new
= !skip_create
;
2643 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2644 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2646 error_report("Invalid cache option: %s", cache
);
2651 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2652 flags
, writethrough
, s
.quiet
, false);
2654 /* TODO ultimately we should allow --target-image-opts
2655 * to be used even when -n is not given.
2656 * That has to wait for bdrv_create to be improved
2657 * to allow filenames in option syntax
2659 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2660 flags
, writethrough
, s
.quiet
, false);
2661 open_opts
= NULL
; /* blk_new_open will have freed it */
2667 out_bs
= blk_bs(s
.target
);
2669 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2670 error_report("Format driver '%s' does not support bitmaps",
2671 out_bs
->drv
->format_name
);
2676 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2677 error_report("Compression not supported for this file format");
2682 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2683 * or discard_alignment of the out_bs is greater. Limit to
2684 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2685 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2687 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2688 out_bs
->bl
.pdiscard_alignment
>>
2689 BDRV_SECTOR_BITS
)));
2691 /* try to align the write requests to the destination to avoid unnecessary
2693 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2694 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2696 assert(is_power_of_2(s
.alignment
));
2699 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2700 if (output_sectors
< 0) {
2701 error_report("unable to get output image length: %s",
2702 strerror(-output_sectors
));
2705 } else if (output_sectors
< s
.total_sectors
) {
2706 error_report("output file is smaller than input file");
2712 if (s
.target_has_backing
&& s
.target_is_new
) {
2713 /* Errors are treated as "backing length unknown" (which means
2714 * s.target_backing_sectors has to be negative, which it will
2715 * be automatically). The backing file length is used only
2716 * for optimizations, so such a case is not fatal. */
2717 s
.target_backing_sectors
=
2718 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2720 s
.target_backing_sectors
= -1;
2723 ret
= bdrv_get_info(out_bs
, &bdi
);
2726 error_report("could not get block driver info");
2730 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2731 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2735 set_rate_limit(s
.target
, rate_limit
);
2738 ret
= convert_do_copy(&s
);
2740 /* Now copy the bitmaps */
2741 if (bitmaps
&& ret
== 0) {
2742 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2747 qemu_progress_print(100, 0);
2749 qemu_progress_end();
2750 qemu_opts_del(opts
);
2751 qemu_opts_free(create_opts
);
2752 qobject_unref(open_opts
);
2753 blk_unref(s
.target
);
2755 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2756 blk_unref(s
.src
[bs_i
]);
2760 g_free(s
.src_sectors
);
2761 g_free(s
.src_alignment
);
2763 qemu_opts_del(sn_opts
);
2770 static void dump_snapshots(BlockDriverState
*bs
)
2772 QEMUSnapshotInfo
*sn_tab
, *sn
;
2775 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2778 printf("Snapshot list:\n");
2779 bdrv_snapshot_dump(NULL
);
2781 for(i
= 0; i
< nb_sns
; i
++) {
2783 bdrv_snapshot_dump(sn
);
2789 static void dump_json_image_info_list(ImageInfoList
*list
)
2793 Visitor
*v
= qobject_output_visitor_new(&obj
);
2795 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2796 visit_complete(v
, &obj
);
2797 str
= qobject_to_json_pretty(obj
, true);
2798 assert(str
!= NULL
);
2799 printf("%s\n", str
->str
);
2802 g_string_free(str
, true);
2805 static void dump_json_image_info(ImageInfo
*info
)
2809 Visitor
*v
= qobject_output_visitor_new(&obj
);
2811 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2812 visit_complete(v
, &obj
);
2813 str
= qobject_to_json_pretty(obj
, true);
2814 assert(str
!= NULL
);
2815 printf("%s\n", str
->str
);
2818 g_string_free(str
, true);
2821 static void dump_human_image_info_list(ImageInfoList
*list
)
2823 ImageInfoList
*elem
;
2826 for (elem
= list
; elem
; elem
= elem
->next
) {
2832 bdrv_image_info_dump(elem
->value
);
2836 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2838 return strcmp(a
, b
) == 0;
2842 * Open an image file chain and return an ImageInfoList
2844 * @filename: topmost image filename
2845 * @fmt: topmost image format (may be NULL to autodetect)
2846 * @chain: true - enumerate entire backing file chain
2847 * false - only topmost image file
2849 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2850 * image file. If there was an error a message will have been printed to
2853 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2854 const char *filename
,
2856 bool chain
, bool force_share
)
2858 ImageInfoList
*head
= NULL
;
2859 ImageInfoList
**tail
= &head
;
2860 GHashTable
*filenames
;
2863 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2867 BlockDriverState
*bs
;
2870 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2871 error_report("Backing file '%s' creates an infinite loop.",
2875 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2877 blk
= img_open(image_opts
, filename
, fmt
,
2878 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2885 bdrv_query_image_info(bs
, &info
, &err
);
2887 error_report_err(err
);
2892 QAPI_LIST_APPEND(tail
, info
);
2896 /* Clear parameters that only apply to the topmost image */
2897 filename
= fmt
= NULL
;
2901 if (info
->has_full_backing_filename
) {
2902 filename
= info
->full_backing_filename
;
2903 } else if (info
->has_backing_filename
) {
2904 error_report("Could not determine absolute backing filename,"
2905 " but backing filename '%s' present",
2906 info
->backing_filename
);
2909 if (info
->has_backing_filename_format
) {
2910 fmt
= info
->backing_filename_format
;
2914 g_hash_table_destroy(filenames
);
2918 qapi_free_ImageInfoList(head
);
2919 g_hash_table_destroy(filenames
);
2923 static int img_info(int argc
, char **argv
)
2926 OutputFormat output_format
= OFORMAT_HUMAN
;
2928 const char *filename
, *fmt
, *output
;
2929 ImageInfoList
*list
;
2930 bool image_opts
= false;
2931 bool force_share
= false;
2936 int option_index
= 0;
2937 static const struct option long_options
[] = {
2938 {"help", no_argument
, 0, 'h'},
2939 {"format", required_argument
, 0, 'f'},
2940 {"output", required_argument
, 0, OPTION_OUTPUT
},
2941 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2942 {"object", required_argument
, 0, OPTION_OBJECT
},
2943 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2944 {"force-share", no_argument
, 0, 'U'},
2947 c
= getopt_long(argc
, argv
, ":f:hU",
2948 long_options
, &option_index
);
2954 missing_argument(argv
[optind
- 1]);
2957 unrecognized_option(argv
[optind
- 1]);
2971 case OPTION_BACKING_CHAIN
:
2974 case OPTION_OBJECT
: {
2976 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2982 case OPTION_IMAGE_OPTS
:
2987 if (optind
!= argc
- 1) {
2988 error_exit("Expecting one image file name");
2990 filename
= argv
[optind
++];
2992 if (output
&& !strcmp(output
, "json")) {
2993 output_format
= OFORMAT_JSON
;
2994 } else if (output
&& !strcmp(output
, "human")) {
2995 output_format
= OFORMAT_HUMAN
;
2996 } else if (output
) {
2997 error_report("--output must be used with human or json as argument.");
3001 if (qemu_opts_foreach(&qemu_object_opts
,
3002 user_creatable_add_opts_foreach
,
3003 qemu_img_object_print_help
, &error_fatal
)) {
3007 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3013 switch (output_format
) {
3015 dump_human_image_info_list(list
);
3019 dump_json_image_info_list(list
);
3021 dump_json_image_info(list
->value
);
3026 qapi_free_ImageInfoList(list
);
3030 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3033 switch (output_format
) {
3035 if (e
->data
&& !e
->has_offset
) {
3036 error_report("File contains external, encrypted or compressed clusters.");
3039 if (e
->data
&& !e
->zero
) {
3040 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3041 e
->start
, e
->length
,
3042 e
->has_offset
? e
->offset
: 0,
3043 e
->has_filename
? e
->filename
: "");
3045 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3046 * Modify the flags here to allow more coalescing.
3048 if (next
&& (!next
->data
|| next
->zero
)) {
3054 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3055 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
3056 e
->start
, e
->length
, e
->depth
,
3057 e
->zero
? "true" : "false",
3058 e
->data
? "true" : "false");
3059 if (e
->has_offset
) {
3060 printf(", \"offset\": %"PRId64
"", e
->offset
);
3072 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3073 int64_t bytes
, MapEntry
*e
)
3077 BlockDriverState
*file
;
3080 char *filename
= NULL
;
3082 /* As an optimization, we could cache the current range of unallocated
3083 * clusters in each file of the chain, and avoid querying the same
3089 bs
= bdrv_skip_filters(bs
);
3090 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3095 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3098 bs
= bdrv_cow_bs(bs
);
3107 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3109 if (file
&& has_offset
) {
3110 bdrv_refresh_filename(file
);
3111 filename
= file
->filename
;
3117 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3118 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3120 .has_offset
= has_offset
,
3122 .has_filename
= filename
,
3123 .filename
= filename
,
3129 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3131 if (curr
->length
== 0) {
3134 if (curr
->zero
!= next
->zero
||
3135 curr
->data
!= next
->data
||
3136 curr
->depth
!= next
->depth
||
3137 curr
->has_filename
!= next
->has_filename
||
3138 curr
->has_offset
!= next
->has_offset
) {
3141 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3144 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3150 static int img_map(int argc
, char **argv
)
3153 OutputFormat output_format
= OFORMAT_HUMAN
;
3155 BlockDriverState
*bs
;
3156 const char *filename
, *fmt
, *output
;
3158 MapEntry curr
= { .length
= 0 }, next
;
3160 bool image_opts
= false;
3161 bool force_share
= false;
3162 int64_t start_offset
= 0;
3163 int64_t max_length
= -1;
3168 int option_index
= 0;
3169 static const struct option long_options
[] = {
3170 {"help", no_argument
, 0, 'h'},
3171 {"format", required_argument
, 0, 'f'},
3172 {"output", required_argument
, 0, OPTION_OUTPUT
},
3173 {"object", required_argument
, 0, OPTION_OBJECT
},
3174 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3175 {"force-share", no_argument
, 0, 'U'},
3176 {"start-offset", required_argument
, 0, 's'},
3177 {"max-length", required_argument
, 0, 'l'},
3180 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3181 long_options
, &option_index
);
3187 missing_argument(argv
[optind
- 1]);
3190 unrecognized_option(argv
[optind
- 1]);
3205 start_offset
= cvtnum("start offset", optarg
);
3206 if (start_offset
< 0) {
3211 max_length
= cvtnum("max length", optarg
);
3212 if (max_length
< 0) {
3216 case OPTION_OBJECT
: {
3218 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3224 case OPTION_IMAGE_OPTS
:
3229 if (optind
!= argc
- 1) {
3230 error_exit("Expecting one image file name");
3232 filename
= argv
[optind
];
3234 if (output
&& !strcmp(output
, "json")) {
3235 output_format
= OFORMAT_JSON
;
3236 } else if (output
&& !strcmp(output
, "human")) {
3237 output_format
= OFORMAT_HUMAN
;
3238 } else if (output
) {
3239 error_report("--output must be used with human or json as argument.");
3243 if (qemu_opts_foreach(&qemu_object_opts
,
3244 user_creatable_add_opts_foreach
,
3245 qemu_img_object_print_help
, &error_fatal
)) {
3249 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3255 if (output_format
== OFORMAT_HUMAN
) {
3256 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3257 } else if (output_format
== OFORMAT_JSON
) {
3261 length
= blk_getlength(blk
);
3263 error_report("Failed to get size for '%s'", filename
);
3266 if (max_length
!= -1) {
3267 length
= MIN(start_offset
+ max_length
, length
);
3270 curr
.start
= start_offset
;
3271 while (curr
.start
+ curr
.length
< length
) {
3272 int64_t offset
= curr
.start
+ curr
.length
;
3273 int64_t n
= length
- offset
;
3275 ret
= get_block_status(bs
, offset
, n
, &next
);
3277 error_report("Could not read file metadata: %s", strerror(-ret
));
3281 if (entry_mergeable(&curr
, &next
)) {
3282 curr
.length
+= next
.length
;
3286 if (curr
.length
> 0) {
3287 ret
= dump_map_entry(output_format
, &curr
, &next
);
3295 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3296 if (output_format
== OFORMAT_JSON
) {
3305 #define SNAPSHOT_LIST 1
3306 #define SNAPSHOT_CREATE 2
3307 #define SNAPSHOT_APPLY 3
3308 #define SNAPSHOT_DELETE 4
3310 static int img_snapshot(int argc
, char **argv
)
3313 BlockDriverState
*bs
;
3314 QEMUSnapshotInfo sn
;
3315 char *filename
, *snapshot_name
= NULL
;
3316 int c
, ret
= 0, bdrv_oflags
;
3321 bool image_opts
= false;
3322 bool force_share
= false;
3324 bdrv_oflags
= BDRV_O_RDWR
;
3325 /* Parse commandline parameters */
3327 static const struct option long_options
[] = {
3328 {"help", no_argument
, 0, 'h'},
3329 {"object", required_argument
, 0, OPTION_OBJECT
},
3330 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3331 {"force-share", no_argument
, 0, 'U'},
3334 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3335 long_options
, NULL
);
3341 missing_argument(argv
[optind
- 1]);
3344 unrecognized_option(argv
[optind
- 1]);
3351 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3354 action
= SNAPSHOT_LIST
;
3355 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3359 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3362 action
= SNAPSHOT_APPLY
;
3363 snapshot_name
= optarg
;
3367 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3370 action
= SNAPSHOT_CREATE
;
3371 snapshot_name
= optarg
;
3375 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3378 action
= SNAPSHOT_DELETE
;
3379 snapshot_name
= optarg
;
3387 case OPTION_OBJECT
: {
3389 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3395 case OPTION_IMAGE_OPTS
:
3401 if (optind
!= argc
- 1) {
3402 error_exit("Expecting one image file name");
3404 filename
= argv
[optind
++];
3406 if (qemu_opts_foreach(&qemu_object_opts
,
3407 user_creatable_add_opts_foreach
,
3408 qemu_img_object_print_help
, &error_fatal
)) {
3412 /* Open the image */
3413 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3420 /* Perform the requested action */
3426 case SNAPSHOT_CREATE
:
3427 memset(&sn
, 0, sizeof(sn
));
3428 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3430 qemu_gettimeofday(&tv
);
3431 sn
.date_sec
= tv
.tv_sec
;
3432 sn
.date_nsec
= tv
.tv_usec
* 1000;
3434 ret
= bdrv_snapshot_create(bs
, &sn
);
3436 error_report("Could not create snapshot '%s': %d (%s)",
3437 snapshot_name
, ret
, strerror(-ret
));
3441 case SNAPSHOT_APPLY
:
3442 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3444 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3449 case SNAPSHOT_DELETE
:
3450 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3452 error_report("Could not delete snapshot '%s': snapshot not "
3453 "found", snapshot_name
);
3456 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3458 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3474 static int img_rebase(int argc
, char **argv
)
3476 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3477 uint8_t *buf_old
= NULL
;
3478 uint8_t *buf_new
= NULL
;
3479 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3480 BlockDriverState
*unfiltered_bs
;
3482 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3483 int c
, flags
, src_flags
, ret
;
3484 bool writethrough
, src_writethrough
;
3486 bool force_share
= false;
3489 Error
*local_err
= NULL
;
3490 bool image_opts
= false;
3492 /* Parse commandline parameters */
3494 cache
= BDRV_DEFAULT_CACHE
;
3495 src_cache
= BDRV_DEFAULT_CACHE
;
3499 static const struct option long_options
[] = {
3500 {"help", no_argument
, 0, 'h'},
3501 {"object", required_argument
, 0, OPTION_OBJECT
},
3502 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3503 {"force-share", no_argument
, 0, 'U'},
3506 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3507 long_options
, NULL
);
3513 missing_argument(argv
[optind
- 1]);
3516 unrecognized_option(argv
[optind
- 1]);
3525 out_basefmt
= optarg
;
3528 out_baseimg
= optarg
;
3545 case OPTION_OBJECT
: {
3547 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3553 case OPTION_IMAGE_OPTS
:
3566 if (optind
!= argc
- 1) {
3567 error_exit("Expecting one image file name");
3569 if (!unsafe
&& !out_baseimg
) {
3570 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3572 filename
= argv
[optind
++];
3574 if (qemu_opts_foreach(&qemu_object_opts
,
3575 user_creatable_add_opts_foreach
,
3576 qemu_img_object_print_help
, &error_fatal
)) {
3580 qemu_progress_init(progress
, 2.0);
3581 qemu_progress_print(0, 100);
3583 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3584 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3586 error_report("Invalid cache option: %s", cache
);
3591 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3593 error_report("Invalid source cache option: %s", src_cache
);
3597 /* The source files are opened read-only, don't care about WCE */
3598 assert((src_flags
& BDRV_O_RDWR
) == 0);
3599 (void) src_writethrough
;
3604 * Ignore the old backing file for unsafe rebase in case we want to correct
3605 * the reference to a renamed or moved backing file.
3607 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3615 unfiltered_bs
= bdrv_skip_filters(bs
);
3617 if (out_basefmt
!= NULL
) {
3618 if (bdrv_find_format(out_basefmt
) == NULL
) {
3619 error_report("Invalid format name: '%s'", out_basefmt
);
3625 /* For safe rebasing we need to compare old and new backing file */
3627 QDict
*options
= NULL
;
3628 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3631 blk_old_backing
= blk_new(qemu_get_aio_context(),
3632 BLK_PERM_CONSISTENT_READ
,
3634 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3637 error_reportf_err(local_err
,
3638 "Could not reuse old backing file '%s': ",
3643 blk_old_backing
= NULL
;
3646 if (out_baseimg
[0]) {
3647 const char *overlay_filename
;
3648 char *out_real_path
;
3650 options
= qdict_new();
3652 qdict_put_str(options
, "driver", out_basefmt
);
3655 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3658 bdrv_refresh_filename(bs
);
3659 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3662 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3666 qobject_unref(options
);
3667 error_reportf_err(local_err
,
3668 "Could not resolve backing filename: ");
3674 * Find out whether we rebase an image on top of a previous image
3677 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3678 if (prefix_chain_bs
) {
3679 qobject_unref(options
);
3680 g_free(out_real_path
);
3682 blk_new_backing
= blk_new(qemu_get_aio_context(),
3683 BLK_PERM_CONSISTENT_READ
,
3685 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3688 error_reportf_err(local_err
,
3689 "Could not reuse backing file '%s': ",
3694 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3695 options
, src_flags
, &local_err
);
3696 g_free(out_real_path
);
3697 if (!blk_new_backing
) {
3698 error_reportf_err(local_err
,
3699 "Could not open new backing file '%s': ",
3709 * Check each unallocated cluster in the COW file. If it is unallocated,
3710 * accesses go to the backing file. We must therefore compare this cluster
3711 * in the old and new backing file, and if they differ we need to copy it
3712 * from the old backing file into the COW file.
3714 * If qemu-img crashes during this step, no harm is done. The content of
3715 * the image is the same as the original one at any time.
3719 int64_t old_backing_size
= 0;
3720 int64_t new_backing_size
= 0;
3723 float local_progress
= 0;
3725 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3726 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3728 size
= blk_getlength(blk
);
3730 error_report("Could not get size of '%s': %s",
3731 filename
, strerror(-size
));
3735 if (blk_old_backing
) {
3736 old_backing_size
= blk_getlength(blk_old_backing
);
3737 if (old_backing_size
< 0) {
3738 char backing_name
[PATH_MAX
];
3740 bdrv_get_backing_filename(bs
, backing_name
,
3741 sizeof(backing_name
));
3742 error_report("Could not get size of '%s': %s",
3743 backing_name
, strerror(-old_backing_size
));
3748 if (blk_new_backing
) {
3749 new_backing_size
= blk_getlength(blk_new_backing
);
3750 if (new_backing_size
< 0) {
3751 error_report("Could not get size of '%s': %s",
3752 out_baseimg
, strerror(-new_backing_size
));
3759 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3762 for (offset
= 0; offset
< size
; offset
+= n
) {
3763 bool buf_old_is_zero
= false;
3765 /* How many bytes can we handle with the next read? */
3766 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3768 /* If the cluster is allocated, we don't need to take action */
3769 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3771 error_report("error while reading image metadata: %s",
3779 if (prefix_chain_bs
) {
3781 * If cluster wasn't changed since prefix_chain, we don't need
3784 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3785 prefix_chain_bs
, false,
3788 error_report("error while reading image metadata: %s",
3798 * Read old and new backing file and take into consideration that
3799 * backing files may be smaller than the COW image.
3801 if (offset
>= old_backing_size
) {
3802 memset(buf_old
, 0, n
);
3803 buf_old_is_zero
= true;
3805 if (offset
+ n
> old_backing_size
) {
3806 n
= old_backing_size
- offset
;
3809 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3811 error_report("error while reading from old backing file");
3816 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3817 memset(buf_new
, 0, n
);
3819 if (offset
+ n
> new_backing_size
) {
3820 n
= new_backing_size
- offset
;
3823 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3825 error_report("error while reading from new backing file");
3830 /* If they differ, we need to write to the COW file */
3831 uint64_t written
= 0;
3833 while (written
< n
) {
3836 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3837 n
- written
, &pnum
))
3839 if (buf_old_is_zero
) {
3840 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3842 ret
= blk_pwrite(blk
, offset
+ written
,
3843 buf_old
+ written
, pnum
, 0);
3846 error_report("Error while writing to COW image: %s",
3854 qemu_progress_print(local_progress
, 100);
3859 * Change the backing file. All clusters that are different from the old
3860 * backing file are overwritten in the COW file now, so the visible content
3861 * doesn't change when we switch the backing file.
3863 if (out_baseimg
&& *out_baseimg
) {
3864 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3867 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3870 if (ret
== -ENOSPC
) {
3871 error_report("Could not change the backing file to '%s': No "
3872 "space left in the file header", out_baseimg
);
3873 } else if (ret
< 0) {
3874 error_report("Could not change the backing file to '%s': %s",
3875 out_baseimg
, strerror(-ret
));
3878 qemu_progress_print(100, 0);
3880 * TODO At this point it is possible to check if any clusters that are
3881 * allocated in the COW file are the same in the backing file. If so, they
3882 * could be dropped from the COW file. Don't do this before switching the
3883 * backing file, in case of a crash this would lead to corruption.
3886 qemu_progress_end();
3889 blk_unref(blk_old_backing
);
3890 blk_unref(blk_new_backing
);
3892 qemu_vfree(buf_old
);
3893 qemu_vfree(buf_new
);
3902 static int img_resize(int argc
, char **argv
)
3905 int c
, ret
, relative
;
3906 const char *filename
, *fmt
, *size
;
3907 int64_t n
, total_size
, current_size
;
3909 BlockBackend
*blk
= NULL
;
3910 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3913 static QemuOptsList resize_options
= {
3914 .name
= "resize_options",
3915 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3918 .name
= BLOCK_OPT_SIZE
,
3919 .type
= QEMU_OPT_SIZE
,
3920 .help
= "Virtual disk size"
3926 bool image_opts
= false;
3927 bool shrink
= false;
3929 /* Remove size from argv manually so that negative numbers are not treated
3930 * as options by getopt. */
3932 error_exit("Not enough arguments");
3936 size
= argv
[--argc
];
3938 /* Parse getopt arguments */
3941 static const struct option long_options
[] = {
3942 {"help", no_argument
, 0, 'h'},
3943 {"object", required_argument
, 0, OPTION_OBJECT
},
3944 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3945 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3946 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3949 c
= getopt_long(argc
, argv
, ":f:hq",
3950 long_options
, NULL
);
3956 missing_argument(argv
[optind
- 1]);
3959 unrecognized_option(argv
[optind
- 1]);
3970 case OPTION_OBJECT
: {
3972 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3978 case OPTION_IMAGE_OPTS
:
3981 case OPTION_PREALLOCATION
:
3982 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3983 PREALLOC_MODE__MAX
, NULL
);
3984 if (prealloc
== PREALLOC_MODE__MAX
) {
3985 error_report("Invalid preallocation mode '%s'", optarg
);
3994 if (optind
!= argc
- 1) {
3995 error_exit("Expecting image file name and size");
3997 filename
= argv
[optind
++];
3999 if (qemu_opts_foreach(&qemu_object_opts
,
4000 user_creatable_add_opts_foreach
,
4001 qemu_img_object_print_help
, &error_fatal
)) {
4005 /* Choose grow, shrink, or absolute resize mode */
4021 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
4022 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
4023 error_report_err(err
);
4025 qemu_opts_del(param
);
4028 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
4029 qemu_opts_del(param
);
4031 blk
= img_open(image_opts
, filename
, fmt
,
4032 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4039 current_size
= blk_getlength(blk
);
4040 if (current_size
< 0) {
4041 error_report("Failed to inquire current image length: %s",
4042 strerror(-current_size
));
4048 total_size
= current_size
+ n
* relative
;
4052 if (total_size
<= 0) {
4053 error_report("New image size must be positive");
4058 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4059 error_report("Preallocation can only be used for growing images");
4064 if (total_size
< current_size
&& !shrink
) {
4065 error_report("Use the --shrink option to perform a shrink operation.");
4066 warn_report("Shrinking an image will delete all data beyond the "
4067 "shrunken image's end. Before performing such an "
4068 "operation, make sure there is no important data there.");
4074 * The user expects the image to have the desired size after
4075 * resizing, so pass @exact=true. It is of no use to report
4076 * success when the image has not actually been resized.
4078 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4080 qprintf(quiet
, "Image resized.\n");
4082 error_report_err(err
);
4092 static void amend_status_cb(BlockDriverState
*bs
,
4093 int64_t offset
, int64_t total_work_size
,
4096 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4099 static int print_amend_option_help(const char *format
)
4103 /* Find driver and parse its options */
4104 drv
= bdrv_find_format(format
);
4106 error_report("Unknown file format '%s'", format
);
4110 if (!drv
->bdrv_amend_options
) {
4111 error_report("Format driver '%s' does not support option amendment",
4116 /* Every driver supporting amendment must have amend_opts */
4117 assert(drv
->amend_opts
);
4119 printf("Amend options for '%s':\n", format
);
4120 qemu_opts_print_help(drv
->amend_opts
, false);
4124 static int img_amend(int argc
, char **argv
)
4128 char *options
= NULL
;
4129 QemuOptsList
*amend_opts
= NULL
;
4130 QemuOpts
*opts
= NULL
;
4131 const char *fmt
= NULL
, *filename
, *cache
;
4134 bool quiet
= false, progress
= false;
4135 BlockBackend
*blk
= NULL
;
4136 BlockDriverState
*bs
= NULL
;
4137 bool image_opts
= false;
4140 cache
= BDRV_DEFAULT_CACHE
;
4142 static const struct option long_options
[] = {
4143 {"help", no_argument
, 0, 'h'},
4144 {"object", required_argument
, 0, OPTION_OBJECT
},
4145 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4146 {"force", no_argument
, 0, OPTION_FORCE
},
4149 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4150 long_options
, NULL
);
4157 missing_argument(argv
[optind
- 1]);
4160 unrecognized_option(argv
[optind
- 1]);
4166 if (accumulate_options(&options
, optarg
) < 0) {
4168 goto out_no_progress
;
4184 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4188 goto out_no_progress
;
4191 case OPTION_IMAGE_OPTS
:
4201 error_exit("Must specify options (-o)");
4204 if (qemu_opts_foreach(&qemu_object_opts
,
4205 user_creatable_add_opts_foreach
,
4206 qemu_img_object_print_help
, &error_fatal
)) {
4208 goto out_no_progress
;
4214 qemu_progress_init(progress
, 1.0);
4216 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4217 if (fmt
&& has_help_option(options
)) {
4218 /* If a format is explicitly specified (and possibly no filename is
4219 * given), print option help here */
4220 ret
= print_amend_option_help(fmt
);
4224 if (optind
!= argc
- 1) {
4225 error_report("Expecting one image file name");
4230 flags
= BDRV_O_RDWR
;
4231 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4233 error_report("Invalid cache option: %s", cache
);
4237 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4245 fmt
= bs
->drv
->format_name
;
4247 if (has_help_option(options
)) {
4248 /* If the format was auto-detected, print option help here */
4249 ret
= print_amend_option_help(fmt
);
4253 if (!bs
->drv
->bdrv_amend_options
) {
4254 error_report("Format driver '%s' does not support option amendment",
4260 /* Every driver supporting amendment must have amend_opts */
4261 assert(bs
->drv
->amend_opts
);
4263 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4264 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4265 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4266 /* Try to parse options using the create options */
4267 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4268 qemu_opts_del(opts
);
4269 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4270 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4271 error_append_hint(&err
,
4272 "This option is only supported for image creation\n");
4275 error_report_err(err
);
4280 /* In case the driver does not call amend_status_cb() */
4281 qemu_progress_print(0.f
, 0);
4282 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4283 qemu_progress_print(100.f
, 0);
4285 error_report_err(err
);
4290 qemu_progress_end();
4294 qemu_opts_del(opts
);
4295 qemu_opts_free(amend_opts
);
4304 typedef struct BenchData
{
4306 uint64_t image_size
;
4313 bool drain_on_flush
;
4322 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4325 error_report("Failed flush request: %s", strerror(-ret
));
4330 static void bench_cb(void *opaque
, int ret
)
4332 BenchData
*b
= opaque
;
4336 error_report("Failed request: %s", strerror(-ret
));
4341 /* Just finished a flush with drained queue: Start next requests */
4342 assert(b
->in_flight
== 0);
4343 b
->in_flush
= false;
4344 } else if (b
->in_flight
> 0) {
4345 int remaining
= b
->n
- b
->in_flight
;
4350 /* Time for flush? Drain queue if requested, then flush */
4351 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4352 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4353 BlockCompletionFunc
*cb
;
4355 if (b
->drain_on_flush
) {
4359 cb
= bench_undrained_flush_cb
;
4362 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4364 error_report("Failed to issue flush request");
4368 if (b
->drain_on_flush
) {
4374 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4375 int64_t offset
= b
->offset
;
4376 /* blk_aio_* might look for completed I/Os and kick bench_cb
4377 * again, so make sure this operation is counted by in_flight
4378 * and b->offset is ready for the next submission.
4381 b
->offset
+= b
->step
;
4382 b
->offset
%= b
->image_size
;
4384 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4386 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4389 error_report("Failed to issue request");
4395 static int img_bench(int argc
, char **argv
)
4398 const char *fmt
= NULL
, *filename
;
4400 bool image_opts
= false;
4401 bool is_write
= false;
4405 size_t bufsize
= 4096;
4408 int flush_interval
= 0;
4409 bool drain_on_flush
= true;
4411 BlockBackend
*blk
= NULL
;
4412 BenchData data
= {};
4414 bool writethrough
= false;
4415 struct timeval t1
, t2
;
4417 bool force_share
= false;
4421 static const struct option long_options
[] = {
4422 {"help", no_argument
, 0, 'h'},
4423 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4424 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4425 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4426 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4427 {"force-share", no_argument
, 0, 'U'},
4430 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4438 missing_argument(argv
[optind
- 1]);
4441 unrecognized_option(argv
[optind
- 1]);
4450 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4451 error_report("Invalid request count specified");
4461 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4462 error_report("Invalid queue depth specified");
4472 flags
|= BDRV_O_NATIVE_AIO
;
4475 ret
= bdrv_parse_aio(optarg
, &flags
);
4477 error_report("Invalid aio option: %s", optarg
);
4484 offset
= cvtnum("offset", optarg
);
4498 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4510 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4519 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4521 error_report("Invalid cache mode");
4527 flags
|= BDRV_O_RDWR
;
4533 case OPTION_PATTERN
:
4537 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4538 error_report("Invalid pattern byte specified");
4544 case OPTION_FLUSH_INTERVAL
:
4548 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4549 error_report("Invalid flush interval specified");
4552 flush_interval
= res
;
4555 case OPTION_NO_DRAIN
:
4556 drain_on_flush
= false;
4558 case OPTION_IMAGE_OPTS
:
4564 if (optind
!= argc
- 1) {
4565 error_exit("Expecting one image file name");
4567 filename
= argv
[argc
- 1];
4569 if (!is_write
&& flush_interval
) {
4570 error_report("--flush-interval is only available in write tests");
4574 if (flush_interval
&& flush_interval
< depth
) {
4575 error_report("Flush interval can't be smaller than depth");
4580 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4587 image_size
= blk_getlength(blk
);
4588 if (image_size
< 0) {
4593 data
= (BenchData
) {
4595 .image_size
= image_size
,
4597 .step
= step
?: bufsize
,
4602 .flush_interval
= flush_interval
,
4603 .drain_on_flush
= drain_on_flush
,
4605 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4606 "(starting at offset %" PRId64
", step size %d)\n",
4607 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4608 data
.offset
, data
.step
);
4609 if (flush_interval
) {
4610 printf("Sending flush every %d requests\n", flush_interval
);
4613 buf_size
= data
.nrreq
* data
.bufsize
;
4614 data
.buf
= blk_blockalign(blk
, buf_size
);
4615 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4617 blk_register_buf(blk
, data
.buf
, buf_size
);
4619 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4620 for (i
= 0; i
< data
.nrreq
; i
++) {
4621 qemu_iovec_init(&data
.qiov
[i
], 1);
4622 qemu_iovec_add(&data
.qiov
[i
],
4623 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4626 gettimeofday(&t1
, NULL
);
4629 while (data
.n
> 0) {
4630 main_loop_wait(false);
4632 gettimeofday(&t2
, NULL
);
4634 printf("Run completed in %3.3f seconds.\n",
4635 (t2
.tv_sec
- t1
.tv_sec
)
4636 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4640 blk_unregister_buf(blk
, data
.buf
);
4642 qemu_vfree(data
.buf
);
4659 typedef struct ImgBitmapAction
{
4660 enum ImgBitmapAct act
;
4661 const char *src
; /* only used for merge */
4662 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4665 static int img_bitmap(int argc
, char **argv
)
4669 QemuOpts
*opts
= NULL
;
4670 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4671 const char *filename
, *bitmap
;
4672 BlockBackend
*blk
= NULL
, *src
= NULL
;
4673 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4674 bool image_opts
= false;
4675 int64_t granularity
= 0;
4676 bool add
= false, merge
= false;
4677 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4678 ImgBitmapAction
*act
, *act_next
;
4681 QSIMPLEQ_INIT(&actions
);
4684 static const struct option long_options
[] = {
4685 {"help", no_argument
, 0, 'h'},
4686 {"object", required_argument
, 0, OPTION_OBJECT
},
4687 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4688 {"add", no_argument
, 0, OPTION_ADD
},
4689 {"remove", no_argument
, 0, OPTION_REMOVE
},
4690 {"clear", no_argument
, 0, OPTION_CLEAR
},
4691 {"enable", no_argument
, 0, OPTION_ENABLE
},
4692 {"disable", no_argument
, 0, OPTION_DISABLE
},
4693 {"merge", required_argument
, 0, OPTION_MERGE
},
4694 {"granularity", required_argument
, 0, 'g'},
4695 {"source-file", required_argument
, 0, 'b'},
4696 {"source-format", required_argument
, 0, 'F'},
4699 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4706 missing_argument(argv
[optind
- 1]);
4709 unrecognized_option(argv
[optind
- 1]);
4715 src_filename
= optarg
;
4724 granularity
= cvtnum("granularity", optarg
);
4725 if (granularity
< 0) {
4730 act
= g_new0(ImgBitmapAction
, 1);
4731 act
->act
= BITMAP_ADD
;
4732 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4736 act
= g_new0(ImgBitmapAction
, 1);
4737 act
->act
= BITMAP_REMOVE
;
4738 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4741 act
= g_new0(ImgBitmapAction
, 1);
4742 act
->act
= BITMAP_CLEAR
;
4743 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4746 act
= g_new0(ImgBitmapAction
, 1);
4747 act
->act
= BITMAP_ENABLE
;
4748 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4750 case OPTION_DISABLE
:
4751 act
= g_new0(ImgBitmapAction
, 1);
4752 act
->act
= BITMAP_DISABLE
;
4753 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4756 act
= g_new0(ImgBitmapAction
, 1);
4757 act
->act
= BITMAP_MERGE
;
4759 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4763 opts
= qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true);
4768 case OPTION_IMAGE_OPTS
:
4774 if (qemu_opts_foreach(&qemu_object_opts
,
4775 user_creatable_add_opts_foreach
,
4776 qemu_img_object_print_help
, &error_fatal
)) {
4780 if (QSIMPLEQ_EMPTY(&actions
)) {
4781 error_report("Need at least one of --add, --remove, --clear, "
4782 "--enable, --disable, or --merge");
4786 if (granularity
&& !add
) {
4787 error_report("granularity only supported with --add");
4790 if (src_fmt
&& !src_filename
) {
4791 error_report("-F only supported with -b");
4794 if (src_filename
&& !merge
) {
4795 error_report("Merge bitmap source file only supported with "
4800 if (optind
!= argc
- 2) {
4801 error_report("Expecting filename and bitmap name");
4805 filename
= argv
[optind
];
4806 bitmap
= argv
[optind
+ 1];
4809 * No need to open backing chains; we will be manipulating bitmaps
4810 * directly in this image without reference to image contents.
4812 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4813 false, false, false);
4819 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4820 false, false, false);
4824 src_bs
= blk_bs(src
);
4829 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4832 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4833 !!granularity
, granularity
, true, true,
4834 false, false, &err
);
4838 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4842 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4846 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4849 case BITMAP_DISABLE
:
4850 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4854 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4859 g_assert_not_reached();
4863 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4875 qemu_opts_del(opts
);
4891 int bsz
; /* Block size */
4899 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4903 static int img_dd_bs(const char *arg
,
4904 struct DdIo
*in
, struct DdIo
*out
,
4909 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4914 in
->bsz
= out
->bsz
= res
;
4919 static int img_dd_count(const char *arg
,
4920 struct DdIo
*in
, struct DdIo
*out
,
4923 dd
->count
= cvtnum("count", arg
);
4925 if (dd
->count
< 0) {
4932 static int img_dd_if(const char *arg
,
4933 struct DdIo
*in
, struct DdIo
*out
,
4936 in
->filename
= g_strdup(arg
);
4941 static int img_dd_of(const char *arg
,
4942 struct DdIo
*in
, struct DdIo
*out
,
4945 out
->filename
= g_strdup(arg
);
4950 static int img_dd_skip(const char *arg
,
4951 struct DdIo
*in
, struct DdIo
*out
,
4954 in
->offset
= cvtnum("skip", arg
);
4956 if (in
->offset
< 0) {
4963 static int img_dd(int argc
, char **argv
)
4968 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4969 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4970 QemuOpts
*opts
= NULL
;
4971 QemuOptsList
*create_opts
= NULL
;
4972 Error
*local_err
= NULL
;
4973 bool image_opts
= false;
4975 const char *out_fmt
= "raw";
4976 const char *fmt
= NULL
;
4978 int64_t block_count
= 0, out_pos
, in_pos
;
4979 bool force_share
= false;
4980 struct DdInfo dd
= {
4985 .bsz
= 512, /* Block size is by default 512 bytes */
4997 const struct DdOpts options
[] = {
4998 { "bs", img_dd_bs
, C_BS
},
4999 { "count", img_dd_count
, C_COUNT
},
5000 { "if", img_dd_if
, C_IF
},
5001 { "of", img_dd_of
, C_OF
},
5002 { "skip", img_dd_skip
, C_SKIP
},
5005 const struct option long_options
[] = {
5006 { "help", no_argument
, 0, 'h'},
5007 { "object", required_argument
, 0, OPTION_OBJECT
},
5008 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5009 { "force-share", no_argument
, 0, 'U'},
5013 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
5025 missing_argument(argv
[optind
- 1]);
5028 unrecognized_option(argv
[optind
- 1]);
5037 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
5042 case OPTION_IMAGE_OPTS
:
5048 for (i
= optind
; i
< argc
; i
++) {
5050 arg
= g_strdup(argv
[i
]);
5052 tmp
= strchr(arg
, '=');
5054 error_report("unrecognized operand %s", arg
);
5061 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5062 if (!strcmp(arg
, options
[j
].name
)) {
5066 if (options
[j
].name
== NULL
) {
5067 error_report("unrecognized operand %s", arg
);
5072 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5076 dd
.flags
|= options
[j
].flag
;
5081 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5082 error_report("Must specify both input and output files");
5087 if (qemu_opts_foreach(&qemu_object_opts
,
5088 user_creatable_add_opts_foreach
,
5089 qemu_img_object_print_help
, &error_fatal
)) {
5094 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5102 drv
= bdrv_find_format(out_fmt
);
5104 error_report("Unknown file format");
5108 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5111 error_report_err(local_err
);
5115 if (!drv
->create_opts
) {
5116 error_report("Format driver '%s' does not support image creation",
5121 if (!proto_drv
->create_opts
) {
5122 error_report("Protocol driver '%s' does not support image creation",
5123 proto_drv
->format_name
);
5127 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5128 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5130 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5132 size
= blk_getlength(blk1
);
5134 error_report("Failed to get size for '%s'", in
.filename
);
5139 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5140 dd
.count
* in
.bsz
< size
) {
5141 size
= dd
.count
* in
.bsz
;
5144 /* Overflow means the specified offset is beyond input image's size */
5145 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5146 size
< in
.bsz
* in
.offset
)) {
5147 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5149 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5150 size
- in
.bsz
* in
.offset
, &error_abort
);
5153 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5155 error_reportf_err(local_err
,
5156 "%s: error while creating output image: ",
5162 /* TODO, we can't honour --image-opts for the target,
5163 * since it needs to be given in a format compatible
5164 * with the bdrv_create() call above which does not
5165 * support image-opts style.
5167 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5168 false, false, false);
5175 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5176 size
< in
.offset
* in
.bsz
)) {
5177 /* We give a warning if the skip option is bigger than the input
5178 * size and create an empty output disk image (i.e. like dd(1)).
5180 error_report("%s: cannot skip to specified offset", in
.filename
);
5183 in_pos
= in
.offset
* in
.bsz
;
5186 in
.buf
= g_new(uint8_t, in
.bsz
);
5188 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5189 int in_ret
, out_ret
;
5191 if (in_pos
+ in
.bsz
> size
) {
5192 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5194 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5197 error_report("error while reading from input image file: %s",
5204 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5207 error_report("error while writing to output image file: %s",
5208 strerror(-out_ret
));
5217 qemu_opts_del(opts
);
5218 qemu_opts_free(create_opts
);
5221 g_free(in
.filename
);
5222 g_free(out
.filename
);
5232 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5236 Visitor
*v
= qobject_output_visitor_new(&obj
);
5238 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5239 visit_complete(v
, &obj
);
5240 str
= qobject_to_json_pretty(obj
, true);
5241 assert(str
!= NULL
);
5242 printf("%s\n", str
->str
);
5245 g_string_free(str
, true);
5248 static int img_measure(int argc
, char **argv
)
5250 static const struct option long_options
[] = {
5251 {"help", no_argument
, 0, 'h'},
5252 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5253 {"object", required_argument
, 0, OPTION_OBJECT
},
5254 {"output", required_argument
, 0, OPTION_OUTPUT
},
5255 {"size", required_argument
, 0, OPTION_SIZE
},
5256 {"force-share", no_argument
, 0, 'U'},
5259 OutputFormat output_format
= OFORMAT_HUMAN
;
5260 BlockBackend
*in_blk
= NULL
;
5262 const char *filename
= NULL
;
5263 const char *fmt
= NULL
;
5264 const char *out_fmt
= "raw";
5265 char *options
= NULL
;
5266 char *snapshot_name
= NULL
;
5267 bool force_share
= false;
5268 QemuOpts
*opts
= NULL
;
5269 QemuOpts
*object_opts
= NULL
;
5270 QemuOpts
*sn_opts
= NULL
;
5271 QemuOptsList
*create_opts
= NULL
;
5272 bool image_opts
= false;
5273 uint64_t img_size
= UINT64_MAX
;
5274 BlockMeasureInfo
*info
= NULL
;
5275 Error
*local_err
= NULL
;
5279 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5280 long_options
, NULL
)) != -1) {
5293 if (accumulate_options(&options
, optarg
) < 0) {
5298 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5299 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5302 error_report("Failed in parsing snapshot param '%s'",
5307 snapshot_name
= optarg
;
5314 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
5320 case OPTION_IMAGE_OPTS
:
5324 if (!strcmp(optarg
, "json")) {
5325 output_format
= OFORMAT_JSON
;
5326 } else if (!strcmp(optarg
, "human")) {
5327 output_format
= OFORMAT_HUMAN
;
5329 error_report("--output must be used with human or json "
5338 sval
= cvtnum("image size", optarg
);
5342 img_size
= (uint64_t)sval
;
5348 if (qemu_opts_foreach(&qemu_object_opts
,
5349 user_creatable_add_opts_foreach
,
5350 qemu_img_object_print_help
, &error_fatal
)) {
5354 if (argc
- optind
> 1) {
5355 error_report("At most one filename argument is allowed.");
5357 } else if (argc
- optind
== 1) {
5358 filename
= argv
[optind
];
5361 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5362 error_report("--image-opts, -f, and -l require a filename argument.");
5365 if (filename
&& img_size
!= UINT64_MAX
) {
5366 error_report("--size N cannot be used together with a filename.");
5369 if (!filename
&& img_size
== UINT64_MAX
) {
5370 error_report("Either --size N or one filename must be specified.");
5375 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5376 false, false, force_share
);
5382 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5383 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5384 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5386 } else if (snapshot_name
!= NULL
) {
5387 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5388 snapshot_name
, &local_err
);
5391 error_reportf_err(local_err
, "Failed to load snapshot: ");
5396 drv
= bdrv_find_format(out_fmt
);
5398 error_report("Unknown file format '%s'", out_fmt
);
5401 if (!drv
->create_opts
) {
5402 error_report("Format driver '%s' does not support image creation",
5407 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5408 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5409 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5411 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5412 error_report_err(local_err
);
5413 error_report("Invalid options for file format '%s'", out_fmt
);
5417 if (img_size
!= UINT64_MAX
) {
5418 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5421 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5423 error_report_err(local_err
);
5427 if (output_format
== OFORMAT_HUMAN
) {
5428 printf("required size: %" PRIu64
"\n", info
->required
);
5429 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5430 if (info
->has_bitmaps
) {
5431 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5434 dump_json_block_measure_info(info
);
5440 qapi_free_BlockMeasureInfo(info
);
5441 qemu_opts_del(object_opts
);
5442 qemu_opts_del(opts
);
5443 qemu_opts_del(sn_opts
);
5444 qemu_opts_free(create_opts
);
5450 static const img_cmd_t img_cmds
[] = {
5451 #define DEF(option, callback, arg_string) \
5452 { option, callback },
5453 #include "qemu-img-cmds.h"
5458 int main(int argc
, char **argv
)
5460 const img_cmd_t
*cmd
;
5461 const char *cmdname
;
5462 Error
*local_error
= NULL
;
5464 static const struct option long_options
[] = {
5465 {"help", no_argument
, 0, 'h'},
5466 {"version", no_argument
, 0, 'V'},
5467 {"trace", required_argument
, NULL
, 'T'},
5472 signal(SIGPIPE
, SIG_IGN
);
5476 error_init(argv
[0]);
5477 module_call_init(MODULE_INIT_TRACE
);
5478 qemu_init_exec_dir(argv
[0]);
5480 if (qemu_init_main_loop(&local_error
)) {
5481 error_report_err(local_error
);
5485 qcrypto_init(&error_fatal
);
5487 module_call_init(MODULE_INIT_QOM
);
5490 error_exit("Not enough arguments");
5493 qemu_add_opts(&qemu_object_opts
);
5494 qemu_add_opts(&qemu_source_opts
);
5495 qemu_add_opts(&qemu_trace_opts
);
5497 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5500 missing_argument(argv
[optind
- 1]);
5503 unrecognized_option(argv
[optind
- 1]);
5509 printf(QEMU_IMG_VERSION
);
5512 trace_opt_parse(optarg
);
5517 cmdname
= argv
[optind
];
5519 /* reset getopt_long scanning */
5525 qemu_reset_optind();
5527 if (!trace_init_backends()) {
5531 qemu_set_log(LOG_TRACE
);
5533 /* find the command */
5534 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5535 if (!strcmp(cmdname
, cmd
->name
)) {
5536 return cmd
->handler(argc
, argv
);
5541 error_exit("Command not found: %s", cmdname
);