2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/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"
53 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
54 "\n" QEMU_COPYRIGHT "\n"
56 typedef struct img_cmd_t
{
58 int (*handler
)(int argc
, char **argv
);
63 OPTION_BACKING_CHAIN
= 257,
65 OPTION_IMAGE_OPTS
= 259,
67 OPTION_FLUSH_INTERVAL
= 261,
68 OPTION_NO_DRAIN
= 262,
69 OPTION_TARGET_IMAGE_OPTS
= 263,
71 OPTION_PREALLOCATION
= 265,
74 OPTION_TARGET_IS_ZERO
= 268,
83 typedef enum OutputFormat
{
88 /* Default to cache=writeback as data integrity is not important for qemu-img */
89 #define BDRV_DEFAULT_CACHE "writeback"
91 static void format_print(void *opaque
, const char *name
)
96 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
101 error_vreport(fmt
, ap
);
104 error_printf("Try 'qemu-img --help' for more information\n");
108 static void QEMU_NORETURN
missing_argument(const char *option
)
110 error_exit("missing argument for option '%s'", option
);
113 static void QEMU_NORETURN
unrecognized_option(const char *option
)
115 error_exit("unrecognized option '%s'", option
);
118 /* Please keep in synch with docs/tools/qemu-img.rst */
119 static void QEMU_NORETURN
help(void)
121 const char *help_msg
=
123 "usage: qemu-img [standard options] command [command options]\n"
124 "QEMU disk image utility\n"
126 " '-h', '--help' display this help and exit\n"
127 " '-V', '--version' output version information and exit\n"
128 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
129 " specify tracing options\n"
132 #define DEF(option, callback, arg_string) \
134 #include "qemu-img-cmds.h"
137 "Command parameters:\n"
138 " 'filename' is a disk image filename\n"
139 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
140 " manual page for a description of the object properties. The most common\n"
141 " object type is a 'secret', which is used to supply passwords and/or\n"
142 " encryption keys.\n"
143 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
144 " 'cache' is the cache mode used to write the output disk image, the valid\n"
145 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
146 " 'directsync' and 'unsafe' (default for convert)\n"
147 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
148 " options are the same as for the 'cache' option\n"
149 " 'size' is the disk image size in bytes. Optional suffixes\n"
150 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
151 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
152 " supported. 'b' is ignored.\n"
153 " 'output_filename' is the destination disk image filename\n"
154 " 'output_fmt' is the destination format\n"
155 " 'options' is a comma separated list of format specific options in a\n"
156 " name=value format. Use -o ? for an overview of the options supported by the\n"
158 " 'snapshot_param' is param used for internal snapshot, format\n"
159 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
161 " '-c' indicates that target image must be compressed (qcow format only)\n"
162 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
163 " new backing file match exactly. The image doesn't need a working\n"
164 " backing file before rebasing in this case (useful for renaming the\n"
165 " backing file). For image creation, allow creating without attempting\n"
166 " to open the backing file.\n"
167 " '-h' with or without a command shows this help and lists the supported formats\n"
168 " '-p' show progress of command (only certain commands)\n"
169 " '-q' use Quiet mode - do not print any output (except errors)\n"
170 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
171 " contain only zeros for qemu-img to create a sparse image during\n"
172 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
173 " unallocated or zero sectors, and the destination image will always be\n"
175 " '--output' takes the format in which the output must be done (human or json)\n"
176 " '-n' skips the target volume creation (useful if the volume is created\n"
177 " prior to running qemu-img)\n"
179 "Parameters to bitmap subcommand:\n"
180 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
181 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
182 " or '--merge source'\n"
183 " '-g granularity' sets the granularity for '--add' actions\n"
184 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
185 " bitmaps from an alternative file\n"
187 "Parameters to check subcommand:\n"
188 " '-r' tries to repair any inconsistencies that are found during the check.\n"
189 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
190 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
191 " hiding corruption that has already occurred.\n"
193 "Parameters to convert subcommand:\n"
194 " '-m' specifies how many coroutines work in parallel during the convert\n"
195 " process (defaults to 8)\n"
196 " '-W' allow to write to the target out of order rather than sequential\n"
198 "Parameters to snapshot subcommand:\n"
199 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
200 " '-a' applies a snapshot (revert disk to saved state)\n"
201 " '-c' creates a snapshot\n"
202 " '-d' deletes a snapshot\n"
203 " '-l' lists all snapshots in the given image\n"
205 "Parameters to compare subcommand:\n"
206 " '-f' first image format\n"
207 " '-F' second image format\n"
208 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
210 "Parameters to dd subcommand:\n"
211 " 'bs=BYTES' read and write up to BYTES bytes at a time "
213 " 'count=N' copy only N input blocks\n"
214 " 'if=FILE' read from FILE\n"
215 " 'of=FILE' write to FILE\n"
216 " 'skip=N' skip N bs-sized blocks at the start of input\n";
218 printf("%s\nSupported formats:", help_msg
);
219 bdrv_iterate_format(format_print
, NULL
, false);
220 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
224 static QemuOptsList qemu_object_opts
= {
226 .implied_opt_name
= "qom-type",
227 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
233 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
235 if (user_creatable_print_help(type
, opts
)) {
242 * Is @optarg safe for accumulate_options()?
243 * It is when multiple of them can be joined together separated by ','.
244 * To make that work, @optarg must not start with ',' (or else a
245 * separating ',' preceding it gets escaped), and it must not end with
246 * an odd number of ',' (or else a separating ',' following it gets
247 * escaped), or be empty (or else a separating ',' preceding it can
248 * escape a separating ',' following it).
251 static bool is_valid_option_list(const char *optarg
)
253 size_t len
= strlen(optarg
);
256 if (!optarg
[0] || optarg
[0] == ',') {
260 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
269 static int accumulate_options(char **options
, char *optarg
)
273 if (!is_valid_option_list(optarg
)) {
274 error_report("Invalid option list: %s", optarg
);
279 *options
= g_strdup(optarg
);
281 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
283 *options
= new_options
;
288 static QemuOptsList qemu_source_opts
= {
290 .implied_opt_name
= "file",
291 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
297 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
303 ret
= vprintf(fmt
, args
);
310 static int print_block_option_help(const char *filename
, const char *fmt
)
312 BlockDriver
*drv
, *proto_drv
;
313 QemuOptsList
*create_opts
= NULL
;
314 Error
*local_err
= NULL
;
316 /* Find driver and parse its options */
317 drv
= bdrv_find_format(fmt
);
319 error_report("Unknown file format '%s'", fmt
);
323 if (!drv
->create_opts
) {
324 error_report("Format driver '%s' does not support image creation", fmt
);
328 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
330 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
332 error_report_err(local_err
);
333 qemu_opts_free(create_opts
);
336 if (!proto_drv
->create_opts
) {
337 error_report("Protocol driver '%s' does not support image creation",
338 proto_drv
->format_name
);
339 qemu_opts_free(create_opts
);
342 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
346 printf("Supported options:\n");
348 printf("Supported %s options:\n", fmt
);
350 qemu_opts_print_help(create_opts
, false);
351 qemu_opts_free(create_opts
);
355 "The protocol level may support further options.\n"
356 "Specify the target filename to include those options.\n");
363 static BlockBackend
*img_open_opts(const char *optstr
,
364 QemuOpts
*opts
, int flags
, bool writethrough
,
365 bool quiet
, bool force_share
)
368 Error
*local_err
= NULL
;
370 options
= qemu_opts_to_qdict(opts
, NULL
);
372 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
373 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
374 error_report("--force-share/-U conflicts with image options");
375 qobject_unref(options
);
378 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
380 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
382 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
385 blk_set_enable_write_cache(blk
, !writethrough
);
390 static BlockBackend
*img_open_file(const char *filename
,
392 const char *fmt
, int flags
,
393 bool writethrough
, bool quiet
,
397 Error
*local_err
= NULL
;
400 options
= qdict_new();
403 qdict_put_str(options
, "driver", fmt
);
407 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
409 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
411 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
414 blk_set_enable_write_cache(blk
, !writethrough
);
420 static int img_add_key_secrets(void *opaque
,
421 const char *name
, const char *value
,
424 QDict
*options
= opaque
;
426 if (g_str_has_suffix(name
, "key-secret")) {
427 qdict_put_str(options
, name
, value
);
434 static BlockBackend
*img_open(bool image_opts
,
435 const char *filename
,
436 const char *fmt
, int flags
, bool writethrough
,
437 bool quiet
, bool force_share
)
443 error_report("--image-opts and --format are mutually exclusive");
446 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
451 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
454 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
461 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
462 const char *base_filename
,
463 const char *base_fmt
)
468 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
470 error_report("Backing file not supported for file format '%s'",
477 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
479 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
);
637 qprintf(quiet
, "%s\n", qstring_get_str(str
));
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
;
986 cache
= BDRV_DEFAULT_CACHE
;
989 static const struct option long_options
[] = {
990 {"help", no_argument
, 0, 'h'},
991 {"object", required_argument
, 0, OPTION_OBJECT
},
992 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
995 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
1002 missing_argument(argv
[optind
- 1]);
1005 unrecognized_option(argv
[optind
- 1]);
1030 case OPTION_OBJECT
: {
1032 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1038 case OPTION_IMAGE_OPTS
:
1044 /* Progress is not shown in Quiet mode */
1049 if (optind
!= argc
- 1) {
1050 error_exit("Expecting one image file name");
1052 filename
= argv
[optind
++];
1054 if (qemu_opts_foreach(&qemu_object_opts
,
1055 user_creatable_add_opts_foreach
,
1056 qemu_img_object_print_help
, &error_fatal
)) {
1060 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1061 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1063 error_report("Invalid cache option: %s", cache
);
1067 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1074 qemu_progress_init(progress
, 1.f
);
1075 qemu_progress_print(0.f
, 100);
1078 base_bs
= bdrv_find_backing_image(bs
, base
);
1080 error_setg(&local_err
,
1081 "Did not find '%s' in the backing chain of '%s'",
1086 /* This is different from QMP, which by default uses the deepest file in
1087 * the backing chain (i.e., the very base); however, the traditional
1088 * behavior of qemu-img commit is using the immediate backing file. */
1089 base_bs
= backing_bs(bs
);
1091 error_setg(&local_err
, "Image does not have a backing file");
1096 cbi
= (CommonBlockJobCBInfo
){
1101 aio_context
= bdrv_get_aio_context(bs
);
1102 aio_context_acquire(aio_context
);
1103 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1104 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1105 &cbi
, false, &local_err
);
1106 aio_context_release(aio_context
);
1111 /* When the block job completes, the BlockBackend reference will point to
1112 * the old backing file. In order to avoid that the top image is already
1113 * deleted, so we can still empty it afterwards, increment the reference
1114 * counter here preemptively. */
1119 job
= block_job_get("commit");
1121 run_block_job(job
, &local_err
);
1127 BlockBackend
*old_backing_blk
;
1129 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1131 if (!old_backing_blk
) {
1134 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1135 blk_unref(old_backing_blk
);
1136 if (ret
== -ENOTSUP
) {
1137 error_free(local_err
);
1139 } else if (ret
< 0) {
1150 qemu_progress_end();
1155 error_report_err(local_err
);
1159 qprintf(quiet
, "Image committed.\n");
1164 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1165 * of the first sector boundary within buf where the sector contains a
1166 * non-zero byte. This function is robust to a buffer that is not
1169 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1172 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1174 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1175 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1179 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1186 * Returns true iff the first sector pointed to by 'buf' contains at least
1189 * 'pnum' is set to the number of sectors (including and immediately following
1190 * the first one) that are known to be in the same allocated/unallocated state.
1191 * The function will try to align the end offset to alignment boundaries so
1192 * that the request will at least end aligned and consequtive requests will
1193 * also start at an aligned offset.
1195 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1196 int64_t sector_num
, int alignment
)
1205 is_zero
= buffer_is_zero(buf
, 512);
1206 for(i
= 1; i
< n
; i
++) {
1208 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1213 tail
= (sector_num
+ i
) & (alignment
- 1);
1215 if (is_zero
&& i
<= tail
) {
1216 /* treat unallocated areas which only consist
1217 * of a small tail as allocated. */
1221 /* align up end offset of allocated areas. */
1222 i
+= alignment
- tail
;
1225 /* align down end offset of zero areas. */
1234 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1235 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1236 * breaking up write requests for only small sparse areas.
1238 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1239 int min
, int64_t sector_num
, int alignment
)
1242 int num_checked
, num_used
;
1248 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1254 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1256 sector_num
+= *pnum
;
1257 num_checked
= num_used
;
1260 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1262 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1264 sector_num
+= *pnum
;
1265 num_checked
+= *pnum
;
1267 num_used
= num_checked
;
1268 } else if (*pnum
>= min
) {
1278 * Compares two buffers sector by sector. Returns 0 if the first
1279 * sector of each buffer matches, non-zero otherwise.
1281 * pnum is set to the sector-aligned size of the buffer prefix that
1282 * has the same matching status as the first sector.
1284 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1285 int64_t bytes
, int64_t *pnum
)
1288 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1292 res
= !!memcmp(buf1
, buf2
, i
);
1294 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1296 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1306 #define IO_BUF_SIZE (2 * MiB)
1309 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1311 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1312 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1313 * failure), and 4 on error (the exit status for read errors), after emitting
1316 * @param blk: BlockBackend for the image
1317 * @param offset: Starting offset to check
1318 * @param bytes: Number of bytes to check
1319 * @param filename: Name of disk file we are checking (logging purpose)
1320 * @param buffer: Allocated buffer for storing read data
1321 * @param quiet: Flag for quiet mode
1323 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1324 int64_t bytes
, const char *filename
,
1325 uint8_t *buffer
, bool quiet
)
1330 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1332 error_report("Error while reading offset %" PRId64
" of %s: %s",
1333 offset
, filename
, strerror(-ret
));
1336 idx
= find_nonzero(buffer
, bytes
);
1338 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1347 * Compares two images. Exit codes:
1349 * 0 - Images are identical
1351 * >1 - Error occurred
1353 static int img_compare(int argc
, char **argv
)
1355 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1356 BlockBackend
*blk1
, *blk2
;
1357 BlockDriverState
*bs1
, *bs2
;
1358 int64_t total_size1
, total_size2
;
1359 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1360 int64_t pnum1
, pnum2
;
1361 int allocated1
, allocated2
;
1362 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1363 bool progress
= false, quiet
= false, strict
= false;
1370 uint64_t progress_base
;
1371 bool image_opts
= false;
1372 bool force_share
= false;
1374 cache
= BDRV_DEFAULT_CACHE
;
1376 static const struct option long_options
[] = {
1377 {"help", no_argument
, 0, 'h'},
1378 {"object", required_argument
, 0, OPTION_OBJECT
},
1379 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1380 {"force-share", no_argument
, 0, 'U'},
1383 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1384 long_options
, NULL
);
1390 missing_argument(argv
[optind
- 1]);
1393 unrecognized_option(argv
[optind
- 1]);
1419 case OPTION_OBJECT
: {
1421 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1428 case OPTION_IMAGE_OPTS
:
1434 /* Progress is not shown in Quiet mode */
1440 if (optind
!= argc
- 2) {
1441 error_exit("Expecting two image file names");
1443 filename1
= argv
[optind
++];
1444 filename2
= argv
[optind
++];
1446 if (qemu_opts_foreach(&qemu_object_opts
,
1447 user_creatable_add_opts_foreach
,
1448 qemu_img_object_print_help
, &error_fatal
)) {
1453 /* Initialize before goto out */
1454 qemu_progress_init(progress
, 2.0);
1457 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1459 error_report("Invalid source cache option: %s", cache
);
1464 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1471 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1480 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1481 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1482 total_size1
= blk_getlength(blk1
);
1483 if (total_size1
< 0) {
1484 error_report("Can't get size of %s: %s",
1485 filename1
, strerror(-total_size1
));
1489 total_size2
= blk_getlength(blk2
);
1490 if (total_size2
< 0) {
1491 error_report("Can't get size of %s: %s",
1492 filename2
, strerror(-total_size2
));
1496 total_size
= MIN(total_size1
, total_size2
);
1497 progress_base
= MAX(total_size1
, total_size2
);
1499 qemu_progress_print(0, 100);
1501 if (strict
&& total_size1
!= total_size2
) {
1503 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1507 while (offset
< total_size
) {
1508 int status1
, status2
;
1510 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1511 total_size1
- offset
, &pnum1
, NULL
,
1515 error_report("Sector allocation test failed for %s", filename1
);
1518 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1520 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1521 total_size2
- offset
, &pnum2
, NULL
,
1525 error_report("Sector allocation test failed for %s", filename2
);
1528 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1530 assert(pnum1
&& pnum2
);
1531 chunk
= MIN(pnum1
, pnum2
);
1534 if (status1
!= status2
) {
1536 qprintf(quiet
, "Strict mode: Offset %" PRId64
1537 " block status mismatch!\n", offset
);
1541 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1543 } else if (allocated1
== allocated2
) {
1547 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1548 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1550 error_report("Error while reading offset %" PRId64
1552 offset
, filename1
, strerror(-ret
));
1556 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1558 error_report("Error while reading offset %" PRId64
1560 offset
, filename2
, strerror(-ret
));
1564 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1565 if (ret
|| pnum
!= chunk
) {
1566 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1567 offset
+ (ret
? 0 : pnum
));
1573 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1575 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1576 filename1
, buf1
, quiet
);
1578 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1579 filename2
, buf1
, quiet
);
1586 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1589 if (total_size1
!= total_size2
) {
1590 BlockBackend
*blk_over
;
1591 const char *filename_over
;
1593 qprintf(quiet
, "Warning: Image size mismatch!\n");
1594 if (total_size1
> total_size2
) {
1596 filename_over
= filename1
;
1599 filename_over
= filename2
;
1602 while (offset
< progress_base
) {
1603 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1604 progress_base
- offset
, &chunk
,
1608 error_report("Sector allocation test failed for %s",
1613 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1614 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1615 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1616 filename_over
, buf1
, quiet
);
1622 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1626 qprintf(quiet
, "Images are identical.\n");
1636 qemu_progress_end();
1641 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1642 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1643 const char *src_node
, const char *src_name
,
1646 BlockDirtyBitmapMergeSource
*merge_src
;
1647 BlockDirtyBitmapMergeSourceList
*list
;
1649 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1650 merge_src
->type
= QTYPE_QDICT
;
1651 merge_src
->u
.external
.node
= g_strdup(src_node
);
1652 merge_src
->u
.external
.name
= g_strdup(src_name
);
1653 list
= g_new0(BlockDirtyBitmapMergeSourceList
, 1);
1654 list
->value
= merge_src
;
1655 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1656 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1659 enum ImgConvertBlockStatus
{
1665 #define MAX_COROUTINES 16
1667 typedef struct ImgConvertState
{
1669 int64_t *src_sectors
;
1671 int64_t total_sectors
;
1672 int64_t allocated_sectors
;
1673 int64_t allocated_done
;
1676 enum ImgConvertBlockStatus status
;
1677 int64_t sector_next_status
;
1678 BlockBackend
*target
;
1681 bool unallocated_blocks_are_zero
;
1683 bool target_has_backing
;
1684 int64_t target_backing_sectors
; /* negative if unknown */
1691 size_t cluster_sectors
;
1693 long num_coroutines
;
1694 int running_coroutines
;
1695 Coroutine
*co
[MAX_COROUTINES
];
1696 int64_t wait_sector_num
[MAX_COROUTINES
];
1701 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1702 int *src_cur
, int64_t *src_cur_offset
)
1705 *src_cur_offset
= 0;
1706 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1707 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1709 assert(*src_cur
< s
->src_num
);
1713 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1715 int64_t src_cur_offset
;
1716 int ret
, n
, src_cur
;
1717 bool post_backing_zero
= false;
1719 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1721 assert(s
->total_sectors
> sector_num
);
1722 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1724 if (s
->target_backing_sectors
>= 0) {
1725 if (sector_num
>= s
->target_backing_sectors
) {
1726 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1727 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1728 /* Split requests around target_backing_sectors (because
1729 * starting from there, zeros are handled differently) */
1730 n
= s
->target_backing_sectors
- sector_num
;
1734 if (s
->sector_next_status
<= sector_num
) {
1735 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1739 count
= n
* BDRV_SECTOR_SIZE
;
1741 if (s
->target_has_backing
) {
1742 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1743 count
, &count
, NULL
, NULL
);
1745 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1746 offset
, count
, &count
, NULL
,
1754 warn_report("error while reading block status at "
1755 "offset %" PRIu64
": %s", offset
,
1758 /* Just try to read the data, then */
1759 ret
= BDRV_BLOCK_DATA
;
1760 count
= BDRV_SECTOR_SIZE
;
1762 /* Retry on a shorter range */
1763 n
= DIV_ROUND_UP(n
, 4);
1766 error_report("error while reading block status at offset "
1767 "%" PRIu64
": %s", offset
, strerror(-ret
));
1773 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1775 if (ret
& BDRV_BLOCK_ZERO
) {
1776 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1777 } else if (ret
& BDRV_BLOCK_DATA
) {
1778 s
->status
= BLK_DATA
;
1780 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1783 s
->sector_next_status
= sector_num
+ n
;
1786 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1787 if (s
->status
== BLK_DATA
) {
1788 n
= MIN(n
, s
->buf_sectors
);
1791 /* We need to write complete clusters for compressed images, so if an
1792 * unallocated area is shorter than that, we must consider the whole
1793 * cluster allocated. */
1794 if (s
->compressed
) {
1795 if (n
< s
->cluster_sectors
) {
1796 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1797 s
->status
= BLK_DATA
;
1799 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1806 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1807 int nb_sectors
, uint8_t *buf
)
1809 uint64_t single_read_until
= 0;
1812 assert(nb_sectors
<= s
->buf_sectors
);
1813 while (nb_sectors
> 0) {
1816 int64_t bs_sectors
, src_cur_offset
;
1819 /* In the case of compression with multiple source files, we can get a
1820 * nb_sectors that spreads into the next part. So we must be able to
1821 * read across multiple BDSes for one convert_read() call. */
1822 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1823 blk
= s
->src
[src_cur
];
1824 bs_sectors
= s
->src_sectors
[src_cur
];
1826 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1828 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1829 if (single_read_until
> offset
) {
1833 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1837 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1841 warn_report("error while reading offset %" PRIu64
1842 ": %s", offset
, strerror(-ret
));
1844 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1853 buf
+= n
* BDRV_SECTOR_SIZE
;
1860 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1861 int nb_sectors
, uint8_t *buf
,
1862 enum ImgConvertBlockStatus status
)
1866 while (nb_sectors
> 0) {
1868 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1871 case BLK_BACKING_FILE
:
1872 /* If we have a backing file, leave clusters unallocated that are
1873 * unallocated in the source image, so that the backing file is
1874 * visible at the respective offset. */
1875 assert(s
->target_has_backing
);
1879 /* If we're told to keep the target fully allocated (-S 0) or there
1880 * is real non-zero data, we must write it. Otherwise we can treat
1881 * it as zero sectors.
1882 * Compressed clusters need to be written as a whole, so in that
1883 * case we can only save the write if the buffer is completely
1885 if (!s
->min_sparse
||
1887 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1888 sector_num
, s
->alignment
)) ||
1890 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1892 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1893 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1902 if (s
->has_zero_init
) {
1903 assert(!s
->target_has_backing
);
1906 ret
= blk_co_pwrite_zeroes(s
->target
,
1907 sector_num
<< BDRV_SECTOR_BITS
,
1908 n
<< BDRV_SECTOR_BITS
,
1909 BDRV_REQ_MAY_UNMAP
);
1918 buf
+= n
* BDRV_SECTOR_SIZE
;
1924 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1929 while (nb_sectors
> 0) {
1932 int64_t bs_sectors
, src_cur_offset
;
1935 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1936 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1937 blk
= s
->src
[src_cur
];
1938 bs_sectors
= s
->src_sectors
[src_cur
];
1940 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1942 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1943 sector_num
<< BDRV_SECTOR_BITS
,
1944 n
<< BDRV_SECTOR_BITS
, 0, 0);
1955 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1957 ImgConvertState
*s
= opaque
;
1958 uint8_t *buf
= NULL
;
1962 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1963 if (s
->co
[i
] == qemu_coroutine_self()) {
1970 s
->running_coroutines
++;
1971 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1976 enum ImgConvertBlockStatus status
;
1979 qemu_co_mutex_lock(&s
->lock
);
1980 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1981 qemu_co_mutex_unlock(&s
->lock
);
1984 n
= convert_iteration_sectors(s
, s
->sector_num
);
1986 qemu_co_mutex_unlock(&s
->lock
);
1990 /* save current sector and allocation status to local variables */
1991 sector_num
= s
->sector_num
;
1993 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1994 n
= MIN(n
, s
->buf_sectors
);
1996 /* increment global sector counter so that other coroutines can
1997 * already continue reading beyond this request */
1999 qemu_co_mutex_unlock(&s
->lock
);
2001 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2002 s
->allocated_done
+= n
;
2003 qemu_progress_print(100.0 * s
->allocated_done
/
2004 s
->allocated_sectors
, 0);
2008 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2009 if (status
== BLK_DATA
&& !copy_range
) {
2010 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2012 error_report("error while reading at byte %lld: %s",
2013 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2016 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2018 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2021 if (s
->wr_in_order
) {
2022 /* keep writes in order */
2023 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2024 s
->wait_sector_num
[index
] = sector_num
;
2025 qemu_coroutine_yield();
2027 s
->wait_sector_num
[index
] = -1;
2030 if (s
->ret
== -EINPROGRESS
) {
2032 ret
= convert_co_copy_range(s
, sector_num
, n
);
2034 s
->copy_range
= false;
2038 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2041 error_report("error while writing at byte %lld: %s",
2042 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2047 if (s
->wr_in_order
) {
2048 /* reenter the coroutine that might have waited
2049 * for this write to complete */
2050 s
->wr_offs
= sector_num
+ n
;
2051 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2052 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2054 * A -> B -> A cannot occur because A has
2055 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2056 * B will never enter A during this time window.
2058 qemu_coroutine_enter(s
->co
[i
]);
2066 s
->co
[index
] = NULL
;
2067 s
->running_coroutines
--;
2068 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2069 /* the convert job finished successfully */
2074 static int convert_do_copy(ImgConvertState
*s
)
2077 int64_t sector_num
= 0;
2079 /* Check whether we have zero initialisation or can get it efficiently */
2080 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2081 !s
->target_has_backing
) {
2082 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2085 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
2086 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
2088 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
2090 s
->has_zero_init
= true;
2094 /* Allocate buffer for copied data. For compressed images, only one cluster
2095 * can be copied at a time. */
2096 if (s
->compressed
) {
2097 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2098 error_report("invalid cluster size");
2101 s
->buf_sectors
= s
->cluster_sectors
;
2104 while (sector_num
< s
->total_sectors
) {
2105 n
= convert_iteration_sectors(s
, sector_num
);
2109 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2111 s
->allocated_sectors
+= n
;
2117 s
->sector_next_status
= 0;
2118 s
->ret
= -EINPROGRESS
;
2120 qemu_co_mutex_init(&s
->lock
);
2121 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2122 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2123 s
->wait_sector_num
[i
] = -1;
2124 qemu_coroutine_enter(s
->co
[i
]);
2127 while (s
->running_coroutines
) {
2128 main_loop_wait(false);
2131 if (s
->compressed
&& !s
->ret
) {
2132 /* signal EOF to align */
2133 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2142 #define MAX_BUF_SECTORS 32768
2144 static int img_convert(int argc
, char **argv
)
2146 int c
, bs_i
, flags
, src_flags
= 0;
2147 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2148 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2149 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2150 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2151 BlockDriverInfo bdi
;
2152 BlockDriverState
*out_bs
;
2153 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2154 QemuOptsList
*create_opts
= NULL
;
2155 QDict
*open_opts
= NULL
;
2156 char *options
= NULL
;
2157 Error
*local_err
= NULL
;
2158 bool writethrough
, src_writethrough
, image_opts
= false,
2159 skip_create
= false, progress
= false, tgt_image_opts
= false;
2160 int64_t ret
= -EINVAL
;
2161 bool force_share
= false;
2162 bool explict_min_sparse
= false;
2164 ImgConvertState s
= (ImgConvertState
) {
2165 /* Need at least 4k of zeros for sparse detection */
2167 .copy_range
= false,
2168 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2169 .wr_in_order
= true,
2170 .num_coroutines
= 8,
2174 static const struct option long_options
[] = {
2175 {"help", no_argument
, 0, 'h'},
2176 {"object", required_argument
, 0, OPTION_OBJECT
},
2177 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2178 {"force-share", no_argument
, 0, 'U'},
2179 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2180 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2181 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2184 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2185 long_options
, NULL
);
2191 missing_argument(argv
[optind
- 1]);
2194 unrecognized_option(argv
[optind
- 1]);
2206 out_baseimg
= optarg
;
2209 s
.copy_range
= true;
2212 s
.compressed
= true;
2215 if (accumulate_options(&options
, optarg
) < 0) {
2220 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2221 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2224 error_report("Failed in parsing snapshot param '%s'",
2229 snapshot_name
= optarg
;
2236 sval
= cvtnum("buffer size for sparse output", optarg
);
2239 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2240 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2241 error_report("Invalid buffer size for sparse output specified. "
2242 "Valid sizes are multiples of %llu up to %llu. Select "
2243 "0 to disable sparse detection (fully allocates output).",
2244 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2248 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2249 explict_min_sparse
= true;
2268 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2269 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2270 error_report("Invalid number of coroutines. Allowed number of"
2271 " coroutines is between 1 and %d", MAX_COROUTINES
);
2276 s
.wr_in_order
= false;
2281 case OPTION_OBJECT
: {
2282 QemuOpts
*object_opts
;
2283 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2290 case OPTION_IMAGE_OPTS
:
2293 case OPTION_SALVAGE
:
2296 case OPTION_TARGET_IMAGE_OPTS
:
2297 tgt_image_opts
= true;
2299 case OPTION_TARGET_IS_ZERO
:
2301 * The user asserting that the target is blank has the
2302 * same effect as the target driver supporting zero
2305 s
.has_zero_init
= true;
2310 if (!out_fmt
&& !tgt_image_opts
) {
2314 if (qemu_opts_foreach(&qemu_object_opts
,
2315 user_creatable_add_opts_foreach
,
2316 qemu_img_object_print_help
, &error_fatal
)) {
2320 if (s
.compressed
&& s
.copy_range
) {
2321 error_report("Cannot enable copy offloading when -c is used");
2325 if (explict_min_sparse
&& s
.copy_range
) {
2326 error_report("Cannot enable copy offloading when -S is used");
2330 if (s
.copy_range
&& s
.salvage
) {
2331 error_report("Cannot use copy offloading in salvaging mode");
2335 if (tgt_image_opts
&& !skip_create
) {
2336 error_report("--target-image-opts requires use of -n flag");
2340 if (skip_create
&& options
) {
2341 warn_report("-o has no effect when skipping image creation");
2342 warn_report("This will become an error in future QEMU versions.");
2345 if (s
.has_zero_init
&& !skip_create
) {
2346 error_report("--target-is-zero requires use of -n flag");
2350 s
.src_num
= argc
- optind
- 1;
2351 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2353 if (options
&& has_help_option(options
)) {
2355 ret
= print_block_option_help(out_filename
, out_fmt
);
2358 error_report("Option help requires a format be specified");
2363 if (s
.src_num
< 1) {
2364 error_report("Must specify image file name");
2369 /* ret is still -EINVAL until here */
2370 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2372 error_report("Invalid source cache option: %s", src_cache
);
2376 /* Initialize before goto out */
2380 qemu_progress_init(progress
, 1.0);
2381 qemu_progress_print(0, 100);
2383 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2384 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2386 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2387 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2388 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2394 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2395 if (s
.src_sectors
[bs_i
] < 0) {
2396 error_report("Could not get size of %s: %s",
2397 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2401 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2405 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2406 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2407 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2409 } else if (snapshot_name
!= NULL
) {
2410 if (s
.src_num
> 1) {
2411 error_report("No support for concatenating multiple snapshot");
2416 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2420 error_reportf_err(local_err
, "Failed to load snapshot: ");
2426 /* Find driver and parse its options */
2427 drv
= bdrv_find_format(out_fmt
);
2429 error_report("Unknown file format '%s'", out_fmt
);
2434 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2436 error_report_err(local_err
);
2441 if (!drv
->create_opts
) {
2442 error_report("Format driver '%s' does not support image creation",
2448 if (!proto_drv
->create_opts
) {
2449 error_report("Protocol driver '%s' does not support image creation",
2450 proto_drv
->format_name
);
2455 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2456 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2458 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2460 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2462 error_report_err(local_err
);
2468 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2470 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2476 /* Get backing file name if -o backing_file was used */
2477 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2478 if (out_baseimg_param
) {
2479 out_baseimg
= out_baseimg_param
;
2481 s
.target_has_backing
= (bool) out_baseimg
;
2483 if (s
.has_zero_init
&& s
.target_has_backing
) {
2484 error_report("Cannot use --target-is-zero when the destination "
2485 "image has a backing file");
2489 if (s
.src_num
> 1 && out_baseimg
) {
2490 error_report("Having a backing file for the target makes no sense when "
2491 "concatenating multiple input images");
2496 /* Check if compression is supported */
2499 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2500 const char *encryptfmt
=
2501 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2502 const char *preallocation
=
2503 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2505 if (drv
&& !block_driver_can_compress(drv
)) {
2506 error_report("Compression not supported for this file format");
2511 if (encryption
|| encryptfmt
) {
2512 error_report("Compression and encryption not supported at "
2519 && strcmp(preallocation
, "off"))
2521 error_report("Compression and preallocation not supported at "
2529 * The later open call will need any decryption secrets, and
2530 * bdrv_create() will purge "opts", so extract them now before
2534 open_opts
= qdict_new();
2535 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2539 /* Create the new image */
2540 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2542 error_reportf_err(local_err
, "%s: error while converting %s: ",
2543 out_filename
, out_fmt
);
2548 s
.target_is_new
= !skip_create
;
2550 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2551 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2553 error_report("Invalid cache option: %s", cache
);
2558 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2559 flags
, writethrough
, s
.quiet
, false);
2561 /* TODO ultimately we should allow --target-image-opts
2562 * to be used even when -n is not given.
2563 * That has to wait for bdrv_create to be improved
2564 * to allow filenames in option syntax
2566 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2567 flags
, writethrough
, s
.quiet
, false);
2568 open_opts
= NULL
; /* blk_new_open will have freed it */
2574 out_bs
= blk_bs(s
.target
);
2576 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2577 error_report("Compression not supported for this file format");
2582 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2583 * or discard_alignment of the out_bs is greater. Limit to
2584 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2585 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2587 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2588 out_bs
->bl
.pdiscard_alignment
>>
2589 BDRV_SECTOR_BITS
)));
2591 /* try to align the write requests to the destination to avoid unnecessary
2593 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2594 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2596 assert(is_power_of_2(s
.alignment
));
2599 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2600 if (output_sectors
< 0) {
2601 error_report("unable to get output image length: %s",
2602 strerror(-output_sectors
));
2605 } else if (output_sectors
< s
.total_sectors
) {
2606 error_report("output file is smaller than input file");
2612 if (s
.target_has_backing
&& s
.target_is_new
) {
2613 /* Errors are treated as "backing length unknown" (which means
2614 * s.target_backing_sectors has to be negative, which it will
2615 * be automatically). The backing file length is used only
2616 * for optimizations, so such a case is not fatal. */
2617 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2619 s
.target_backing_sectors
= -1;
2622 ret
= bdrv_get_info(out_bs
, &bdi
);
2625 error_report("could not get block driver info");
2629 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2630 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2631 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2634 ret
= convert_do_copy(&s
);
2637 qemu_progress_print(100, 0);
2639 qemu_progress_end();
2640 qemu_opts_del(opts
);
2641 qemu_opts_free(create_opts
);
2642 qemu_opts_del(sn_opts
);
2643 qobject_unref(open_opts
);
2644 blk_unref(s
.target
);
2646 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2647 blk_unref(s
.src
[bs_i
]);
2651 g_free(s
.src_sectors
);
2659 static void dump_snapshots(BlockDriverState
*bs
)
2661 QEMUSnapshotInfo
*sn_tab
, *sn
;
2664 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2667 printf("Snapshot list:\n");
2668 bdrv_snapshot_dump(NULL
);
2670 for(i
= 0; i
< nb_sns
; i
++) {
2672 bdrv_snapshot_dump(sn
);
2678 static void dump_json_image_info_list(ImageInfoList
*list
)
2682 Visitor
*v
= qobject_output_visitor_new(&obj
);
2684 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2685 visit_complete(v
, &obj
);
2686 str
= qobject_to_json_pretty(obj
);
2687 assert(str
!= NULL
);
2688 printf("%s\n", qstring_get_str(str
));
2694 static void dump_json_image_info(ImageInfo
*info
)
2698 Visitor
*v
= qobject_output_visitor_new(&obj
);
2700 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2701 visit_complete(v
, &obj
);
2702 str
= qobject_to_json_pretty(obj
);
2703 assert(str
!= NULL
);
2704 printf("%s\n", qstring_get_str(str
));
2710 static void dump_human_image_info_list(ImageInfoList
*list
)
2712 ImageInfoList
*elem
;
2715 for (elem
= list
; elem
; elem
= elem
->next
) {
2721 bdrv_image_info_dump(elem
->value
);
2725 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2727 return strcmp(a
, b
) == 0;
2731 * Open an image file chain and return an ImageInfoList
2733 * @filename: topmost image filename
2734 * @fmt: topmost image format (may be NULL to autodetect)
2735 * @chain: true - enumerate entire backing file chain
2736 * false - only topmost image file
2738 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2739 * image file. If there was an error a message will have been printed to
2742 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2743 const char *filename
,
2745 bool chain
, bool force_share
)
2747 ImageInfoList
*head
= NULL
;
2748 ImageInfoList
**last
= &head
;
2749 GHashTable
*filenames
;
2752 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2756 BlockDriverState
*bs
;
2758 ImageInfoList
*elem
;
2760 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2761 error_report("Backing file '%s' creates an infinite loop.",
2765 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2767 blk
= img_open(image_opts
, filename
, fmt
,
2768 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2775 bdrv_query_image_info(bs
, &info
, &err
);
2777 error_report_err(err
);
2782 elem
= g_new0(ImageInfoList
, 1);
2789 /* Clear parameters that only apply to the topmost image */
2790 filename
= fmt
= NULL
;
2794 if (info
->has_full_backing_filename
) {
2795 filename
= info
->full_backing_filename
;
2796 } else if (info
->has_backing_filename
) {
2797 error_report("Could not determine absolute backing filename,"
2798 " but backing filename '%s' present",
2799 info
->backing_filename
);
2802 if (info
->has_backing_filename_format
) {
2803 fmt
= info
->backing_filename_format
;
2807 g_hash_table_destroy(filenames
);
2811 qapi_free_ImageInfoList(head
);
2812 g_hash_table_destroy(filenames
);
2816 static int img_info(int argc
, char **argv
)
2819 OutputFormat output_format
= OFORMAT_HUMAN
;
2821 const char *filename
, *fmt
, *output
;
2822 ImageInfoList
*list
;
2823 bool image_opts
= false;
2824 bool force_share
= false;
2829 int option_index
= 0;
2830 static const struct option long_options
[] = {
2831 {"help", no_argument
, 0, 'h'},
2832 {"format", required_argument
, 0, 'f'},
2833 {"output", required_argument
, 0, OPTION_OUTPUT
},
2834 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2835 {"object", required_argument
, 0, OPTION_OBJECT
},
2836 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2837 {"force-share", no_argument
, 0, 'U'},
2840 c
= getopt_long(argc
, argv
, ":f:hU",
2841 long_options
, &option_index
);
2847 missing_argument(argv
[optind
- 1]);
2850 unrecognized_option(argv
[optind
- 1]);
2864 case OPTION_BACKING_CHAIN
:
2867 case OPTION_OBJECT
: {
2869 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2875 case OPTION_IMAGE_OPTS
:
2880 if (optind
!= argc
- 1) {
2881 error_exit("Expecting one image file name");
2883 filename
= argv
[optind
++];
2885 if (output
&& !strcmp(output
, "json")) {
2886 output_format
= OFORMAT_JSON
;
2887 } else if (output
&& !strcmp(output
, "human")) {
2888 output_format
= OFORMAT_HUMAN
;
2889 } else if (output
) {
2890 error_report("--output must be used with human or json as argument.");
2894 if (qemu_opts_foreach(&qemu_object_opts
,
2895 user_creatable_add_opts_foreach
,
2896 qemu_img_object_print_help
, &error_fatal
)) {
2900 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2906 switch (output_format
) {
2908 dump_human_image_info_list(list
);
2912 dump_json_image_info_list(list
);
2914 dump_json_image_info(list
->value
);
2919 qapi_free_ImageInfoList(list
);
2923 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2926 switch (output_format
) {
2928 if (e
->data
&& !e
->has_offset
) {
2929 error_report("File contains external, encrypted or compressed clusters.");
2932 if (e
->data
&& !e
->zero
) {
2933 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2934 e
->start
, e
->length
,
2935 e
->has_offset
? e
->offset
: 0,
2936 e
->has_filename
? e
->filename
: "");
2938 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2939 * Modify the flags here to allow more coalescing.
2941 if (next
&& (!next
->data
|| next
->zero
)) {
2947 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2948 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2949 e
->start
, e
->length
, e
->depth
,
2950 e
->zero
? "true" : "false",
2951 e
->data
? "true" : "false");
2952 if (e
->has_offset
) {
2953 printf(", \"offset\": %"PRId64
"", e
->offset
);
2965 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2966 int64_t bytes
, MapEntry
*e
)
2970 BlockDriverState
*file
;
2973 char *filename
= NULL
;
2975 /* As an optimization, we could cache the current range of unallocated
2976 * clusters in each file of the chain, and avoid querying the same
2982 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2987 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2990 bs
= backing_bs(bs
);
2999 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3001 if (file
&& has_offset
) {
3002 bdrv_refresh_filename(file
);
3003 filename
= file
->filename
;
3009 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3010 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3012 .has_offset
= has_offset
,
3014 .has_filename
= filename
,
3015 .filename
= filename
,
3021 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3023 if (curr
->length
== 0) {
3026 if (curr
->zero
!= next
->zero
||
3027 curr
->data
!= next
->data
||
3028 curr
->depth
!= next
->depth
||
3029 curr
->has_filename
!= next
->has_filename
||
3030 curr
->has_offset
!= next
->has_offset
) {
3033 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3036 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3042 static int img_map(int argc
, char **argv
)
3045 OutputFormat output_format
= OFORMAT_HUMAN
;
3047 BlockDriverState
*bs
;
3048 const char *filename
, *fmt
, *output
;
3050 MapEntry curr
= { .length
= 0 }, next
;
3052 bool image_opts
= false;
3053 bool force_share
= false;
3054 int64_t start_offset
= 0;
3055 int64_t max_length
= -1;
3060 int option_index
= 0;
3061 static const struct option long_options
[] = {
3062 {"help", no_argument
, 0, 'h'},
3063 {"format", required_argument
, 0, 'f'},
3064 {"output", required_argument
, 0, OPTION_OUTPUT
},
3065 {"object", required_argument
, 0, OPTION_OBJECT
},
3066 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3067 {"force-share", no_argument
, 0, 'U'},
3068 {"start-offset", required_argument
, 0, 's'},
3069 {"max-length", required_argument
, 0, 'l'},
3072 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3073 long_options
, &option_index
);
3079 missing_argument(argv
[optind
- 1]);
3082 unrecognized_option(argv
[optind
- 1]);
3097 start_offset
= cvtnum("start offset", optarg
);
3098 if (start_offset
< 0) {
3103 max_length
= cvtnum("max length", optarg
);
3104 if (max_length
< 0) {
3108 case OPTION_OBJECT
: {
3110 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3116 case OPTION_IMAGE_OPTS
:
3121 if (optind
!= argc
- 1) {
3122 error_exit("Expecting one image file name");
3124 filename
= argv
[optind
];
3126 if (output
&& !strcmp(output
, "json")) {
3127 output_format
= OFORMAT_JSON
;
3128 } else if (output
&& !strcmp(output
, "human")) {
3129 output_format
= OFORMAT_HUMAN
;
3130 } else if (output
) {
3131 error_report("--output must be used with human or json as argument.");
3135 if (qemu_opts_foreach(&qemu_object_opts
,
3136 user_creatable_add_opts_foreach
,
3137 qemu_img_object_print_help
, &error_fatal
)) {
3141 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3147 if (output_format
== OFORMAT_HUMAN
) {
3148 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3149 } else if (output_format
== OFORMAT_JSON
) {
3153 length
= blk_getlength(blk
);
3155 error_report("Failed to get size for '%s'", filename
);
3158 if (max_length
!= -1) {
3159 length
= MIN(start_offset
+ max_length
, length
);
3162 curr
.start
= start_offset
;
3163 while (curr
.start
+ curr
.length
< length
) {
3164 int64_t offset
= curr
.start
+ curr
.length
;
3167 /* Probe up to 1 GiB at a time. */
3168 n
= MIN(1 * GiB
, length
- offset
);
3169 ret
= get_block_status(bs
, offset
, n
, &next
);
3172 error_report("Could not read file metadata: %s", strerror(-ret
));
3176 if (entry_mergeable(&curr
, &next
)) {
3177 curr
.length
+= next
.length
;
3181 if (curr
.length
> 0) {
3182 ret
= dump_map_entry(output_format
, &curr
, &next
);
3190 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3191 if (output_format
== OFORMAT_JSON
) {
3200 #define SNAPSHOT_LIST 1
3201 #define SNAPSHOT_CREATE 2
3202 #define SNAPSHOT_APPLY 3
3203 #define SNAPSHOT_DELETE 4
3205 static int img_snapshot(int argc
, char **argv
)
3208 BlockDriverState
*bs
;
3209 QEMUSnapshotInfo sn
;
3210 char *filename
, *snapshot_name
= NULL
;
3211 int c
, ret
= 0, bdrv_oflags
;
3216 bool image_opts
= false;
3217 bool force_share
= false;
3219 bdrv_oflags
= BDRV_O_RDWR
;
3220 /* Parse commandline parameters */
3222 static const struct option long_options
[] = {
3223 {"help", no_argument
, 0, 'h'},
3224 {"object", required_argument
, 0, OPTION_OBJECT
},
3225 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3226 {"force-share", no_argument
, 0, 'U'},
3229 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3230 long_options
, NULL
);
3236 missing_argument(argv
[optind
- 1]);
3239 unrecognized_option(argv
[optind
- 1]);
3246 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3249 action
= SNAPSHOT_LIST
;
3250 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3254 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3257 action
= SNAPSHOT_APPLY
;
3258 snapshot_name
= optarg
;
3262 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3265 action
= SNAPSHOT_CREATE
;
3266 snapshot_name
= optarg
;
3270 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3273 action
= SNAPSHOT_DELETE
;
3274 snapshot_name
= optarg
;
3282 case OPTION_OBJECT
: {
3284 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3290 case OPTION_IMAGE_OPTS
:
3296 if (optind
!= argc
- 1) {
3297 error_exit("Expecting one image file name");
3299 filename
= argv
[optind
++];
3301 if (qemu_opts_foreach(&qemu_object_opts
,
3302 user_creatable_add_opts_foreach
,
3303 qemu_img_object_print_help
, &error_fatal
)) {
3307 /* Open the image */
3308 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3315 /* Perform the requested action */
3321 case SNAPSHOT_CREATE
:
3322 memset(&sn
, 0, sizeof(sn
));
3323 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3325 qemu_gettimeofday(&tv
);
3326 sn
.date_sec
= tv
.tv_sec
;
3327 sn
.date_nsec
= tv
.tv_usec
* 1000;
3329 ret
= bdrv_snapshot_create(bs
, &sn
);
3331 error_report("Could not create snapshot '%s': %d (%s)",
3332 snapshot_name
, ret
, strerror(-ret
));
3336 case SNAPSHOT_APPLY
:
3337 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3339 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3344 case SNAPSHOT_DELETE
:
3345 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3347 error_report("Could not delete snapshot '%s': snapshot not "
3348 "found", snapshot_name
);
3351 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3353 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3369 static int img_rebase(int argc
, char **argv
)
3371 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3372 uint8_t *buf_old
= NULL
;
3373 uint8_t *buf_new
= NULL
;
3374 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3376 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3377 int c
, flags
, src_flags
, ret
;
3378 bool writethrough
, src_writethrough
;
3380 bool force_share
= false;
3383 Error
*local_err
= NULL
;
3384 bool image_opts
= false;
3386 /* Parse commandline parameters */
3388 cache
= BDRV_DEFAULT_CACHE
;
3389 src_cache
= BDRV_DEFAULT_CACHE
;
3393 static const struct option long_options
[] = {
3394 {"help", no_argument
, 0, 'h'},
3395 {"object", required_argument
, 0, OPTION_OBJECT
},
3396 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3397 {"force-share", no_argument
, 0, 'U'},
3400 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3401 long_options
, NULL
);
3407 missing_argument(argv
[optind
- 1]);
3410 unrecognized_option(argv
[optind
- 1]);
3419 out_basefmt
= optarg
;
3422 out_baseimg
= optarg
;
3439 case OPTION_OBJECT
: {
3441 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3447 case OPTION_IMAGE_OPTS
:
3460 if (optind
!= argc
- 1) {
3461 error_exit("Expecting one image file name");
3463 if (!unsafe
&& !out_baseimg
) {
3464 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3466 filename
= argv
[optind
++];
3468 if (qemu_opts_foreach(&qemu_object_opts
,
3469 user_creatable_add_opts_foreach
,
3470 qemu_img_object_print_help
, &error_fatal
)) {
3474 qemu_progress_init(progress
, 2.0);
3475 qemu_progress_print(0, 100);
3477 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3478 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3480 error_report("Invalid cache option: %s", cache
);
3485 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3487 error_report("Invalid source cache option: %s", src_cache
);
3491 /* The source files are opened read-only, don't care about WCE */
3492 assert((src_flags
& BDRV_O_RDWR
) == 0);
3493 (void) src_writethrough
;
3498 * Ignore the old backing file for unsafe rebase in case we want to correct
3499 * the reference to a renamed or moved backing file.
3501 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3509 if (out_basefmt
!= NULL
) {
3510 if (bdrv_find_format(out_basefmt
) == NULL
) {
3511 error_report("Invalid format name: '%s'", out_basefmt
);
3517 /* For safe rebasing we need to compare old and new backing file */
3519 QDict
*options
= NULL
;
3520 BlockDriverState
*base_bs
= backing_bs(bs
);
3523 blk_old_backing
= blk_new(qemu_get_aio_context(),
3524 BLK_PERM_CONSISTENT_READ
,
3526 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3529 error_reportf_err(local_err
,
3530 "Could not reuse old backing file '%s': ",
3535 blk_old_backing
= NULL
;
3538 if (out_baseimg
[0]) {
3539 const char *overlay_filename
;
3540 char *out_real_path
;
3542 options
= qdict_new();
3544 qdict_put_str(options
, "driver", out_basefmt
);
3547 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3550 bdrv_refresh_filename(bs
);
3551 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3554 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3558 qobject_unref(options
);
3559 error_reportf_err(local_err
,
3560 "Could not resolve backing filename: ");
3566 * Find out whether we rebase an image on top of a previous image
3569 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3570 if (prefix_chain_bs
) {
3571 qobject_unref(options
);
3572 g_free(out_real_path
);
3574 blk_new_backing
= blk_new(qemu_get_aio_context(),
3575 BLK_PERM_CONSISTENT_READ
,
3577 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3580 error_reportf_err(local_err
,
3581 "Could not reuse backing file '%s': ",
3586 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3587 options
, src_flags
, &local_err
);
3588 g_free(out_real_path
);
3589 if (!blk_new_backing
) {
3590 error_reportf_err(local_err
,
3591 "Could not open new backing file '%s': ",
3601 * Check each unallocated cluster in the COW file. If it is unallocated,
3602 * accesses go to the backing file. We must therefore compare this cluster
3603 * in the old and new backing file, and if they differ we need to copy it
3604 * from the old backing file into the COW file.
3606 * If qemu-img crashes during this step, no harm is done. The content of
3607 * the image is the same as the original one at any time.
3611 int64_t old_backing_size
= 0;
3612 int64_t new_backing_size
= 0;
3615 float local_progress
= 0;
3617 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3618 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3620 size
= blk_getlength(blk
);
3622 error_report("Could not get size of '%s': %s",
3623 filename
, strerror(-size
));
3627 if (blk_old_backing
) {
3628 old_backing_size
= blk_getlength(blk_old_backing
);
3629 if (old_backing_size
< 0) {
3630 char backing_name
[PATH_MAX
];
3632 bdrv_get_backing_filename(bs
, backing_name
,
3633 sizeof(backing_name
));
3634 error_report("Could not get size of '%s': %s",
3635 backing_name
, strerror(-old_backing_size
));
3640 if (blk_new_backing
) {
3641 new_backing_size
= blk_getlength(blk_new_backing
);
3642 if (new_backing_size
< 0) {
3643 error_report("Could not get size of '%s': %s",
3644 out_baseimg
, strerror(-new_backing_size
));
3651 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3654 for (offset
= 0; offset
< size
; offset
+= n
) {
3655 bool buf_old_is_zero
= false;
3657 /* How many bytes can we handle with the next read? */
3658 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3660 /* If the cluster is allocated, we don't need to take action */
3661 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3663 error_report("error while reading image metadata: %s",
3671 if (prefix_chain_bs
) {
3673 * If cluster wasn't changed since prefix_chain, we don't need
3676 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3677 false, offset
, n
, &n
);
3679 error_report("error while reading image metadata: %s",
3689 * Read old and new backing file and take into consideration that
3690 * backing files may be smaller than the COW image.
3692 if (offset
>= old_backing_size
) {
3693 memset(buf_old
, 0, n
);
3694 buf_old_is_zero
= true;
3696 if (offset
+ n
> old_backing_size
) {
3697 n
= old_backing_size
- offset
;
3700 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3702 error_report("error while reading from old backing file");
3707 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3708 memset(buf_new
, 0, n
);
3710 if (offset
+ n
> new_backing_size
) {
3711 n
= new_backing_size
- offset
;
3714 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3716 error_report("error while reading from new backing file");
3721 /* If they differ, we need to write to the COW file */
3722 uint64_t written
= 0;
3724 while (written
< n
) {
3727 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3728 n
- written
, &pnum
))
3730 if (buf_old_is_zero
) {
3731 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3733 ret
= blk_pwrite(blk
, offset
+ written
,
3734 buf_old
+ written
, pnum
, 0);
3737 error_report("Error while writing to COW image: %s",
3745 qemu_progress_print(local_progress
, 100);
3750 * Change the backing file. All clusters that are different from the old
3751 * backing file are overwritten in the COW file now, so the visible content
3752 * doesn't change when we switch the backing file.
3754 if (out_baseimg
&& *out_baseimg
) {
3755 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3757 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3760 if (ret
== -ENOSPC
) {
3761 error_report("Could not change the backing file to '%s': No "
3762 "space left in the file header", out_baseimg
);
3763 } else if (ret
< 0) {
3764 error_report("Could not change the backing file to '%s': %s",
3765 out_baseimg
, strerror(-ret
));
3768 qemu_progress_print(100, 0);
3770 * TODO At this point it is possible to check if any clusters that are
3771 * allocated in the COW file are the same in the backing file. If so, they
3772 * could be dropped from the COW file. Don't do this before switching the
3773 * backing file, in case of a crash this would lead to corruption.
3776 qemu_progress_end();
3779 blk_unref(blk_old_backing
);
3780 blk_unref(blk_new_backing
);
3782 qemu_vfree(buf_old
);
3783 qemu_vfree(buf_new
);
3792 static int img_resize(int argc
, char **argv
)
3795 int c
, ret
, relative
;
3796 const char *filename
, *fmt
, *size
;
3797 int64_t n
, total_size
, current_size
;
3799 BlockBackend
*blk
= NULL
;
3800 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3803 static QemuOptsList resize_options
= {
3804 .name
= "resize_options",
3805 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3808 .name
= BLOCK_OPT_SIZE
,
3809 .type
= QEMU_OPT_SIZE
,
3810 .help
= "Virtual disk size"
3816 bool image_opts
= false;
3817 bool shrink
= false;
3819 /* Remove size from argv manually so that negative numbers are not treated
3820 * as options by getopt. */
3822 error_exit("Not enough arguments");
3826 size
= argv
[--argc
];
3828 /* Parse getopt arguments */
3831 static const struct option long_options
[] = {
3832 {"help", no_argument
, 0, 'h'},
3833 {"object", required_argument
, 0, OPTION_OBJECT
},
3834 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3835 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3836 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3839 c
= getopt_long(argc
, argv
, ":f:hq",
3840 long_options
, NULL
);
3846 missing_argument(argv
[optind
- 1]);
3849 unrecognized_option(argv
[optind
- 1]);
3860 case OPTION_OBJECT
: {
3862 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3868 case OPTION_IMAGE_OPTS
:
3871 case OPTION_PREALLOCATION
:
3872 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3873 PREALLOC_MODE__MAX
, NULL
);
3874 if (prealloc
== PREALLOC_MODE__MAX
) {
3875 error_report("Invalid preallocation mode '%s'", optarg
);
3884 if (optind
!= argc
- 1) {
3885 error_exit("Expecting image file name and size");
3887 filename
= argv
[optind
++];
3889 if (qemu_opts_foreach(&qemu_object_opts
,
3890 user_creatable_add_opts_foreach
,
3891 qemu_img_object_print_help
, &error_fatal
)) {
3895 /* Choose grow, shrink, or absolute resize mode */
3911 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3912 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3914 error_report_err(err
);
3916 qemu_opts_del(param
);
3919 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3920 qemu_opts_del(param
);
3922 blk
= img_open(image_opts
, filename
, fmt
,
3923 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3930 current_size
= blk_getlength(blk
);
3931 if (current_size
< 0) {
3932 error_report("Failed to inquire current image length: %s",
3933 strerror(-current_size
));
3939 total_size
= current_size
+ n
* relative
;
3943 if (total_size
<= 0) {
3944 error_report("New image size must be positive");
3949 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3950 error_report("Preallocation can only be used for growing images");
3955 if (total_size
< current_size
&& !shrink
) {
3956 warn_report("Shrinking an image will delete all data beyond the "
3957 "shrunken image's end. Before performing such an "
3958 "operation, make sure there is no important data there.");
3960 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3962 "Use the --shrink option to perform a shrink operation.");
3966 warn_report("Using the --shrink option will suppress this message. "
3967 "Note that future versions of qemu-img may refuse to "
3968 "shrink images without this option.");
3973 * The user expects the image to have the desired size after
3974 * resizing, so pass @exact=true. It is of no use to report
3975 * success when the image has not actually been resized.
3977 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
3979 qprintf(quiet
, "Image resized.\n");
3981 error_report_err(err
);
3991 static void amend_status_cb(BlockDriverState
*bs
,
3992 int64_t offset
, int64_t total_work_size
,
3995 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3998 static int print_amend_option_help(const char *format
)
4002 /* Find driver and parse its options */
4003 drv
= bdrv_find_format(format
);
4005 error_report("Unknown file format '%s'", format
);
4009 if (!drv
->bdrv_amend_options
) {
4010 error_report("Format driver '%s' does not support option amendment",
4015 /* Every driver supporting amendment must have create_opts */
4016 assert(drv
->create_opts
);
4018 printf("Creation options for '%s':\n", format
);
4019 qemu_opts_print_help(drv
->create_opts
, false);
4020 printf("\nNote that not all of these options may be amendable.\n");
4024 static int img_amend(int argc
, char **argv
)
4028 char *options
= NULL
;
4029 QemuOptsList
*create_opts
= NULL
;
4030 QemuOpts
*opts
= NULL
;
4031 const char *fmt
= NULL
, *filename
, *cache
;
4034 bool quiet
= false, progress
= false;
4035 BlockBackend
*blk
= NULL
;
4036 BlockDriverState
*bs
= NULL
;
4037 bool image_opts
= false;
4039 cache
= BDRV_DEFAULT_CACHE
;
4041 static const struct option long_options
[] = {
4042 {"help", no_argument
, 0, 'h'},
4043 {"object", required_argument
, 0, OPTION_OBJECT
},
4044 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4047 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4048 long_options
, NULL
);
4055 missing_argument(argv
[optind
- 1]);
4058 unrecognized_option(argv
[optind
- 1]);
4064 if (accumulate_options(&options
, optarg
) < 0) {
4066 goto out_no_progress
;
4082 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4086 goto out_no_progress
;
4089 case OPTION_IMAGE_OPTS
:
4096 error_exit("Must specify options (-o)");
4099 if (qemu_opts_foreach(&qemu_object_opts
,
4100 user_creatable_add_opts_foreach
,
4101 qemu_img_object_print_help
, &error_fatal
)) {
4103 goto out_no_progress
;
4109 qemu_progress_init(progress
, 1.0);
4111 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4112 if (fmt
&& has_help_option(options
)) {
4113 /* If a format is explicitly specified (and possibly no filename is
4114 * given), print option help here */
4115 ret
= print_amend_option_help(fmt
);
4119 if (optind
!= argc
- 1) {
4120 error_report("Expecting one image file name");
4125 flags
= BDRV_O_RDWR
;
4126 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4128 error_report("Invalid cache option: %s", cache
);
4132 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4140 fmt
= bs
->drv
->format_name
;
4142 if (has_help_option(options
)) {
4143 /* If the format was auto-detected, print option help here */
4144 ret
= print_amend_option_help(fmt
);
4148 if (!bs
->drv
->bdrv_amend_options
) {
4149 error_report("Format driver '%s' does not support option amendment",
4155 /* Every driver supporting amendment must have create_opts */
4156 assert(bs
->drv
->create_opts
);
4158 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4159 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4160 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4162 error_report_err(err
);
4167 /* In case the driver does not call amend_status_cb() */
4168 qemu_progress_print(0.f
, 0);
4169 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4170 qemu_progress_print(100.f
, 0);
4172 error_report_err(err
);
4177 qemu_progress_end();
4181 qemu_opts_del(opts
);
4182 qemu_opts_free(create_opts
);
4191 typedef struct BenchData
{
4193 uint64_t image_size
;
4200 bool drain_on_flush
;
4209 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4212 error_report("Failed flush request: %s", strerror(-ret
));
4217 static void bench_cb(void *opaque
, int ret
)
4219 BenchData
*b
= opaque
;
4223 error_report("Failed request: %s", strerror(-ret
));
4228 /* Just finished a flush with drained queue: Start next requests */
4229 assert(b
->in_flight
== 0);
4230 b
->in_flush
= false;
4231 } else if (b
->in_flight
> 0) {
4232 int remaining
= b
->n
- b
->in_flight
;
4237 /* Time for flush? Drain queue if requested, then flush */
4238 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4239 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4240 BlockCompletionFunc
*cb
;
4242 if (b
->drain_on_flush
) {
4246 cb
= bench_undrained_flush_cb
;
4249 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4251 error_report("Failed to issue flush request");
4255 if (b
->drain_on_flush
) {
4261 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4262 int64_t offset
= b
->offset
;
4263 /* blk_aio_* might look for completed I/Os and kick bench_cb
4264 * again, so make sure this operation is counted by in_flight
4265 * and b->offset is ready for the next submission.
4268 b
->offset
+= b
->step
;
4269 b
->offset
%= b
->image_size
;
4271 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4273 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4276 error_report("Failed to issue request");
4282 static int img_bench(int argc
, char **argv
)
4285 const char *fmt
= NULL
, *filename
;
4287 bool image_opts
= false;
4288 bool is_write
= false;
4292 size_t bufsize
= 4096;
4295 int flush_interval
= 0;
4296 bool drain_on_flush
= true;
4298 BlockBackend
*blk
= NULL
;
4299 BenchData data
= {};
4301 bool writethrough
= false;
4302 struct timeval t1
, t2
;
4304 bool force_share
= false;
4308 static const struct option long_options
[] = {
4309 {"help", no_argument
, 0, 'h'},
4310 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4311 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4312 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4313 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4314 {"force-share", no_argument
, 0, 'U'},
4317 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4325 missing_argument(argv
[optind
- 1]);
4328 unrecognized_option(argv
[optind
- 1]);
4337 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4338 error_report("Invalid request count specified");
4348 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4349 error_report("Invalid queue depth specified");
4359 flags
|= BDRV_O_NATIVE_AIO
;
4362 ret
= bdrv_parse_aio(optarg
, &flags
);
4364 error_report("Invalid aio option: %s", optarg
);
4371 offset
= cvtnum("offset", optarg
);
4385 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4397 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4406 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4408 error_report("Invalid cache mode");
4414 flags
|= BDRV_O_RDWR
;
4420 case OPTION_PATTERN
:
4424 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4425 error_report("Invalid pattern byte specified");
4431 case OPTION_FLUSH_INTERVAL
:
4435 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4436 error_report("Invalid flush interval specified");
4439 flush_interval
= res
;
4442 case OPTION_NO_DRAIN
:
4443 drain_on_flush
= false;
4445 case OPTION_IMAGE_OPTS
:
4451 if (optind
!= argc
- 1) {
4452 error_exit("Expecting one image file name");
4454 filename
= argv
[argc
- 1];
4456 if (!is_write
&& flush_interval
) {
4457 error_report("--flush-interval is only available in write tests");
4461 if (flush_interval
&& flush_interval
< depth
) {
4462 error_report("Flush interval can't be smaller than depth");
4467 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4474 image_size
= blk_getlength(blk
);
4475 if (image_size
< 0) {
4480 data
= (BenchData
) {
4482 .image_size
= image_size
,
4484 .step
= step
?: bufsize
,
4489 .flush_interval
= flush_interval
,
4490 .drain_on_flush
= drain_on_flush
,
4492 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4493 "(starting at offset %" PRId64
", step size %d)\n",
4494 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4495 data
.offset
, data
.step
);
4496 if (flush_interval
) {
4497 printf("Sending flush every %d requests\n", flush_interval
);
4500 buf_size
= data
.nrreq
* data
.bufsize
;
4501 data
.buf
= blk_blockalign(blk
, buf_size
);
4502 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4504 blk_register_buf(blk
, data
.buf
, buf_size
);
4506 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4507 for (i
= 0; i
< data
.nrreq
; i
++) {
4508 qemu_iovec_init(&data
.qiov
[i
], 1);
4509 qemu_iovec_add(&data
.qiov
[i
],
4510 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4513 gettimeofday(&t1
, NULL
);
4516 while (data
.n
> 0) {
4517 main_loop_wait(false);
4519 gettimeofday(&t2
, NULL
);
4521 printf("Run completed in %3.3f seconds.\n",
4522 (t2
.tv_sec
- t1
.tv_sec
)
4523 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4527 blk_unregister_buf(blk
, data
.buf
);
4529 qemu_vfree(data
.buf
);
4546 typedef struct ImgBitmapAction
{
4547 enum ImgBitmapAct act
;
4548 const char *src
; /* only used for merge */
4549 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4552 static int img_bitmap(int argc
, char **argv
)
4556 QemuOpts
*opts
= NULL
;
4557 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4558 const char *filename
, *bitmap
;
4559 BlockBackend
*blk
= NULL
, *src
= NULL
;
4560 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4561 bool image_opts
= false;
4562 int64_t granularity
= 0;
4563 bool add
= false, merge
= false;
4564 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4565 ImgBitmapAction
*act
, *act_next
;
4568 QSIMPLEQ_INIT(&actions
);
4571 static const struct option long_options
[] = {
4572 {"help", no_argument
, 0, 'h'},
4573 {"object", required_argument
, 0, OPTION_OBJECT
},
4574 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4575 {"add", no_argument
, 0, OPTION_ADD
},
4576 {"remove", no_argument
, 0, OPTION_REMOVE
},
4577 {"clear", no_argument
, 0, OPTION_CLEAR
},
4578 {"enable", no_argument
, 0, OPTION_ENABLE
},
4579 {"disable", no_argument
, 0, OPTION_DISABLE
},
4580 {"merge", required_argument
, 0, OPTION_MERGE
},
4581 {"granularity", required_argument
, 0, 'g'},
4582 {"source-file", required_argument
, 0, 'b'},
4583 {"source-format", required_argument
, 0, 'F'},
4586 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4593 missing_argument(argv
[optind
- 1]);
4596 unrecognized_option(argv
[optind
- 1]);
4602 src_filename
= optarg
;
4611 granularity
= cvtnum("granularity", optarg
);
4612 if (granularity
< 0) {
4617 act
= g_new0(ImgBitmapAction
, 1);
4618 act
->act
= BITMAP_ADD
;
4619 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4623 act
= g_new0(ImgBitmapAction
, 1);
4624 act
->act
= BITMAP_REMOVE
;
4625 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4628 act
= g_new0(ImgBitmapAction
, 1);
4629 act
->act
= BITMAP_CLEAR
;
4630 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4633 act
= g_new0(ImgBitmapAction
, 1);
4634 act
->act
= BITMAP_ENABLE
;
4635 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4637 case OPTION_DISABLE
:
4638 act
= g_new0(ImgBitmapAction
, 1);
4639 act
->act
= BITMAP_DISABLE
;
4640 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4643 act
= g_new0(ImgBitmapAction
, 1);
4644 act
->act
= BITMAP_MERGE
;
4646 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4650 opts
= qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true);
4655 case OPTION_IMAGE_OPTS
:
4661 if (qemu_opts_foreach(&qemu_object_opts
,
4662 user_creatable_add_opts_foreach
,
4663 qemu_img_object_print_help
, &error_fatal
)) {
4667 if (QSIMPLEQ_EMPTY(&actions
)) {
4668 error_report("Need at least one of --add, --remove, --clear, "
4669 "--enable, --disable, or --merge");
4673 if (granularity
&& !add
) {
4674 error_report("granularity only supported with --add");
4677 if (src_fmt
&& !src_filename
) {
4678 error_report("-F only supported with -b");
4681 if (src_filename
&& !merge
) {
4682 error_report("Merge bitmap source file only supported with "
4687 if (optind
!= argc
- 2) {
4688 error_report("Expecting filename and bitmap name");
4692 filename
= argv
[optind
];
4693 bitmap
= argv
[optind
+ 1];
4695 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
, false, false,
4702 src
= img_open(false, src_filename
, src_fmt
, 0, false, false, false);
4706 src_bs
= blk_bs(src
);
4711 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4714 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4715 !!granularity
, granularity
, true, true,
4716 false, false, &err
);
4720 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4724 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4728 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4731 case BITMAP_DISABLE
:
4732 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4736 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4741 g_assert_not_reached();
4745 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4757 qemu_opts_del(opts
);
4773 int bsz
; /* Block size */
4781 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4785 static int img_dd_bs(const char *arg
,
4786 struct DdIo
*in
, struct DdIo
*out
,
4791 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4796 in
->bsz
= out
->bsz
= res
;
4801 static int img_dd_count(const char *arg
,
4802 struct DdIo
*in
, struct DdIo
*out
,
4805 dd
->count
= cvtnum("count", arg
);
4807 if (dd
->count
< 0) {
4814 static int img_dd_if(const char *arg
,
4815 struct DdIo
*in
, struct DdIo
*out
,
4818 in
->filename
= g_strdup(arg
);
4823 static int img_dd_of(const char *arg
,
4824 struct DdIo
*in
, struct DdIo
*out
,
4827 out
->filename
= g_strdup(arg
);
4832 static int img_dd_skip(const char *arg
,
4833 struct DdIo
*in
, struct DdIo
*out
,
4836 in
->offset
= cvtnum("skip", arg
);
4838 if (in
->offset
< 0) {
4845 static int img_dd(int argc
, char **argv
)
4850 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4851 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4852 QemuOpts
*opts
= NULL
;
4853 QemuOptsList
*create_opts
= NULL
;
4854 Error
*local_err
= NULL
;
4855 bool image_opts
= false;
4857 const char *out_fmt
= "raw";
4858 const char *fmt
= NULL
;
4860 int64_t block_count
= 0, out_pos
, in_pos
;
4861 bool force_share
= false;
4862 struct DdInfo dd
= {
4867 .bsz
= 512, /* Block size is by default 512 bytes */
4879 const struct DdOpts options
[] = {
4880 { "bs", img_dd_bs
, C_BS
},
4881 { "count", img_dd_count
, C_COUNT
},
4882 { "if", img_dd_if
, C_IF
},
4883 { "of", img_dd_of
, C_OF
},
4884 { "skip", img_dd_skip
, C_SKIP
},
4887 const struct option long_options
[] = {
4888 { "help", no_argument
, 0, 'h'},
4889 { "object", required_argument
, 0, OPTION_OBJECT
},
4890 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4891 { "force-share", no_argument
, 0, 'U'},
4895 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4907 missing_argument(argv
[optind
- 1]);
4910 unrecognized_option(argv
[optind
- 1]);
4919 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4924 case OPTION_IMAGE_OPTS
:
4930 for (i
= optind
; i
< argc
; i
++) {
4932 arg
= g_strdup(argv
[i
]);
4934 tmp
= strchr(arg
, '=');
4936 error_report("unrecognized operand %s", arg
);
4943 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4944 if (!strcmp(arg
, options
[j
].name
)) {
4948 if (options
[j
].name
== NULL
) {
4949 error_report("unrecognized operand %s", arg
);
4954 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4958 dd
.flags
|= options
[j
].flag
;
4963 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4964 error_report("Must specify both input and output files");
4969 if (qemu_opts_foreach(&qemu_object_opts
,
4970 user_creatable_add_opts_foreach
,
4971 qemu_img_object_print_help
, &error_fatal
)) {
4976 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4984 drv
= bdrv_find_format(out_fmt
);
4986 error_report("Unknown file format");
4990 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4993 error_report_err(local_err
);
4997 if (!drv
->create_opts
) {
4998 error_report("Format driver '%s' does not support image creation",
5003 if (!proto_drv
->create_opts
) {
5004 error_report("Protocol driver '%s' does not support image creation",
5005 proto_drv
->format_name
);
5009 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5010 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5012 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5014 size
= blk_getlength(blk1
);
5016 error_report("Failed to get size for '%s'", in
.filename
);
5021 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5022 dd
.count
* in
.bsz
< size
) {
5023 size
= dd
.count
* in
.bsz
;
5026 /* Overflow means the specified offset is beyond input image's size */
5027 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5028 size
< in
.bsz
* in
.offset
)) {
5029 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5031 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5032 size
- in
.bsz
* in
.offset
, &error_abort
);
5035 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5037 error_reportf_err(local_err
,
5038 "%s: error while creating output image: ",
5044 /* TODO, we can't honour --image-opts for the target,
5045 * since it needs to be given in a format compatible
5046 * with the bdrv_create() call above which does not
5047 * support image-opts style.
5049 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5050 false, false, false);
5057 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5058 size
< in
.offset
* in
.bsz
)) {
5059 /* We give a warning if the skip option is bigger than the input
5060 * size and create an empty output disk image (i.e. like dd(1)).
5062 error_report("%s: cannot skip to specified offset", in
.filename
);
5065 in_pos
= in
.offset
* in
.bsz
;
5068 in
.buf
= g_new(uint8_t, in
.bsz
);
5070 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5071 int in_ret
, out_ret
;
5073 if (in_pos
+ in
.bsz
> size
) {
5074 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5076 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5079 error_report("error while reading from input image file: %s",
5086 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5089 error_report("error while writing to output image file: %s",
5090 strerror(-out_ret
));
5099 qemu_opts_del(opts
);
5100 qemu_opts_free(create_opts
);
5103 g_free(in
.filename
);
5104 g_free(out
.filename
);
5114 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5118 Visitor
*v
= qobject_output_visitor_new(&obj
);
5120 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5121 visit_complete(v
, &obj
);
5122 str
= qobject_to_json_pretty(obj
);
5123 assert(str
!= NULL
);
5124 printf("%s\n", qstring_get_str(str
));
5130 static int img_measure(int argc
, char **argv
)
5132 static const struct option long_options
[] = {
5133 {"help", no_argument
, 0, 'h'},
5134 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5135 {"object", required_argument
, 0, OPTION_OBJECT
},
5136 {"output", required_argument
, 0, OPTION_OUTPUT
},
5137 {"size", required_argument
, 0, OPTION_SIZE
},
5138 {"force-share", no_argument
, 0, 'U'},
5141 OutputFormat output_format
= OFORMAT_HUMAN
;
5142 BlockBackend
*in_blk
= NULL
;
5144 const char *filename
= NULL
;
5145 const char *fmt
= NULL
;
5146 const char *out_fmt
= "raw";
5147 char *options
= NULL
;
5148 char *snapshot_name
= NULL
;
5149 bool force_share
= false;
5150 QemuOpts
*opts
= NULL
;
5151 QemuOpts
*object_opts
= NULL
;
5152 QemuOpts
*sn_opts
= NULL
;
5153 QemuOptsList
*create_opts
= NULL
;
5154 bool image_opts
= false;
5155 uint64_t img_size
= UINT64_MAX
;
5156 BlockMeasureInfo
*info
= NULL
;
5157 Error
*local_err
= NULL
;
5161 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5162 long_options
, NULL
)) != -1) {
5175 if (accumulate_options(&options
, optarg
) < 0) {
5180 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5181 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5184 error_report("Failed in parsing snapshot param '%s'",
5189 snapshot_name
= optarg
;
5196 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
5202 case OPTION_IMAGE_OPTS
:
5206 if (!strcmp(optarg
, "json")) {
5207 output_format
= OFORMAT_JSON
;
5208 } else if (!strcmp(optarg
, "human")) {
5209 output_format
= OFORMAT_HUMAN
;
5211 error_report("--output must be used with human or json "
5220 sval
= cvtnum("image size", optarg
);
5224 img_size
= (uint64_t)sval
;
5230 if (qemu_opts_foreach(&qemu_object_opts
,
5231 user_creatable_add_opts_foreach
,
5232 qemu_img_object_print_help
, &error_fatal
)) {
5236 if (argc
- optind
> 1) {
5237 error_report("At most one filename argument is allowed.");
5239 } else if (argc
- optind
== 1) {
5240 filename
= argv
[optind
];
5243 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5244 error_report("--image-opts, -f, and -l require a filename argument.");
5247 if (filename
&& img_size
!= UINT64_MAX
) {
5248 error_report("--size N cannot be used together with a filename.");
5251 if (!filename
&& img_size
== UINT64_MAX
) {
5252 error_report("Either --size N or one filename must be specified.");
5257 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5258 false, false, force_share
);
5264 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5265 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5266 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5268 } else if (snapshot_name
!= NULL
) {
5269 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5270 snapshot_name
, &local_err
);
5273 error_reportf_err(local_err
, "Failed to load snapshot: ");
5278 drv
= bdrv_find_format(out_fmt
);
5280 error_report("Unknown file format '%s'", out_fmt
);
5283 if (!drv
->create_opts
) {
5284 error_report("Format driver '%s' does not support image creation",
5289 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5290 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5291 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5293 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
5295 error_report_err(local_err
);
5296 error_report("Invalid options for file format '%s'", out_fmt
);
5300 if (img_size
!= UINT64_MAX
) {
5301 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5304 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5306 error_report_err(local_err
);
5310 if (output_format
== OFORMAT_HUMAN
) {
5311 printf("required size: %" PRIu64
"\n", info
->required
);
5312 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5313 if (info
->has_bitmaps
) {
5314 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5317 dump_json_block_measure_info(info
);
5323 qapi_free_BlockMeasureInfo(info
);
5324 qemu_opts_del(object_opts
);
5325 qemu_opts_del(opts
);
5326 qemu_opts_del(sn_opts
);
5327 qemu_opts_free(create_opts
);
5333 static const img_cmd_t img_cmds
[] = {
5334 #define DEF(option, callback, arg_string) \
5335 { option, callback },
5336 #include "qemu-img-cmds.h"
5341 int main(int argc
, char **argv
)
5343 const img_cmd_t
*cmd
;
5344 const char *cmdname
;
5345 Error
*local_error
= NULL
;
5346 char *trace_file
= NULL
;
5348 static const struct option long_options
[] = {
5349 {"help", no_argument
, 0, 'h'},
5350 {"version", no_argument
, 0, 'V'},
5351 {"trace", required_argument
, NULL
, 'T'},
5356 signal(SIGPIPE
, SIG_IGN
);
5359 error_init(argv
[0]);
5360 module_call_init(MODULE_INIT_TRACE
);
5361 qemu_init_exec_dir(argv
[0]);
5363 if (qemu_init_main_loop(&local_error
)) {
5364 error_report_err(local_error
);
5368 qcrypto_init(&error_fatal
);
5370 module_call_init(MODULE_INIT_QOM
);
5373 error_exit("Not enough arguments");
5376 qemu_add_opts(&qemu_object_opts
);
5377 qemu_add_opts(&qemu_source_opts
);
5378 qemu_add_opts(&qemu_trace_opts
);
5380 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5383 missing_argument(argv
[optind
- 1]);
5386 unrecognized_option(argv
[optind
- 1]);
5392 printf(QEMU_IMG_VERSION
);
5396 trace_file
= trace_opt_parse(optarg
);
5401 cmdname
= argv
[optind
];
5403 /* reset getopt_long scanning */
5409 qemu_reset_optind();
5411 if (!trace_init_backends()) {
5414 trace_init_file(trace_file
);
5415 qemu_set_log(LOG_TRACE
);
5417 /* find the command */
5418 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5419 if (!strcmp(cmdname
, cmd
->name
)) {
5420 return cmd
->handler(argc
, argv
);
5425 error_exit("Command not found: %s", cmdname
);