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,
85 typedef enum OutputFormat
{
90 /* Default to cache=writeback as data integrity is not important for qemu-img */
91 #define BDRV_DEFAULT_CACHE "writeback"
93 static void format_print(void *opaque
, const char *name
)
98 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
103 error_vreport(fmt
, ap
);
106 error_printf("Try 'qemu-img --help' for more information\n");
110 static void QEMU_NORETURN
missing_argument(const char *option
)
112 error_exit("missing argument for option '%s'", option
);
115 static void QEMU_NORETURN
unrecognized_option(const char *option
)
117 error_exit("unrecognized option '%s'", option
);
120 /* Please keep in synch with docs/tools/qemu-img.rst */
121 static void QEMU_NORETURN
help(void)
123 const char *help_msg
=
125 "usage: qemu-img [standard options] command [command options]\n"
126 "QEMU disk image utility\n"
128 " '-h', '--help' display this help and exit\n"
129 " '-V', '--version' output version information and exit\n"
130 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
131 " specify tracing options\n"
134 #define DEF(option, callback, arg_string) \
136 #include "qemu-img-cmds.h"
139 "Command parameters:\n"
140 " 'filename' is a disk image filename\n"
141 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
142 " manual page for a description of the object properties. The most common\n"
143 " object type is a 'secret', which is used to supply passwords and/or\n"
144 " encryption keys.\n"
145 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
146 " 'cache' is the cache mode used to write the output disk image, the valid\n"
147 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
148 " 'directsync' and 'unsafe' (default for convert)\n"
149 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
150 " options are the same as for the 'cache' option\n"
151 " 'size' is the disk image size in bytes. Optional suffixes\n"
152 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
153 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
154 " supported. 'b' is ignored.\n"
155 " 'output_filename' is the destination disk image filename\n"
156 " 'output_fmt' is the destination format\n"
157 " 'options' is a comma separated list of format specific options in a\n"
158 " name=value format. Use -o ? for an overview of the options supported by the\n"
160 " 'snapshot_param' is param used for internal snapshot, format\n"
161 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
163 " '-c' indicates that target image must be compressed (qcow format only)\n"
164 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
165 " new backing file match exactly. The image doesn't need a working\n"
166 " backing file before rebasing in this case (useful for renaming the\n"
167 " backing file). For image creation, allow creating without attempting\n"
168 " to open the backing file.\n"
169 " '-h' with or without a command shows this help and lists the supported formats\n"
170 " '-p' show progress of command (only certain commands)\n"
171 " '-q' use Quiet mode - do not print any output (except errors)\n"
172 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
173 " contain only zeros for qemu-img to create a sparse image during\n"
174 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
175 " unallocated or zero sectors, and the destination image will always be\n"
177 " '--output' takes the format in which the output must be done (human or json)\n"
178 " '-n' skips the target volume creation (useful if the volume is created\n"
179 " prior to running qemu-img)\n"
181 "Parameters to bitmap subcommand:\n"
182 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
183 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
184 " or '--merge source'\n"
185 " '-g granularity' sets the granularity for '--add' actions\n"
186 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
187 " bitmaps from an alternative file\n"
189 "Parameters to check subcommand:\n"
190 " '-r' tries to repair any inconsistencies that are found during the check.\n"
191 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
192 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
193 " hiding corruption that has already occurred.\n"
195 "Parameters to convert subcommand:\n"
196 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
197 " '-m' specifies how many coroutines work in parallel during the convert\n"
198 " process (defaults to 8)\n"
199 " '-W' allow to write to the target out of order rather than sequential\n"
201 "Parameters to snapshot subcommand:\n"
202 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
203 " '-a' applies a snapshot (revert disk to saved state)\n"
204 " '-c' creates a snapshot\n"
205 " '-d' deletes a snapshot\n"
206 " '-l' lists all snapshots in the given image\n"
208 "Parameters to compare subcommand:\n"
209 " '-f' first image format\n"
210 " '-F' second image format\n"
211 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
213 "Parameters to dd subcommand:\n"
214 " 'bs=BYTES' read and write up to BYTES bytes at a time "
216 " 'count=N' copy only N input blocks\n"
217 " 'if=FILE' read from FILE\n"
218 " 'of=FILE' write to FILE\n"
219 " 'skip=N' skip N bs-sized blocks at the start of input\n";
221 printf("%s\nSupported formats:", help_msg
);
222 bdrv_iterate_format(format_print
, NULL
, false);
223 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
227 static QemuOptsList qemu_object_opts
= {
229 .implied_opt_name
= "qom-type",
230 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
236 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
238 if (user_creatable_print_help(type
, opts
)) {
245 * Is @optarg safe for accumulate_options()?
246 * It is when multiple of them can be joined together separated by ','.
247 * To make that work, @optarg must not start with ',' (or else a
248 * separating ',' preceding it gets escaped), and it must not end with
249 * an odd number of ',' (or else a separating ',' following it gets
250 * escaped), or be empty (or else a separating ',' preceding it can
251 * escape a separating ',' following it).
254 static bool is_valid_option_list(const char *optarg
)
256 size_t len
= strlen(optarg
);
259 if (!optarg
[0] || optarg
[0] == ',') {
263 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
272 static int accumulate_options(char **options
, char *optarg
)
276 if (!is_valid_option_list(optarg
)) {
277 error_report("Invalid option list: %s", optarg
);
282 *options
= g_strdup(optarg
);
284 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
286 *options
= new_options
;
291 static QemuOptsList qemu_source_opts
= {
293 .implied_opt_name
= "file",
294 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
300 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
306 ret
= vprintf(fmt
, args
);
313 static int print_block_option_help(const char *filename
, const char *fmt
)
315 BlockDriver
*drv
, *proto_drv
;
316 QemuOptsList
*create_opts
= NULL
;
317 Error
*local_err
= NULL
;
319 /* Find driver and parse its options */
320 drv
= bdrv_find_format(fmt
);
322 error_report("Unknown file format '%s'", fmt
);
326 if (!drv
->create_opts
) {
327 error_report("Format driver '%s' does not support image creation", fmt
);
331 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
333 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
335 error_report_err(local_err
);
336 qemu_opts_free(create_opts
);
339 if (!proto_drv
->create_opts
) {
340 error_report("Protocol driver '%s' does not support image creation",
341 proto_drv
->format_name
);
342 qemu_opts_free(create_opts
);
345 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
349 printf("Supported options:\n");
351 printf("Supported %s options:\n", fmt
);
353 qemu_opts_print_help(create_opts
, false);
354 qemu_opts_free(create_opts
);
358 "The protocol level may support further options.\n"
359 "Specify the target filename to include those options.\n");
366 static BlockBackend
*img_open_opts(const char *optstr
,
367 QemuOpts
*opts
, int flags
, bool writethrough
,
368 bool quiet
, bool force_share
)
371 Error
*local_err
= NULL
;
373 options
= qemu_opts_to_qdict(opts
, NULL
);
375 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
376 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
377 error_report("--force-share/-U conflicts with image options");
378 qobject_unref(options
);
381 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
383 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
385 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
388 blk_set_enable_write_cache(blk
, !writethrough
);
393 static BlockBackend
*img_open_file(const char *filename
,
395 const char *fmt
, int flags
,
396 bool writethrough
, bool quiet
,
400 Error
*local_err
= NULL
;
403 options
= qdict_new();
406 qdict_put_str(options
, "driver", fmt
);
410 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
412 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
414 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
417 blk_set_enable_write_cache(blk
, !writethrough
);
423 static int img_add_key_secrets(void *opaque
,
424 const char *name
, const char *value
,
427 QDict
*options
= opaque
;
429 if (g_str_has_suffix(name
, "key-secret")) {
430 qdict_put_str(options
, name
, value
);
437 static BlockBackend
*img_open(bool image_opts
,
438 const char *filename
,
439 const char *fmt
, int flags
, bool writethrough
,
440 bool quiet
, bool force_share
)
446 error_report("--image-opts and --format are mutually exclusive");
449 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
454 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
457 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
464 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
465 const char *base_filename
,
466 const char *base_fmt
)
471 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
473 error_report("Backing file not supported for file format '%s'",
480 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
482 error_report("Backing file format not supported for file "
491 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
497 err
= qemu_strtosz(value
, NULL
, &res
);
498 if (err
< 0 && err
!= -ERANGE
) {
499 error_report("Invalid %s specified. You may use "
500 "k, M, G, T, P or E suffixes for", name
);
501 error_report("kilobytes, megabytes, gigabytes, terabytes, "
502 "petabytes and exabytes.");
505 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
506 error_report("Invalid %s specified. Must be between %" PRId64
507 " and %" PRId64
".", name
, min
, max
);
513 static int64_t cvtnum(const char *name
, const char *value
)
515 return cvtnum_full(name
, value
, 0, INT64_MAX
);
518 static int img_create(int argc
, char **argv
)
521 uint64_t img_size
= -1;
522 const char *fmt
= "raw";
523 const char *base_fmt
= NULL
;
524 const char *filename
;
525 const char *base_filename
= NULL
;
526 char *options
= NULL
;
527 Error
*local_err
= NULL
;
532 static const struct option long_options
[] = {
533 {"help", no_argument
, 0, 'h'},
534 {"object", required_argument
, 0, OPTION_OBJECT
},
537 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
544 missing_argument(argv
[optind
- 1]);
547 unrecognized_option(argv
[optind
- 1]);
556 base_filename
= optarg
;
562 if (accumulate_options(&options
, optarg
) < 0) {
570 flags
|= BDRV_O_NO_BACKING
;
572 case OPTION_OBJECT
: {
574 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
583 /* Get the filename */
584 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
585 if (options
&& has_help_option(options
)) {
587 return print_block_option_help(filename
, fmt
);
590 if (optind
>= argc
) {
591 error_exit("Expecting image file name");
595 if (qemu_opts_foreach(&qemu_object_opts
,
596 user_creatable_add_opts_foreach
,
597 qemu_img_object_print_help
, &error_fatal
)) {
601 /* Get image size, if specified */
605 sval
= cvtnum("image size", argv
[optind
++]);
609 img_size
= (uint64_t)sval
;
611 if (optind
!= argc
) {
612 error_exit("Unexpected argument: %s", argv
[optind
]);
615 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
616 options
, img_size
, flags
, quiet
, &local_err
);
618 error_reportf_err(local_err
, "%s: ", filename
);
630 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
634 Visitor
*v
= qobject_output_visitor_new(&obj
);
636 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
637 visit_complete(v
, &obj
);
638 str
= qobject_to_json_pretty(obj
);
640 qprintf(quiet
, "%s\n", qstring_get_str(str
));
646 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
648 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
649 qprintf(quiet
, "No errors were found on the image.\n");
651 if (check
->corruptions
) {
652 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
653 "Data may be corrupted, or further writes to the image "
660 "\n%" PRId64
" leaked clusters were found on the image.\n"
661 "This means waste of disk space, but no harm to data.\n",
665 if (check
->check_errors
) {
668 " internal errors have occurred during the check.\n",
669 check
->check_errors
);
673 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
674 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
675 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
676 check
->allocated_clusters
, check
->total_clusters
,
677 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
678 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
679 check
->compressed_clusters
* 100.0 /
680 check
->allocated_clusters
);
683 if (check
->image_end_offset
) {
685 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
689 static int collect_image_check(BlockDriverState
*bs
,
691 const char *filename
,
696 BdrvCheckResult result
;
698 ret
= bdrv_check(bs
, &result
, fix
);
703 check
->filename
= g_strdup(filename
);
704 check
->format
= g_strdup(bdrv_get_format_name(bs
));
705 check
->check_errors
= result
.check_errors
;
706 check
->corruptions
= result
.corruptions
;
707 check
->has_corruptions
= result
.corruptions
!= 0;
708 check
->leaks
= result
.leaks
;
709 check
->has_leaks
= result
.leaks
!= 0;
710 check
->corruptions_fixed
= result
.corruptions_fixed
;
711 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
712 check
->leaks_fixed
= result
.leaks_fixed
;
713 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
714 check
->image_end_offset
= result
.image_end_offset
;
715 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
716 check
->total_clusters
= result
.bfi
.total_clusters
;
717 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
718 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
719 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
720 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
721 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
722 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
723 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
729 * Checks an image for consistency. Exit codes:
731 * 0 - Check completed, image is good
732 * 1 - Check not completed because of internal errors
733 * 2 - Check completed, image is corrupted
734 * 3 - Check completed, image has leaked clusters, but is good otherwise
735 * 63 - Checks are not supported by the image format
737 static int img_check(int argc
, char **argv
)
740 OutputFormat output_format
= OFORMAT_HUMAN
;
741 const char *filename
, *fmt
, *output
, *cache
;
743 BlockDriverState
*bs
;
745 int flags
= BDRV_O_CHECK
;
749 bool image_opts
= false;
750 bool force_share
= false;
754 cache
= BDRV_DEFAULT_CACHE
;
757 int option_index
= 0;
758 static const struct option long_options
[] = {
759 {"help", no_argument
, 0, 'h'},
760 {"format", required_argument
, 0, 'f'},
761 {"repair", required_argument
, 0, 'r'},
762 {"output", required_argument
, 0, OPTION_OUTPUT
},
763 {"object", required_argument
, 0, OPTION_OBJECT
},
764 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
765 {"force-share", no_argument
, 0, 'U'},
768 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
769 long_options
, &option_index
);
775 missing_argument(argv
[optind
- 1]);
778 unrecognized_option(argv
[optind
- 1]);
787 flags
|= BDRV_O_RDWR
;
789 if (!strcmp(optarg
, "leaks")) {
790 fix
= BDRV_FIX_LEAKS
;
791 } else if (!strcmp(optarg
, "all")) {
792 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
794 error_exit("Unknown option value for -r "
795 "(expecting 'leaks' or 'all'): %s", optarg
);
810 case OPTION_OBJECT
: {
812 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
818 case OPTION_IMAGE_OPTS
:
823 if (optind
!= argc
- 1) {
824 error_exit("Expecting one image file name");
826 filename
= argv
[optind
++];
828 if (output
&& !strcmp(output
, "json")) {
829 output_format
= OFORMAT_JSON
;
830 } else if (output
&& !strcmp(output
, "human")) {
831 output_format
= OFORMAT_HUMAN
;
833 error_report("--output must be used with human or json as argument.");
837 if (qemu_opts_foreach(&qemu_object_opts
,
838 user_creatable_add_opts_foreach
,
839 qemu_img_object_print_help
, &error_fatal
)) {
843 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
845 error_report("Invalid source cache option: %s", cache
);
849 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
856 check
= g_new0(ImageCheck
, 1);
857 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
859 if (ret
== -ENOTSUP
) {
860 error_report("This image format does not support checks");
865 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
866 int corruptions_fixed
, leaks_fixed
;
867 bool has_leaks_fixed
, has_corruptions_fixed
;
869 leaks_fixed
= check
->leaks_fixed
;
870 has_leaks_fixed
= check
->has_leaks_fixed
;
871 corruptions_fixed
= check
->corruptions_fixed
;
872 has_corruptions_fixed
= check
->has_corruptions_fixed
;
874 if (output_format
== OFORMAT_HUMAN
) {
876 "The following inconsistencies were found and repaired:\n\n"
877 " %" PRId64
" leaked clusters\n"
878 " %" PRId64
" corruptions\n\n"
879 "Double checking the fixed image now...\n",
881 check
->corruptions_fixed
);
884 qapi_free_ImageCheck(check
);
885 check
= g_new0(ImageCheck
, 1);
886 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
888 check
->leaks_fixed
= leaks_fixed
;
889 check
->has_leaks_fixed
= has_leaks_fixed
;
890 check
->corruptions_fixed
= corruptions_fixed
;
891 check
->has_corruptions_fixed
= has_corruptions_fixed
;
895 switch (output_format
) {
897 dump_human_image_check(check
, quiet
);
900 dump_json_image_check(check
, quiet
);
905 if (ret
|| check
->check_errors
) {
907 error_report("Check failed: %s", strerror(-ret
));
909 error_report("Check failed");
915 if (check
->corruptions
) {
917 } else if (check
->leaks
) {
924 qapi_free_ImageCheck(check
);
929 typedef struct CommonBlockJobCBInfo
{
930 BlockDriverState
*bs
;
932 } CommonBlockJobCBInfo
;
934 static void common_block_job_cb(void *opaque
, int ret
)
936 CommonBlockJobCBInfo
*cbi
= opaque
;
939 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
943 static void run_block_job(BlockJob
*job
, Error
**errp
)
945 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
948 aio_context_acquire(aio_context
);
951 float progress
= 0.0f
;
952 aio_poll(aio_context
, true);
953 if (job
->job
.progress
.total
) {
954 progress
= (float)job
->job
.progress
.current
/
955 job
->job
.progress
.total
* 100.f
;
957 qemu_progress_print(progress
, 0);
958 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
960 if (!job_is_completed(&job
->job
)) {
961 ret
= job_complete_sync(&job
->job
, errp
);
965 job_unref(&job
->job
);
966 aio_context_release(aio_context
);
968 /* publish completion progress only when success */
970 qemu_progress_print(100.f
, 0);
974 static int img_commit(int argc
, char **argv
)
977 const char *filename
, *fmt
, *cache
, *base
;
979 BlockDriverState
*bs
, *base_bs
;
981 bool progress
= false, quiet
= false, drop
= false;
983 Error
*local_err
= NULL
;
984 CommonBlockJobCBInfo cbi
;
985 bool image_opts
= false;
986 AioContext
*aio_context
;
989 cache
= BDRV_DEFAULT_CACHE
;
992 static const struct option long_options
[] = {
993 {"help", no_argument
, 0, 'h'},
994 {"object", required_argument
, 0, OPTION_OBJECT
},
995 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
998 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
1005 missing_argument(argv
[optind
- 1]);
1008 unrecognized_option(argv
[optind
- 1]);
1033 case OPTION_OBJECT
: {
1035 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1041 case OPTION_IMAGE_OPTS
:
1047 /* Progress is not shown in Quiet mode */
1052 if (optind
!= argc
- 1) {
1053 error_exit("Expecting one image file name");
1055 filename
= argv
[optind
++];
1057 if (qemu_opts_foreach(&qemu_object_opts
,
1058 user_creatable_add_opts_foreach
,
1059 qemu_img_object_print_help
, &error_fatal
)) {
1063 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1064 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1066 error_report("Invalid cache option: %s", cache
);
1070 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1077 qemu_progress_init(progress
, 1.f
);
1078 qemu_progress_print(0.f
, 100);
1081 base_bs
= bdrv_find_backing_image(bs
, base
);
1083 error_setg(&local_err
,
1084 "Did not find '%s' in the backing chain of '%s'",
1089 /* This is different from QMP, which by default uses the deepest file in
1090 * the backing chain (i.e., the very base); however, the traditional
1091 * behavior of qemu-img commit is using the immediate backing file. */
1092 base_bs
= backing_bs(bs
);
1094 error_setg(&local_err
, "Image does not have a backing file");
1099 cbi
= (CommonBlockJobCBInfo
){
1104 aio_context
= bdrv_get_aio_context(bs
);
1105 aio_context_acquire(aio_context
);
1106 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1107 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1108 &cbi
, false, &local_err
);
1109 aio_context_release(aio_context
);
1114 /* When the block job completes, the BlockBackend reference will point to
1115 * the old backing file. In order to avoid that the top image is already
1116 * deleted, so we can still empty it afterwards, increment the reference
1117 * counter here preemptively. */
1122 job
= block_job_get("commit");
1124 run_block_job(job
, &local_err
);
1130 BlockBackend
*old_backing_blk
;
1132 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1134 if (!old_backing_blk
) {
1137 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1138 blk_unref(old_backing_blk
);
1139 if (ret
== -ENOTSUP
) {
1140 error_free(local_err
);
1142 } else if (ret
< 0) {
1153 qemu_progress_end();
1158 error_report_err(local_err
);
1162 qprintf(quiet
, "Image committed.\n");
1167 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1168 * of the first sector boundary within buf where the sector contains a
1169 * non-zero byte. This function is robust to a buffer that is not
1172 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1175 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1177 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1178 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1182 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1189 * Returns true iff the first sector pointed to by 'buf' contains at least
1192 * 'pnum' is set to the number of sectors (including and immediately following
1193 * the first one) that are known to be in the same allocated/unallocated state.
1194 * The function will try to align the end offset to alignment boundaries so
1195 * that the request will at least end aligned and consequtive requests will
1196 * also start at an aligned offset.
1198 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1199 int64_t sector_num
, int alignment
)
1208 is_zero
= buffer_is_zero(buf
, 512);
1209 for(i
= 1; i
< n
; i
++) {
1211 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1216 tail
= (sector_num
+ i
) & (alignment
- 1);
1218 if (is_zero
&& i
<= tail
) {
1219 /* treat unallocated areas which only consist
1220 * of a small tail as allocated. */
1224 /* align up end offset of allocated areas. */
1225 i
+= alignment
- tail
;
1228 /* align down end offset of zero areas. */
1237 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1238 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1239 * breaking up write requests for only small sparse areas.
1241 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1242 int min
, int64_t sector_num
, int alignment
)
1245 int num_checked
, num_used
;
1251 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1257 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1259 sector_num
+= *pnum
;
1260 num_checked
= num_used
;
1263 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1265 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1267 sector_num
+= *pnum
;
1268 num_checked
+= *pnum
;
1270 num_used
= num_checked
;
1271 } else if (*pnum
>= min
) {
1281 * Compares two buffers sector by sector. Returns 0 if the first
1282 * sector of each buffer matches, non-zero otherwise.
1284 * pnum is set to the sector-aligned size of the buffer prefix that
1285 * has the same matching status as the first sector.
1287 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1288 int64_t bytes
, int64_t *pnum
)
1291 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1295 res
= !!memcmp(buf1
, buf2
, i
);
1297 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1299 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1309 #define IO_BUF_SIZE (2 * MiB)
1312 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1314 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1315 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1316 * failure), and 4 on error (the exit status for read errors), after emitting
1319 * @param blk: BlockBackend for the image
1320 * @param offset: Starting offset to check
1321 * @param bytes: Number of bytes to check
1322 * @param filename: Name of disk file we are checking (logging purpose)
1323 * @param buffer: Allocated buffer for storing read data
1324 * @param quiet: Flag for quiet mode
1326 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1327 int64_t bytes
, const char *filename
,
1328 uint8_t *buffer
, bool quiet
)
1333 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1335 error_report("Error while reading offset %" PRId64
" of %s: %s",
1336 offset
, filename
, strerror(-ret
));
1339 idx
= find_nonzero(buffer
, bytes
);
1341 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1350 * Compares two images. Exit codes:
1352 * 0 - Images are identical
1354 * >1 - Error occurred
1356 static int img_compare(int argc
, char **argv
)
1358 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1359 BlockBackend
*blk1
, *blk2
;
1360 BlockDriverState
*bs1
, *bs2
;
1361 int64_t total_size1
, total_size2
;
1362 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1363 int64_t pnum1
, pnum2
;
1364 int allocated1
, allocated2
;
1365 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1366 bool progress
= false, quiet
= false, strict
= false;
1373 uint64_t progress_base
;
1374 bool image_opts
= false;
1375 bool force_share
= false;
1377 cache
= BDRV_DEFAULT_CACHE
;
1379 static const struct option long_options
[] = {
1380 {"help", no_argument
, 0, 'h'},
1381 {"object", required_argument
, 0, OPTION_OBJECT
},
1382 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1383 {"force-share", no_argument
, 0, 'U'},
1386 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1387 long_options
, NULL
);
1393 missing_argument(argv
[optind
- 1]);
1396 unrecognized_option(argv
[optind
- 1]);
1422 case OPTION_OBJECT
: {
1424 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1431 case OPTION_IMAGE_OPTS
:
1437 /* Progress is not shown in Quiet mode */
1443 if (optind
!= argc
- 2) {
1444 error_exit("Expecting two image file names");
1446 filename1
= argv
[optind
++];
1447 filename2
= argv
[optind
++];
1449 if (qemu_opts_foreach(&qemu_object_opts
,
1450 user_creatable_add_opts_foreach
,
1451 qemu_img_object_print_help
, &error_fatal
)) {
1456 /* Initialize before goto out */
1457 qemu_progress_init(progress
, 2.0);
1460 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1462 error_report("Invalid source cache option: %s", cache
);
1467 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1474 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1483 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1484 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1485 total_size1
= blk_getlength(blk1
);
1486 if (total_size1
< 0) {
1487 error_report("Can't get size of %s: %s",
1488 filename1
, strerror(-total_size1
));
1492 total_size2
= blk_getlength(blk2
);
1493 if (total_size2
< 0) {
1494 error_report("Can't get size of %s: %s",
1495 filename2
, strerror(-total_size2
));
1499 total_size
= MIN(total_size1
, total_size2
);
1500 progress_base
= MAX(total_size1
, total_size2
);
1502 qemu_progress_print(0, 100);
1504 if (strict
&& total_size1
!= total_size2
) {
1506 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1510 while (offset
< total_size
) {
1511 int status1
, status2
;
1513 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1514 total_size1
- offset
, &pnum1
, NULL
,
1518 error_report("Sector allocation test failed for %s", filename1
);
1521 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1523 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1524 total_size2
- offset
, &pnum2
, NULL
,
1528 error_report("Sector allocation test failed for %s", filename2
);
1531 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1533 assert(pnum1
&& pnum2
);
1534 chunk
= MIN(pnum1
, pnum2
);
1537 if (status1
!= status2
) {
1539 qprintf(quiet
, "Strict mode: Offset %" PRId64
1540 " block status mismatch!\n", offset
);
1544 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1546 } else if (allocated1
== allocated2
) {
1550 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1551 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1553 error_report("Error while reading offset %" PRId64
1555 offset
, filename1
, strerror(-ret
));
1559 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1561 error_report("Error while reading offset %" PRId64
1563 offset
, filename2
, strerror(-ret
));
1567 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1568 if (ret
|| pnum
!= chunk
) {
1569 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1570 offset
+ (ret
? 0 : pnum
));
1576 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1578 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1579 filename1
, buf1
, quiet
);
1581 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1582 filename2
, buf1
, quiet
);
1589 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1592 if (total_size1
!= total_size2
) {
1593 BlockBackend
*blk_over
;
1594 const char *filename_over
;
1596 qprintf(quiet
, "Warning: Image size mismatch!\n");
1597 if (total_size1
> total_size2
) {
1599 filename_over
= filename1
;
1602 filename_over
= filename2
;
1605 while (offset
< progress_base
) {
1606 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1607 progress_base
- offset
, &chunk
,
1611 error_report("Sector allocation test failed for %s",
1616 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1617 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1618 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1619 filename_over
, buf1
, quiet
);
1625 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1629 qprintf(quiet
, "Images are identical.\n");
1639 qemu_progress_end();
1644 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1645 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1646 const char *src_node
, const char *src_name
,
1649 BlockDirtyBitmapMergeSource
*merge_src
;
1650 BlockDirtyBitmapMergeSourceList
*list
;
1652 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1653 merge_src
->type
= QTYPE_QDICT
;
1654 merge_src
->u
.external
.node
= g_strdup(src_node
);
1655 merge_src
->u
.external
.name
= g_strdup(src_name
);
1656 list
= g_new0(BlockDirtyBitmapMergeSourceList
, 1);
1657 list
->value
= merge_src
;
1658 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1659 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1662 enum ImgConvertBlockStatus
{
1668 #define MAX_COROUTINES 16
1670 typedef struct ImgConvertState
{
1672 int64_t *src_sectors
;
1674 int64_t total_sectors
;
1675 int64_t allocated_sectors
;
1676 int64_t allocated_done
;
1679 enum ImgConvertBlockStatus status
;
1680 int64_t sector_next_status
;
1681 BlockBackend
*target
;
1684 bool unallocated_blocks_are_zero
;
1686 bool target_has_backing
;
1687 int64_t target_backing_sectors
; /* negative if unknown */
1694 size_t cluster_sectors
;
1696 long num_coroutines
;
1697 int running_coroutines
;
1698 Coroutine
*co
[MAX_COROUTINES
];
1699 int64_t wait_sector_num
[MAX_COROUTINES
];
1704 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1705 int *src_cur
, int64_t *src_cur_offset
)
1708 *src_cur_offset
= 0;
1709 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1710 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1712 assert(*src_cur
< s
->src_num
);
1716 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1718 int64_t src_cur_offset
;
1719 int ret
, n
, src_cur
;
1720 bool post_backing_zero
= false;
1722 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1724 assert(s
->total_sectors
> sector_num
);
1725 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1727 if (s
->target_backing_sectors
>= 0) {
1728 if (sector_num
>= s
->target_backing_sectors
) {
1729 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1730 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1731 /* Split requests around target_backing_sectors (because
1732 * starting from there, zeros are handled differently) */
1733 n
= s
->target_backing_sectors
- sector_num
;
1737 if (s
->sector_next_status
<= sector_num
) {
1738 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1742 count
= n
* BDRV_SECTOR_SIZE
;
1744 if (s
->target_has_backing
) {
1745 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1746 count
, &count
, NULL
, NULL
);
1748 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1749 offset
, count
, &count
, NULL
,
1757 warn_report("error while reading block status at "
1758 "offset %" PRIu64
": %s", offset
,
1761 /* Just try to read the data, then */
1762 ret
= BDRV_BLOCK_DATA
;
1763 count
= BDRV_SECTOR_SIZE
;
1765 /* Retry on a shorter range */
1766 n
= DIV_ROUND_UP(n
, 4);
1769 error_report("error while reading block status at offset "
1770 "%" PRIu64
": %s", offset
, strerror(-ret
));
1776 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1778 if (ret
& BDRV_BLOCK_ZERO
) {
1779 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1780 } else if (ret
& BDRV_BLOCK_DATA
) {
1781 s
->status
= BLK_DATA
;
1783 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1786 s
->sector_next_status
= sector_num
+ n
;
1789 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1790 if (s
->status
== BLK_DATA
) {
1791 n
= MIN(n
, s
->buf_sectors
);
1794 /* We need to write complete clusters for compressed images, so if an
1795 * unallocated area is shorter than that, we must consider the whole
1796 * cluster allocated. */
1797 if (s
->compressed
) {
1798 if (n
< s
->cluster_sectors
) {
1799 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1800 s
->status
= BLK_DATA
;
1802 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1809 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1810 int nb_sectors
, uint8_t *buf
)
1812 uint64_t single_read_until
= 0;
1815 assert(nb_sectors
<= s
->buf_sectors
);
1816 while (nb_sectors
> 0) {
1819 int64_t bs_sectors
, src_cur_offset
;
1822 /* In the case of compression with multiple source files, we can get a
1823 * nb_sectors that spreads into the next part. So we must be able to
1824 * read across multiple BDSes for one convert_read() call. */
1825 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1826 blk
= s
->src
[src_cur
];
1827 bs_sectors
= s
->src_sectors
[src_cur
];
1829 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1831 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1832 if (single_read_until
> offset
) {
1836 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1840 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1844 warn_report("error while reading offset %" PRIu64
1845 ": %s", offset
, strerror(-ret
));
1847 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1856 buf
+= n
* BDRV_SECTOR_SIZE
;
1863 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1864 int nb_sectors
, uint8_t *buf
,
1865 enum ImgConvertBlockStatus status
)
1869 while (nb_sectors
> 0) {
1871 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1874 case BLK_BACKING_FILE
:
1875 /* If we have a backing file, leave clusters unallocated that are
1876 * unallocated in the source image, so that the backing file is
1877 * visible at the respective offset. */
1878 assert(s
->target_has_backing
);
1882 /* If we're told to keep the target fully allocated (-S 0) or there
1883 * is real non-zero data, we must write it. Otherwise we can treat
1884 * it as zero sectors.
1885 * Compressed clusters need to be written as a whole, so in that
1886 * case we can only save the write if the buffer is completely
1888 if (!s
->min_sparse
||
1890 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1891 sector_num
, s
->alignment
)) ||
1893 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1895 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1896 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1905 if (s
->has_zero_init
) {
1906 assert(!s
->target_has_backing
);
1909 ret
= blk_co_pwrite_zeroes(s
->target
,
1910 sector_num
<< BDRV_SECTOR_BITS
,
1911 n
<< BDRV_SECTOR_BITS
,
1912 BDRV_REQ_MAY_UNMAP
);
1921 buf
+= n
* BDRV_SECTOR_SIZE
;
1927 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1932 while (nb_sectors
> 0) {
1935 int64_t bs_sectors
, src_cur_offset
;
1938 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1939 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1940 blk
= s
->src
[src_cur
];
1941 bs_sectors
= s
->src_sectors
[src_cur
];
1943 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1945 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1946 sector_num
<< BDRV_SECTOR_BITS
,
1947 n
<< BDRV_SECTOR_BITS
, 0, 0);
1958 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1960 ImgConvertState
*s
= opaque
;
1961 uint8_t *buf
= NULL
;
1965 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1966 if (s
->co
[i
] == qemu_coroutine_self()) {
1973 s
->running_coroutines
++;
1974 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1979 enum ImgConvertBlockStatus status
;
1982 qemu_co_mutex_lock(&s
->lock
);
1983 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1984 qemu_co_mutex_unlock(&s
->lock
);
1987 n
= convert_iteration_sectors(s
, s
->sector_num
);
1989 qemu_co_mutex_unlock(&s
->lock
);
1993 /* save current sector and allocation status to local variables */
1994 sector_num
= s
->sector_num
;
1996 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1997 n
= MIN(n
, s
->buf_sectors
);
1999 /* increment global sector counter so that other coroutines can
2000 * already continue reading beyond this request */
2002 qemu_co_mutex_unlock(&s
->lock
);
2004 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2005 s
->allocated_done
+= n
;
2006 qemu_progress_print(100.0 * s
->allocated_done
/
2007 s
->allocated_sectors
, 0);
2011 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2012 if (status
== BLK_DATA
&& !copy_range
) {
2013 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2015 error_report("error while reading at byte %lld: %s",
2016 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2019 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2021 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2024 if (s
->wr_in_order
) {
2025 /* keep writes in order */
2026 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2027 s
->wait_sector_num
[index
] = sector_num
;
2028 qemu_coroutine_yield();
2030 s
->wait_sector_num
[index
] = -1;
2033 if (s
->ret
== -EINPROGRESS
) {
2035 ret
= convert_co_copy_range(s
, sector_num
, n
);
2037 s
->copy_range
= false;
2041 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2044 error_report("error while writing at byte %lld: %s",
2045 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2050 if (s
->wr_in_order
) {
2051 /* reenter the coroutine that might have waited
2052 * for this write to complete */
2053 s
->wr_offs
= sector_num
+ n
;
2054 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2055 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2057 * A -> B -> A cannot occur because A has
2058 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2059 * B will never enter A during this time window.
2061 qemu_coroutine_enter(s
->co
[i
]);
2069 s
->co
[index
] = NULL
;
2070 s
->running_coroutines
--;
2071 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2072 /* the convert job finished successfully */
2077 static int convert_do_copy(ImgConvertState
*s
)
2080 int64_t sector_num
= 0;
2082 /* Check whether we have zero initialisation or can get it efficiently */
2083 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2084 !s
->target_has_backing
) {
2085 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2088 /* Allocate buffer for copied data. For compressed images, only one cluster
2089 * can be copied at a time. */
2090 if (s
->compressed
) {
2091 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2092 error_report("invalid cluster size");
2095 s
->buf_sectors
= s
->cluster_sectors
;
2098 while (sector_num
< s
->total_sectors
) {
2099 n
= convert_iteration_sectors(s
, sector_num
);
2103 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2105 s
->allocated_sectors
+= n
;
2111 s
->sector_next_status
= 0;
2112 s
->ret
= -EINPROGRESS
;
2114 qemu_co_mutex_init(&s
->lock
);
2115 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2116 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2117 s
->wait_sector_num
[i
] = -1;
2118 qemu_coroutine_enter(s
->co
[i
]);
2121 while (s
->running_coroutines
) {
2122 main_loop_wait(false);
2125 if (s
->compressed
&& !s
->ret
) {
2126 /* signal EOF to align */
2127 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2136 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2138 BdrvDirtyBitmap
*bm
;
2141 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2144 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2147 name
= bdrv_dirty_bitmap_name(bm
);
2148 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2149 true, bdrv_dirty_bitmap_granularity(bm
),
2151 true, !bdrv_dirty_bitmap_enabled(bm
),
2154 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2158 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2161 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2169 #define MAX_BUF_SECTORS 32768
2171 static int img_convert(int argc
, char **argv
)
2173 int c
, bs_i
, flags
, src_flags
= 0;
2174 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2175 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2176 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2177 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2178 BlockDriverInfo bdi
;
2179 BlockDriverState
*out_bs
;
2180 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2181 QemuOptsList
*create_opts
= NULL
;
2182 QDict
*open_opts
= NULL
;
2183 char *options
= NULL
;
2184 Error
*local_err
= NULL
;
2185 bool writethrough
, src_writethrough
, image_opts
= false,
2186 skip_create
= false, progress
= false, tgt_image_opts
= false;
2187 int64_t ret
= -EINVAL
;
2188 bool force_share
= false;
2189 bool explict_min_sparse
= false;
2190 bool bitmaps
= false;
2192 ImgConvertState s
= (ImgConvertState
) {
2193 /* Need at least 4k of zeros for sparse detection */
2195 .copy_range
= false,
2196 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2197 .wr_in_order
= true,
2198 .num_coroutines
= 8,
2202 static const struct option long_options
[] = {
2203 {"help", no_argument
, 0, 'h'},
2204 {"object", required_argument
, 0, OPTION_OBJECT
},
2205 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2206 {"force-share", no_argument
, 0, 'U'},
2207 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2208 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2209 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2210 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2213 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2214 long_options
, NULL
);
2220 missing_argument(argv
[optind
- 1]);
2223 unrecognized_option(argv
[optind
- 1]);
2235 out_baseimg
= optarg
;
2238 s
.copy_range
= true;
2241 s
.compressed
= true;
2244 if (accumulate_options(&options
, optarg
) < 0) {
2249 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2250 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2253 error_report("Failed in parsing snapshot param '%s'",
2258 snapshot_name
= optarg
;
2265 sval
= cvtnum("buffer size for sparse output", optarg
);
2268 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2269 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2270 error_report("Invalid buffer size for sparse output specified. "
2271 "Valid sizes are multiples of %llu up to %llu. Select "
2272 "0 to disable sparse detection (fully allocates output).",
2273 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2277 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2278 explict_min_sparse
= true;
2297 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2298 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2299 error_report("Invalid number of coroutines. Allowed number of"
2300 " coroutines is between 1 and %d", MAX_COROUTINES
);
2305 s
.wr_in_order
= false;
2310 case OPTION_OBJECT
: {
2311 QemuOpts
*object_opts
;
2312 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2319 case OPTION_IMAGE_OPTS
:
2322 case OPTION_SALVAGE
:
2325 case OPTION_TARGET_IMAGE_OPTS
:
2326 tgt_image_opts
= true;
2328 case OPTION_TARGET_IS_ZERO
:
2330 * The user asserting that the target is blank has the
2331 * same effect as the target driver supporting zero
2334 s
.has_zero_init
= true;
2336 case OPTION_BITMAPS
:
2342 if (!out_fmt
&& !tgt_image_opts
) {
2346 if (qemu_opts_foreach(&qemu_object_opts
,
2347 user_creatable_add_opts_foreach
,
2348 qemu_img_object_print_help
, &error_fatal
)) {
2352 if (s
.compressed
&& s
.copy_range
) {
2353 error_report("Cannot enable copy offloading when -c is used");
2357 if (explict_min_sparse
&& s
.copy_range
) {
2358 error_report("Cannot enable copy offloading when -S is used");
2362 if (s
.copy_range
&& s
.salvage
) {
2363 error_report("Cannot use copy offloading in salvaging mode");
2367 if (tgt_image_opts
&& !skip_create
) {
2368 error_report("--target-image-opts requires use of -n flag");
2372 if (skip_create
&& options
) {
2373 warn_report("-o has no effect when skipping image creation");
2374 warn_report("This will become an error in future QEMU versions.");
2377 if (s
.has_zero_init
&& !skip_create
) {
2378 error_report("--target-is-zero requires use of -n flag");
2382 s
.src_num
= argc
- optind
- 1;
2383 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2385 if (options
&& has_help_option(options
)) {
2387 ret
= print_block_option_help(out_filename
, out_fmt
);
2390 error_report("Option help requires a format be specified");
2395 if (s
.src_num
< 1) {
2396 error_report("Must specify image file name");
2400 /* ret is still -EINVAL until here */
2401 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2403 error_report("Invalid source cache option: %s", src_cache
);
2407 /* Initialize before goto out */
2411 qemu_progress_init(progress
, 1.0);
2412 qemu_progress_print(0, 100);
2414 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2415 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2417 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2418 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2419 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2425 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2426 if (s
.src_sectors
[bs_i
] < 0) {
2427 error_report("Could not get size of %s: %s",
2428 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2432 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2436 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2437 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2438 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2440 } else if (snapshot_name
!= NULL
) {
2441 if (s
.src_num
> 1) {
2442 error_report("No support for concatenating multiple snapshot");
2447 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2451 error_reportf_err(local_err
, "Failed to load snapshot: ");
2457 /* Find driver and parse its options */
2458 drv
= bdrv_find_format(out_fmt
);
2460 error_report("Unknown file format '%s'", out_fmt
);
2465 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2467 error_report_err(local_err
);
2472 if (!drv
->create_opts
) {
2473 error_report("Format driver '%s' does not support image creation",
2479 if (!proto_drv
->create_opts
) {
2480 error_report("Protocol driver '%s' does not support image creation",
2481 proto_drv
->format_name
);
2486 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2487 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2489 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2491 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2493 error_report_err(local_err
);
2499 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2501 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2507 /* Get backing file name if -o backing_file was used */
2508 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2509 if (out_baseimg_param
) {
2510 out_baseimg
= out_baseimg_param
;
2512 s
.target_has_backing
= (bool) out_baseimg
;
2514 if (s
.has_zero_init
&& s
.target_has_backing
) {
2515 error_report("Cannot use --target-is-zero when the destination "
2516 "image has a backing file");
2520 if (s
.src_num
> 1 && out_baseimg
) {
2521 error_report("Having a backing file for the target makes no sense when "
2522 "concatenating multiple input images");
2527 /* Check if compression is supported */
2530 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2531 const char *encryptfmt
=
2532 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2533 const char *preallocation
=
2534 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2536 if (drv
&& !block_driver_can_compress(drv
)) {
2537 error_report("Compression not supported for this file format");
2542 if (encryption
|| encryptfmt
) {
2543 error_report("Compression and encryption not supported at "
2550 && strcmp(preallocation
, "off"))
2552 error_report("Compression and preallocation not supported at "
2559 /* Determine if bitmaps need copying */
2561 if (s
.src_num
> 1) {
2562 error_report("Copying bitmaps only possible with single source");
2566 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2567 error_report("Source lacks bitmap support");
2574 * The later open call will need any decryption secrets, and
2575 * bdrv_create() will purge "opts", so extract them now before
2579 open_opts
= qdict_new();
2580 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2582 /* Create the new image */
2583 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2585 error_reportf_err(local_err
, "%s: error while converting %s: ",
2586 out_filename
, out_fmt
);
2591 s
.target_is_new
= !skip_create
;
2593 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2594 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2596 error_report("Invalid cache option: %s", cache
);
2601 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2602 flags
, writethrough
, s
.quiet
, false);
2604 /* TODO ultimately we should allow --target-image-opts
2605 * to be used even when -n is not given.
2606 * That has to wait for bdrv_create to be improved
2607 * to allow filenames in option syntax
2609 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2610 flags
, writethrough
, s
.quiet
, false);
2611 open_opts
= NULL
; /* blk_new_open will have freed it */
2617 out_bs
= blk_bs(s
.target
);
2619 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2620 error_report("Format driver '%s' does not support bitmaps",
2621 out_bs
->drv
->format_name
);
2626 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2627 error_report("Compression not supported for this file format");
2632 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2633 * or discard_alignment of the out_bs is greater. Limit to
2634 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2635 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2637 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2638 out_bs
->bl
.pdiscard_alignment
>>
2639 BDRV_SECTOR_BITS
)));
2641 /* try to align the write requests to the destination to avoid unnecessary
2643 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2644 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2646 assert(is_power_of_2(s
.alignment
));
2649 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2650 if (output_sectors
< 0) {
2651 error_report("unable to get output image length: %s",
2652 strerror(-output_sectors
));
2655 } else if (output_sectors
< s
.total_sectors
) {
2656 error_report("output file is smaller than input file");
2662 if (s
.target_has_backing
&& s
.target_is_new
) {
2663 /* Errors are treated as "backing length unknown" (which means
2664 * s.target_backing_sectors has to be negative, which it will
2665 * be automatically). The backing file length is used only
2666 * for optimizations, so such a case is not fatal. */
2667 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2669 s
.target_backing_sectors
= -1;
2672 ret
= bdrv_get_info(out_bs
, &bdi
);
2675 error_report("could not get block driver info");
2679 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2680 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2681 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2684 ret
= convert_do_copy(&s
);
2686 /* Now copy the bitmaps */
2687 if (bitmaps
&& ret
== 0) {
2688 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2693 qemu_progress_print(100, 0);
2695 qemu_progress_end();
2696 qemu_opts_del(opts
);
2697 qemu_opts_free(create_opts
);
2698 qemu_opts_del(sn_opts
);
2699 qobject_unref(open_opts
);
2700 blk_unref(s
.target
);
2702 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2703 blk_unref(s
.src
[bs_i
]);
2707 g_free(s
.src_sectors
);
2715 static void dump_snapshots(BlockDriverState
*bs
)
2717 QEMUSnapshotInfo
*sn_tab
, *sn
;
2720 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2723 printf("Snapshot list:\n");
2724 bdrv_snapshot_dump(NULL
);
2726 for(i
= 0; i
< nb_sns
; i
++) {
2728 bdrv_snapshot_dump(sn
);
2734 static void dump_json_image_info_list(ImageInfoList
*list
)
2738 Visitor
*v
= qobject_output_visitor_new(&obj
);
2740 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2741 visit_complete(v
, &obj
);
2742 str
= qobject_to_json_pretty(obj
);
2743 assert(str
!= NULL
);
2744 printf("%s\n", qstring_get_str(str
));
2750 static void dump_json_image_info(ImageInfo
*info
)
2754 Visitor
*v
= qobject_output_visitor_new(&obj
);
2756 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2757 visit_complete(v
, &obj
);
2758 str
= qobject_to_json_pretty(obj
);
2759 assert(str
!= NULL
);
2760 printf("%s\n", qstring_get_str(str
));
2766 static void dump_human_image_info_list(ImageInfoList
*list
)
2768 ImageInfoList
*elem
;
2771 for (elem
= list
; elem
; elem
= elem
->next
) {
2777 bdrv_image_info_dump(elem
->value
);
2781 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2783 return strcmp(a
, b
) == 0;
2787 * Open an image file chain and return an ImageInfoList
2789 * @filename: topmost image filename
2790 * @fmt: topmost image format (may be NULL to autodetect)
2791 * @chain: true - enumerate entire backing file chain
2792 * false - only topmost image file
2794 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2795 * image file. If there was an error a message will have been printed to
2798 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2799 const char *filename
,
2801 bool chain
, bool force_share
)
2803 ImageInfoList
*head
= NULL
;
2804 ImageInfoList
**last
= &head
;
2805 GHashTable
*filenames
;
2808 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2812 BlockDriverState
*bs
;
2814 ImageInfoList
*elem
;
2816 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2817 error_report("Backing file '%s' creates an infinite loop.",
2821 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2823 blk
= img_open(image_opts
, filename
, fmt
,
2824 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2831 bdrv_query_image_info(bs
, &info
, &err
);
2833 error_report_err(err
);
2838 elem
= g_new0(ImageInfoList
, 1);
2845 /* Clear parameters that only apply to the topmost image */
2846 filename
= fmt
= NULL
;
2850 if (info
->has_full_backing_filename
) {
2851 filename
= info
->full_backing_filename
;
2852 } else if (info
->has_backing_filename
) {
2853 error_report("Could not determine absolute backing filename,"
2854 " but backing filename '%s' present",
2855 info
->backing_filename
);
2858 if (info
->has_backing_filename_format
) {
2859 fmt
= info
->backing_filename_format
;
2863 g_hash_table_destroy(filenames
);
2867 qapi_free_ImageInfoList(head
);
2868 g_hash_table_destroy(filenames
);
2872 static int img_info(int argc
, char **argv
)
2875 OutputFormat output_format
= OFORMAT_HUMAN
;
2877 const char *filename
, *fmt
, *output
;
2878 ImageInfoList
*list
;
2879 bool image_opts
= false;
2880 bool force_share
= false;
2885 int option_index
= 0;
2886 static const struct option long_options
[] = {
2887 {"help", no_argument
, 0, 'h'},
2888 {"format", required_argument
, 0, 'f'},
2889 {"output", required_argument
, 0, OPTION_OUTPUT
},
2890 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2891 {"object", required_argument
, 0, OPTION_OBJECT
},
2892 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2893 {"force-share", no_argument
, 0, 'U'},
2896 c
= getopt_long(argc
, argv
, ":f:hU",
2897 long_options
, &option_index
);
2903 missing_argument(argv
[optind
- 1]);
2906 unrecognized_option(argv
[optind
- 1]);
2920 case OPTION_BACKING_CHAIN
:
2923 case OPTION_OBJECT
: {
2925 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2931 case OPTION_IMAGE_OPTS
:
2936 if (optind
!= argc
- 1) {
2937 error_exit("Expecting one image file name");
2939 filename
= argv
[optind
++];
2941 if (output
&& !strcmp(output
, "json")) {
2942 output_format
= OFORMAT_JSON
;
2943 } else if (output
&& !strcmp(output
, "human")) {
2944 output_format
= OFORMAT_HUMAN
;
2945 } else if (output
) {
2946 error_report("--output must be used with human or json as argument.");
2950 if (qemu_opts_foreach(&qemu_object_opts
,
2951 user_creatable_add_opts_foreach
,
2952 qemu_img_object_print_help
, &error_fatal
)) {
2956 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2962 switch (output_format
) {
2964 dump_human_image_info_list(list
);
2968 dump_json_image_info_list(list
);
2970 dump_json_image_info(list
->value
);
2975 qapi_free_ImageInfoList(list
);
2979 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2982 switch (output_format
) {
2984 if (e
->data
&& !e
->has_offset
) {
2985 error_report("File contains external, encrypted or compressed clusters.");
2988 if (e
->data
&& !e
->zero
) {
2989 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2990 e
->start
, e
->length
,
2991 e
->has_offset
? e
->offset
: 0,
2992 e
->has_filename
? e
->filename
: "");
2994 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2995 * Modify the flags here to allow more coalescing.
2997 if (next
&& (!next
->data
|| next
->zero
)) {
3003 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3004 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
3005 e
->start
, e
->length
, e
->depth
,
3006 e
->zero
? "true" : "false",
3007 e
->data
? "true" : "false");
3008 if (e
->has_offset
) {
3009 printf(", \"offset\": %"PRId64
"", e
->offset
);
3021 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3022 int64_t bytes
, MapEntry
*e
)
3026 BlockDriverState
*file
;
3029 char *filename
= NULL
;
3031 /* As an optimization, we could cache the current range of unallocated
3032 * clusters in each file of the chain, and avoid querying the same
3038 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3043 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3046 bs
= backing_bs(bs
);
3055 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3057 if (file
&& has_offset
) {
3058 bdrv_refresh_filename(file
);
3059 filename
= file
->filename
;
3065 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3066 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3068 .has_offset
= has_offset
,
3070 .has_filename
= filename
,
3071 .filename
= filename
,
3077 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3079 if (curr
->length
== 0) {
3082 if (curr
->zero
!= next
->zero
||
3083 curr
->data
!= next
->data
||
3084 curr
->depth
!= next
->depth
||
3085 curr
->has_filename
!= next
->has_filename
||
3086 curr
->has_offset
!= next
->has_offset
) {
3089 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3092 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3098 static int img_map(int argc
, char **argv
)
3101 OutputFormat output_format
= OFORMAT_HUMAN
;
3103 BlockDriverState
*bs
;
3104 const char *filename
, *fmt
, *output
;
3106 MapEntry curr
= { .length
= 0 }, next
;
3108 bool image_opts
= false;
3109 bool force_share
= false;
3110 int64_t start_offset
= 0;
3111 int64_t max_length
= -1;
3116 int option_index
= 0;
3117 static const struct option long_options
[] = {
3118 {"help", no_argument
, 0, 'h'},
3119 {"format", required_argument
, 0, 'f'},
3120 {"output", required_argument
, 0, OPTION_OUTPUT
},
3121 {"object", required_argument
, 0, OPTION_OBJECT
},
3122 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3123 {"force-share", no_argument
, 0, 'U'},
3124 {"start-offset", required_argument
, 0, 's'},
3125 {"max-length", required_argument
, 0, 'l'},
3128 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3129 long_options
, &option_index
);
3135 missing_argument(argv
[optind
- 1]);
3138 unrecognized_option(argv
[optind
- 1]);
3153 start_offset
= cvtnum("start offset", optarg
);
3154 if (start_offset
< 0) {
3159 max_length
= cvtnum("max length", optarg
);
3160 if (max_length
< 0) {
3164 case OPTION_OBJECT
: {
3166 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3172 case OPTION_IMAGE_OPTS
:
3177 if (optind
!= argc
- 1) {
3178 error_exit("Expecting one image file name");
3180 filename
= argv
[optind
];
3182 if (output
&& !strcmp(output
, "json")) {
3183 output_format
= OFORMAT_JSON
;
3184 } else if (output
&& !strcmp(output
, "human")) {
3185 output_format
= OFORMAT_HUMAN
;
3186 } else if (output
) {
3187 error_report("--output must be used with human or json as argument.");
3191 if (qemu_opts_foreach(&qemu_object_opts
,
3192 user_creatable_add_opts_foreach
,
3193 qemu_img_object_print_help
, &error_fatal
)) {
3197 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3203 if (output_format
== OFORMAT_HUMAN
) {
3204 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3205 } else if (output_format
== OFORMAT_JSON
) {
3209 length
= blk_getlength(blk
);
3211 error_report("Failed to get size for '%s'", filename
);
3214 if (max_length
!= -1) {
3215 length
= MIN(start_offset
+ max_length
, length
);
3218 curr
.start
= start_offset
;
3219 while (curr
.start
+ curr
.length
< length
) {
3220 int64_t offset
= curr
.start
+ curr
.length
;
3223 /* Probe up to 1 GiB at a time. */
3224 n
= MIN(1 * GiB
, length
- offset
);
3225 ret
= get_block_status(bs
, offset
, n
, &next
);
3228 error_report("Could not read file metadata: %s", strerror(-ret
));
3232 if (entry_mergeable(&curr
, &next
)) {
3233 curr
.length
+= next
.length
;
3237 if (curr
.length
> 0) {
3238 ret
= dump_map_entry(output_format
, &curr
, &next
);
3246 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3247 if (output_format
== OFORMAT_JSON
) {
3256 #define SNAPSHOT_LIST 1
3257 #define SNAPSHOT_CREATE 2
3258 #define SNAPSHOT_APPLY 3
3259 #define SNAPSHOT_DELETE 4
3261 static int img_snapshot(int argc
, char **argv
)
3264 BlockDriverState
*bs
;
3265 QEMUSnapshotInfo sn
;
3266 char *filename
, *snapshot_name
= NULL
;
3267 int c
, ret
= 0, bdrv_oflags
;
3272 bool image_opts
= false;
3273 bool force_share
= false;
3275 bdrv_oflags
= BDRV_O_RDWR
;
3276 /* Parse commandline parameters */
3278 static const struct option long_options
[] = {
3279 {"help", no_argument
, 0, 'h'},
3280 {"object", required_argument
, 0, OPTION_OBJECT
},
3281 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3282 {"force-share", no_argument
, 0, 'U'},
3285 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3286 long_options
, NULL
);
3292 missing_argument(argv
[optind
- 1]);
3295 unrecognized_option(argv
[optind
- 1]);
3302 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3305 action
= SNAPSHOT_LIST
;
3306 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3310 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3313 action
= SNAPSHOT_APPLY
;
3314 snapshot_name
= optarg
;
3318 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3321 action
= SNAPSHOT_CREATE
;
3322 snapshot_name
= optarg
;
3326 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3329 action
= SNAPSHOT_DELETE
;
3330 snapshot_name
= optarg
;
3338 case OPTION_OBJECT
: {
3340 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3346 case OPTION_IMAGE_OPTS
:
3352 if (optind
!= argc
- 1) {
3353 error_exit("Expecting one image file name");
3355 filename
= argv
[optind
++];
3357 if (qemu_opts_foreach(&qemu_object_opts
,
3358 user_creatable_add_opts_foreach
,
3359 qemu_img_object_print_help
, &error_fatal
)) {
3363 /* Open the image */
3364 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3371 /* Perform the requested action */
3377 case SNAPSHOT_CREATE
:
3378 memset(&sn
, 0, sizeof(sn
));
3379 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3381 qemu_gettimeofday(&tv
);
3382 sn
.date_sec
= tv
.tv_sec
;
3383 sn
.date_nsec
= tv
.tv_usec
* 1000;
3385 ret
= bdrv_snapshot_create(bs
, &sn
);
3387 error_report("Could not create snapshot '%s': %d (%s)",
3388 snapshot_name
, ret
, strerror(-ret
));
3392 case SNAPSHOT_APPLY
:
3393 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3395 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3400 case SNAPSHOT_DELETE
:
3401 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3403 error_report("Could not delete snapshot '%s': snapshot not "
3404 "found", snapshot_name
);
3407 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3409 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3425 static int img_rebase(int argc
, char **argv
)
3427 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3428 uint8_t *buf_old
= NULL
;
3429 uint8_t *buf_new
= NULL
;
3430 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3432 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3433 int c
, flags
, src_flags
, ret
;
3434 bool writethrough
, src_writethrough
;
3436 bool force_share
= false;
3439 Error
*local_err
= NULL
;
3440 bool image_opts
= false;
3442 /* Parse commandline parameters */
3444 cache
= BDRV_DEFAULT_CACHE
;
3445 src_cache
= BDRV_DEFAULT_CACHE
;
3449 static const struct option long_options
[] = {
3450 {"help", no_argument
, 0, 'h'},
3451 {"object", required_argument
, 0, OPTION_OBJECT
},
3452 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3453 {"force-share", no_argument
, 0, 'U'},
3456 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3457 long_options
, NULL
);
3463 missing_argument(argv
[optind
- 1]);
3466 unrecognized_option(argv
[optind
- 1]);
3475 out_basefmt
= optarg
;
3478 out_baseimg
= optarg
;
3495 case OPTION_OBJECT
: {
3497 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3503 case OPTION_IMAGE_OPTS
:
3516 if (optind
!= argc
- 1) {
3517 error_exit("Expecting one image file name");
3519 if (!unsafe
&& !out_baseimg
) {
3520 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3522 filename
= argv
[optind
++];
3524 if (qemu_opts_foreach(&qemu_object_opts
,
3525 user_creatable_add_opts_foreach
,
3526 qemu_img_object_print_help
, &error_fatal
)) {
3530 qemu_progress_init(progress
, 2.0);
3531 qemu_progress_print(0, 100);
3533 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3534 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3536 error_report("Invalid cache option: %s", cache
);
3541 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3543 error_report("Invalid source cache option: %s", src_cache
);
3547 /* The source files are opened read-only, don't care about WCE */
3548 assert((src_flags
& BDRV_O_RDWR
) == 0);
3549 (void) src_writethrough
;
3554 * Ignore the old backing file for unsafe rebase in case we want to correct
3555 * the reference to a renamed or moved backing file.
3557 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3565 if (out_basefmt
!= NULL
) {
3566 if (bdrv_find_format(out_basefmt
) == NULL
) {
3567 error_report("Invalid format name: '%s'", out_basefmt
);
3573 /* For safe rebasing we need to compare old and new backing file */
3575 QDict
*options
= NULL
;
3576 BlockDriverState
*base_bs
= backing_bs(bs
);
3579 blk_old_backing
= blk_new(qemu_get_aio_context(),
3580 BLK_PERM_CONSISTENT_READ
,
3582 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3585 error_reportf_err(local_err
,
3586 "Could not reuse old backing file '%s': ",
3591 blk_old_backing
= NULL
;
3594 if (out_baseimg
[0]) {
3595 const char *overlay_filename
;
3596 char *out_real_path
;
3598 options
= qdict_new();
3600 qdict_put_str(options
, "driver", out_basefmt
);
3603 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3606 bdrv_refresh_filename(bs
);
3607 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3610 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3614 qobject_unref(options
);
3615 error_reportf_err(local_err
,
3616 "Could not resolve backing filename: ");
3622 * Find out whether we rebase an image on top of a previous image
3625 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3626 if (prefix_chain_bs
) {
3627 qobject_unref(options
);
3628 g_free(out_real_path
);
3630 blk_new_backing
= blk_new(qemu_get_aio_context(),
3631 BLK_PERM_CONSISTENT_READ
,
3633 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3636 error_reportf_err(local_err
,
3637 "Could not reuse backing file '%s': ",
3642 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3643 options
, src_flags
, &local_err
);
3644 g_free(out_real_path
);
3645 if (!blk_new_backing
) {
3646 error_reportf_err(local_err
,
3647 "Could not open new backing file '%s': ",
3657 * Check each unallocated cluster in the COW file. If it is unallocated,
3658 * accesses go to the backing file. We must therefore compare this cluster
3659 * in the old and new backing file, and if they differ we need to copy it
3660 * from the old backing file into the COW file.
3662 * If qemu-img crashes during this step, no harm is done. The content of
3663 * the image is the same as the original one at any time.
3667 int64_t old_backing_size
= 0;
3668 int64_t new_backing_size
= 0;
3671 float local_progress
= 0;
3673 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3674 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3676 size
= blk_getlength(blk
);
3678 error_report("Could not get size of '%s': %s",
3679 filename
, strerror(-size
));
3683 if (blk_old_backing
) {
3684 old_backing_size
= blk_getlength(blk_old_backing
);
3685 if (old_backing_size
< 0) {
3686 char backing_name
[PATH_MAX
];
3688 bdrv_get_backing_filename(bs
, backing_name
,
3689 sizeof(backing_name
));
3690 error_report("Could not get size of '%s': %s",
3691 backing_name
, strerror(-old_backing_size
));
3696 if (blk_new_backing
) {
3697 new_backing_size
= blk_getlength(blk_new_backing
);
3698 if (new_backing_size
< 0) {
3699 error_report("Could not get size of '%s': %s",
3700 out_baseimg
, strerror(-new_backing_size
));
3707 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3710 for (offset
= 0; offset
< size
; offset
+= n
) {
3711 bool buf_old_is_zero
= false;
3713 /* How many bytes can we handle with the next read? */
3714 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3716 /* If the cluster is allocated, we don't need to take action */
3717 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3719 error_report("error while reading image metadata: %s",
3727 if (prefix_chain_bs
) {
3729 * If cluster wasn't changed since prefix_chain, we don't need
3732 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3733 false, offset
, n
, &n
);
3735 error_report("error while reading image metadata: %s",
3745 * Read old and new backing file and take into consideration that
3746 * backing files may be smaller than the COW image.
3748 if (offset
>= old_backing_size
) {
3749 memset(buf_old
, 0, n
);
3750 buf_old_is_zero
= true;
3752 if (offset
+ n
> old_backing_size
) {
3753 n
= old_backing_size
- offset
;
3756 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3758 error_report("error while reading from old backing file");
3763 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3764 memset(buf_new
, 0, n
);
3766 if (offset
+ n
> new_backing_size
) {
3767 n
= new_backing_size
- offset
;
3770 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3772 error_report("error while reading from new backing file");
3777 /* If they differ, we need to write to the COW file */
3778 uint64_t written
= 0;
3780 while (written
< n
) {
3783 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3784 n
- written
, &pnum
))
3786 if (buf_old_is_zero
) {
3787 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3789 ret
= blk_pwrite(blk
, offset
+ written
,
3790 buf_old
+ written
, pnum
, 0);
3793 error_report("Error while writing to COW image: %s",
3801 qemu_progress_print(local_progress
, 100);
3806 * Change the backing file. All clusters that are different from the old
3807 * backing file are overwritten in the COW file now, so the visible content
3808 * doesn't change when we switch the backing file.
3810 if (out_baseimg
&& *out_baseimg
) {
3811 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3813 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3816 if (ret
== -ENOSPC
) {
3817 error_report("Could not change the backing file to '%s': No "
3818 "space left in the file header", out_baseimg
);
3819 } else if (ret
< 0) {
3820 error_report("Could not change the backing file to '%s': %s",
3821 out_baseimg
, strerror(-ret
));
3824 qemu_progress_print(100, 0);
3826 * TODO At this point it is possible to check if any clusters that are
3827 * allocated in the COW file are the same in the backing file. If so, they
3828 * could be dropped from the COW file. Don't do this before switching the
3829 * backing file, in case of a crash this would lead to corruption.
3832 qemu_progress_end();
3835 blk_unref(blk_old_backing
);
3836 blk_unref(blk_new_backing
);
3838 qemu_vfree(buf_old
);
3839 qemu_vfree(buf_new
);
3848 static int img_resize(int argc
, char **argv
)
3851 int c
, ret
, relative
;
3852 const char *filename
, *fmt
, *size
;
3853 int64_t n
, total_size
, current_size
;
3855 BlockBackend
*blk
= NULL
;
3856 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3859 static QemuOptsList resize_options
= {
3860 .name
= "resize_options",
3861 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3864 .name
= BLOCK_OPT_SIZE
,
3865 .type
= QEMU_OPT_SIZE
,
3866 .help
= "Virtual disk size"
3872 bool image_opts
= false;
3873 bool shrink
= false;
3875 /* Remove size from argv manually so that negative numbers are not treated
3876 * as options by getopt. */
3878 error_exit("Not enough arguments");
3882 size
= argv
[--argc
];
3884 /* Parse getopt arguments */
3887 static const struct option long_options
[] = {
3888 {"help", no_argument
, 0, 'h'},
3889 {"object", required_argument
, 0, OPTION_OBJECT
},
3890 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3891 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3892 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3895 c
= getopt_long(argc
, argv
, ":f:hq",
3896 long_options
, NULL
);
3902 missing_argument(argv
[optind
- 1]);
3905 unrecognized_option(argv
[optind
- 1]);
3916 case OPTION_OBJECT
: {
3918 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3924 case OPTION_IMAGE_OPTS
:
3927 case OPTION_PREALLOCATION
:
3928 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3929 PREALLOC_MODE__MAX
, NULL
);
3930 if (prealloc
== PREALLOC_MODE__MAX
) {
3931 error_report("Invalid preallocation mode '%s'", optarg
);
3940 if (optind
!= argc
- 1) {
3941 error_exit("Expecting image file name and size");
3943 filename
= argv
[optind
++];
3945 if (qemu_opts_foreach(&qemu_object_opts
,
3946 user_creatable_add_opts_foreach
,
3947 qemu_img_object_print_help
, &error_fatal
)) {
3951 /* Choose grow, shrink, or absolute resize mode */
3967 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3968 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3970 error_report_err(err
);
3972 qemu_opts_del(param
);
3975 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3976 qemu_opts_del(param
);
3978 blk
= img_open(image_opts
, filename
, fmt
,
3979 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3986 current_size
= blk_getlength(blk
);
3987 if (current_size
< 0) {
3988 error_report("Failed to inquire current image length: %s",
3989 strerror(-current_size
));
3995 total_size
= current_size
+ n
* relative
;
3999 if (total_size
<= 0) {
4000 error_report("New image size must be positive");
4005 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4006 error_report("Preallocation can only be used for growing images");
4011 if (total_size
< current_size
&& !shrink
) {
4012 warn_report("Shrinking an image will delete all data beyond the "
4013 "shrunken image's end. Before performing such an "
4014 "operation, make sure there is no important data there.");
4016 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
4018 "Use the --shrink option to perform a shrink operation.");
4022 warn_report("Using the --shrink option will suppress this message. "
4023 "Note that future versions of qemu-img may refuse to "
4024 "shrink images without this option.");
4029 * The user expects the image to have the desired size after
4030 * resizing, so pass @exact=true. It is of no use to report
4031 * success when the image has not actually been resized.
4033 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4035 qprintf(quiet
, "Image resized.\n");
4037 error_report_err(err
);
4047 static void amend_status_cb(BlockDriverState
*bs
,
4048 int64_t offset
, int64_t total_work_size
,
4051 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4054 static int print_amend_option_help(const char *format
)
4058 /* Find driver and parse its options */
4059 drv
= bdrv_find_format(format
);
4061 error_report("Unknown file format '%s'", format
);
4065 if (!drv
->bdrv_amend_options
) {
4066 error_report("Format driver '%s' does not support option amendment",
4071 /* Every driver supporting amendment must have amend_opts */
4072 assert(drv
->amend_opts
);
4074 printf("Creation options for '%s':\n", format
);
4075 qemu_opts_print_help(drv
->amend_opts
, false);
4076 printf("\nNote that not all of these options may be amendable.\n");
4080 static int img_amend(int argc
, char **argv
)
4084 char *options
= NULL
;
4085 QemuOptsList
*amend_opts
= NULL
;
4086 QemuOpts
*opts
= NULL
;
4087 const char *fmt
= NULL
, *filename
, *cache
;
4090 bool quiet
= false, progress
= false;
4091 BlockBackend
*blk
= NULL
;
4092 BlockDriverState
*bs
= NULL
;
4093 bool image_opts
= false;
4096 cache
= BDRV_DEFAULT_CACHE
;
4098 static const struct option long_options
[] = {
4099 {"help", no_argument
, 0, 'h'},
4100 {"object", required_argument
, 0, OPTION_OBJECT
},
4101 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4102 {"force", no_argument
, 0, OPTION_FORCE
},
4105 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4106 long_options
, NULL
);
4113 missing_argument(argv
[optind
- 1]);
4116 unrecognized_option(argv
[optind
- 1]);
4122 if (accumulate_options(&options
, optarg
) < 0) {
4124 goto out_no_progress
;
4140 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4144 goto out_no_progress
;
4147 case OPTION_IMAGE_OPTS
:
4157 error_exit("Must specify options (-o)");
4160 if (qemu_opts_foreach(&qemu_object_opts
,
4161 user_creatable_add_opts_foreach
,
4162 qemu_img_object_print_help
, &error_fatal
)) {
4164 goto out_no_progress
;
4170 qemu_progress_init(progress
, 1.0);
4172 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4173 if (fmt
&& has_help_option(options
)) {
4174 /* If a format is explicitly specified (and possibly no filename is
4175 * given), print option help here */
4176 ret
= print_amend_option_help(fmt
);
4180 if (optind
!= argc
- 1) {
4181 error_report("Expecting one image file name");
4186 flags
= BDRV_O_RDWR
;
4187 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4189 error_report("Invalid cache option: %s", cache
);
4193 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4201 fmt
= bs
->drv
->format_name
;
4203 if (has_help_option(options
)) {
4204 /* If the format was auto-detected, print option help here */
4205 ret
= print_amend_option_help(fmt
);
4209 if (!bs
->drv
->bdrv_amend_options
) {
4210 error_report("Format driver '%s' does not support option amendment",
4216 /* Every driver supporting amendment must have amend_opts */
4217 assert(bs
->drv
->amend_opts
);
4219 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4220 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4221 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4223 error_report_err(err
);
4228 /* In case the driver does not call amend_status_cb() */
4229 qemu_progress_print(0.f
, 0);
4230 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4231 qemu_progress_print(100.f
, 0);
4233 error_report_err(err
);
4238 qemu_progress_end();
4242 qemu_opts_del(opts
);
4243 qemu_opts_free(amend_opts
);
4252 typedef struct BenchData
{
4254 uint64_t image_size
;
4261 bool drain_on_flush
;
4270 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4273 error_report("Failed flush request: %s", strerror(-ret
));
4278 static void bench_cb(void *opaque
, int ret
)
4280 BenchData
*b
= opaque
;
4284 error_report("Failed request: %s", strerror(-ret
));
4289 /* Just finished a flush with drained queue: Start next requests */
4290 assert(b
->in_flight
== 0);
4291 b
->in_flush
= false;
4292 } else if (b
->in_flight
> 0) {
4293 int remaining
= b
->n
- b
->in_flight
;
4298 /* Time for flush? Drain queue if requested, then flush */
4299 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4300 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4301 BlockCompletionFunc
*cb
;
4303 if (b
->drain_on_flush
) {
4307 cb
= bench_undrained_flush_cb
;
4310 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4312 error_report("Failed to issue flush request");
4316 if (b
->drain_on_flush
) {
4322 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4323 int64_t offset
= b
->offset
;
4324 /* blk_aio_* might look for completed I/Os and kick bench_cb
4325 * again, so make sure this operation is counted by in_flight
4326 * and b->offset is ready for the next submission.
4329 b
->offset
+= b
->step
;
4330 b
->offset
%= b
->image_size
;
4332 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4334 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4337 error_report("Failed to issue request");
4343 static int img_bench(int argc
, char **argv
)
4346 const char *fmt
= NULL
, *filename
;
4348 bool image_opts
= false;
4349 bool is_write
= false;
4353 size_t bufsize
= 4096;
4356 int flush_interval
= 0;
4357 bool drain_on_flush
= true;
4359 BlockBackend
*blk
= NULL
;
4360 BenchData data
= {};
4362 bool writethrough
= false;
4363 struct timeval t1
, t2
;
4365 bool force_share
= false;
4369 static const struct option long_options
[] = {
4370 {"help", no_argument
, 0, 'h'},
4371 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4372 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4373 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4374 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4375 {"force-share", no_argument
, 0, 'U'},
4378 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4386 missing_argument(argv
[optind
- 1]);
4389 unrecognized_option(argv
[optind
- 1]);
4398 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4399 error_report("Invalid request count specified");
4409 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4410 error_report("Invalid queue depth specified");
4420 flags
|= BDRV_O_NATIVE_AIO
;
4423 ret
= bdrv_parse_aio(optarg
, &flags
);
4425 error_report("Invalid aio option: %s", optarg
);
4432 offset
= cvtnum("offset", optarg
);
4446 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4458 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4467 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4469 error_report("Invalid cache mode");
4475 flags
|= BDRV_O_RDWR
;
4481 case OPTION_PATTERN
:
4485 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4486 error_report("Invalid pattern byte specified");
4492 case OPTION_FLUSH_INTERVAL
:
4496 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4497 error_report("Invalid flush interval specified");
4500 flush_interval
= res
;
4503 case OPTION_NO_DRAIN
:
4504 drain_on_flush
= false;
4506 case OPTION_IMAGE_OPTS
:
4512 if (optind
!= argc
- 1) {
4513 error_exit("Expecting one image file name");
4515 filename
= argv
[argc
- 1];
4517 if (!is_write
&& flush_interval
) {
4518 error_report("--flush-interval is only available in write tests");
4522 if (flush_interval
&& flush_interval
< depth
) {
4523 error_report("Flush interval can't be smaller than depth");
4528 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4535 image_size
= blk_getlength(blk
);
4536 if (image_size
< 0) {
4541 data
= (BenchData
) {
4543 .image_size
= image_size
,
4545 .step
= step
?: bufsize
,
4550 .flush_interval
= flush_interval
,
4551 .drain_on_flush
= drain_on_flush
,
4553 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4554 "(starting at offset %" PRId64
", step size %d)\n",
4555 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4556 data
.offset
, data
.step
);
4557 if (flush_interval
) {
4558 printf("Sending flush every %d requests\n", flush_interval
);
4561 buf_size
= data
.nrreq
* data
.bufsize
;
4562 data
.buf
= blk_blockalign(blk
, buf_size
);
4563 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4565 blk_register_buf(blk
, data
.buf
, buf_size
);
4567 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4568 for (i
= 0; i
< data
.nrreq
; i
++) {
4569 qemu_iovec_init(&data
.qiov
[i
], 1);
4570 qemu_iovec_add(&data
.qiov
[i
],
4571 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4574 gettimeofday(&t1
, NULL
);
4577 while (data
.n
> 0) {
4578 main_loop_wait(false);
4580 gettimeofday(&t2
, NULL
);
4582 printf("Run completed in %3.3f seconds.\n",
4583 (t2
.tv_sec
- t1
.tv_sec
)
4584 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4588 blk_unregister_buf(blk
, data
.buf
);
4590 qemu_vfree(data
.buf
);
4607 typedef struct ImgBitmapAction
{
4608 enum ImgBitmapAct act
;
4609 const char *src
; /* only used for merge */
4610 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4613 static int img_bitmap(int argc
, char **argv
)
4617 QemuOpts
*opts
= NULL
;
4618 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4619 const char *filename
, *bitmap
;
4620 BlockBackend
*blk
= NULL
, *src
= NULL
;
4621 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4622 bool image_opts
= false;
4623 int64_t granularity
= 0;
4624 bool add
= false, merge
= false;
4625 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4626 ImgBitmapAction
*act
, *act_next
;
4629 QSIMPLEQ_INIT(&actions
);
4632 static const struct option long_options
[] = {
4633 {"help", no_argument
, 0, 'h'},
4634 {"object", required_argument
, 0, OPTION_OBJECT
},
4635 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4636 {"add", no_argument
, 0, OPTION_ADD
},
4637 {"remove", no_argument
, 0, OPTION_REMOVE
},
4638 {"clear", no_argument
, 0, OPTION_CLEAR
},
4639 {"enable", no_argument
, 0, OPTION_ENABLE
},
4640 {"disable", no_argument
, 0, OPTION_DISABLE
},
4641 {"merge", required_argument
, 0, OPTION_MERGE
},
4642 {"granularity", required_argument
, 0, 'g'},
4643 {"source-file", required_argument
, 0, 'b'},
4644 {"source-format", required_argument
, 0, 'F'},
4647 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4654 missing_argument(argv
[optind
- 1]);
4657 unrecognized_option(argv
[optind
- 1]);
4663 src_filename
= optarg
;
4672 granularity
= cvtnum("granularity", optarg
);
4673 if (granularity
< 0) {
4678 act
= g_new0(ImgBitmapAction
, 1);
4679 act
->act
= BITMAP_ADD
;
4680 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4684 act
= g_new0(ImgBitmapAction
, 1);
4685 act
->act
= BITMAP_REMOVE
;
4686 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4689 act
= g_new0(ImgBitmapAction
, 1);
4690 act
->act
= BITMAP_CLEAR
;
4691 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4694 act
= g_new0(ImgBitmapAction
, 1);
4695 act
->act
= BITMAP_ENABLE
;
4696 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4698 case OPTION_DISABLE
:
4699 act
= g_new0(ImgBitmapAction
, 1);
4700 act
->act
= BITMAP_DISABLE
;
4701 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4704 act
= g_new0(ImgBitmapAction
, 1);
4705 act
->act
= BITMAP_MERGE
;
4707 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4711 opts
= qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true);
4716 case OPTION_IMAGE_OPTS
:
4722 if (qemu_opts_foreach(&qemu_object_opts
,
4723 user_creatable_add_opts_foreach
,
4724 qemu_img_object_print_help
, &error_fatal
)) {
4728 if (QSIMPLEQ_EMPTY(&actions
)) {
4729 error_report("Need at least one of --add, --remove, --clear, "
4730 "--enable, --disable, or --merge");
4734 if (granularity
&& !add
) {
4735 error_report("granularity only supported with --add");
4738 if (src_fmt
&& !src_filename
) {
4739 error_report("-F only supported with -b");
4742 if (src_filename
&& !merge
) {
4743 error_report("Merge bitmap source file only supported with "
4748 if (optind
!= argc
- 2) {
4749 error_report("Expecting filename and bitmap name");
4753 filename
= argv
[optind
];
4754 bitmap
= argv
[optind
+ 1];
4756 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
, false, false,
4763 src
= img_open(false, src_filename
, src_fmt
, 0, false, false, false);
4767 src_bs
= blk_bs(src
);
4772 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4775 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4776 !!granularity
, granularity
, true, true,
4777 false, false, &err
);
4781 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4785 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4789 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4792 case BITMAP_DISABLE
:
4793 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4797 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4802 g_assert_not_reached();
4806 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4818 qemu_opts_del(opts
);
4834 int bsz
; /* Block size */
4842 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4846 static int img_dd_bs(const char *arg
,
4847 struct DdIo
*in
, struct DdIo
*out
,
4852 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4857 in
->bsz
= out
->bsz
= res
;
4862 static int img_dd_count(const char *arg
,
4863 struct DdIo
*in
, struct DdIo
*out
,
4866 dd
->count
= cvtnum("count", arg
);
4868 if (dd
->count
< 0) {
4875 static int img_dd_if(const char *arg
,
4876 struct DdIo
*in
, struct DdIo
*out
,
4879 in
->filename
= g_strdup(arg
);
4884 static int img_dd_of(const char *arg
,
4885 struct DdIo
*in
, struct DdIo
*out
,
4888 out
->filename
= g_strdup(arg
);
4893 static int img_dd_skip(const char *arg
,
4894 struct DdIo
*in
, struct DdIo
*out
,
4897 in
->offset
= cvtnum("skip", arg
);
4899 if (in
->offset
< 0) {
4906 static int img_dd(int argc
, char **argv
)
4911 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4912 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4913 QemuOpts
*opts
= NULL
;
4914 QemuOptsList
*create_opts
= NULL
;
4915 Error
*local_err
= NULL
;
4916 bool image_opts
= false;
4918 const char *out_fmt
= "raw";
4919 const char *fmt
= NULL
;
4921 int64_t block_count
= 0, out_pos
, in_pos
;
4922 bool force_share
= false;
4923 struct DdInfo dd
= {
4928 .bsz
= 512, /* Block size is by default 512 bytes */
4940 const struct DdOpts options
[] = {
4941 { "bs", img_dd_bs
, C_BS
},
4942 { "count", img_dd_count
, C_COUNT
},
4943 { "if", img_dd_if
, C_IF
},
4944 { "of", img_dd_of
, C_OF
},
4945 { "skip", img_dd_skip
, C_SKIP
},
4948 const struct option long_options
[] = {
4949 { "help", no_argument
, 0, 'h'},
4950 { "object", required_argument
, 0, OPTION_OBJECT
},
4951 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4952 { "force-share", no_argument
, 0, 'U'},
4956 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4968 missing_argument(argv
[optind
- 1]);
4971 unrecognized_option(argv
[optind
- 1]);
4980 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4985 case OPTION_IMAGE_OPTS
:
4991 for (i
= optind
; i
< argc
; i
++) {
4993 arg
= g_strdup(argv
[i
]);
4995 tmp
= strchr(arg
, '=');
4997 error_report("unrecognized operand %s", arg
);
5004 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5005 if (!strcmp(arg
, options
[j
].name
)) {
5009 if (options
[j
].name
== NULL
) {
5010 error_report("unrecognized operand %s", arg
);
5015 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5019 dd
.flags
|= options
[j
].flag
;
5024 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5025 error_report("Must specify both input and output files");
5030 if (qemu_opts_foreach(&qemu_object_opts
,
5031 user_creatable_add_opts_foreach
,
5032 qemu_img_object_print_help
, &error_fatal
)) {
5037 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5045 drv
= bdrv_find_format(out_fmt
);
5047 error_report("Unknown file format");
5051 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5054 error_report_err(local_err
);
5058 if (!drv
->create_opts
) {
5059 error_report("Format driver '%s' does not support image creation",
5064 if (!proto_drv
->create_opts
) {
5065 error_report("Protocol driver '%s' does not support image creation",
5066 proto_drv
->format_name
);
5070 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5071 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5073 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5075 size
= blk_getlength(blk1
);
5077 error_report("Failed to get size for '%s'", in
.filename
);
5082 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5083 dd
.count
* in
.bsz
< size
) {
5084 size
= dd
.count
* in
.bsz
;
5087 /* Overflow means the specified offset is beyond input image's size */
5088 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5089 size
< in
.bsz
* in
.offset
)) {
5090 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5092 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5093 size
- in
.bsz
* in
.offset
, &error_abort
);
5096 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5098 error_reportf_err(local_err
,
5099 "%s: error while creating output image: ",
5105 /* TODO, we can't honour --image-opts for the target,
5106 * since it needs to be given in a format compatible
5107 * with the bdrv_create() call above which does not
5108 * support image-opts style.
5110 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5111 false, false, false);
5118 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5119 size
< in
.offset
* in
.bsz
)) {
5120 /* We give a warning if the skip option is bigger than the input
5121 * size and create an empty output disk image (i.e. like dd(1)).
5123 error_report("%s: cannot skip to specified offset", in
.filename
);
5126 in_pos
= in
.offset
* in
.bsz
;
5129 in
.buf
= g_new(uint8_t, in
.bsz
);
5131 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5132 int in_ret
, out_ret
;
5134 if (in_pos
+ in
.bsz
> size
) {
5135 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5137 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5140 error_report("error while reading from input image file: %s",
5147 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5150 error_report("error while writing to output image file: %s",
5151 strerror(-out_ret
));
5160 qemu_opts_del(opts
);
5161 qemu_opts_free(create_opts
);
5164 g_free(in
.filename
);
5165 g_free(out
.filename
);
5175 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5179 Visitor
*v
= qobject_output_visitor_new(&obj
);
5181 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5182 visit_complete(v
, &obj
);
5183 str
= qobject_to_json_pretty(obj
);
5184 assert(str
!= NULL
);
5185 printf("%s\n", qstring_get_str(str
));
5191 static int img_measure(int argc
, char **argv
)
5193 static const struct option long_options
[] = {
5194 {"help", no_argument
, 0, 'h'},
5195 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5196 {"object", required_argument
, 0, OPTION_OBJECT
},
5197 {"output", required_argument
, 0, OPTION_OUTPUT
},
5198 {"size", required_argument
, 0, OPTION_SIZE
},
5199 {"force-share", no_argument
, 0, 'U'},
5202 OutputFormat output_format
= OFORMAT_HUMAN
;
5203 BlockBackend
*in_blk
= NULL
;
5205 const char *filename
= NULL
;
5206 const char *fmt
= NULL
;
5207 const char *out_fmt
= "raw";
5208 char *options
= NULL
;
5209 char *snapshot_name
= NULL
;
5210 bool force_share
= false;
5211 QemuOpts
*opts
= NULL
;
5212 QemuOpts
*object_opts
= NULL
;
5213 QemuOpts
*sn_opts
= NULL
;
5214 QemuOptsList
*create_opts
= NULL
;
5215 bool image_opts
= false;
5216 uint64_t img_size
= UINT64_MAX
;
5217 BlockMeasureInfo
*info
= NULL
;
5218 Error
*local_err
= NULL
;
5222 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5223 long_options
, NULL
)) != -1) {
5236 if (accumulate_options(&options
, optarg
) < 0) {
5241 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5242 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5245 error_report("Failed in parsing snapshot param '%s'",
5250 snapshot_name
= optarg
;
5257 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
5263 case OPTION_IMAGE_OPTS
:
5267 if (!strcmp(optarg
, "json")) {
5268 output_format
= OFORMAT_JSON
;
5269 } else if (!strcmp(optarg
, "human")) {
5270 output_format
= OFORMAT_HUMAN
;
5272 error_report("--output must be used with human or json "
5281 sval
= cvtnum("image size", optarg
);
5285 img_size
= (uint64_t)sval
;
5291 if (qemu_opts_foreach(&qemu_object_opts
,
5292 user_creatable_add_opts_foreach
,
5293 qemu_img_object_print_help
, &error_fatal
)) {
5297 if (argc
- optind
> 1) {
5298 error_report("At most one filename argument is allowed.");
5300 } else if (argc
- optind
== 1) {
5301 filename
= argv
[optind
];
5304 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5305 error_report("--image-opts, -f, and -l require a filename argument.");
5308 if (filename
&& img_size
!= UINT64_MAX
) {
5309 error_report("--size N cannot be used together with a filename.");
5312 if (!filename
&& img_size
== UINT64_MAX
) {
5313 error_report("Either --size N or one filename must be specified.");
5318 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5319 false, false, force_share
);
5325 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5326 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5327 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5329 } else if (snapshot_name
!= NULL
) {
5330 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5331 snapshot_name
, &local_err
);
5334 error_reportf_err(local_err
, "Failed to load snapshot: ");
5339 drv
= bdrv_find_format(out_fmt
);
5341 error_report("Unknown file format '%s'", out_fmt
);
5344 if (!drv
->create_opts
) {
5345 error_report("Format driver '%s' does not support image creation",
5350 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5351 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5352 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5354 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
5356 error_report_err(local_err
);
5357 error_report("Invalid options for file format '%s'", out_fmt
);
5361 if (img_size
!= UINT64_MAX
) {
5362 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5365 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5367 error_report_err(local_err
);
5371 if (output_format
== OFORMAT_HUMAN
) {
5372 printf("required size: %" PRIu64
"\n", info
->required
);
5373 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5374 if (info
->has_bitmaps
) {
5375 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5378 dump_json_block_measure_info(info
);
5384 qapi_free_BlockMeasureInfo(info
);
5385 qemu_opts_del(object_opts
);
5386 qemu_opts_del(opts
);
5387 qemu_opts_del(sn_opts
);
5388 qemu_opts_free(create_opts
);
5394 static const img_cmd_t img_cmds
[] = {
5395 #define DEF(option, callback, arg_string) \
5396 { option, callback },
5397 #include "qemu-img-cmds.h"
5402 int main(int argc
, char **argv
)
5404 const img_cmd_t
*cmd
;
5405 const char *cmdname
;
5406 Error
*local_error
= NULL
;
5407 char *trace_file
= NULL
;
5409 static const struct option long_options
[] = {
5410 {"help", no_argument
, 0, 'h'},
5411 {"version", no_argument
, 0, 'V'},
5412 {"trace", required_argument
, NULL
, 'T'},
5417 signal(SIGPIPE
, SIG_IGN
);
5420 error_init(argv
[0]);
5421 module_call_init(MODULE_INIT_TRACE
);
5422 qemu_init_exec_dir(argv
[0]);
5424 if (qemu_init_main_loop(&local_error
)) {
5425 error_report_err(local_error
);
5429 qcrypto_init(&error_fatal
);
5431 module_call_init(MODULE_INIT_QOM
);
5434 error_exit("Not enough arguments");
5437 qemu_add_opts(&qemu_object_opts
);
5438 qemu_add_opts(&qemu_source_opts
);
5439 qemu_add_opts(&qemu_trace_opts
);
5441 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5444 missing_argument(argv
[optind
- 1]);
5447 unrecognized_option(argv
[optind
- 1]);
5453 printf(QEMU_IMG_VERSION
);
5457 trace_file
= trace_opt_parse(optarg
);
5462 cmdname
= argv
[optind
];
5464 /* reset getopt_long scanning */
5470 qemu_reset_optind();
5472 if (!trace_init_backends()) {
5475 trace_init_file(trace_file
);
5476 qemu_set_log(LOG_TRACE
);
5478 /* find the command */
5479 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5480 if (!strcmp(cmdname
, cmd
->name
)) {
5481 return cmd
->handler(argc
, argv
);
5486 error_exit("Command not found: %s", cmdname
);