2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/sockets.h"
44 #include "qemu/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
52 #include "qemu/throttle.h"
53 #include "block/throttle-groups.h"
55 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
56 "\n" QEMU_COPYRIGHT "\n"
58 typedef struct img_cmd_t
{
60 int (*handler
)(int argc
, char **argv
);
65 OPTION_BACKING_CHAIN
= 257,
67 OPTION_IMAGE_OPTS
= 259,
69 OPTION_FLUSH_INTERVAL
= 261,
70 OPTION_NO_DRAIN
= 262,
71 OPTION_TARGET_IMAGE_OPTS
= 263,
73 OPTION_PREALLOCATION
= 265,
76 OPTION_TARGET_IS_ZERO
= 268,
85 OPTION_SKIP_BROKEN
= 277,
88 typedef enum OutputFormat
{
93 /* Default to cache=writeback as data integrity is not important for qemu-img */
94 #define BDRV_DEFAULT_CACHE "writeback"
96 static void format_print(void *opaque
, const char *name
)
101 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
106 error_vreport(fmt
, ap
);
109 error_printf("Try 'qemu-img --help' for more information\n");
113 static void QEMU_NORETURN
missing_argument(const char *option
)
115 error_exit("missing argument for option '%s'", option
);
118 static void QEMU_NORETURN
unrecognized_option(const char *option
)
120 error_exit("unrecognized option '%s'", option
);
123 /* Please keep in synch with docs/tools/qemu-img.rst */
124 static void QEMU_NORETURN
help(void)
126 const char *help_msg
=
128 "usage: qemu-img [standard options] command [command options]\n"
129 "QEMU disk image utility\n"
131 " '-h', '--help' display this help and exit\n"
132 " '-V', '--version' output version information and exit\n"
133 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
134 " specify tracing options\n"
137 #define DEF(option, callback, arg_string) \
139 #include "qemu-img-cmds.h"
142 "Command parameters:\n"
143 " 'filename' is a disk image filename\n"
144 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
145 " manual page for a description of the object properties. The most common\n"
146 " object type is a 'secret', which is used to supply passwords and/or\n"
147 " encryption keys.\n"
148 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
149 " 'cache' is the cache mode used to write the output disk image, the valid\n"
150 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
151 " 'directsync' and 'unsafe' (default for convert)\n"
152 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
153 " options are the same as for the 'cache' option\n"
154 " 'size' is the disk image size in bytes. Optional suffixes\n"
155 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
156 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
157 " supported. 'b' is ignored.\n"
158 " 'output_filename' is the destination disk image filename\n"
159 " 'output_fmt' is the destination format\n"
160 " 'options' is a comma separated list of format specific options in a\n"
161 " name=value format. Use -o ? for an overview of the options supported by the\n"
163 " 'snapshot_param' is param used for internal snapshot, format\n"
164 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
166 " '-c' indicates that target image must be compressed (qcow format only)\n"
167 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
168 " new backing file match exactly. The image doesn't need a working\n"
169 " backing file before rebasing in this case (useful for renaming the\n"
170 " backing file). For image creation, allow creating without attempting\n"
171 " to open the backing file.\n"
172 " '-h' with or without a command shows this help and lists the supported formats\n"
173 " '-p' show progress of command (only certain commands)\n"
174 " '-q' use Quiet mode - do not print any output (except errors)\n"
175 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
176 " contain only zeros for qemu-img to create a sparse image during\n"
177 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
178 " unallocated or zero sectors, and the destination image will always be\n"
180 " '--output' takes the format in which the output must be done (human or json)\n"
181 " '-n' skips the target volume creation (useful if the volume is created\n"
182 " prior to running qemu-img)\n"
184 "Parameters to bitmap subcommand:\n"
185 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
186 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
187 " or '--merge source'\n"
188 " '-g granularity' sets the granularity for '--add' actions\n"
189 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
190 " bitmaps from an alternative file\n"
192 "Parameters to check subcommand:\n"
193 " '-r' tries to repair any inconsistencies that are found during the check.\n"
194 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
195 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
196 " hiding corruption that has already occurred.\n"
198 "Parameters to convert subcommand:\n"
199 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
200 " '-m' specifies how many coroutines work in parallel during the convert\n"
201 " process (defaults to 8)\n"
202 " '-W' allow to write to the target out of order rather than sequential\n"
204 "Parameters to snapshot subcommand:\n"
205 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
206 " '-a' applies a snapshot (revert disk to saved state)\n"
207 " '-c' creates a snapshot\n"
208 " '-d' deletes a snapshot\n"
209 " '-l' lists all snapshots in the given image\n"
211 "Parameters to compare subcommand:\n"
212 " '-f' first image format\n"
213 " '-F' second image format\n"
214 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
216 "Parameters to dd subcommand:\n"
217 " 'bs=BYTES' read and write up to BYTES bytes at a time "
219 " 'count=N' copy only N input blocks\n"
220 " 'if=FILE' read from FILE\n"
221 " 'of=FILE' write to FILE\n"
222 " 'skip=N' skip N bs-sized blocks at the start of input\n";
224 printf("%s\nSupported formats:", help_msg
);
225 bdrv_iterate_format(format_print
, NULL
, false);
226 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
231 * Is @optarg safe for accumulate_options()?
232 * It is when multiple of them can be joined together separated by ','.
233 * To make that work, @optarg must not start with ',' (or else a
234 * separating ',' preceding it gets escaped), and it must not end with
235 * an odd number of ',' (or else a separating ',' following it gets
236 * escaped), or be empty (or else a separating ',' preceding it can
237 * escape a separating ',' following it).
240 static bool is_valid_option_list(const char *optarg
)
242 size_t len
= strlen(optarg
);
245 if (!optarg
[0] || optarg
[0] == ',') {
249 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
258 static int accumulate_options(char **options
, char *optarg
)
262 if (!is_valid_option_list(optarg
)) {
263 error_report("Invalid option list: %s", optarg
);
268 *options
= g_strdup(optarg
);
270 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
272 *options
= new_options
;
277 static QemuOptsList qemu_source_opts
= {
279 .implied_opt_name
= "file",
280 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
286 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
292 ret
= vprintf(fmt
, args
);
299 static int print_block_option_help(const char *filename
, const char *fmt
)
301 BlockDriver
*drv
, *proto_drv
;
302 QemuOptsList
*create_opts
= NULL
;
303 Error
*local_err
= NULL
;
305 /* Find driver and parse its options */
306 drv
= bdrv_find_format(fmt
);
308 error_report("Unknown file format '%s'", fmt
);
312 if (!drv
->create_opts
) {
313 error_report("Format driver '%s' does not support image creation", fmt
);
317 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
319 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
321 error_report_err(local_err
);
322 qemu_opts_free(create_opts
);
325 if (!proto_drv
->create_opts
) {
326 error_report("Protocol driver '%s' does not support image creation",
327 proto_drv
->format_name
);
328 qemu_opts_free(create_opts
);
331 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
335 printf("Supported options:\n");
337 printf("Supported %s options:\n", fmt
);
339 qemu_opts_print_help(create_opts
, false);
340 qemu_opts_free(create_opts
);
344 "The protocol level may support further options.\n"
345 "Specify the target filename to include those options.\n");
352 static BlockBackend
*img_open_opts(const char *optstr
,
353 QemuOpts
*opts
, int flags
, bool writethrough
,
354 bool quiet
, bool force_share
)
357 Error
*local_err
= NULL
;
359 options
= qemu_opts_to_qdict(opts
, NULL
);
361 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
362 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
363 error_report("--force-share/-U conflicts with image options");
364 qobject_unref(options
);
367 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
369 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
371 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
374 blk_set_enable_write_cache(blk
, !writethrough
);
379 static BlockBackend
*img_open_file(const char *filename
,
381 const char *fmt
, int flags
,
382 bool writethrough
, bool quiet
,
386 Error
*local_err
= NULL
;
389 options
= qdict_new();
392 qdict_put_str(options
, "driver", fmt
);
396 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
398 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
400 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
403 blk_set_enable_write_cache(blk
, !writethrough
);
409 static int img_add_key_secrets(void *opaque
,
410 const char *name
, const char *value
,
413 QDict
*options
= opaque
;
415 if (g_str_has_suffix(name
, "key-secret")) {
416 qdict_put_str(options
, name
, value
);
423 static BlockBackend
*img_open(bool image_opts
,
424 const char *filename
,
425 const char *fmt
, int flags
, bool writethrough
,
426 bool quiet
, bool force_share
)
432 error_report("--image-opts and --format are mutually exclusive");
435 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
440 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
443 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
450 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
451 const char *base_filename
,
452 const char *base_fmt
)
455 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
457 error_report("Backing file not supported for file format '%s'",
463 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
464 error_report("Backing file format not supported for file "
472 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
478 err
= qemu_strtosz(value
, NULL
, &res
);
479 if (err
< 0 && err
!= -ERANGE
) {
480 error_report("Invalid %s specified. You may use "
481 "k, M, G, T, P or E suffixes for", name
);
482 error_report("kilobytes, megabytes, gigabytes, terabytes, "
483 "petabytes and exabytes.");
486 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
487 error_report("Invalid %s specified. Must be between %" PRId64
488 " and %" PRId64
".", name
, min
, max
);
494 static int64_t cvtnum(const char *name
, const char *value
)
496 return cvtnum_full(name
, value
, 0, INT64_MAX
);
499 static int img_create(int argc
, char **argv
)
502 uint64_t img_size
= -1;
503 const char *fmt
= "raw";
504 const char *base_fmt
= NULL
;
505 const char *filename
;
506 const char *base_filename
= NULL
;
507 char *options
= NULL
;
508 Error
*local_err
= NULL
;
513 static const struct option long_options
[] = {
514 {"help", no_argument
, 0, 'h'},
515 {"object", required_argument
, 0, OPTION_OBJECT
},
518 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
525 missing_argument(argv
[optind
- 1]);
528 unrecognized_option(argv
[optind
- 1]);
537 base_filename
= optarg
;
543 if (accumulate_options(&options
, optarg
) < 0) {
551 flags
|= BDRV_O_NO_BACKING
;
554 user_creatable_process_cmdline(optarg
);
559 /* Get the filename */
560 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
561 if (options
&& has_help_option(options
)) {
563 return print_block_option_help(filename
, fmt
);
566 if (optind
>= argc
) {
567 error_exit("Expecting image file name");
571 /* Get image size, if specified */
575 sval
= cvtnum("image size", argv
[optind
++]);
579 img_size
= (uint64_t)sval
;
581 if (optind
!= argc
) {
582 error_exit("Unexpected argument: %s", argv
[optind
]);
585 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
586 options
, img_size
, flags
, quiet
, &local_err
);
588 error_reportf_err(local_err
, "%s: ", filename
);
600 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
604 Visitor
*v
= qobject_output_visitor_new(&obj
);
606 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
607 visit_complete(v
, &obj
);
608 str
= qobject_to_json_pretty(obj
, true);
610 qprintf(quiet
, "%s\n", str
->str
);
613 g_string_free(str
, true);
616 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
618 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
619 qprintf(quiet
, "No errors were found on the image.\n");
621 if (check
->corruptions
) {
622 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
623 "Data may be corrupted, or further writes to the image "
630 "\n%" PRId64
" leaked clusters were found on the image.\n"
631 "This means waste of disk space, but no harm to data.\n",
635 if (check
->check_errors
) {
638 " internal errors have occurred during the check.\n",
639 check
->check_errors
);
643 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
644 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
645 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
646 check
->allocated_clusters
, check
->total_clusters
,
647 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
648 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
649 check
->compressed_clusters
* 100.0 /
650 check
->allocated_clusters
);
653 if (check
->image_end_offset
) {
655 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
659 static int collect_image_check(BlockDriverState
*bs
,
661 const char *filename
,
666 BdrvCheckResult result
;
668 ret
= bdrv_check(bs
, &result
, fix
);
673 check
->filename
= g_strdup(filename
);
674 check
->format
= g_strdup(bdrv_get_format_name(bs
));
675 check
->check_errors
= result
.check_errors
;
676 check
->corruptions
= result
.corruptions
;
677 check
->has_corruptions
= result
.corruptions
!= 0;
678 check
->leaks
= result
.leaks
;
679 check
->has_leaks
= result
.leaks
!= 0;
680 check
->corruptions_fixed
= result
.corruptions_fixed
;
681 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
682 check
->leaks_fixed
= result
.leaks_fixed
;
683 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
684 check
->image_end_offset
= result
.image_end_offset
;
685 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
686 check
->total_clusters
= result
.bfi
.total_clusters
;
687 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
688 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
689 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
690 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
691 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
692 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
693 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
699 * Checks an image for consistency. Exit codes:
701 * 0 - Check completed, image is good
702 * 1 - Check not completed because of internal errors
703 * 2 - Check completed, image is corrupted
704 * 3 - Check completed, image has leaked clusters, but is good otherwise
705 * 63 - Checks are not supported by the image format
707 static int img_check(int argc
, char **argv
)
710 OutputFormat output_format
= OFORMAT_HUMAN
;
711 const char *filename
, *fmt
, *output
, *cache
;
713 BlockDriverState
*bs
;
715 int flags
= BDRV_O_CHECK
;
719 bool image_opts
= false;
720 bool force_share
= false;
724 cache
= BDRV_DEFAULT_CACHE
;
727 int option_index
= 0;
728 static const struct option long_options
[] = {
729 {"help", no_argument
, 0, 'h'},
730 {"format", required_argument
, 0, 'f'},
731 {"repair", required_argument
, 0, 'r'},
732 {"output", required_argument
, 0, OPTION_OUTPUT
},
733 {"object", required_argument
, 0, OPTION_OBJECT
},
734 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
735 {"force-share", no_argument
, 0, 'U'},
738 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
739 long_options
, &option_index
);
745 missing_argument(argv
[optind
- 1]);
748 unrecognized_option(argv
[optind
- 1]);
757 flags
|= BDRV_O_RDWR
;
759 if (!strcmp(optarg
, "leaks")) {
760 fix
= BDRV_FIX_LEAKS
;
761 } else if (!strcmp(optarg
, "all")) {
762 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
764 error_exit("Unknown option value for -r "
765 "(expecting 'leaks' or 'all'): %s", optarg
);
781 user_creatable_process_cmdline(optarg
);
783 case OPTION_IMAGE_OPTS
:
788 if (optind
!= argc
- 1) {
789 error_exit("Expecting one image file name");
791 filename
= argv
[optind
++];
793 if (output
&& !strcmp(output
, "json")) {
794 output_format
= OFORMAT_JSON
;
795 } else if (output
&& !strcmp(output
, "human")) {
796 output_format
= OFORMAT_HUMAN
;
798 error_report("--output must be used with human or json as argument.");
802 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
804 error_report("Invalid source cache option: %s", cache
);
808 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
815 check
= g_new0(ImageCheck
, 1);
816 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
818 if (ret
== -ENOTSUP
) {
819 error_report("This image format does not support checks");
824 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
825 int corruptions_fixed
, leaks_fixed
;
826 bool has_leaks_fixed
, has_corruptions_fixed
;
828 leaks_fixed
= check
->leaks_fixed
;
829 has_leaks_fixed
= check
->has_leaks_fixed
;
830 corruptions_fixed
= check
->corruptions_fixed
;
831 has_corruptions_fixed
= check
->has_corruptions_fixed
;
833 if (output_format
== OFORMAT_HUMAN
) {
835 "The following inconsistencies were found and repaired:\n\n"
836 " %" PRId64
" leaked clusters\n"
837 " %" PRId64
" corruptions\n\n"
838 "Double checking the fixed image now...\n",
840 check
->corruptions_fixed
);
843 qapi_free_ImageCheck(check
);
844 check
= g_new0(ImageCheck
, 1);
845 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
847 check
->leaks_fixed
= leaks_fixed
;
848 check
->has_leaks_fixed
= has_leaks_fixed
;
849 check
->corruptions_fixed
= corruptions_fixed
;
850 check
->has_corruptions_fixed
= has_corruptions_fixed
;
854 switch (output_format
) {
856 dump_human_image_check(check
, quiet
);
859 dump_json_image_check(check
, quiet
);
864 if (ret
|| check
->check_errors
) {
866 error_report("Check failed: %s", strerror(-ret
));
868 error_report("Check failed");
874 if (check
->corruptions
) {
876 } else if (check
->leaks
) {
883 qapi_free_ImageCheck(check
);
888 typedef struct CommonBlockJobCBInfo
{
889 BlockDriverState
*bs
;
891 } CommonBlockJobCBInfo
;
893 static void common_block_job_cb(void *opaque
, int ret
)
895 CommonBlockJobCBInfo
*cbi
= opaque
;
898 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
902 static void run_block_job(BlockJob
*job
, Error
**errp
)
904 uint64_t progress_current
, progress_total
;
905 AioContext
*aio_context
= block_job_get_aio_context(job
);
908 aio_context_acquire(aio_context
);
911 float progress
= 0.0f
;
912 aio_poll(aio_context
, true);
914 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
916 if (progress_total
) {
917 progress
= (float)progress_current
/ progress_total
* 100.f
;
919 qemu_progress_print(progress
, 0);
920 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
922 if (!job_is_completed(&job
->job
)) {
923 ret
= job_complete_sync(&job
->job
, errp
);
927 job_unref(&job
->job
);
928 aio_context_release(aio_context
);
930 /* publish completion progress only when success */
932 qemu_progress_print(100.f
, 0);
936 static int img_commit(int argc
, char **argv
)
939 const char *filename
, *fmt
, *cache
, *base
;
941 BlockDriverState
*bs
, *base_bs
;
943 bool progress
= false, quiet
= false, drop
= false;
945 Error
*local_err
= NULL
;
946 CommonBlockJobCBInfo cbi
;
947 bool image_opts
= false;
948 AioContext
*aio_context
;
949 int64_t rate_limit
= 0;
952 cache
= BDRV_DEFAULT_CACHE
;
955 static const struct option long_options
[] = {
956 {"help", no_argument
, 0, 'h'},
957 {"object", required_argument
, 0, OPTION_OBJECT
},
958 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
961 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
968 missing_argument(argv
[optind
- 1]);
971 unrecognized_option(argv
[optind
- 1]);
997 rate_limit
= cvtnum("rate limit", optarg
);
998 if (rate_limit
< 0) {
1003 user_creatable_process_cmdline(optarg
);
1005 case OPTION_IMAGE_OPTS
:
1011 /* Progress is not shown in Quiet mode */
1016 if (optind
!= argc
- 1) {
1017 error_exit("Expecting one image file name");
1019 filename
= argv
[optind
++];
1021 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1022 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1024 error_report("Invalid cache option: %s", cache
);
1028 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1035 qemu_progress_init(progress
, 1.f
);
1036 qemu_progress_print(0.f
, 100);
1039 base_bs
= bdrv_find_backing_image(bs
, base
);
1041 error_setg(&local_err
,
1042 "Did not find '%s' in the backing chain of '%s'",
1047 /* This is different from QMP, which by default uses the deepest file in
1048 * the backing chain (i.e., the very base); however, the traditional
1049 * behavior of qemu-img commit is using the immediate backing file. */
1050 base_bs
= bdrv_backing_chain_next(bs
);
1052 error_setg(&local_err
, "Image does not have a backing file");
1057 cbi
= (CommonBlockJobCBInfo
){
1062 aio_context
= bdrv_get_aio_context(bs
);
1063 aio_context_acquire(aio_context
);
1064 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1065 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1066 &cbi
, false, &local_err
);
1067 aio_context_release(aio_context
);
1072 /* When the block job completes, the BlockBackend reference will point to
1073 * the old backing file. In order to avoid that the top image is already
1074 * deleted, so we can still empty it afterwards, increment the reference
1075 * counter here preemptively. */
1080 job
= block_job_get("commit");
1082 run_block_job(job
, &local_err
);
1088 BlockBackend
*old_backing_blk
;
1090 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1092 if (!old_backing_blk
) {
1095 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1096 blk_unref(old_backing_blk
);
1097 if (ret
== -ENOTSUP
) {
1098 error_free(local_err
);
1100 } else if (ret
< 0) {
1111 qemu_progress_end();
1116 error_report_err(local_err
);
1120 qprintf(quiet
, "Image committed.\n");
1125 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1126 * of the first sector boundary within buf where the sector contains a
1127 * non-zero byte. This function is robust to a buffer that is not
1130 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1133 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1135 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1136 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1140 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1147 * Returns true iff the first sector pointed to by 'buf' contains at least
1150 * 'pnum' is set to the number of sectors (including and immediately following
1151 * the first one) that are known to be in the same allocated/unallocated state.
1152 * The function will try to align the end offset to alignment boundaries so
1153 * that the request will at least end aligned and consecutive requests will
1154 * also start at an aligned offset.
1156 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1157 int64_t sector_num
, int alignment
)
1166 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1167 for(i
= 1; i
< n
; i
++) {
1168 buf
+= BDRV_SECTOR_SIZE
;
1169 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1176 * The whole buf is the same.
1177 * No reason to split it into chunks, so return now.
1183 tail
= (sector_num
+ i
) & (alignment
- 1);
1185 if (is_zero
&& i
<= tail
) {
1187 * For sure next sector after i is data, and it will rewrite this
1188 * tail anyway due to RMW. So, let's just write data now.
1193 /* If possible, align up end offset of allocated areas. */
1194 i
+= alignment
- tail
;
1198 * For sure next sector after i is data, and it will rewrite this
1199 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1210 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1211 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1212 * breaking up write requests for only small sparse areas.
1214 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1215 int min
, int64_t sector_num
, int alignment
)
1218 int num_checked
, num_used
;
1224 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1230 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1232 sector_num
+= *pnum
;
1233 num_checked
= num_used
;
1236 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1238 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1240 sector_num
+= *pnum
;
1241 num_checked
+= *pnum
;
1243 num_used
= num_checked
;
1244 } else if (*pnum
>= min
) {
1254 * Compares two buffers sector by sector. Returns 0 if the first
1255 * sector of each buffer matches, non-zero otherwise.
1257 * pnum is set to the sector-aligned size of the buffer prefix that
1258 * has the same matching status as the first sector.
1260 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1261 int64_t bytes
, int64_t *pnum
)
1264 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1268 res
= !!memcmp(buf1
, buf2
, i
);
1270 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1272 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1282 #define IO_BUF_SIZE (2 * MiB)
1285 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1287 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1288 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1289 * failure), and 4 on error (the exit status for read errors), after emitting
1292 * @param blk: BlockBackend for the image
1293 * @param offset: Starting offset to check
1294 * @param bytes: Number of bytes to check
1295 * @param filename: Name of disk file we are checking (logging purpose)
1296 * @param buffer: Allocated buffer for storing read data
1297 * @param quiet: Flag for quiet mode
1299 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1300 int64_t bytes
, const char *filename
,
1301 uint8_t *buffer
, bool quiet
)
1306 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1308 error_report("Error while reading offset %" PRId64
" of %s: %s",
1309 offset
, filename
, strerror(-ret
));
1312 idx
= find_nonzero(buffer
, bytes
);
1314 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1323 * Compares two images. Exit codes:
1325 * 0 - Images are identical or the requested help was printed
1327 * >1 - Error occurred
1329 static int img_compare(int argc
, char **argv
)
1331 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1332 BlockBackend
*blk1
, *blk2
;
1333 BlockDriverState
*bs1
, *bs2
;
1334 int64_t total_size1
, total_size2
;
1335 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1336 int64_t pnum1
, pnum2
;
1337 int allocated1
, allocated2
;
1338 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1339 bool progress
= false, quiet
= false, strict
= false;
1346 uint64_t progress_base
;
1347 bool image_opts
= false;
1348 bool force_share
= false;
1350 cache
= BDRV_DEFAULT_CACHE
;
1352 static const struct option long_options
[] = {
1353 {"help", no_argument
, 0, 'h'},
1354 {"object", required_argument
, 0, OPTION_OBJECT
},
1355 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1356 {"force-share", no_argument
, 0, 'U'},
1359 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1360 long_options
, NULL
);
1366 missing_argument(argv
[optind
- 1]);
1369 unrecognized_option(argv
[optind
- 1]);
1397 Error
*local_err
= NULL
;
1399 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1401 error_report_err(local_err
);
1404 /* Help was printed */
1410 case OPTION_IMAGE_OPTS
:
1416 /* Progress is not shown in Quiet mode */
1422 if (optind
!= argc
- 2) {
1423 error_exit("Expecting two image file names");
1425 filename1
= argv
[optind
++];
1426 filename2
= argv
[optind
++];
1428 /* Initialize before goto out */
1429 qemu_progress_init(progress
, 2.0);
1432 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1434 error_report("Invalid source cache option: %s", cache
);
1439 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1446 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1455 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1456 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1457 total_size1
= blk_getlength(blk1
);
1458 if (total_size1
< 0) {
1459 error_report("Can't get size of %s: %s",
1460 filename1
, strerror(-total_size1
));
1464 total_size2
= blk_getlength(blk2
);
1465 if (total_size2
< 0) {
1466 error_report("Can't get size of %s: %s",
1467 filename2
, strerror(-total_size2
));
1471 total_size
= MIN(total_size1
, total_size2
);
1472 progress_base
= MAX(total_size1
, total_size2
);
1474 qemu_progress_print(0, 100);
1476 if (strict
&& total_size1
!= total_size2
) {
1478 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1482 while (offset
< total_size
) {
1483 int status1
, status2
;
1485 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1486 total_size1
- offset
, &pnum1
, NULL
,
1490 error_report("Sector allocation test failed for %s", filename1
);
1493 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1495 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1496 total_size2
- offset
, &pnum2
, NULL
,
1500 error_report("Sector allocation test failed for %s", filename2
);
1503 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1505 assert(pnum1
&& pnum2
);
1506 chunk
= MIN(pnum1
, pnum2
);
1509 if (status1
!= status2
) {
1511 qprintf(quiet
, "Strict mode: Offset %" PRId64
1512 " block status mismatch!\n", offset
);
1516 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1518 } else if (allocated1
== allocated2
) {
1522 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1523 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1525 error_report("Error while reading offset %" PRId64
1527 offset
, filename1
, strerror(-ret
));
1531 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1533 error_report("Error while reading offset %" PRId64
1535 offset
, filename2
, strerror(-ret
));
1539 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1540 if (ret
|| pnum
!= chunk
) {
1541 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1542 offset
+ (ret
? 0 : pnum
));
1548 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1550 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1551 filename1
, buf1
, quiet
);
1553 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1554 filename2
, buf1
, quiet
);
1561 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1564 if (total_size1
!= total_size2
) {
1565 BlockBackend
*blk_over
;
1566 const char *filename_over
;
1568 qprintf(quiet
, "Warning: Image size mismatch!\n");
1569 if (total_size1
> total_size2
) {
1571 filename_over
= filename1
;
1574 filename_over
= filename2
;
1577 while (offset
< progress_base
) {
1578 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1579 progress_base
- offset
, &chunk
,
1583 error_report("Sector allocation test failed for %s",
1588 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1589 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1590 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1591 filename_over
, buf1
, quiet
);
1597 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1601 qprintf(quiet
, "Images are identical.\n");
1611 qemu_progress_end();
1615 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1616 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1617 const char *src_node
, const char *src_name
,
1620 BlockDirtyBitmapMergeSource
*merge_src
;
1621 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1623 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1624 merge_src
->type
= QTYPE_QDICT
;
1625 merge_src
->u
.external
.node
= g_strdup(src_node
);
1626 merge_src
->u
.external
.name
= g_strdup(src_name
);
1627 QAPI_LIST_PREPEND(list
, merge_src
);
1628 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1629 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1632 enum ImgConvertBlockStatus
{
1638 #define MAX_COROUTINES 16
1639 #define CONVERT_THROTTLE_GROUP "img_convert"
1641 typedef struct ImgConvertState
{
1643 int64_t *src_sectors
;
1646 int64_t total_sectors
;
1647 int64_t allocated_sectors
;
1648 int64_t allocated_done
;
1651 enum ImgConvertBlockStatus status
;
1652 int64_t sector_next_status
;
1653 BlockBackend
*target
;
1657 bool target_has_backing
;
1658 int64_t target_backing_sectors
; /* negative if unknown */
1665 size_t cluster_sectors
;
1667 long num_coroutines
;
1668 int running_coroutines
;
1669 Coroutine
*co
[MAX_COROUTINES
];
1670 int64_t wait_sector_num
[MAX_COROUTINES
];
1675 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1676 int *src_cur
, int64_t *src_cur_offset
)
1679 *src_cur_offset
= 0;
1680 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1681 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1683 assert(*src_cur
< s
->src_num
);
1687 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1689 int64_t src_cur_offset
;
1690 int ret
, n
, src_cur
;
1691 bool post_backing_zero
= false;
1693 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1695 assert(s
->total_sectors
> sector_num
);
1696 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1698 if (s
->target_backing_sectors
>= 0) {
1699 if (sector_num
>= s
->target_backing_sectors
) {
1700 post_backing_zero
= true;
1701 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1702 /* Split requests around target_backing_sectors (because
1703 * starting from there, zeros are handled differently) */
1704 n
= s
->target_backing_sectors
- sector_num
;
1708 if (s
->sector_next_status
<= sector_num
) {
1709 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1712 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1713 BlockDriverState
*base
;
1715 if (s
->target_has_backing
) {
1716 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1722 count
= n
* BDRV_SECTOR_SIZE
;
1724 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1731 warn_report("error while reading block status at "
1732 "offset %" PRIu64
": %s", offset
,
1735 /* Just try to read the data, then */
1736 ret
= BDRV_BLOCK_DATA
;
1737 count
= BDRV_SECTOR_SIZE
;
1739 /* Retry on a shorter range */
1740 n
= DIV_ROUND_UP(n
, 4);
1743 error_report("error while reading block status at offset "
1744 "%" PRIu64
": %s", offset
, strerror(-ret
));
1750 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1753 * Avoid that s->sector_next_status becomes unaligned to the source
1754 * request alignment and/or cluster size to avoid unnecessary read
1757 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1762 if (ret
& BDRV_BLOCK_ZERO
) {
1763 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1764 } else if (ret
& BDRV_BLOCK_DATA
) {
1765 s
->status
= BLK_DATA
;
1767 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1770 s
->sector_next_status
= sector_num
+ n
;
1773 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1774 if (s
->status
== BLK_DATA
) {
1775 n
= MIN(n
, s
->buf_sectors
);
1778 /* We need to write complete clusters for compressed images, so if an
1779 * unallocated area is shorter than that, we must consider the whole
1780 * cluster allocated. */
1781 if (s
->compressed
) {
1782 if (n
< s
->cluster_sectors
) {
1783 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1784 s
->status
= BLK_DATA
;
1786 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1793 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1794 int nb_sectors
, uint8_t *buf
)
1796 uint64_t single_read_until
= 0;
1799 assert(nb_sectors
<= s
->buf_sectors
);
1800 while (nb_sectors
> 0) {
1803 int64_t bs_sectors
, src_cur_offset
;
1806 /* In the case of compression with multiple source files, we can get a
1807 * nb_sectors that spreads into the next part. So we must be able to
1808 * read across multiple BDSes for one convert_read() call. */
1809 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1810 blk
= s
->src
[src_cur
];
1811 bs_sectors
= s
->src_sectors
[src_cur
];
1813 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1815 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1816 if (single_read_until
> offset
) {
1820 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1824 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1828 warn_report("error while reading offset %" PRIu64
1829 ": %s", offset
, strerror(-ret
));
1831 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1840 buf
+= n
* BDRV_SECTOR_SIZE
;
1847 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1848 int nb_sectors
, uint8_t *buf
,
1849 enum ImgConvertBlockStatus status
)
1853 while (nb_sectors
> 0) {
1855 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1858 case BLK_BACKING_FILE
:
1859 /* If we have a backing file, leave clusters unallocated that are
1860 * unallocated in the source image, so that the backing file is
1861 * visible at the respective offset. */
1862 assert(s
->target_has_backing
);
1866 /* If we're told to keep the target fully allocated (-S 0) or there
1867 * is real non-zero data, we must write it. Otherwise we can treat
1868 * it as zero sectors.
1869 * Compressed clusters need to be written as a whole, so in that
1870 * case we can only save the write if the buffer is completely
1872 if (!s
->min_sparse
||
1874 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1875 sector_num
, s
->alignment
)) ||
1877 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1879 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1880 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1889 if (s
->has_zero_init
) {
1890 assert(!s
->target_has_backing
);
1893 ret
= blk_co_pwrite_zeroes(s
->target
,
1894 sector_num
<< BDRV_SECTOR_BITS
,
1895 n
<< BDRV_SECTOR_BITS
,
1896 BDRV_REQ_MAY_UNMAP
);
1905 buf
+= n
* BDRV_SECTOR_SIZE
;
1911 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1916 while (nb_sectors
> 0) {
1919 int64_t bs_sectors
, src_cur_offset
;
1922 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1923 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1924 blk
= s
->src
[src_cur
];
1925 bs_sectors
= s
->src_sectors
[src_cur
];
1927 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1929 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1930 sector_num
<< BDRV_SECTOR_BITS
,
1931 n
<< BDRV_SECTOR_BITS
, 0, 0);
1942 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1944 ImgConvertState
*s
= opaque
;
1945 uint8_t *buf
= NULL
;
1949 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1950 if (s
->co
[i
] == qemu_coroutine_self()) {
1957 s
->running_coroutines
++;
1958 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1963 enum ImgConvertBlockStatus status
;
1966 qemu_co_mutex_lock(&s
->lock
);
1967 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1968 qemu_co_mutex_unlock(&s
->lock
);
1971 n
= convert_iteration_sectors(s
, s
->sector_num
);
1973 qemu_co_mutex_unlock(&s
->lock
);
1977 /* save current sector and allocation status to local variables */
1978 sector_num
= s
->sector_num
;
1980 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1981 n
= MIN(n
, s
->buf_sectors
);
1983 /* increment global sector counter so that other coroutines can
1984 * already continue reading beyond this request */
1986 qemu_co_mutex_unlock(&s
->lock
);
1988 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1989 s
->allocated_done
+= n
;
1990 qemu_progress_print(100.0 * s
->allocated_done
/
1991 s
->allocated_sectors
, 0);
1995 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1996 if (status
== BLK_DATA
&& !copy_range
) {
1997 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1999 error_report("error while reading at byte %lld: %s",
2000 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2003 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2005 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2008 if (s
->wr_in_order
) {
2009 /* keep writes in order */
2010 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2011 s
->wait_sector_num
[index
] = sector_num
;
2012 qemu_coroutine_yield();
2014 s
->wait_sector_num
[index
] = -1;
2017 if (s
->ret
== -EINPROGRESS
) {
2019 ret
= convert_co_copy_range(s
, sector_num
, n
);
2021 s
->copy_range
= false;
2025 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2028 error_report("error while writing at byte %lld: %s",
2029 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2034 if (s
->wr_in_order
) {
2035 /* reenter the coroutine that might have waited
2036 * for this write to complete */
2037 s
->wr_offs
= sector_num
+ n
;
2038 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2039 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2041 * A -> B -> A cannot occur because A has
2042 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2043 * B will never enter A during this time window.
2045 qemu_coroutine_enter(s
->co
[i
]);
2053 s
->co
[index
] = NULL
;
2054 s
->running_coroutines
--;
2055 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2056 /* the convert job finished successfully */
2061 static int convert_do_copy(ImgConvertState
*s
)
2064 int64_t sector_num
= 0;
2066 /* Check whether we have zero initialisation or can get it efficiently */
2067 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2068 !s
->target_has_backing
) {
2069 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2072 /* Allocate buffer for copied data. For compressed images, only one cluster
2073 * can be copied at a time. */
2074 if (s
->compressed
) {
2075 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2076 error_report("invalid cluster size");
2079 s
->buf_sectors
= s
->cluster_sectors
;
2082 while (sector_num
< s
->total_sectors
) {
2083 n
= convert_iteration_sectors(s
, sector_num
);
2087 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2089 s
->allocated_sectors
+= n
;
2095 s
->sector_next_status
= 0;
2096 s
->ret
= -EINPROGRESS
;
2098 qemu_co_mutex_init(&s
->lock
);
2099 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2100 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2101 s
->wait_sector_num
[i
] = -1;
2102 qemu_coroutine_enter(s
->co
[i
]);
2105 while (s
->running_coroutines
) {
2106 main_loop_wait(false);
2109 if (s
->compressed
&& !s
->ret
) {
2110 /* signal EOF to align */
2111 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2120 /* Check that bitmaps can be copied, or output an error */
2121 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2123 BdrvDirtyBitmap
*bm
;
2125 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2126 error_report("Source lacks bitmap support");
2129 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2130 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2133 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2134 error_report("Cannot copy inconsistent bitmap '%s'",
2135 bdrv_dirty_bitmap_name(bm
));
2136 error_printf("Try --skip-broken-bitmaps, or "
2137 "use 'qemu-img bitmap --remove' to delete it\n");
2144 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2147 BdrvDirtyBitmap
*bm
;
2150 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2153 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2156 name
= bdrv_dirty_bitmap_name(bm
);
2157 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2158 warn_report("Skipping inconsistent bitmap '%s'", name
);
2161 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2162 true, bdrv_dirty_bitmap_granularity(bm
),
2164 true, !bdrv_dirty_bitmap_enabled(bm
),
2167 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2171 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2174 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2175 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2183 #define MAX_BUF_SECTORS 32768
2185 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2189 throttle_config_init(&cfg
);
2190 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2192 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2193 blk_set_io_limits(blk
, &cfg
);
2196 static int img_convert(int argc
, char **argv
)
2198 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2199 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2200 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2201 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2202 *backing_fmt
= NULL
;
2203 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2204 BlockDriverInfo bdi
;
2205 BlockDriverState
*out_bs
;
2206 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2207 QemuOptsList
*create_opts
= NULL
;
2208 QDict
*open_opts
= NULL
;
2209 char *options
= NULL
;
2210 Error
*local_err
= NULL
;
2211 bool writethrough
, src_writethrough
, image_opts
= false,
2212 skip_create
= false, progress
= false, tgt_image_opts
= false;
2213 int64_t ret
= -EINVAL
;
2214 bool force_share
= false;
2215 bool explict_min_sparse
= false;
2216 bool bitmaps
= false;
2217 bool skip_broken
= false;
2218 int64_t rate_limit
= 0;
2220 ImgConvertState s
= (ImgConvertState
) {
2221 /* Need at least 4k of zeros for sparse detection */
2223 .copy_range
= false,
2224 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2225 .wr_in_order
= true,
2226 .num_coroutines
= 8,
2230 static const struct option long_options
[] = {
2231 {"help", no_argument
, 0, 'h'},
2232 {"object", required_argument
, 0, OPTION_OBJECT
},
2233 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2234 {"force-share", no_argument
, 0, 'U'},
2235 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2236 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2237 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2238 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2239 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2242 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2243 long_options
, NULL
);
2249 missing_argument(argv
[optind
- 1]);
2252 unrecognized_option(argv
[optind
- 1]);
2264 out_baseimg
= optarg
;
2267 s
.copy_range
= true;
2270 s
.compressed
= true;
2273 backing_fmt
= optarg
;
2276 if (accumulate_options(&options
, optarg
) < 0) {
2281 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2282 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2285 error_report("Failed in parsing snapshot param '%s'",
2290 snapshot_name
= optarg
;
2297 sval
= cvtnum("buffer size for sparse output", optarg
);
2300 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2301 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2302 error_report("Invalid buffer size for sparse output specified. "
2303 "Valid sizes are multiples of %llu up to %llu. Select "
2304 "0 to disable sparse detection (fully allocates output).",
2305 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2309 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2310 explict_min_sparse
= true;
2329 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2330 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2331 error_report("Invalid number of coroutines. Allowed number of"
2332 " coroutines is between 1 and %d", MAX_COROUTINES
);
2337 s
.wr_in_order
= false;
2343 rate_limit
= cvtnum("rate limit", optarg
);
2344 if (rate_limit
< 0) {
2349 user_creatable_process_cmdline(optarg
);
2351 case OPTION_IMAGE_OPTS
:
2354 case OPTION_SALVAGE
:
2357 case OPTION_TARGET_IMAGE_OPTS
:
2358 tgt_image_opts
= true;
2360 case OPTION_TARGET_IS_ZERO
:
2362 * The user asserting that the target is blank has the
2363 * same effect as the target driver supporting zero
2366 s
.has_zero_init
= true;
2368 case OPTION_BITMAPS
:
2371 case OPTION_SKIP_BROKEN
:
2377 if (!out_fmt
&& !tgt_image_opts
) {
2381 if (skip_broken
&& !bitmaps
) {
2382 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2386 if (s
.compressed
&& s
.copy_range
) {
2387 error_report("Cannot enable copy offloading when -c is used");
2391 if (explict_min_sparse
&& s
.copy_range
) {
2392 error_report("Cannot enable copy offloading when -S is used");
2396 if (s
.copy_range
&& s
.salvage
) {
2397 error_report("Cannot use copy offloading in salvaging mode");
2401 if (tgt_image_opts
&& !skip_create
) {
2402 error_report("--target-image-opts requires use of -n flag");
2406 if (skip_create
&& options
) {
2407 error_report("-o has no effect when skipping image creation");
2411 if (s
.has_zero_init
&& !skip_create
) {
2412 error_report("--target-is-zero requires use of -n flag");
2416 s
.src_num
= argc
- optind
- 1;
2417 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2419 if (options
&& has_help_option(options
)) {
2421 ret
= print_block_option_help(out_filename
, out_fmt
);
2424 error_report("Option help requires a format be specified");
2429 if (s
.src_num
< 1) {
2430 error_report("Must specify image file name");
2434 /* ret is still -EINVAL until here */
2435 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2437 error_report("Invalid source cache option: %s", src_cache
);
2441 /* Initialize before goto out */
2445 qemu_progress_init(progress
, 1.0);
2446 qemu_progress_print(0, 100);
2448 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2449 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2450 s
.src_alignment
= g_new(int, s
.src_num
);
2452 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2453 BlockDriverState
*src_bs
;
2454 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2455 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2461 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2462 if (s
.src_sectors
[bs_i
] < 0) {
2463 error_report("Could not get size of %s: %s",
2464 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2468 src_bs
= blk_bs(s
.src
[bs_i
]);
2469 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2471 if (!bdrv_get_info(src_bs
, &bdi
)) {
2472 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2473 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2475 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2479 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2480 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2481 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2483 } else if (snapshot_name
!= NULL
) {
2484 if (s
.src_num
> 1) {
2485 error_report("No support for concatenating multiple snapshot");
2490 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2494 error_reportf_err(local_err
, "Failed to load snapshot: ");
2500 /* Find driver and parse its options */
2501 drv
= bdrv_find_format(out_fmt
);
2503 error_report("Unknown file format '%s'", out_fmt
);
2508 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2510 error_report_err(local_err
);
2515 if (!drv
->create_opts
) {
2516 error_report("Format driver '%s' does not support image creation",
2522 if (!proto_drv
->create_opts
) {
2523 error_report("Protocol driver '%s' does not support image creation",
2524 proto_drv
->format_name
);
2529 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2530 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2532 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2534 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2535 error_report_err(local_err
);
2541 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2542 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2543 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2549 /* Get backing file name if -o backing_file was used */
2550 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2551 if (out_baseimg_param
) {
2552 out_baseimg
= out_baseimg_param
;
2554 s
.target_has_backing
= (bool) out_baseimg
;
2556 if (s
.has_zero_init
&& s
.target_has_backing
) {
2557 error_report("Cannot use --target-is-zero when the destination "
2558 "image has a backing file");
2562 if (s
.src_num
> 1 && out_baseimg
) {
2563 error_report("Having a backing file for the target makes no sense when "
2564 "concatenating multiple input images");
2569 if (out_baseimg_param
) {
2570 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2571 error_report("Use of backing file requires explicit "
2578 /* Check if compression is supported */
2581 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2582 const char *encryptfmt
=
2583 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2584 const char *preallocation
=
2585 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2587 if (drv
&& !block_driver_can_compress(drv
)) {
2588 error_report("Compression not supported for this file format");
2593 if (encryption
|| encryptfmt
) {
2594 error_report("Compression and encryption not supported at "
2601 && strcmp(preallocation
, "off"))
2603 error_report("Compression and preallocation not supported at "
2610 /* Determine if bitmaps need copying */
2612 if (s
.src_num
> 1) {
2613 error_report("Copying bitmaps only possible with single source");
2617 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2624 * The later open call will need any decryption secrets, and
2625 * bdrv_create() will purge "opts", so extract them now before
2629 open_opts
= qdict_new();
2630 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2632 /* Create the new image */
2633 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2635 error_reportf_err(local_err
, "%s: error while converting %s: ",
2636 out_filename
, out_fmt
);
2641 s
.target_is_new
= !skip_create
;
2643 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2644 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2646 error_report("Invalid cache option: %s", cache
);
2650 if (flags
& BDRV_O_NOCACHE
) {
2652 * If we open the target with O_DIRECT, it may be necessary to
2653 * extend its size to align to the physical sector size.
2655 flags
|= BDRV_O_RESIZE
;
2659 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2660 flags
, writethrough
, s
.quiet
, false);
2662 /* TODO ultimately we should allow --target-image-opts
2663 * to be used even when -n is not given.
2664 * That has to wait for bdrv_create to be improved
2665 * to allow filenames in option syntax
2667 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2668 flags
, writethrough
, s
.quiet
, false);
2669 open_opts
= NULL
; /* blk_new_open will have freed it */
2675 out_bs
= blk_bs(s
.target
);
2677 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2678 error_report("Format driver '%s' does not support bitmaps",
2679 out_bs
->drv
->format_name
);
2684 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2685 error_report("Compression not supported for this file format");
2690 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2691 * or discard_alignment of the out_bs is greater. Limit to
2692 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2693 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2695 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2696 out_bs
->bl
.pdiscard_alignment
>>
2697 BDRV_SECTOR_BITS
)));
2699 /* try to align the write requests to the destination to avoid unnecessary
2701 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2702 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2704 assert(is_power_of_2(s
.alignment
));
2707 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2708 if (output_sectors
< 0) {
2709 error_report("unable to get output image length: %s",
2710 strerror(-output_sectors
));
2713 } else if (output_sectors
< s
.total_sectors
) {
2714 error_report("output file is smaller than input file");
2720 if (s
.target_has_backing
&& s
.target_is_new
) {
2721 /* Errors are treated as "backing length unknown" (which means
2722 * s.target_backing_sectors has to be negative, which it will
2723 * be automatically). The backing file length is used only
2724 * for optimizations, so such a case is not fatal. */
2725 s
.target_backing_sectors
=
2726 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2728 s
.target_backing_sectors
= -1;
2731 ret
= bdrv_get_info(out_bs
, &bdi
);
2734 error_report("could not get block driver info");
2738 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2739 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2743 set_rate_limit(s
.target
, rate_limit
);
2746 ret
= convert_do_copy(&s
);
2748 /* Now copy the bitmaps */
2749 if (bitmaps
&& ret
== 0) {
2750 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2755 qemu_progress_print(100, 0);
2757 qemu_progress_end();
2758 qemu_opts_del(opts
);
2759 qemu_opts_free(create_opts
);
2760 qobject_unref(open_opts
);
2761 blk_unref(s
.target
);
2763 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2764 blk_unref(s
.src
[bs_i
]);
2768 g_free(s
.src_sectors
);
2769 g_free(s
.src_alignment
);
2771 qemu_opts_del(sn_opts
);
2778 static void dump_snapshots(BlockDriverState
*bs
)
2780 QEMUSnapshotInfo
*sn_tab
, *sn
;
2783 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2786 printf("Snapshot list:\n");
2787 bdrv_snapshot_dump(NULL
);
2789 for(i
= 0; i
< nb_sns
; i
++) {
2791 bdrv_snapshot_dump(sn
);
2797 static void dump_json_image_info_list(ImageInfoList
*list
)
2801 Visitor
*v
= qobject_output_visitor_new(&obj
);
2803 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2804 visit_complete(v
, &obj
);
2805 str
= qobject_to_json_pretty(obj
, true);
2806 assert(str
!= NULL
);
2807 printf("%s\n", str
->str
);
2810 g_string_free(str
, true);
2813 static void dump_json_image_info(ImageInfo
*info
)
2817 Visitor
*v
= qobject_output_visitor_new(&obj
);
2819 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2820 visit_complete(v
, &obj
);
2821 str
= qobject_to_json_pretty(obj
, true);
2822 assert(str
!= NULL
);
2823 printf("%s\n", str
->str
);
2826 g_string_free(str
, true);
2829 static void dump_human_image_info_list(ImageInfoList
*list
)
2831 ImageInfoList
*elem
;
2834 for (elem
= list
; elem
; elem
= elem
->next
) {
2840 bdrv_image_info_dump(elem
->value
);
2844 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2846 return strcmp(a
, b
) == 0;
2850 * Open an image file chain and return an ImageInfoList
2852 * @filename: topmost image filename
2853 * @fmt: topmost image format (may be NULL to autodetect)
2854 * @chain: true - enumerate entire backing file chain
2855 * false - only topmost image file
2857 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2858 * image file. If there was an error a message will have been printed to
2861 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2862 const char *filename
,
2864 bool chain
, bool force_share
)
2866 ImageInfoList
*head
= NULL
;
2867 ImageInfoList
**tail
= &head
;
2868 GHashTable
*filenames
;
2871 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2875 BlockDriverState
*bs
;
2878 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2879 error_report("Backing file '%s' creates an infinite loop.",
2883 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2885 blk
= img_open(image_opts
, filename
, fmt
,
2886 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2893 bdrv_query_image_info(bs
, &info
, &err
);
2895 error_report_err(err
);
2900 QAPI_LIST_APPEND(tail
, info
);
2904 /* Clear parameters that only apply to the topmost image */
2905 filename
= fmt
= NULL
;
2909 if (info
->has_full_backing_filename
) {
2910 filename
= info
->full_backing_filename
;
2911 } else if (info
->has_backing_filename
) {
2912 error_report("Could not determine absolute backing filename,"
2913 " but backing filename '%s' present",
2914 info
->backing_filename
);
2917 if (info
->has_backing_filename_format
) {
2918 fmt
= info
->backing_filename_format
;
2922 g_hash_table_destroy(filenames
);
2926 qapi_free_ImageInfoList(head
);
2927 g_hash_table_destroy(filenames
);
2931 static int img_info(int argc
, char **argv
)
2934 OutputFormat output_format
= OFORMAT_HUMAN
;
2936 const char *filename
, *fmt
, *output
;
2937 ImageInfoList
*list
;
2938 bool image_opts
= false;
2939 bool force_share
= false;
2944 int option_index
= 0;
2945 static const struct option long_options
[] = {
2946 {"help", no_argument
, 0, 'h'},
2947 {"format", required_argument
, 0, 'f'},
2948 {"output", required_argument
, 0, OPTION_OUTPUT
},
2949 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2950 {"object", required_argument
, 0, OPTION_OBJECT
},
2951 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2952 {"force-share", no_argument
, 0, 'U'},
2955 c
= getopt_long(argc
, argv
, ":f:hU",
2956 long_options
, &option_index
);
2962 missing_argument(argv
[optind
- 1]);
2965 unrecognized_option(argv
[optind
- 1]);
2979 case OPTION_BACKING_CHAIN
:
2983 user_creatable_process_cmdline(optarg
);
2985 case OPTION_IMAGE_OPTS
:
2990 if (optind
!= argc
- 1) {
2991 error_exit("Expecting one image file name");
2993 filename
= argv
[optind
++];
2995 if (output
&& !strcmp(output
, "json")) {
2996 output_format
= OFORMAT_JSON
;
2997 } else if (output
&& !strcmp(output
, "human")) {
2998 output_format
= OFORMAT_HUMAN
;
2999 } else if (output
) {
3000 error_report("--output must be used with human or json as argument.");
3004 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3010 switch (output_format
) {
3012 dump_human_image_info_list(list
);
3016 dump_json_image_info_list(list
);
3018 dump_json_image_info(list
->value
);
3023 qapi_free_ImageInfoList(list
);
3027 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3030 switch (output_format
) {
3032 if (e
->data
&& !e
->has_offset
) {
3033 error_report("File contains external, encrypted or compressed clusters.");
3036 if (e
->data
&& !e
->zero
) {
3037 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3038 e
->start
, e
->length
,
3039 e
->has_offset
? e
->offset
: 0,
3040 e
->has_filename
? e
->filename
: "");
3042 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3043 * Modify the flags here to allow more coalescing.
3045 if (next
&& (!next
->data
|| next
->zero
)) {
3051 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3052 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3053 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
3054 e
->present
? "true" : "false",
3055 e
->zero
? "true" : "false",
3056 e
->data
? "true" : "false");
3057 if (e
->has_offset
) {
3058 printf(", \"offset\": %"PRId64
"", e
->offset
);
3070 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3071 int64_t bytes
, MapEntry
*e
)
3075 BlockDriverState
*file
;
3078 char *filename
= NULL
;
3080 /* As an optimization, we could cache the current range of unallocated
3081 * clusters in each file of the chain, and avoid querying the same
3087 bs
= bdrv_skip_filters(bs
);
3088 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3093 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3096 bs
= bdrv_cow_bs(bs
);
3105 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3107 if (file
&& has_offset
) {
3108 bdrv_refresh_filename(file
);
3109 filename
= file
->filename
;
3115 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3116 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3118 .has_offset
= has_offset
,
3120 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3121 .has_filename
= filename
,
3122 .filename
= filename
,
3128 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3130 if (curr
->length
== 0) {
3133 if (curr
->zero
!= next
->zero
||
3134 curr
->data
!= next
->data
||
3135 curr
->depth
!= next
->depth
||
3136 curr
->present
!= next
->present
||
3137 curr
->has_filename
!= next
->has_filename
||
3138 curr
->has_offset
!= next
->has_offset
) {
3141 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3144 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3150 static int img_map(int argc
, char **argv
)
3153 OutputFormat output_format
= OFORMAT_HUMAN
;
3155 BlockDriverState
*bs
;
3156 const char *filename
, *fmt
, *output
;
3158 MapEntry curr
= { .length
= 0 }, next
;
3160 bool image_opts
= false;
3161 bool force_share
= false;
3162 int64_t start_offset
= 0;
3163 int64_t max_length
= -1;
3168 int option_index
= 0;
3169 static const struct option long_options
[] = {
3170 {"help", no_argument
, 0, 'h'},
3171 {"format", required_argument
, 0, 'f'},
3172 {"output", required_argument
, 0, OPTION_OUTPUT
},
3173 {"object", required_argument
, 0, OPTION_OBJECT
},
3174 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3175 {"force-share", no_argument
, 0, 'U'},
3176 {"start-offset", required_argument
, 0, 's'},
3177 {"max-length", required_argument
, 0, 'l'},
3180 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3181 long_options
, &option_index
);
3187 missing_argument(argv
[optind
- 1]);
3190 unrecognized_option(argv
[optind
- 1]);
3205 start_offset
= cvtnum("start offset", optarg
);
3206 if (start_offset
< 0) {
3211 max_length
= cvtnum("max length", optarg
);
3212 if (max_length
< 0) {
3217 user_creatable_process_cmdline(optarg
);
3219 case OPTION_IMAGE_OPTS
:
3224 if (optind
!= argc
- 1) {
3225 error_exit("Expecting one image file name");
3227 filename
= argv
[optind
];
3229 if (output
&& !strcmp(output
, "json")) {
3230 output_format
= OFORMAT_JSON
;
3231 } else if (output
&& !strcmp(output
, "human")) {
3232 output_format
= OFORMAT_HUMAN
;
3233 } else if (output
) {
3234 error_report("--output must be used with human or json as argument.");
3238 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3244 if (output_format
== OFORMAT_HUMAN
) {
3245 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3246 } else if (output_format
== OFORMAT_JSON
) {
3250 length
= blk_getlength(blk
);
3252 error_report("Failed to get size for '%s'", filename
);
3255 if (max_length
!= -1) {
3256 length
= MIN(start_offset
+ max_length
, length
);
3259 curr
.start
= start_offset
;
3260 while (curr
.start
+ curr
.length
< length
) {
3261 int64_t offset
= curr
.start
+ curr
.length
;
3262 int64_t n
= length
- offset
;
3264 ret
= get_block_status(bs
, offset
, n
, &next
);
3266 error_report("Could not read file metadata: %s", strerror(-ret
));
3270 if (entry_mergeable(&curr
, &next
)) {
3271 curr
.length
+= next
.length
;
3275 if (curr
.length
> 0) {
3276 ret
= dump_map_entry(output_format
, &curr
, &next
);
3284 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3285 if (output_format
== OFORMAT_JSON
) {
3294 #define SNAPSHOT_LIST 1
3295 #define SNAPSHOT_CREATE 2
3296 #define SNAPSHOT_APPLY 3
3297 #define SNAPSHOT_DELETE 4
3299 static int img_snapshot(int argc
, char **argv
)
3302 BlockDriverState
*bs
;
3303 QEMUSnapshotInfo sn
;
3304 char *filename
, *snapshot_name
= NULL
;
3305 int c
, ret
= 0, bdrv_oflags
;
3310 bool image_opts
= false;
3311 bool force_share
= false;
3313 bdrv_oflags
= BDRV_O_RDWR
;
3314 /* Parse commandline parameters */
3316 static const struct option long_options
[] = {
3317 {"help", no_argument
, 0, 'h'},
3318 {"object", required_argument
, 0, OPTION_OBJECT
},
3319 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3320 {"force-share", no_argument
, 0, 'U'},
3323 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3324 long_options
, NULL
);
3330 missing_argument(argv
[optind
- 1]);
3333 unrecognized_option(argv
[optind
- 1]);
3340 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3343 action
= SNAPSHOT_LIST
;
3344 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3348 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3351 action
= SNAPSHOT_APPLY
;
3352 snapshot_name
= optarg
;
3356 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3359 action
= SNAPSHOT_CREATE
;
3360 snapshot_name
= optarg
;
3364 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3367 action
= SNAPSHOT_DELETE
;
3368 snapshot_name
= optarg
;
3377 user_creatable_process_cmdline(optarg
);
3379 case OPTION_IMAGE_OPTS
:
3385 if (optind
!= argc
- 1) {
3386 error_exit("Expecting one image file name");
3388 filename
= argv
[optind
++];
3390 /* Open the image */
3391 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3398 /* Perform the requested action */
3404 case SNAPSHOT_CREATE
:
3405 memset(&sn
, 0, sizeof(sn
));
3406 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3408 qemu_gettimeofday(&tv
);
3409 sn
.date_sec
= tv
.tv_sec
;
3410 sn
.date_nsec
= tv
.tv_usec
* 1000;
3412 ret
= bdrv_snapshot_create(bs
, &sn
);
3414 error_report("Could not create snapshot '%s': %d (%s)",
3415 snapshot_name
, ret
, strerror(-ret
));
3419 case SNAPSHOT_APPLY
:
3420 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3422 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3427 case SNAPSHOT_DELETE
:
3428 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3430 error_report("Could not delete snapshot '%s': snapshot not "
3431 "found", snapshot_name
);
3434 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3436 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3452 static int img_rebase(int argc
, char **argv
)
3454 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3455 uint8_t *buf_old
= NULL
;
3456 uint8_t *buf_new
= NULL
;
3457 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3458 BlockDriverState
*unfiltered_bs
;
3460 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3461 int c
, flags
, src_flags
, ret
;
3462 bool writethrough
, src_writethrough
;
3464 bool force_share
= false;
3467 Error
*local_err
= NULL
;
3468 bool image_opts
= false;
3470 /* Parse commandline parameters */
3472 cache
= BDRV_DEFAULT_CACHE
;
3473 src_cache
= BDRV_DEFAULT_CACHE
;
3477 static const struct option long_options
[] = {
3478 {"help", no_argument
, 0, 'h'},
3479 {"object", required_argument
, 0, OPTION_OBJECT
},
3480 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3481 {"force-share", no_argument
, 0, 'U'},
3484 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3485 long_options
, NULL
);
3491 missing_argument(argv
[optind
- 1]);
3494 unrecognized_option(argv
[optind
- 1]);
3503 out_basefmt
= optarg
;
3506 out_baseimg
= optarg
;
3524 user_creatable_process_cmdline(optarg
);
3526 case OPTION_IMAGE_OPTS
:
3539 if (optind
!= argc
- 1) {
3540 error_exit("Expecting one image file name");
3542 if (!unsafe
&& !out_baseimg
) {
3543 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3545 filename
= argv
[optind
++];
3547 qemu_progress_init(progress
, 2.0);
3548 qemu_progress_print(0, 100);
3550 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3551 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3553 error_report("Invalid cache option: %s", cache
);
3558 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3560 error_report("Invalid source cache option: %s", src_cache
);
3564 /* The source files are opened read-only, don't care about WCE */
3565 assert((src_flags
& BDRV_O_RDWR
) == 0);
3566 (void) src_writethrough
;
3571 * Ignore the old backing file for unsafe rebase in case we want to correct
3572 * the reference to a renamed or moved backing file.
3574 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3582 unfiltered_bs
= bdrv_skip_filters(bs
);
3584 if (out_basefmt
!= NULL
) {
3585 if (bdrv_find_format(out_basefmt
) == NULL
) {
3586 error_report("Invalid format name: '%s'", out_basefmt
);
3592 /* For safe rebasing we need to compare old and new backing file */
3594 QDict
*options
= NULL
;
3595 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3598 blk_old_backing
= blk_new(qemu_get_aio_context(),
3599 BLK_PERM_CONSISTENT_READ
,
3601 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3604 error_reportf_err(local_err
,
3605 "Could not reuse old backing file '%s': ",
3610 blk_old_backing
= NULL
;
3613 if (out_baseimg
[0]) {
3614 const char *overlay_filename
;
3615 char *out_real_path
;
3617 options
= qdict_new();
3619 qdict_put_str(options
, "driver", out_basefmt
);
3622 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3625 bdrv_refresh_filename(bs
);
3626 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3629 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3633 qobject_unref(options
);
3634 error_reportf_err(local_err
,
3635 "Could not resolve backing filename: ");
3641 * Find out whether we rebase an image on top of a previous image
3644 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3645 if (prefix_chain_bs
) {
3646 qobject_unref(options
);
3647 g_free(out_real_path
);
3649 blk_new_backing
= blk_new(qemu_get_aio_context(),
3650 BLK_PERM_CONSISTENT_READ
,
3652 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3655 error_reportf_err(local_err
,
3656 "Could not reuse backing file '%s': ",
3661 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3662 options
, src_flags
, &local_err
);
3663 g_free(out_real_path
);
3664 if (!blk_new_backing
) {
3665 error_reportf_err(local_err
,
3666 "Could not open new backing file '%s': ",
3676 * Check each unallocated cluster in the COW file. If it is unallocated,
3677 * accesses go to the backing file. We must therefore compare this cluster
3678 * in the old and new backing file, and if they differ we need to copy it
3679 * from the old backing file into the COW file.
3681 * If qemu-img crashes during this step, no harm is done. The content of
3682 * the image is the same as the original one at any time.
3686 int64_t old_backing_size
= 0;
3687 int64_t new_backing_size
= 0;
3690 float local_progress
= 0;
3692 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3693 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3695 size
= blk_getlength(blk
);
3697 error_report("Could not get size of '%s': %s",
3698 filename
, strerror(-size
));
3702 if (blk_old_backing
) {
3703 old_backing_size
= blk_getlength(blk_old_backing
);
3704 if (old_backing_size
< 0) {
3705 char backing_name
[PATH_MAX
];
3707 bdrv_get_backing_filename(bs
, backing_name
,
3708 sizeof(backing_name
));
3709 error_report("Could not get size of '%s': %s",
3710 backing_name
, strerror(-old_backing_size
));
3715 if (blk_new_backing
) {
3716 new_backing_size
= blk_getlength(blk_new_backing
);
3717 if (new_backing_size
< 0) {
3718 error_report("Could not get size of '%s': %s",
3719 out_baseimg
, strerror(-new_backing_size
));
3726 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3729 for (offset
= 0; offset
< size
; offset
+= n
) {
3730 bool buf_old_is_zero
= false;
3732 /* How many bytes can we handle with the next read? */
3733 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3735 /* If the cluster is allocated, we don't need to take action */
3736 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3738 error_report("error while reading image metadata: %s",
3746 if (prefix_chain_bs
) {
3748 * If cluster wasn't changed since prefix_chain, we don't need
3751 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3752 prefix_chain_bs
, false,
3755 error_report("error while reading image metadata: %s",
3765 * Read old and new backing file and take into consideration that
3766 * backing files may be smaller than the COW image.
3768 if (offset
>= old_backing_size
) {
3769 memset(buf_old
, 0, n
);
3770 buf_old_is_zero
= true;
3772 if (offset
+ n
> old_backing_size
) {
3773 n
= old_backing_size
- offset
;
3776 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3778 error_report("error while reading from old backing file");
3783 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3784 memset(buf_new
, 0, n
);
3786 if (offset
+ n
> new_backing_size
) {
3787 n
= new_backing_size
- offset
;
3790 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3792 error_report("error while reading from new backing file");
3797 /* If they differ, we need to write to the COW file */
3798 uint64_t written
= 0;
3800 while (written
< n
) {
3803 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3804 n
- written
, &pnum
))
3806 if (buf_old_is_zero
) {
3807 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3809 ret
= blk_pwrite(blk
, offset
+ written
,
3810 buf_old
+ written
, pnum
, 0);
3813 error_report("Error while writing to COW image: %s",
3821 qemu_progress_print(local_progress
, 100);
3826 * Change the backing file. All clusters that are different from the old
3827 * backing file are overwritten in the COW file now, so the visible content
3828 * doesn't change when we switch the backing file.
3830 if (out_baseimg
&& *out_baseimg
) {
3831 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3834 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3837 if (ret
== -ENOSPC
) {
3838 error_report("Could not change the backing file to '%s': No "
3839 "space left in the file header", out_baseimg
);
3840 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3841 error_report("Could not change the backing file to '%s': backing "
3842 "format must be specified", out_baseimg
);
3843 } else if (ret
< 0) {
3844 error_report("Could not change the backing file to '%s': %s",
3845 out_baseimg
, strerror(-ret
));
3848 qemu_progress_print(100, 0);
3850 * TODO At this point it is possible to check if any clusters that are
3851 * allocated in the COW file are the same in the backing file. If so, they
3852 * could be dropped from the COW file. Don't do this before switching the
3853 * backing file, in case of a crash this would lead to corruption.
3856 qemu_progress_end();
3859 blk_unref(blk_old_backing
);
3860 blk_unref(blk_new_backing
);
3862 qemu_vfree(buf_old
);
3863 qemu_vfree(buf_new
);
3872 static int img_resize(int argc
, char **argv
)
3875 int c
, ret
, relative
;
3876 const char *filename
, *fmt
, *size
;
3877 int64_t n
, total_size
, current_size
;
3879 BlockBackend
*blk
= NULL
;
3880 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3883 static QemuOptsList resize_options
= {
3884 .name
= "resize_options",
3885 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3888 .name
= BLOCK_OPT_SIZE
,
3889 .type
= QEMU_OPT_SIZE
,
3890 .help
= "Virtual disk size"
3896 bool image_opts
= false;
3897 bool shrink
= false;
3899 /* Remove size from argv manually so that negative numbers are not treated
3900 * as options by getopt. */
3902 error_exit("Not enough arguments");
3906 size
= argv
[--argc
];
3908 /* Parse getopt arguments */
3911 static const struct option long_options
[] = {
3912 {"help", no_argument
, 0, 'h'},
3913 {"object", required_argument
, 0, OPTION_OBJECT
},
3914 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3915 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3916 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3919 c
= getopt_long(argc
, argv
, ":f:hq",
3920 long_options
, NULL
);
3926 missing_argument(argv
[optind
- 1]);
3929 unrecognized_option(argv
[optind
- 1]);
3941 user_creatable_process_cmdline(optarg
);
3943 case OPTION_IMAGE_OPTS
:
3946 case OPTION_PREALLOCATION
:
3947 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3948 PREALLOC_MODE__MAX
, NULL
);
3949 if (prealloc
== PREALLOC_MODE__MAX
) {
3950 error_report("Invalid preallocation mode '%s'", optarg
);
3959 if (optind
!= argc
- 1) {
3960 error_exit("Expecting image file name and size");
3962 filename
= argv
[optind
++];
3964 /* Choose grow, shrink, or absolute resize mode */
3980 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3981 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3982 error_report_err(err
);
3984 qemu_opts_del(param
);
3987 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3988 qemu_opts_del(param
);
3990 blk
= img_open(image_opts
, filename
, fmt
,
3991 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3998 current_size
= blk_getlength(blk
);
3999 if (current_size
< 0) {
4000 error_report("Failed to inquire current image length: %s",
4001 strerror(-current_size
));
4007 total_size
= current_size
+ n
* relative
;
4011 if (total_size
<= 0) {
4012 error_report("New image size must be positive");
4017 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4018 error_report("Preallocation can only be used for growing images");
4023 if (total_size
< current_size
&& !shrink
) {
4024 error_report("Use the --shrink option to perform a shrink operation.");
4025 warn_report("Shrinking an image will delete all data beyond the "
4026 "shrunken image's end. Before performing such an "
4027 "operation, make sure there is no important data there.");
4033 * The user expects the image to have the desired size after
4034 * resizing, so pass @exact=true. It is of no use to report
4035 * success when the image has not actually been resized.
4037 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4039 qprintf(quiet
, "Image resized.\n");
4041 error_report_err(err
);
4051 static void amend_status_cb(BlockDriverState
*bs
,
4052 int64_t offset
, int64_t total_work_size
,
4055 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4058 static int print_amend_option_help(const char *format
)
4062 /* Find driver and parse its options */
4063 drv
= bdrv_find_format(format
);
4065 error_report("Unknown file format '%s'", format
);
4069 if (!drv
->bdrv_amend_options
) {
4070 error_report("Format driver '%s' does not support option amendment",
4075 /* Every driver supporting amendment must have amend_opts */
4076 assert(drv
->amend_opts
);
4078 printf("Amend options for '%s':\n", format
);
4079 qemu_opts_print_help(drv
->amend_opts
, false);
4083 static int img_amend(int argc
, char **argv
)
4087 char *options
= NULL
;
4088 QemuOptsList
*amend_opts
= NULL
;
4089 QemuOpts
*opts
= NULL
;
4090 const char *fmt
= NULL
, *filename
, *cache
;
4093 bool quiet
= false, progress
= false;
4094 BlockBackend
*blk
= NULL
;
4095 BlockDriverState
*bs
= NULL
;
4096 bool image_opts
= false;
4099 cache
= BDRV_DEFAULT_CACHE
;
4101 static const struct option long_options
[] = {
4102 {"help", no_argument
, 0, 'h'},
4103 {"object", required_argument
, 0, OPTION_OBJECT
},
4104 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4105 {"force", no_argument
, 0, OPTION_FORCE
},
4108 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4109 long_options
, NULL
);
4116 missing_argument(argv
[optind
- 1]);
4119 unrecognized_option(argv
[optind
- 1]);
4125 if (accumulate_options(&options
, optarg
) < 0) {
4127 goto out_no_progress
;
4143 user_creatable_process_cmdline(optarg
);
4145 case OPTION_IMAGE_OPTS
:
4155 error_exit("Must specify options (-o)");
4161 qemu_progress_init(progress
, 1.0);
4163 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4164 if (fmt
&& has_help_option(options
)) {
4165 /* If a format is explicitly specified (and possibly no filename is
4166 * given), print option help here */
4167 ret
= print_amend_option_help(fmt
);
4171 if (optind
!= argc
- 1) {
4172 error_report("Expecting one image file name");
4177 flags
= BDRV_O_RDWR
;
4178 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4180 error_report("Invalid cache option: %s", cache
);
4184 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4192 fmt
= bs
->drv
->format_name
;
4194 if (has_help_option(options
)) {
4195 /* If the format was auto-detected, print option help here */
4196 ret
= print_amend_option_help(fmt
);
4200 if (!bs
->drv
->bdrv_amend_options
) {
4201 error_report("Format driver '%s' does not support option amendment",
4207 /* Every driver supporting amendment must have amend_opts */
4208 assert(bs
->drv
->amend_opts
);
4210 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4211 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4212 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4213 /* Try to parse options using the create options */
4214 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4215 qemu_opts_del(opts
);
4216 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4217 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4218 error_append_hint(&err
,
4219 "This option is only supported for image creation\n");
4222 error_report_err(err
);
4227 /* In case the driver does not call amend_status_cb() */
4228 qemu_progress_print(0.f
, 0);
4229 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4230 qemu_progress_print(100.f
, 0);
4232 error_report_err(err
);
4237 qemu_progress_end();
4241 qemu_opts_del(opts
);
4242 qemu_opts_free(amend_opts
);
4251 typedef struct BenchData
{
4253 uint64_t image_size
;
4260 bool drain_on_flush
;
4269 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4272 error_report("Failed flush request: %s", strerror(-ret
));
4277 static void bench_cb(void *opaque
, int ret
)
4279 BenchData
*b
= opaque
;
4283 error_report("Failed request: %s", strerror(-ret
));
4288 /* Just finished a flush with drained queue: Start next requests */
4289 assert(b
->in_flight
== 0);
4290 b
->in_flush
= false;
4291 } else if (b
->in_flight
> 0) {
4292 int remaining
= b
->n
- b
->in_flight
;
4297 /* Time for flush? Drain queue if requested, then flush */
4298 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4299 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4300 BlockCompletionFunc
*cb
;
4302 if (b
->drain_on_flush
) {
4306 cb
= bench_undrained_flush_cb
;
4309 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4311 error_report("Failed to issue flush request");
4315 if (b
->drain_on_flush
) {
4321 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4322 int64_t offset
= b
->offset
;
4323 /* blk_aio_* might look for completed I/Os and kick bench_cb
4324 * again, so make sure this operation is counted by in_flight
4325 * and b->offset is ready for the next submission.
4328 b
->offset
+= b
->step
;
4329 b
->offset
%= b
->image_size
;
4331 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4333 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4336 error_report("Failed to issue request");
4342 static int img_bench(int argc
, char **argv
)
4345 const char *fmt
= NULL
, *filename
;
4347 bool image_opts
= false;
4348 bool is_write
= false;
4352 size_t bufsize
= 4096;
4355 int flush_interval
= 0;
4356 bool drain_on_flush
= true;
4358 BlockBackend
*blk
= NULL
;
4359 BenchData data
= {};
4361 bool writethrough
= false;
4362 struct timeval t1
, t2
;
4364 bool force_share
= false;
4368 static const struct option long_options
[] = {
4369 {"help", no_argument
, 0, 'h'},
4370 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4371 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4372 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4373 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4374 {"force-share", no_argument
, 0, 'U'},
4377 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4385 missing_argument(argv
[optind
- 1]);
4388 unrecognized_option(argv
[optind
- 1]);
4397 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4398 error_report("Invalid request count specified");
4408 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4409 error_report("Invalid queue depth specified");
4419 flags
|= BDRV_O_NATIVE_AIO
;
4422 ret
= bdrv_parse_aio(optarg
, &flags
);
4424 error_report("Invalid aio option: %s", optarg
);
4431 offset
= cvtnum("offset", optarg
);
4445 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4457 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4466 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4468 error_report("Invalid cache mode");
4474 flags
|= BDRV_O_RDWR
;
4480 case OPTION_PATTERN
:
4484 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4485 error_report("Invalid pattern byte specified");
4491 case OPTION_FLUSH_INTERVAL
:
4495 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4496 error_report("Invalid flush interval specified");
4499 flush_interval
= res
;
4502 case OPTION_NO_DRAIN
:
4503 drain_on_flush
= false;
4505 case OPTION_IMAGE_OPTS
:
4511 if (optind
!= argc
- 1) {
4512 error_exit("Expecting one image file name");
4514 filename
= argv
[argc
- 1];
4516 if (!is_write
&& flush_interval
) {
4517 error_report("--flush-interval is only available in write tests");
4521 if (flush_interval
&& flush_interval
< depth
) {
4522 error_report("Flush interval can't be smaller than depth");
4527 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4534 image_size
= blk_getlength(blk
);
4535 if (image_size
< 0) {
4540 data
= (BenchData
) {
4542 .image_size
= image_size
,
4544 .step
= step
?: bufsize
,
4549 .flush_interval
= flush_interval
,
4550 .drain_on_flush
= drain_on_flush
,
4552 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4553 "(starting at offset %" PRId64
", step size %d)\n",
4554 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4555 data
.offset
, data
.step
);
4556 if (flush_interval
) {
4557 printf("Sending flush every %d requests\n", flush_interval
);
4560 buf_size
= data
.nrreq
* data
.bufsize
;
4561 data
.buf
= blk_blockalign(blk
, buf_size
);
4562 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4564 blk_register_buf(blk
, data
.buf
, buf_size
);
4566 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4567 for (i
= 0; i
< data
.nrreq
; i
++) {
4568 qemu_iovec_init(&data
.qiov
[i
], 1);
4569 qemu_iovec_add(&data
.qiov
[i
],
4570 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4573 gettimeofday(&t1
, NULL
);
4576 while (data
.n
> 0) {
4577 main_loop_wait(false);
4579 gettimeofday(&t2
, NULL
);
4581 printf("Run completed in %3.3f seconds.\n",
4582 (t2
.tv_sec
- t1
.tv_sec
)
4583 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4587 blk_unregister_buf(blk
, data
.buf
);
4589 qemu_vfree(data
.buf
);
4606 typedef struct ImgBitmapAction
{
4607 enum ImgBitmapAct act
;
4608 const char *src
; /* only used for merge */
4609 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4612 static int img_bitmap(int argc
, char **argv
)
4616 QemuOpts
*opts
= NULL
;
4617 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4618 const char *filename
, *bitmap
;
4619 BlockBackend
*blk
= NULL
, *src
= NULL
;
4620 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4621 bool image_opts
= false;
4622 int64_t granularity
= 0;
4623 bool add
= false, merge
= false;
4624 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4625 ImgBitmapAction
*act
, *act_next
;
4628 QSIMPLEQ_INIT(&actions
);
4631 static const struct option long_options
[] = {
4632 {"help", no_argument
, 0, 'h'},
4633 {"object", required_argument
, 0, OPTION_OBJECT
},
4634 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4635 {"add", no_argument
, 0, OPTION_ADD
},
4636 {"remove", no_argument
, 0, OPTION_REMOVE
},
4637 {"clear", no_argument
, 0, OPTION_CLEAR
},
4638 {"enable", no_argument
, 0, OPTION_ENABLE
},
4639 {"disable", no_argument
, 0, OPTION_DISABLE
},
4640 {"merge", required_argument
, 0, OPTION_MERGE
},
4641 {"granularity", required_argument
, 0, 'g'},
4642 {"source-file", required_argument
, 0, 'b'},
4643 {"source-format", required_argument
, 0, 'F'},
4646 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4653 missing_argument(argv
[optind
- 1]);
4656 unrecognized_option(argv
[optind
- 1]);
4662 src_filename
= optarg
;
4671 granularity
= cvtnum("granularity", optarg
);
4672 if (granularity
< 0) {
4677 act
= g_new0(ImgBitmapAction
, 1);
4678 act
->act
= BITMAP_ADD
;
4679 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4683 act
= g_new0(ImgBitmapAction
, 1);
4684 act
->act
= BITMAP_REMOVE
;
4685 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4688 act
= g_new0(ImgBitmapAction
, 1);
4689 act
->act
= BITMAP_CLEAR
;
4690 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4693 act
= g_new0(ImgBitmapAction
, 1);
4694 act
->act
= BITMAP_ENABLE
;
4695 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4697 case OPTION_DISABLE
:
4698 act
= g_new0(ImgBitmapAction
, 1);
4699 act
->act
= BITMAP_DISABLE
;
4700 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4703 act
= g_new0(ImgBitmapAction
, 1);
4704 act
->act
= BITMAP_MERGE
;
4706 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4710 user_creatable_process_cmdline(optarg
);
4712 case OPTION_IMAGE_OPTS
:
4718 if (QSIMPLEQ_EMPTY(&actions
)) {
4719 error_report("Need at least one of --add, --remove, --clear, "
4720 "--enable, --disable, or --merge");
4724 if (granularity
&& !add
) {
4725 error_report("granularity only supported with --add");
4728 if (src_fmt
&& !src_filename
) {
4729 error_report("-F only supported with -b");
4732 if (src_filename
&& !merge
) {
4733 error_report("Merge bitmap source file only supported with "
4738 if (optind
!= argc
- 2) {
4739 error_report("Expecting filename and bitmap name");
4743 filename
= argv
[optind
];
4744 bitmap
= argv
[optind
+ 1];
4747 * No need to open backing chains; we will be manipulating bitmaps
4748 * directly in this image without reference to image contents.
4750 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4751 false, false, false);
4757 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4758 false, false, false);
4762 src_bs
= blk_bs(src
);
4767 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4770 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4771 !!granularity
, granularity
, true, true,
4772 false, false, &err
);
4776 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4780 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4784 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4787 case BITMAP_DISABLE
:
4788 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4792 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4797 g_assert_not_reached();
4801 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4813 qemu_opts_del(opts
);
4829 int bsz
; /* Block size */
4837 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4841 static int img_dd_bs(const char *arg
,
4842 struct DdIo
*in
, struct DdIo
*out
,
4847 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4852 in
->bsz
= out
->bsz
= res
;
4857 static int img_dd_count(const char *arg
,
4858 struct DdIo
*in
, struct DdIo
*out
,
4861 dd
->count
= cvtnum("count", arg
);
4863 if (dd
->count
< 0) {
4870 static int img_dd_if(const char *arg
,
4871 struct DdIo
*in
, struct DdIo
*out
,
4874 in
->filename
= g_strdup(arg
);
4879 static int img_dd_of(const char *arg
,
4880 struct DdIo
*in
, struct DdIo
*out
,
4883 out
->filename
= g_strdup(arg
);
4888 static int img_dd_skip(const char *arg
,
4889 struct DdIo
*in
, struct DdIo
*out
,
4892 in
->offset
= cvtnum("skip", arg
);
4894 if (in
->offset
< 0) {
4901 static int img_dd(int argc
, char **argv
)
4906 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4907 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4908 QemuOpts
*opts
= NULL
;
4909 QemuOptsList
*create_opts
= NULL
;
4910 Error
*local_err
= NULL
;
4911 bool image_opts
= false;
4913 const char *out_fmt
= "raw";
4914 const char *fmt
= NULL
;
4916 int64_t block_count
= 0, out_pos
, in_pos
;
4917 bool force_share
= false;
4918 struct DdInfo dd
= {
4923 .bsz
= 512, /* Block size is by default 512 bytes */
4935 const struct DdOpts options
[] = {
4936 { "bs", img_dd_bs
, C_BS
},
4937 { "count", img_dd_count
, C_COUNT
},
4938 { "if", img_dd_if
, C_IF
},
4939 { "of", img_dd_of
, C_OF
},
4940 { "skip", img_dd_skip
, C_SKIP
},
4943 const struct option long_options
[] = {
4944 { "help", no_argument
, 0, 'h'},
4945 { "object", required_argument
, 0, OPTION_OBJECT
},
4946 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4947 { "force-share", no_argument
, 0, 'U'},
4951 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4963 missing_argument(argv
[optind
- 1]);
4966 unrecognized_option(argv
[optind
- 1]);
4975 user_creatable_process_cmdline(optarg
);
4977 case OPTION_IMAGE_OPTS
:
4983 for (i
= optind
; i
< argc
; i
++) {
4985 arg
= g_strdup(argv
[i
]);
4987 tmp
= strchr(arg
, '=');
4989 error_report("unrecognized operand %s", arg
);
4996 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4997 if (!strcmp(arg
, options
[j
].name
)) {
5001 if (options
[j
].name
== NULL
) {
5002 error_report("unrecognized operand %s", arg
);
5007 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5011 dd
.flags
|= options
[j
].flag
;
5016 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5017 error_report("Must specify both input and output files");
5022 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5030 drv
= bdrv_find_format(out_fmt
);
5032 error_report("Unknown file format");
5036 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5039 error_report_err(local_err
);
5043 if (!drv
->create_opts
) {
5044 error_report("Format driver '%s' does not support image creation",
5049 if (!proto_drv
->create_opts
) {
5050 error_report("Protocol driver '%s' does not support image creation",
5051 proto_drv
->format_name
);
5055 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5056 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5058 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5060 size
= blk_getlength(blk1
);
5062 error_report("Failed to get size for '%s'", in
.filename
);
5067 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5068 dd
.count
* in
.bsz
< size
) {
5069 size
= dd
.count
* in
.bsz
;
5072 /* Overflow means the specified offset is beyond input image's size */
5073 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5074 size
< in
.bsz
* in
.offset
)) {
5075 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5077 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5078 size
- in
.bsz
* in
.offset
, &error_abort
);
5081 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5083 error_reportf_err(local_err
,
5084 "%s: error while creating output image: ",
5090 /* TODO, we can't honour --image-opts for the target,
5091 * since it needs to be given in a format compatible
5092 * with the bdrv_create() call above which does not
5093 * support image-opts style.
5095 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5096 false, false, false);
5103 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5104 size
< in
.offset
* in
.bsz
)) {
5105 /* We give a warning if the skip option is bigger than the input
5106 * size and create an empty output disk image (i.e. like dd(1)).
5108 error_report("%s: cannot skip to specified offset", in
.filename
);
5111 in_pos
= in
.offset
* in
.bsz
;
5114 in
.buf
= g_new(uint8_t, in
.bsz
);
5116 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5117 int in_ret
, out_ret
;
5119 if (in_pos
+ in
.bsz
> size
) {
5120 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5122 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5125 error_report("error while reading from input image file: %s",
5132 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5135 error_report("error while writing to output image file: %s",
5136 strerror(-out_ret
));
5145 qemu_opts_del(opts
);
5146 qemu_opts_free(create_opts
);
5149 g_free(in
.filename
);
5150 g_free(out
.filename
);
5160 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5164 Visitor
*v
= qobject_output_visitor_new(&obj
);
5166 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5167 visit_complete(v
, &obj
);
5168 str
= qobject_to_json_pretty(obj
, true);
5169 assert(str
!= NULL
);
5170 printf("%s\n", str
->str
);
5173 g_string_free(str
, true);
5176 static int img_measure(int argc
, char **argv
)
5178 static const struct option long_options
[] = {
5179 {"help", no_argument
, 0, 'h'},
5180 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5181 {"object", required_argument
, 0, OPTION_OBJECT
},
5182 {"output", required_argument
, 0, OPTION_OUTPUT
},
5183 {"size", required_argument
, 0, OPTION_SIZE
},
5184 {"force-share", no_argument
, 0, 'U'},
5187 OutputFormat output_format
= OFORMAT_HUMAN
;
5188 BlockBackend
*in_blk
= NULL
;
5190 const char *filename
= NULL
;
5191 const char *fmt
= NULL
;
5192 const char *out_fmt
= "raw";
5193 char *options
= NULL
;
5194 char *snapshot_name
= NULL
;
5195 bool force_share
= false;
5196 QemuOpts
*opts
= NULL
;
5197 QemuOpts
*object_opts
= NULL
;
5198 QemuOpts
*sn_opts
= NULL
;
5199 QemuOptsList
*create_opts
= NULL
;
5200 bool image_opts
= false;
5201 uint64_t img_size
= UINT64_MAX
;
5202 BlockMeasureInfo
*info
= NULL
;
5203 Error
*local_err
= NULL
;
5207 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5208 long_options
, NULL
)) != -1) {
5221 if (accumulate_options(&options
, optarg
) < 0) {
5226 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5227 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5230 error_report("Failed in parsing snapshot param '%s'",
5235 snapshot_name
= optarg
;
5242 user_creatable_process_cmdline(optarg
);
5244 case OPTION_IMAGE_OPTS
:
5248 if (!strcmp(optarg
, "json")) {
5249 output_format
= OFORMAT_JSON
;
5250 } else if (!strcmp(optarg
, "human")) {
5251 output_format
= OFORMAT_HUMAN
;
5253 error_report("--output must be used with human or json "
5262 sval
= cvtnum("image size", optarg
);
5266 img_size
= (uint64_t)sval
;
5272 if (argc
- optind
> 1) {
5273 error_report("At most one filename argument is allowed.");
5275 } else if (argc
- optind
== 1) {
5276 filename
= argv
[optind
];
5279 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5280 error_report("--image-opts, -f, and -l require a filename argument.");
5283 if (filename
&& img_size
!= UINT64_MAX
) {
5284 error_report("--size N cannot be used together with a filename.");
5287 if (!filename
&& img_size
== UINT64_MAX
) {
5288 error_report("Either --size N or one filename must be specified.");
5293 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5294 false, false, force_share
);
5300 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5301 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5302 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5304 } else if (snapshot_name
!= NULL
) {
5305 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5306 snapshot_name
, &local_err
);
5309 error_reportf_err(local_err
, "Failed to load snapshot: ");
5314 drv
= bdrv_find_format(out_fmt
);
5316 error_report("Unknown file format '%s'", out_fmt
);
5319 if (!drv
->create_opts
) {
5320 error_report("Format driver '%s' does not support image creation",
5325 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5326 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5327 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5329 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5330 error_report_err(local_err
);
5331 error_report("Invalid options for file format '%s'", out_fmt
);
5335 if (img_size
!= UINT64_MAX
) {
5336 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5339 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5341 error_report_err(local_err
);
5345 if (output_format
== OFORMAT_HUMAN
) {
5346 printf("required size: %" PRIu64
"\n", info
->required
);
5347 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5348 if (info
->has_bitmaps
) {
5349 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5352 dump_json_block_measure_info(info
);
5358 qapi_free_BlockMeasureInfo(info
);
5359 qemu_opts_del(object_opts
);
5360 qemu_opts_del(opts
);
5361 qemu_opts_del(sn_opts
);
5362 qemu_opts_free(create_opts
);
5368 static const img_cmd_t img_cmds
[] = {
5369 #define DEF(option, callback, arg_string) \
5370 { option, callback },
5371 #include "qemu-img-cmds.h"
5376 int main(int argc
, char **argv
)
5378 const img_cmd_t
*cmd
;
5379 const char *cmdname
;
5381 static const struct option long_options
[] = {
5382 {"help", no_argument
, 0, 'h'},
5383 {"version", no_argument
, 0, 'V'},
5384 {"trace", required_argument
, NULL
, 'T'},
5389 signal(SIGPIPE
, SIG_IGN
);
5393 error_init(argv
[0]);
5394 module_call_init(MODULE_INIT_TRACE
);
5395 qemu_init_exec_dir(argv
[0]);
5397 qemu_init_main_loop(&error_fatal
);
5399 qcrypto_init(&error_fatal
);
5401 module_call_init(MODULE_INIT_QOM
);
5404 error_exit("Not enough arguments");
5407 qemu_add_opts(&qemu_source_opts
);
5408 qemu_add_opts(&qemu_trace_opts
);
5410 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5413 missing_argument(argv
[optind
- 1]);
5416 unrecognized_option(argv
[optind
- 1]);
5422 printf(QEMU_IMG_VERSION
);
5425 trace_opt_parse(optarg
);
5430 cmdname
= argv
[optind
];
5432 /* reset getopt_long scanning */
5438 qemu_reset_optind();
5440 if (!trace_init_backends()) {
5444 qemu_set_log(LOG_TRACE
);
5446 /* find the command */
5447 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5448 if (!strcmp(cmdname
, cmd
->name
)) {
5449 return cmd
->handler(argc
, argv
);
5454 error_exit("Command not found: %s", cmdname
);