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/help-texts.h"
29 #include "qemu/qemu-progress.h"
30 #include "qemu-version.h"
31 #include "qapi/error.h"
32 #include "qapi/qapi-commands-block-core.h"
33 #include "qapi/qapi-visit-block-core.h"
34 #include "qapi/qobject-output-visitor.h"
35 #include "qapi/qmp/qjson.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/sockets.h"
45 #include "qemu/units.h"
46 #include "qemu/memalign.h"
47 #include "qom/object_interfaces.h"
48 #include "sysemu/block-backend.h"
49 #include "block/block_int.h"
50 #include "block/blockjob.h"
51 #include "block/qapi.h"
52 #include "crypto/init.h"
53 #include "trace/control.h"
54 #include "qemu/throttle.h"
55 #include "block/throttle-groups.h"
57 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
58 "\n" QEMU_COPYRIGHT "\n"
60 typedef struct img_cmd_t
{
62 int (*handler
)(int argc
, char **argv
);
67 OPTION_BACKING_CHAIN
= 257,
69 OPTION_IMAGE_OPTS
= 259,
71 OPTION_FLUSH_INTERVAL
= 261,
72 OPTION_NO_DRAIN
= 262,
73 OPTION_TARGET_IMAGE_OPTS
= 263,
75 OPTION_PREALLOCATION
= 265,
78 OPTION_TARGET_IS_ZERO
= 268,
87 OPTION_SKIP_BROKEN
= 277,
90 typedef enum OutputFormat
{
95 /* Default to cache=writeback as data integrity is not important for qemu-img */
96 #define BDRV_DEFAULT_CACHE "writeback"
98 static void format_print(void *opaque
, const char *name
)
103 static G_NORETURN
G_GNUC_PRINTF(1, 2)
104 void error_exit(const char *fmt
, ...)
109 error_vreport(fmt
, ap
);
112 error_printf("Try 'qemu-img --help' for more information\n");
117 void missing_argument(const char *option
)
119 error_exit("missing argument for option '%s'", option
);
123 void unrecognized_option(const char *option
)
125 error_exit("unrecognized option '%s'", option
);
128 /* Please keep in synch with docs/tools/qemu-img.rst */
132 const char *help_msg
=
134 "usage: qemu-img [standard options] command [command options]\n"
135 "QEMU disk image utility\n"
137 " '-h', '--help' display this help and exit\n"
138 " '-V', '--version' output version information and exit\n"
139 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
140 " specify tracing options\n"
143 #define DEF(option, callback, arg_string) \
145 #include "qemu-img-cmds.h"
148 "Command parameters:\n"
149 " 'filename' is a disk image filename\n"
150 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
151 " manual page for a description of the object properties. The most common\n"
152 " object type is a 'secret', which is used to supply passwords and/or\n"
153 " encryption keys.\n"
154 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
155 " 'cache' is the cache mode used to write the output disk image, the valid\n"
156 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
157 " 'directsync' and 'unsafe' (default for convert)\n"
158 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
159 " options are the same as for the 'cache' option\n"
160 " 'size' is the disk image size in bytes. Optional suffixes\n"
161 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
162 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
163 " supported. 'b' is ignored.\n"
164 " 'output_filename' is the destination disk image filename\n"
165 " 'output_fmt' is the destination format\n"
166 " 'options' is a comma separated list of format specific options in a\n"
167 " name=value format. Use -o ? for an overview of the options supported by the\n"
169 " 'snapshot_param' is param used for internal snapshot, format\n"
170 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
172 " '-c' indicates that target image must be compressed (qcow format only)\n"
173 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
174 " new backing file match exactly. The image doesn't need a working\n"
175 " backing file before rebasing in this case (useful for renaming the\n"
176 " backing file). For image creation, allow creating without attempting\n"
177 " to open the backing file.\n"
178 " '-h' with or without a command shows this help and lists the supported formats\n"
179 " '-p' show progress of command (only certain commands)\n"
180 " '-q' use Quiet mode - do not print any output (except errors)\n"
181 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
182 " contain only zeros for qemu-img to create a sparse image during\n"
183 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
184 " unallocated or zero sectors, and the destination image will always be\n"
186 " '--output' takes the format in which the output must be done (human or json)\n"
187 " '-n' skips the target volume creation (useful if the volume is created\n"
188 " prior to running qemu-img)\n"
190 "Parameters to bitmap subcommand:\n"
191 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
192 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
193 " or '--merge source'\n"
194 " '-g granularity' sets the granularity for '--add' actions\n"
195 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
196 " bitmaps from an alternative file\n"
198 "Parameters to check subcommand:\n"
199 " '-r' tries to repair any inconsistencies that are found during the check.\n"
200 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
201 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
202 " hiding corruption that has already occurred.\n"
204 "Parameters to convert subcommand:\n"
205 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
206 " '-m' specifies how many coroutines work in parallel during the convert\n"
207 " process (defaults to 8)\n"
208 " '-W' allow to write to the target out of order rather than sequential\n"
210 "Parameters to snapshot subcommand:\n"
211 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
212 " '-a' applies a snapshot (revert disk to saved state)\n"
213 " '-c' creates a snapshot\n"
214 " '-d' deletes a snapshot\n"
215 " '-l' lists all snapshots in the given image\n"
217 "Parameters to compare subcommand:\n"
218 " '-f' first image format\n"
219 " '-F' second image format\n"
220 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
222 "Parameters to dd subcommand:\n"
223 " 'bs=BYTES' read and write up to BYTES bytes at a time "
225 " 'count=N' copy only N input blocks\n"
226 " 'if=FILE' read from FILE\n"
227 " 'of=FILE' write to FILE\n"
228 " 'skip=N' skip N bs-sized blocks at the start of input\n";
230 printf("%s\nSupported formats:", help_msg
);
231 bdrv_iterate_format(format_print
, NULL
, false);
232 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
237 * Is @optarg safe for accumulate_options()?
238 * It is when multiple of them can be joined together separated by ','.
239 * To make that work, @optarg must not start with ',' (or else a
240 * separating ',' preceding it gets escaped), and it must not end with
241 * an odd number of ',' (or else a separating ',' following it gets
242 * escaped), or be empty (or else a separating ',' preceding it can
243 * escape a separating ',' following it).
246 static bool is_valid_option_list(const char *optarg
)
248 size_t len
= strlen(optarg
);
251 if (!optarg
[0] || optarg
[0] == ',') {
255 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
264 static int accumulate_options(char **options
, char *optarg
)
268 if (!is_valid_option_list(optarg
)) {
269 error_report("Invalid option list: %s", optarg
);
274 *options
= g_strdup(optarg
);
276 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
278 *options
= new_options
;
283 static QemuOptsList qemu_source_opts
= {
285 .implied_opt_name
= "file",
286 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
292 static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
298 ret
= vprintf(fmt
, args
);
305 static int print_block_option_help(const char *filename
, const char *fmt
)
307 BlockDriver
*drv
, *proto_drv
;
308 QemuOptsList
*create_opts
= NULL
;
309 Error
*local_err
= NULL
;
311 /* Find driver and parse its options */
312 drv
= bdrv_find_format(fmt
);
314 error_report("Unknown file format '%s'", fmt
);
318 if (!drv
->create_opts
) {
319 error_report("Format driver '%s' does not support image creation", fmt
);
323 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
325 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
327 error_report_err(local_err
);
328 qemu_opts_free(create_opts
);
331 if (!proto_drv
->create_opts
) {
332 error_report("Protocol driver '%s' does not support image creation",
333 proto_drv
->format_name
);
334 qemu_opts_free(create_opts
);
337 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
341 printf("Supported options:\n");
343 printf("Supported %s options:\n", fmt
);
345 qemu_opts_print_help(create_opts
, false);
346 qemu_opts_free(create_opts
);
350 "The protocol level may support further options.\n"
351 "Specify the target filename to include those options.\n");
358 static BlockBackend
*img_open_opts(const char *optstr
,
359 QemuOpts
*opts
, int flags
, bool writethrough
,
360 bool quiet
, bool force_share
)
363 Error
*local_err
= NULL
;
365 options
= qemu_opts_to_qdict(opts
, NULL
);
367 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
368 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
369 error_report("--force-share/-U conflicts with image options");
370 qobject_unref(options
);
373 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
375 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
377 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
380 blk_set_enable_write_cache(blk
, !writethrough
);
385 static BlockBackend
*img_open_file(const char *filename
,
387 const char *fmt
, int flags
,
388 bool writethrough
, bool quiet
,
392 Error
*local_err
= NULL
;
395 options
= qdict_new();
398 qdict_put_str(options
, "driver", fmt
);
402 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
404 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
406 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
409 blk_set_enable_write_cache(blk
, !writethrough
);
415 static int img_add_key_secrets(void *opaque
,
416 const char *name
, const char *value
,
419 QDict
*options
= opaque
;
421 if (g_str_has_suffix(name
, "key-secret")) {
422 qdict_put_str(options
, name
, value
);
429 static BlockBackend
*img_open(bool image_opts
,
430 const char *filename
,
431 const char *fmt
, int flags
, bool writethrough
,
432 bool quiet
, bool force_share
)
438 error_report("--image-opts and --format are mutually exclusive");
441 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
446 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
449 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
456 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
457 const char *base_filename
,
458 const char *base_fmt
)
461 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
463 error_report("Backing file not supported for file format '%s'",
469 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
470 error_report("Backing file format not supported for file "
478 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
484 err
= qemu_strtosz(value
, NULL
, &res
);
485 if (err
< 0 && err
!= -ERANGE
) {
486 error_report("Invalid %s specified. You may use "
487 "k, M, G, T, P or E suffixes for", name
);
488 error_report("kilobytes, megabytes, gigabytes, terabytes, "
489 "petabytes and exabytes.");
492 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
493 error_report("Invalid %s specified. Must be between %" PRId64
494 " and %" PRId64
".", name
, min
, max
);
500 static int64_t cvtnum(const char *name
, const char *value
)
502 return cvtnum_full(name
, value
, 0, INT64_MAX
);
505 static int img_create(int argc
, char **argv
)
508 uint64_t img_size
= -1;
509 const char *fmt
= "raw";
510 const char *base_fmt
= NULL
;
511 const char *filename
;
512 const char *base_filename
= NULL
;
513 char *options
= NULL
;
514 Error
*local_err
= NULL
;
519 static const struct option long_options
[] = {
520 {"help", no_argument
, 0, 'h'},
521 {"object", required_argument
, 0, OPTION_OBJECT
},
524 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
531 missing_argument(argv
[optind
- 1]);
534 unrecognized_option(argv
[optind
- 1]);
543 base_filename
= optarg
;
549 if (accumulate_options(&options
, optarg
) < 0) {
557 flags
|= BDRV_O_NO_BACKING
;
560 user_creatable_process_cmdline(optarg
);
565 /* Get the filename */
566 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
567 if (options
&& has_help_option(options
)) {
569 return print_block_option_help(filename
, fmt
);
572 if (optind
>= argc
) {
573 error_exit("Expecting image file name");
577 /* Get image size, if specified */
581 sval
= cvtnum("image size", argv
[optind
++]);
585 img_size
= (uint64_t)sval
;
587 if (optind
!= argc
) {
588 error_exit("Unexpected argument: %s", argv
[optind
]);
591 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
592 options
, img_size
, flags
, quiet
, &local_err
);
594 error_reportf_err(local_err
, "%s: ", filename
);
606 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
610 Visitor
*v
= qobject_output_visitor_new(&obj
);
612 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
613 visit_complete(v
, &obj
);
614 str
= qobject_to_json_pretty(obj
, true);
616 qprintf(quiet
, "%s\n", str
->str
);
619 g_string_free(str
, true);
622 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
624 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
625 qprintf(quiet
, "No errors were found on the image.\n");
627 if (check
->corruptions
) {
628 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
629 "Data may be corrupted, or further writes to the image "
636 "\n%" PRId64
" leaked clusters were found on the image.\n"
637 "This means waste of disk space, but no harm to data.\n",
641 if (check
->check_errors
) {
644 " internal errors have occurred during the check.\n",
645 check
->check_errors
);
649 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
650 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
651 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
652 check
->allocated_clusters
, check
->total_clusters
,
653 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
654 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
655 check
->compressed_clusters
* 100.0 /
656 check
->allocated_clusters
);
659 if (check
->image_end_offset
) {
661 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
665 static int collect_image_check(BlockDriverState
*bs
,
667 const char *filename
,
672 BdrvCheckResult result
;
674 ret
= bdrv_check(bs
, &result
, fix
);
679 check
->filename
= g_strdup(filename
);
680 check
->format
= g_strdup(bdrv_get_format_name(bs
));
681 check
->check_errors
= result
.check_errors
;
682 check
->corruptions
= result
.corruptions
;
683 check
->has_corruptions
= result
.corruptions
!= 0;
684 check
->leaks
= result
.leaks
;
685 check
->has_leaks
= result
.leaks
!= 0;
686 check
->corruptions_fixed
= result
.corruptions_fixed
;
687 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
688 check
->leaks_fixed
= result
.leaks_fixed
;
689 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
690 check
->image_end_offset
= result
.image_end_offset
;
691 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
692 check
->total_clusters
= result
.bfi
.total_clusters
;
693 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
694 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
695 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
696 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
697 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
698 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
699 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
705 * Checks an image for consistency. Exit codes:
707 * 0 - Check completed, image is good
708 * 1 - Check not completed because of internal errors
709 * 2 - Check completed, image is corrupted
710 * 3 - Check completed, image has leaked clusters, but is good otherwise
711 * 63 - Checks are not supported by the image format
713 static int img_check(int argc
, char **argv
)
716 OutputFormat output_format
= OFORMAT_HUMAN
;
717 const char *filename
, *fmt
, *output
, *cache
;
719 BlockDriverState
*bs
;
721 int flags
= BDRV_O_CHECK
;
725 bool image_opts
= false;
726 bool force_share
= false;
730 cache
= BDRV_DEFAULT_CACHE
;
733 int option_index
= 0;
734 static const struct option long_options
[] = {
735 {"help", no_argument
, 0, 'h'},
736 {"format", required_argument
, 0, 'f'},
737 {"repair", required_argument
, 0, 'r'},
738 {"output", required_argument
, 0, OPTION_OUTPUT
},
739 {"object", required_argument
, 0, OPTION_OBJECT
},
740 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
741 {"force-share", no_argument
, 0, 'U'},
744 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
745 long_options
, &option_index
);
751 missing_argument(argv
[optind
- 1]);
754 unrecognized_option(argv
[optind
- 1]);
763 flags
|= BDRV_O_RDWR
;
765 if (!strcmp(optarg
, "leaks")) {
766 fix
= BDRV_FIX_LEAKS
;
767 } else if (!strcmp(optarg
, "all")) {
768 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
770 error_exit("Unknown option value for -r "
771 "(expecting 'leaks' or 'all'): %s", optarg
);
787 user_creatable_process_cmdline(optarg
);
789 case OPTION_IMAGE_OPTS
:
794 if (optind
!= argc
- 1) {
795 error_exit("Expecting one image file name");
797 filename
= argv
[optind
++];
799 if (output
&& !strcmp(output
, "json")) {
800 output_format
= OFORMAT_JSON
;
801 } else if (output
&& !strcmp(output
, "human")) {
802 output_format
= OFORMAT_HUMAN
;
804 error_report("--output must be used with human or json as argument.");
808 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
810 error_report("Invalid source cache option: %s", cache
);
814 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
821 check
= g_new0(ImageCheck
, 1);
822 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
824 if (ret
== -ENOTSUP
) {
825 error_report("This image format does not support checks");
830 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
831 int corruptions_fixed
, leaks_fixed
;
832 bool has_leaks_fixed
, has_corruptions_fixed
;
834 leaks_fixed
= check
->leaks_fixed
;
835 has_leaks_fixed
= check
->has_leaks_fixed
;
836 corruptions_fixed
= check
->corruptions_fixed
;
837 has_corruptions_fixed
= check
->has_corruptions_fixed
;
839 if (output_format
== OFORMAT_HUMAN
) {
841 "The following inconsistencies were found and repaired:\n\n"
842 " %" PRId64
" leaked clusters\n"
843 " %" PRId64
" corruptions\n\n"
844 "Double checking the fixed image now...\n",
846 check
->corruptions_fixed
);
849 qapi_free_ImageCheck(check
);
850 check
= g_new0(ImageCheck
, 1);
851 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
853 check
->leaks_fixed
= leaks_fixed
;
854 check
->has_leaks_fixed
= has_leaks_fixed
;
855 check
->corruptions_fixed
= corruptions_fixed
;
856 check
->has_corruptions_fixed
= has_corruptions_fixed
;
860 switch (output_format
) {
862 dump_human_image_check(check
, quiet
);
865 dump_json_image_check(check
, quiet
);
870 if (ret
|| check
->check_errors
) {
872 error_report("Check failed: %s", strerror(-ret
));
874 error_report("Check failed");
880 if (check
->corruptions
) {
882 } else if (check
->leaks
) {
889 qapi_free_ImageCheck(check
);
894 typedef struct CommonBlockJobCBInfo
{
895 BlockDriverState
*bs
;
897 } CommonBlockJobCBInfo
;
899 static void common_block_job_cb(void *opaque
, int ret
)
901 CommonBlockJobCBInfo
*cbi
= opaque
;
904 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
908 static void run_block_job(BlockJob
*job
, Error
**errp
)
910 uint64_t progress_current
, progress_total
;
911 AioContext
*aio_context
= block_job_get_aio_context(job
);
914 aio_context_acquire(aio_context
);
917 float progress
= 0.0f
;
918 aio_poll(aio_context
, true);
920 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
922 if (progress_total
) {
923 progress
= (float)progress_current
/ progress_total
* 100.f
;
925 qemu_progress_print(progress
, 0);
926 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
928 if (!job_is_completed(&job
->job
)) {
929 ret
= job_complete_sync(&job
->job
, errp
);
933 job_unref(&job
->job
);
934 aio_context_release(aio_context
);
936 /* publish completion progress only when success */
938 qemu_progress_print(100.f
, 0);
942 static int img_commit(int argc
, char **argv
)
945 const char *filename
, *fmt
, *cache
, *base
;
947 BlockDriverState
*bs
, *base_bs
;
949 bool progress
= false, quiet
= false, drop
= false;
951 Error
*local_err
= NULL
;
952 CommonBlockJobCBInfo cbi
;
953 bool image_opts
= false;
954 AioContext
*aio_context
;
955 int64_t rate_limit
= 0;
958 cache
= BDRV_DEFAULT_CACHE
;
961 static const struct option long_options
[] = {
962 {"help", no_argument
, 0, 'h'},
963 {"object", required_argument
, 0, OPTION_OBJECT
},
964 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
967 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
974 missing_argument(argv
[optind
- 1]);
977 unrecognized_option(argv
[optind
- 1]);
1003 rate_limit
= cvtnum("rate limit", optarg
);
1004 if (rate_limit
< 0) {
1009 user_creatable_process_cmdline(optarg
);
1011 case OPTION_IMAGE_OPTS
:
1017 /* Progress is not shown in Quiet mode */
1022 if (optind
!= argc
- 1) {
1023 error_exit("Expecting one image file name");
1025 filename
= argv
[optind
++];
1027 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1028 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1030 error_report("Invalid cache option: %s", cache
);
1034 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1041 qemu_progress_init(progress
, 1.f
);
1042 qemu_progress_print(0.f
, 100);
1045 base_bs
= bdrv_find_backing_image(bs
, base
);
1047 error_setg(&local_err
,
1048 "Did not find '%s' in the backing chain of '%s'",
1053 /* This is different from QMP, which by default uses the deepest file in
1054 * the backing chain (i.e., the very base); however, the traditional
1055 * behavior of qemu-img commit is using the immediate backing file. */
1056 base_bs
= bdrv_backing_chain_next(bs
);
1058 error_setg(&local_err
, "Image does not have a backing file");
1063 cbi
= (CommonBlockJobCBInfo
){
1068 aio_context
= bdrv_get_aio_context(bs
);
1069 aio_context_acquire(aio_context
);
1070 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1071 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1072 &cbi
, false, &local_err
);
1073 aio_context_release(aio_context
);
1078 /* When the block job completes, the BlockBackend reference will point to
1079 * the old backing file. In order to avoid that the top image is already
1080 * deleted, so we can still empty it afterwards, increment the reference
1081 * counter here preemptively. */
1086 job
= block_job_get("commit");
1088 run_block_job(job
, &local_err
);
1094 BlockBackend
*old_backing_blk
;
1096 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1098 if (!old_backing_blk
) {
1101 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1102 blk_unref(old_backing_blk
);
1103 if (ret
== -ENOTSUP
) {
1104 error_free(local_err
);
1106 } else if (ret
< 0) {
1117 qemu_progress_end();
1122 error_report_err(local_err
);
1126 qprintf(quiet
, "Image committed.\n");
1131 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1132 * of the first sector boundary within buf where the sector contains a
1133 * non-zero byte. This function is robust to a buffer that is not
1136 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1139 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1141 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1142 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1146 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1153 * Returns true iff the first sector pointed to by 'buf' contains at least
1156 * 'pnum' is set to the number of sectors (including and immediately following
1157 * the first one) that are known to be in the same allocated/unallocated state.
1158 * The function will try to align the end offset to alignment boundaries so
1159 * that the request will at least end aligned and consecutive requests will
1160 * also start at an aligned offset.
1162 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1163 int64_t sector_num
, int alignment
)
1172 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1173 for(i
= 1; i
< n
; i
++) {
1174 buf
+= BDRV_SECTOR_SIZE
;
1175 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1182 * The whole buf is the same.
1183 * No reason to split it into chunks, so return now.
1189 tail
= (sector_num
+ i
) & (alignment
- 1);
1191 if (is_zero
&& i
<= tail
) {
1193 * For sure next sector after i is data, and it will rewrite this
1194 * tail anyway due to RMW. So, let's just write data now.
1199 /* If possible, align up end offset of allocated areas. */
1200 i
+= alignment
- tail
;
1204 * For sure next sector after i is data, and it will rewrite this
1205 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1216 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1217 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1218 * breaking up write requests for only small sparse areas.
1220 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1221 int min
, int64_t sector_num
, int alignment
)
1224 int num_checked
, num_used
;
1230 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1236 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1238 sector_num
+= *pnum
;
1239 num_checked
= num_used
;
1242 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1244 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1246 sector_num
+= *pnum
;
1247 num_checked
+= *pnum
;
1249 num_used
= num_checked
;
1250 } else if (*pnum
>= min
) {
1260 * Compares two buffers sector by sector. Returns 0 if the first
1261 * sector of each buffer matches, non-zero otherwise.
1263 * pnum is set to the sector-aligned size of the buffer prefix that
1264 * has the same matching status as the first sector.
1266 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1267 int64_t bytes
, int64_t *pnum
)
1270 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1274 res
= !!memcmp(buf1
, buf2
, i
);
1276 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1278 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1288 #define IO_BUF_SIZE (2 * MiB)
1291 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1293 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1294 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1295 * failure), and 4 on error (the exit status for read errors), after emitting
1298 * @param blk: BlockBackend for the image
1299 * @param offset: Starting offset to check
1300 * @param bytes: Number of bytes to check
1301 * @param filename: Name of disk file we are checking (logging purpose)
1302 * @param buffer: Allocated buffer for storing read data
1303 * @param quiet: Flag for quiet mode
1305 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1306 int64_t bytes
, const char *filename
,
1307 uint8_t *buffer
, bool quiet
)
1312 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1314 error_report("Error while reading offset %" PRId64
" of %s: %s",
1315 offset
, filename
, strerror(-ret
));
1318 idx
= find_nonzero(buffer
, bytes
);
1320 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1329 * Compares two images. Exit codes:
1331 * 0 - Images are identical or the requested help was printed
1333 * >1 - Error occurred
1335 static int img_compare(int argc
, char **argv
)
1337 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1338 BlockBackend
*blk1
, *blk2
;
1339 BlockDriverState
*bs1
, *bs2
;
1340 int64_t total_size1
, total_size2
;
1341 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1342 int64_t pnum1
, pnum2
;
1343 int allocated1
, allocated2
;
1344 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1345 bool progress
= false, quiet
= false, strict
= false;
1352 uint64_t progress_base
;
1353 bool image_opts
= false;
1354 bool force_share
= false;
1356 cache
= BDRV_DEFAULT_CACHE
;
1358 static const struct option long_options
[] = {
1359 {"help", no_argument
, 0, 'h'},
1360 {"object", required_argument
, 0, OPTION_OBJECT
},
1361 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1362 {"force-share", no_argument
, 0, 'U'},
1365 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1366 long_options
, NULL
);
1372 missing_argument(argv
[optind
- 1]);
1375 unrecognized_option(argv
[optind
- 1]);
1403 Error
*local_err
= NULL
;
1405 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1407 error_report_err(local_err
);
1410 /* Help was printed */
1416 case OPTION_IMAGE_OPTS
:
1422 /* Progress is not shown in Quiet mode */
1428 if (optind
!= argc
- 2) {
1429 error_exit("Expecting two image file names");
1431 filename1
= argv
[optind
++];
1432 filename2
= argv
[optind
++];
1434 /* Initialize before goto out */
1435 qemu_progress_init(progress
, 2.0);
1438 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1440 error_report("Invalid source cache option: %s", cache
);
1445 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1452 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1461 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1462 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1463 total_size1
= blk_getlength(blk1
);
1464 if (total_size1
< 0) {
1465 error_report("Can't get size of %s: %s",
1466 filename1
, strerror(-total_size1
));
1470 total_size2
= blk_getlength(blk2
);
1471 if (total_size2
< 0) {
1472 error_report("Can't get size of %s: %s",
1473 filename2
, strerror(-total_size2
));
1477 total_size
= MIN(total_size1
, total_size2
);
1478 progress_base
= MAX(total_size1
, total_size2
);
1480 qemu_progress_print(0, 100);
1482 if (strict
&& total_size1
!= total_size2
) {
1484 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1488 while (offset
< total_size
) {
1489 int status1
, status2
;
1491 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1492 total_size1
- offset
, &pnum1
, NULL
,
1496 error_report("Sector allocation test failed for %s", filename1
);
1499 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1501 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1502 total_size2
- offset
, &pnum2
, NULL
,
1506 error_report("Sector allocation test failed for %s", filename2
);
1509 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1511 assert(pnum1
&& pnum2
);
1512 chunk
= MIN(pnum1
, pnum2
);
1515 if (status1
!= status2
) {
1517 qprintf(quiet
, "Strict mode: Offset %" PRId64
1518 " block status mismatch!\n", offset
);
1522 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1524 } else if (allocated1
== allocated2
) {
1528 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1529 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1531 error_report("Error while reading offset %" PRId64
1533 offset
, filename1
, strerror(-ret
));
1537 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1539 error_report("Error while reading offset %" PRId64
1541 offset
, filename2
, strerror(-ret
));
1545 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1546 if (ret
|| pnum
!= chunk
) {
1547 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1548 offset
+ (ret
? 0 : pnum
));
1554 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1556 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1557 filename1
, buf1
, quiet
);
1559 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1560 filename2
, buf1
, quiet
);
1567 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1570 if (total_size1
!= total_size2
) {
1571 BlockBackend
*blk_over
;
1572 const char *filename_over
;
1574 qprintf(quiet
, "Warning: Image size mismatch!\n");
1575 if (total_size1
> total_size2
) {
1577 filename_over
= filename1
;
1580 filename_over
= filename2
;
1583 while (offset
< progress_base
) {
1584 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1585 progress_base
- offset
, &chunk
,
1589 error_report("Sector allocation test failed for %s",
1594 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1595 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1596 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1597 filename_over
, buf1
, quiet
);
1603 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1607 qprintf(quiet
, "Images are identical.\n");
1617 qemu_progress_end();
1621 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1622 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1623 const char *src_node
, const char *src_name
,
1626 BlockDirtyBitmapMergeSource
*merge_src
;
1627 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1629 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1630 merge_src
->type
= QTYPE_QDICT
;
1631 merge_src
->u
.external
.node
= g_strdup(src_node
);
1632 merge_src
->u
.external
.name
= g_strdup(src_name
);
1633 QAPI_LIST_PREPEND(list
, merge_src
);
1634 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1635 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1638 enum ImgConvertBlockStatus
{
1644 #define MAX_COROUTINES 16
1645 #define CONVERT_THROTTLE_GROUP "img_convert"
1647 typedef struct ImgConvertState
{
1649 int64_t *src_sectors
;
1652 int64_t total_sectors
;
1653 int64_t allocated_sectors
;
1654 int64_t allocated_done
;
1657 enum ImgConvertBlockStatus status
;
1658 int64_t sector_next_status
;
1659 BlockBackend
*target
;
1663 bool target_has_backing
;
1664 int64_t target_backing_sectors
; /* negative if unknown */
1671 size_t cluster_sectors
;
1673 long num_coroutines
;
1674 int running_coroutines
;
1675 Coroutine
*co
[MAX_COROUTINES
];
1676 int64_t wait_sector_num
[MAX_COROUTINES
];
1681 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1682 int *src_cur
, int64_t *src_cur_offset
)
1685 *src_cur_offset
= 0;
1686 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1687 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1689 assert(*src_cur
< s
->src_num
);
1693 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1695 int64_t src_cur_offset
;
1696 int ret
, n
, src_cur
;
1697 bool post_backing_zero
= false;
1699 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1701 assert(s
->total_sectors
> sector_num
);
1702 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1704 if (s
->target_backing_sectors
>= 0) {
1705 if (sector_num
>= s
->target_backing_sectors
) {
1706 post_backing_zero
= true;
1707 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1708 /* Split requests around target_backing_sectors (because
1709 * starting from there, zeros are handled differently) */
1710 n
= s
->target_backing_sectors
- sector_num
;
1714 if (s
->sector_next_status
<= sector_num
) {
1715 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1718 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1719 BlockDriverState
*base
;
1721 if (s
->target_has_backing
) {
1722 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1728 count
= n
* BDRV_SECTOR_SIZE
;
1730 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1737 warn_report("error while reading block status at "
1738 "offset %" PRIu64
": %s", offset
,
1741 /* Just try to read the data, then */
1742 ret
= BDRV_BLOCK_DATA
;
1743 count
= BDRV_SECTOR_SIZE
;
1745 /* Retry on a shorter range */
1746 n
= DIV_ROUND_UP(n
, 4);
1749 error_report("error while reading block status at offset "
1750 "%" PRIu64
": %s", offset
, strerror(-ret
));
1756 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1759 * Avoid that s->sector_next_status becomes unaligned to the source
1760 * request alignment and/or cluster size to avoid unnecessary read
1763 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1768 if (ret
& BDRV_BLOCK_ZERO
) {
1769 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1770 } else if (ret
& BDRV_BLOCK_DATA
) {
1771 s
->status
= BLK_DATA
;
1773 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1776 s
->sector_next_status
= sector_num
+ n
;
1779 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1780 if (s
->status
== BLK_DATA
) {
1781 n
= MIN(n
, s
->buf_sectors
);
1784 /* We need to write complete clusters for compressed images, so if an
1785 * unallocated area is shorter than that, we must consider the whole
1786 * cluster allocated. */
1787 if (s
->compressed
) {
1788 if (n
< s
->cluster_sectors
) {
1789 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1790 s
->status
= BLK_DATA
;
1792 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1799 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1800 int nb_sectors
, uint8_t *buf
)
1802 uint64_t single_read_until
= 0;
1805 assert(nb_sectors
<= s
->buf_sectors
);
1806 while (nb_sectors
> 0) {
1809 int64_t bs_sectors
, src_cur_offset
;
1812 /* In the case of compression with multiple source files, we can get a
1813 * nb_sectors that spreads into the next part. So we must be able to
1814 * read across multiple BDSes for one convert_read() call. */
1815 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1816 blk
= s
->src
[src_cur
];
1817 bs_sectors
= s
->src_sectors
[src_cur
];
1819 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1821 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1822 if (single_read_until
> offset
) {
1826 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1830 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1834 warn_report("error while reading offset %" PRIu64
1835 ": %s", offset
, strerror(-ret
));
1837 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1846 buf
+= n
* BDRV_SECTOR_SIZE
;
1853 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1854 int nb_sectors
, uint8_t *buf
,
1855 enum ImgConvertBlockStatus status
)
1859 while (nb_sectors
> 0) {
1861 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1864 case BLK_BACKING_FILE
:
1865 /* If we have a backing file, leave clusters unallocated that are
1866 * unallocated in the source image, so that the backing file is
1867 * visible at the respective offset. */
1868 assert(s
->target_has_backing
);
1872 /* If we're told to keep the target fully allocated (-S 0) or there
1873 * is real non-zero data, we must write it. Otherwise we can treat
1874 * it as zero sectors.
1875 * Compressed clusters need to be written as a whole, so in that
1876 * case we can only save the write if the buffer is completely
1878 if (!s
->min_sparse
||
1880 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1881 sector_num
, s
->alignment
)) ||
1883 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1885 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1886 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1895 if (s
->has_zero_init
) {
1896 assert(!s
->target_has_backing
);
1899 ret
= blk_co_pwrite_zeroes(s
->target
,
1900 sector_num
<< BDRV_SECTOR_BITS
,
1901 n
<< BDRV_SECTOR_BITS
,
1902 BDRV_REQ_MAY_UNMAP
);
1911 buf
+= n
* BDRV_SECTOR_SIZE
;
1917 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1922 while (nb_sectors
> 0) {
1925 int64_t bs_sectors
, src_cur_offset
;
1928 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1929 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1930 blk
= s
->src
[src_cur
];
1931 bs_sectors
= s
->src_sectors
[src_cur
];
1933 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1935 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1936 sector_num
<< BDRV_SECTOR_BITS
,
1937 n
<< BDRV_SECTOR_BITS
, 0, 0);
1948 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1950 ImgConvertState
*s
= opaque
;
1951 uint8_t *buf
= NULL
;
1955 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1956 if (s
->co
[i
] == qemu_coroutine_self()) {
1963 s
->running_coroutines
++;
1964 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1969 enum ImgConvertBlockStatus status
;
1972 qemu_co_mutex_lock(&s
->lock
);
1973 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1974 qemu_co_mutex_unlock(&s
->lock
);
1977 n
= convert_iteration_sectors(s
, s
->sector_num
);
1979 qemu_co_mutex_unlock(&s
->lock
);
1983 /* save current sector and allocation status to local variables */
1984 sector_num
= s
->sector_num
;
1986 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1987 n
= MIN(n
, s
->buf_sectors
);
1989 /* increment global sector counter so that other coroutines can
1990 * already continue reading beyond this request */
1992 qemu_co_mutex_unlock(&s
->lock
);
1994 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1995 s
->allocated_done
+= n
;
1996 qemu_progress_print(100.0 * s
->allocated_done
/
1997 s
->allocated_sectors
, 0);
2001 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2002 if (status
== BLK_DATA
&& !copy_range
) {
2003 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2005 error_report("error while reading at byte %lld: %s",
2006 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2009 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2011 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2014 if (s
->wr_in_order
) {
2015 /* keep writes in order */
2016 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2017 s
->wait_sector_num
[index
] = sector_num
;
2018 qemu_coroutine_yield();
2020 s
->wait_sector_num
[index
] = -1;
2023 if (s
->ret
== -EINPROGRESS
) {
2025 ret
= convert_co_copy_range(s
, sector_num
, n
);
2027 s
->copy_range
= false;
2031 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2034 error_report("error while writing at byte %lld: %s",
2035 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2040 if (s
->wr_in_order
) {
2041 /* reenter the coroutine that might have waited
2042 * for this write to complete */
2043 s
->wr_offs
= sector_num
+ n
;
2044 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2045 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2047 * A -> B -> A cannot occur because A has
2048 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2049 * B will never enter A during this time window.
2051 qemu_coroutine_enter(s
->co
[i
]);
2059 s
->co
[index
] = NULL
;
2060 s
->running_coroutines
--;
2061 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2062 /* the convert job finished successfully */
2067 static int convert_do_copy(ImgConvertState
*s
)
2070 int64_t sector_num
= 0;
2072 /* Check whether we have zero initialisation or can get it efficiently */
2073 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2074 !s
->target_has_backing
) {
2075 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2078 /* Allocate buffer for copied data. For compressed images, only one cluster
2079 * can be copied at a time. */
2080 if (s
->compressed
) {
2081 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2082 error_report("invalid cluster size");
2085 s
->buf_sectors
= s
->cluster_sectors
;
2088 while (sector_num
< s
->total_sectors
) {
2089 n
= convert_iteration_sectors(s
, sector_num
);
2093 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2095 s
->allocated_sectors
+= n
;
2101 s
->sector_next_status
= 0;
2102 s
->ret
= -EINPROGRESS
;
2104 qemu_co_mutex_init(&s
->lock
);
2105 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2106 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2107 s
->wait_sector_num
[i
] = -1;
2108 qemu_coroutine_enter(s
->co
[i
]);
2111 while (s
->running_coroutines
) {
2112 main_loop_wait(false);
2115 if (s
->compressed
&& !s
->ret
) {
2116 /* signal EOF to align */
2117 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2126 /* Check that bitmaps can be copied, or output an error */
2127 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2129 BdrvDirtyBitmap
*bm
;
2131 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2132 error_report("Source lacks bitmap support");
2135 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2136 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2139 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2140 error_report("Cannot copy inconsistent bitmap '%s'",
2141 bdrv_dirty_bitmap_name(bm
));
2142 error_printf("Try --skip-broken-bitmaps, or "
2143 "use 'qemu-img bitmap --remove' to delete it\n");
2150 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2153 BdrvDirtyBitmap
*bm
;
2156 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2159 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2162 name
= bdrv_dirty_bitmap_name(bm
);
2163 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2164 warn_report("Skipping inconsistent bitmap '%s'", name
);
2167 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2168 true, bdrv_dirty_bitmap_granularity(bm
),
2170 true, !bdrv_dirty_bitmap_enabled(bm
),
2173 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2177 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2180 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2181 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2189 #define MAX_BUF_SECTORS 32768
2191 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2195 throttle_config_init(&cfg
);
2196 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2198 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2199 blk_set_io_limits(blk
, &cfg
);
2202 static int img_convert(int argc
, char **argv
)
2204 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2205 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2206 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2207 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2208 *backing_fmt
= NULL
;
2209 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2210 BlockDriverInfo bdi
;
2211 BlockDriverState
*out_bs
;
2212 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2213 QemuOptsList
*create_opts
= NULL
;
2214 QDict
*open_opts
= NULL
;
2215 char *options
= NULL
;
2216 Error
*local_err
= NULL
;
2217 bool writethrough
, src_writethrough
, image_opts
= false,
2218 skip_create
= false, progress
= false, tgt_image_opts
= false;
2219 int64_t ret
= -EINVAL
;
2220 bool force_share
= false;
2221 bool explict_min_sparse
= false;
2222 bool bitmaps
= false;
2223 bool skip_broken
= false;
2224 int64_t rate_limit
= 0;
2226 ImgConvertState s
= (ImgConvertState
) {
2227 /* Need at least 4k of zeros for sparse detection */
2229 .copy_range
= false,
2230 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2231 .wr_in_order
= true,
2232 .num_coroutines
= 8,
2236 static const struct option long_options
[] = {
2237 {"help", no_argument
, 0, 'h'},
2238 {"object", required_argument
, 0, OPTION_OBJECT
},
2239 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2240 {"force-share", no_argument
, 0, 'U'},
2241 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2242 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2243 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2244 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2245 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2248 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2249 long_options
, NULL
);
2255 missing_argument(argv
[optind
- 1]);
2258 unrecognized_option(argv
[optind
- 1]);
2270 out_baseimg
= optarg
;
2273 s
.copy_range
= true;
2276 s
.compressed
= true;
2279 backing_fmt
= optarg
;
2282 if (accumulate_options(&options
, optarg
) < 0) {
2287 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2288 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2291 error_report("Failed in parsing snapshot param '%s'",
2296 snapshot_name
= optarg
;
2303 sval
= cvtnum("buffer size for sparse output", optarg
);
2306 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2307 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2308 error_report("Invalid buffer size for sparse output specified. "
2309 "Valid sizes are multiples of %llu up to %llu. Select "
2310 "0 to disable sparse detection (fully allocates output).",
2311 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2315 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2316 explict_min_sparse
= true;
2335 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2336 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2337 error_report("Invalid number of coroutines. Allowed number of"
2338 " coroutines is between 1 and %d", MAX_COROUTINES
);
2343 s
.wr_in_order
= false;
2349 rate_limit
= cvtnum("rate limit", optarg
);
2350 if (rate_limit
< 0) {
2355 user_creatable_process_cmdline(optarg
);
2357 case OPTION_IMAGE_OPTS
:
2360 case OPTION_SALVAGE
:
2363 case OPTION_TARGET_IMAGE_OPTS
:
2364 tgt_image_opts
= true;
2366 case OPTION_TARGET_IS_ZERO
:
2368 * The user asserting that the target is blank has the
2369 * same effect as the target driver supporting zero
2372 s
.has_zero_init
= true;
2374 case OPTION_BITMAPS
:
2377 case OPTION_SKIP_BROKEN
:
2383 if (!out_fmt
&& !tgt_image_opts
) {
2387 if (skip_broken
&& !bitmaps
) {
2388 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2392 if (s
.compressed
&& s
.copy_range
) {
2393 error_report("Cannot enable copy offloading when -c is used");
2397 if (explict_min_sparse
&& s
.copy_range
) {
2398 error_report("Cannot enable copy offloading when -S is used");
2402 if (s
.copy_range
&& s
.salvage
) {
2403 error_report("Cannot use copy offloading in salvaging mode");
2407 if (tgt_image_opts
&& !skip_create
) {
2408 error_report("--target-image-opts requires use of -n flag");
2412 if (skip_create
&& options
) {
2413 error_report("-o has no effect when skipping image creation");
2417 if (s
.has_zero_init
&& !skip_create
) {
2418 error_report("--target-is-zero requires use of -n flag");
2422 s
.src_num
= argc
- optind
- 1;
2423 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2425 if (options
&& has_help_option(options
)) {
2427 ret
= print_block_option_help(out_filename
, out_fmt
);
2430 error_report("Option help requires a format be specified");
2435 if (s
.src_num
< 1) {
2436 error_report("Must specify image file name");
2440 /* ret is still -EINVAL until here */
2441 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2443 error_report("Invalid source cache option: %s", src_cache
);
2447 /* Initialize before goto out */
2451 qemu_progress_init(progress
, 1.0);
2452 qemu_progress_print(0, 100);
2454 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2455 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2456 s
.src_alignment
= g_new(int, s
.src_num
);
2458 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2459 BlockDriverState
*src_bs
;
2460 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2461 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2467 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2468 if (s
.src_sectors
[bs_i
] < 0) {
2469 error_report("Could not get size of %s: %s",
2470 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2474 src_bs
= blk_bs(s
.src
[bs_i
]);
2475 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2477 if (!bdrv_get_info(src_bs
, &bdi
)) {
2478 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2479 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2481 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2485 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2486 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2487 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2489 } else if (snapshot_name
!= NULL
) {
2490 if (s
.src_num
> 1) {
2491 error_report("No support for concatenating multiple snapshot");
2496 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2500 error_reportf_err(local_err
, "Failed to load snapshot: ");
2506 /* Find driver and parse its options */
2507 drv
= bdrv_find_format(out_fmt
);
2509 error_report("Unknown file format '%s'", out_fmt
);
2514 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2516 error_report_err(local_err
);
2521 if (!drv
->create_opts
) {
2522 error_report("Format driver '%s' does not support image creation",
2528 if (!proto_drv
->create_opts
) {
2529 error_report("Protocol driver '%s' does not support image creation",
2530 proto_drv
->format_name
);
2535 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2536 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2538 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2540 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2541 error_report_err(local_err
);
2547 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2548 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2549 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2555 /* Get backing file name if -o backing_file was used */
2556 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2557 if (out_baseimg_param
) {
2558 out_baseimg
= out_baseimg_param
;
2560 s
.target_has_backing
= (bool) out_baseimg
;
2562 if (s
.has_zero_init
&& s
.target_has_backing
) {
2563 error_report("Cannot use --target-is-zero when the destination "
2564 "image has a backing file");
2568 if (s
.src_num
> 1 && out_baseimg
) {
2569 error_report("Having a backing file for the target makes no sense when "
2570 "concatenating multiple input images");
2575 if (out_baseimg_param
) {
2576 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2577 error_report("Use of backing file requires explicit "
2584 /* Check if compression is supported */
2587 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2588 const char *encryptfmt
=
2589 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2590 const char *preallocation
=
2591 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2593 if (drv
&& !block_driver_can_compress(drv
)) {
2594 error_report("Compression not supported for this file format");
2599 if (encryption
|| encryptfmt
) {
2600 error_report("Compression and encryption not supported at "
2607 && strcmp(preallocation
, "off"))
2609 error_report("Compression and preallocation not supported at "
2616 /* Determine if bitmaps need copying */
2618 if (s
.src_num
> 1) {
2619 error_report("Copying bitmaps only possible with single source");
2623 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2630 * The later open call will need any decryption secrets, and
2631 * bdrv_create() will purge "opts", so extract them now before
2635 open_opts
= qdict_new();
2636 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2638 /* Create the new image */
2639 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2641 error_reportf_err(local_err
, "%s: error while converting %s: ",
2642 out_filename
, out_fmt
);
2647 s
.target_is_new
= !skip_create
;
2649 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2650 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2652 error_report("Invalid cache option: %s", cache
);
2656 if (flags
& BDRV_O_NOCACHE
) {
2658 * If we open the target with O_DIRECT, it may be necessary to
2659 * extend its size to align to the physical sector size.
2661 flags
|= BDRV_O_RESIZE
;
2665 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2666 flags
, writethrough
, s
.quiet
, false);
2668 /* TODO ultimately we should allow --target-image-opts
2669 * to be used even when -n is not given.
2670 * That has to wait for bdrv_create to be improved
2671 * to allow filenames in option syntax
2673 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2674 flags
, writethrough
, s
.quiet
, false);
2675 open_opts
= NULL
; /* blk_new_open will have freed it */
2681 out_bs
= blk_bs(s
.target
);
2683 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2684 error_report("Format driver '%s' does not support bitmaps",
2685 out_bs
->drv
->format_name
);
2690 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2691 error_report("Compression not supported for this file format");
2696 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2697 * or discard_alignment of the out_bs is greater. Limit to
2698 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2699 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2701 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2702 out_bs
->bl
.pdiscard_alignment
>>
2703 BDRV_SECTOR_BITS
)));
2705 /* try to align the write requests to the destination to avoid unnecessary
2707 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2708 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2710 assert(is_power_of_2(s
.alignment
));
2713 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2714 if (output_sectors
< 0) {
2715 error_report("unable to get output image length: %s",
2716 strerror(-output_sectors
));
2719 } else if (output_sectors
< s
.total_sectors
) {
2720 error_report("output file is smaller than input file");
2726 if (s
.target_has_backing
&& s
.target_is_new
) {
2727 /* Errors are treated as "backing length unknown" (which means
2728 * s.target_backing_sectors has to be negative, which it will
2729 * be automatically). The backing file length is used only
2730 * for optimizations, so such a case is not fatal. */
2731 s
.target_backing_sectors
=
2732 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2734 s
.target_backing_sectors
= -1;
2737 ret
= bdrv_get_info(out_bs
, &bdi
);
2740 error_report("could not get block driver info");
2744 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2745 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2749 set_rate_limit(s
.target
, rate_limit
);
2752 ret
= convert_do_copy(&s
);
2754 /* Now copy the bitmaps */
2755 if (bitmaps
&& ret
== 0) {
2756 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2761 qemu_progress_print(100, 0);
2763 qemu_progress_end();
2764 qemu_opts_del(opts
);
2765 qemu_opts_free(create_opts
);
2766 qobject_unref(open_opts
);
2767 blk_unref(s
.target
);
2769 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2770 blk_unref(s
.src
[bs_i
]);
2774 g_free(s
.src_sectors
);
2775 g_free(s
.src_alignment
);
2777 qemu_opts_del(sn_opts
);
2784 static void dump_snapshots(BlockDriverState
*bs
)
2786 QEMUSnapshotInfo
*sn_tab
, *sn
;
2789 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2792 printf("Snapshot list:\n");
2793 bdrv_snapshot_dump(NULL
);
2795 for(i
= 0; i
< nb_sns
; i
++) {
2797 bdrv_snapshot_dump(sn
);
2803 static void dump_json_image_info_list(ImageInfoList
*list
)
2807 Visitor
*v
= qobject_output_visitor_new(&obj
);
2809 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2810 visit_complete(v
, &obj
);
2811 str
= qobject_to_json_pretty(obj
, true);
2812 assert(str
!= NULL
);
2813 printf("%s\n", str
->str
);
2816 g_string_free(str
, true);
2819 static void dump_json_image_info(ImageInfo
*info
)
2823 Visitor
*v
= qobject_output_visitor_new(&obj
);
2825 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2826 visit_complete(v
, &obj
);
2827 str
= qobject_to_json_pretty(obj
, true);
2828 assert(str
!= NULL
);
2829 printf("%s\n", str
->str
);
2832 g_string_free(str
, true);
2835 static void dump_human_image_info_list(ImageInfoList
*list
)
2837 ImageInfoList
*elem
;
2840 for (elem
= list
; elem
; elem
= elem
->next
) {
2846 bdrv_image_info_dump(elem
->value
);
2850 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2852 return strcmp(a
, b
) == 0;
2856 * Open an image file chain and return an ImageInfoList
2858 * @filename: topmost image filename
2859 * @fmt: topmost image format (may be NULL to autodetect)
2860 * @chain: true - enumerate entire backing file chain
2861 * false - only topmost image file
2863 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2864 * image file. If there was an error a message will have been printed to
2867 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2868 const char *filename
,
2870 bool chain
, bool force_share
)
2872 ImageInfoList
*head
= NULL
;
2873 ImageInfoList
**tail
= &head
;
2874 GHashTable
*filenames
;
2877 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2881 BlockDriverState
*bs
;
2884 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2885 error_report("Backing file '%s' creates an infinite loop.",
2889 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2891 blk
= img_open(image_opts
, filename
, fmt
,
2892 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2899 bdrv_query_image_info(bs
, &info
, &err
);
2901 error_report_err(err
);
2906 QAPI_LIST_APPEND(tail
, info
);
2910 /* Clear parameters that only apply to the topmost image */
2911 filename
= fmt
= NULL
;
2915 if (info
->has_full_backing_filename
) {
2916 filename
= info
->full_backing_filename
;
2917 } else if (info
->has_backing_filename
) {
2918 error_report("Could not determine absolute backing filename,"
2919 " but backing filename '%s' present",
2920 info
->backing_filename
);
2923 if (info
->has_backing_filename_format
) {
2924 fmt
= info
->backing_filename_format
;
2928 g_hash_table_destroy(filenames
);
2932 qapi_free_ImageInfoList(head
);
2933 g_hash_table_destroy(filenames
);
2937 static int img_info(int argc
, char **argv
)
2940 OutputFormat output_format
= OFORMAT_HUMAN
;
2942 const char *filename
, *fmt
, *output
;
2943 ImageInfoList
*list
;
2944 bool image_opts
= false;
2945 bool force_share
= false;
2950 int option_index
= 0;
2951 static const struct option long_options
[] = {
2952 {"help", no_argument
, 0, 'h'},
2953 {"format", required_argument
, 0, 'f'},
2954 {"output", required_argument
, 0, OPTION_OUTPUT
},
2955 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2956 {"object", required_argument
, 0, OPTION_OBJECT
},
2957 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2958 {"force-share", no_argument
, 0, 'U'},
2961 c
= getopt_long(argc
, argv
, ":f:hU",
2962 long_options
, &option_index
);
2968 missing_argument(argv
[optind
- 1]);
2971 unrecognized_option(argv
[optind
- 1]);
2985 case OPTION_BACKING_CHAIN
:
2989 user_creatable_process_cmdline(optarg
);
2991 case OPTION_IMAGE_OPTS
:
2996 if (optind
!= argc
- 1) {
2997 error_exit("Expecting one image file name");
2999 filename
= argv
[optind
++];
3001 if (output
&& !strcmp(output
, "json")) {
3002 output_format
= OFORMAT_JSON
;
3003 } else if (output
&& !strcmp(output
, "human")) {
3004 output_format
= OFORMAT_HUMAN
;
3005 } else if (output
) {
3006 error_report("--output must be used with human or json as argument.");
3010 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3016 switch (output_format
) {
3018 dump_human_image_info_list(list
);
3022 dump_json_image_info_list(list
);
3024 dump_json_image_info(list
->value
);
3029 qapi_free_ImageInfoList(list
);
3033 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3036 switch (output_format
) {
3038 if (e
->data
&& !e
->has_offset
) {
3039 error_report("File contains external, encrypted or compressed clusters.");
3042 if (e
->data
&& !e
->zero
) {
3043 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3044 e
->start
, e
->length
,
3045 e
->has_offset
? e
->offset
: 0,
3046 e
->has_filename
? e
->filename
: "");
3048 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3049 * Modify the flags here to allow more coalescing.
3051 if (next
&& (!next
->data
|| next
->zero
)) {
3057 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3058 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3059 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
3060 e
->present
? "true" : "false",
3061 e
->zero
? "true" : "false",
3062 e
->data
? "true" : "false");
3063 if (e
->has_offset
) {
3064 printf(", \"offset\": %"PRId64
"", e
->offset
);
3076 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3077 int64_t bytes
, MapEntry
*e
)
3081 BlockDriverState
*file
;
3084 char *filename
= NULL
;
3086 /* As an optimization, we could cache the current range of unallocated
3087 * clusters in each file of the chain, and avoid querying the same
3093 bs
= bdrv_skip_filters(bs
);
3094 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3099 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3102 bs
= bdrv_cow_bs(bs
);
3111 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3113 if (file
&& has_offset
) {
3114 bdrv_refresh_filename(file
);
3115 filename
= file
->filename
;
3121 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3122 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3124 .has_offset
= has_offset
,
3126 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3127 .has_filename
= filename
,
3128 .filename
= filename
,
3134 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3136 if (curr
->length
== 0) {
3139 if (curr
->zero
!= next
->zero
||
3140 curr
->data
!= next
->data
||
3141 curr
->depth
!= next
->depth
||
3142 curr
->present
!= next
->present
||
3143 curr
->has_filename
!= next
->has_filename
||
3144 curr
->has_offset
!= next
->has_offset
) {
3147 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3150 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3156 static int img_map(int argc
, char **argv
)
3159 OutputFormat output_format
= OFORMAT_HUMAN
;
3161 BlockDriverState
*bs
;
3162 const char *filename
, *fmt
, *output
;
3164 MapEntry curr
= { .length
= 0 }, next
;
3166 bool image_opts
= false;
3167 bool force_share
= false;
3168 int64_t start_offset
= 0;
3169 int64_t max_length
= -1;
3174 int option_index
= 0;
3175 static const struct option long_options
[] = {
3176 {"help", no_argument
, 0, 'h'},
3177 {"format", required_argument
, 0, 'f'},
3178 {"output", required_argument
, 0, OPTION_OUTPUT
},
3179 {"object", required_argument
, 0, OPTION_OBJECT
},
3180 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3181 {"force-share", no_argument
, 0, 'U'},
3182 {"start-offset", required_argument
, 0, 's'},
3183 {"max-length", required_argument
, 0, 'l'},
3186 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3187 long_options
, &option_index
);
3193 missing_argument(argv
[optind
- 1]);
3196 unrecognized_option(argv
[optind
- 1]);
3211 start_offset
= cvtnum("start offset", optarg
);
3212 if (start_offset
< 0) {
3217 max_length
= cvtnum("max length", optarg
);
3218 if (max_length
< 0) {
3223 user_creatable_process_cmdline(optarg
);
3225 case OPTION_IMAGE_OPTS
:
3230 if (optind
!= argc
- 1) {
3231 error_exit("Expecting one image file name");
3233 filename
= argv
[optind
];
3235 if (output
&& !strcmp(output
, "json")) {
3236 output_format
= OFORMAT_JSON
;
3237 } else if (output
&& !strcmp(output
, "human")) {
3238 output_format
= OFORMAT_HUMAN
;
3239 } else if (output
) {
3240 error_report("--output must be used with human or json as argument.");
3244 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3250 if (output_format
== OFORMAT_HUMAN
) {
3251 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3252 } else if (output_format
== OFORMAT_JSON
) {
3256 length
= blk_getlength(blk
);
3258 error_report("Failed to get size for '%s'", filename
);
3261 if (max_length
!= -1) {
3262 length
= MIN(start_offset
+ max_length
, length
);
3265 curr
.start
= start_offset
;
3266 while (curr
.start
+ curr
.length
< length
) {
3267 int64_t offset
= curr
.start
+ curr
.length
;
3268 int64_t n
= length
- offset
;
3270 ret
= get_block_status(bs
, offset
, n
, &next
);
3272 error_report("Could not read file metadata: %s", strerror(-ret
));
3276 if (entry_mergeable(&curr
, &next
)) {
3277 curr
.length
+= next
.length
;
3281 if (curr
.length
> 0) {
3282 ret
= dump_map_entry(output_format
, &curr
, &next
);
3290 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3291 if (output_format
== OFORMAT_JSON
) {
3300 #define SNAPSHOT_LIST 1
3301 #define SNAPSHOT_CREATE 2
3302 #define SNAPSHOT_APPLY 3
3303 #define SNAPSHOT_DELETE 4
3305 static int img_snapshot(int argc
, char **argv
)
3308 BlockDriverState
*bs
;
3309 QEMUSnapshotInfo sn
;
3310 char *filename
, *snapshot_name
= NULL
;
3311 int c
, ret
= 0, bdrv_oflags
;
3315 bool image_opts
= false;
3316 bool force_share
= false;
3319 bdrv_oflags
= BDRV_O_RDWR
;
3320 /* Parse commandline parameters */
3322 static const struct option long_options
[] = {
3323 {"help", no_argument
, 0, 'h'},
3324 {"object", required_argument
, 0, OPTION_OBJECT
},
3325 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3326 {"force-share", no_argument
, 0, 'U'},
3329 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3330 long_options
, NULL
);
3336 missing_argument(argv
[optind
- 1]);
3339 unrecognized_option(argv
[optind
- 1]);
3346 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3349 action
= SNAPSHOT_LIST
;
3350 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3354 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3357 action
= SNAPSHOT_APPLY
;
3358 snapshot_name
= optarg
;
3362 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3365 action
= SNAPSHOT_CREATE
;
3366 snapshot_name
= optarg
;
3370 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3373 action
= SNAPSHOT_DELETE
;
3374 snapshot_name
= optarg
;
3383 user_creatable_process_cmdline(optarg
);
3385 case OPTION_IMAGE_OPTS
:
3391 if (optind
!= argc
- 1) {
3392 error_exit("Expecting one image file name");
3394 filename
= argv
[optind
++];
3396 /* Open the image */
3397 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3404 /* Perform the requested action */
3410 case SNAPSHOT_CREATE
:
3411 memset(&sn
, 0, sizeof(sn
));
3412 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3414 rt
= g_get_real_time();
3415 sn
.date_sec
= rt
/ G_USEC_PER_SEC
;
3416 sn
.date_nsec
= (rt
% G_USEC_PER_SEC
) * 1000;
3418 ret
= bdrv_snapshot_create(bs
, &sn
);
3420 error_report("Could not create snapshot '%s': %d (%s)",
3421 snapshot_name
, ret
, strerror(-ret
));
3425 case SNAPSHOT_APPLY
:
3426 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3428 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3433 case SNAPSHOT_DELETE
:
3434 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3436 error_report("Could not delete snapshot '%s': snapshot not "
3437 "found", snapshot_name
);
3440 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3442 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3458 static int img_rebase(int argc
, char **argv
)
3460 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3461 uint8_t *buf_old
= NULL
;
3462 uint8_t *buf_new
= NULL
;
3463 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3464 BlockDriverState
*unfiltered_bs
;
3466 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3467 int c
, flags
, src_flags
, ret
;
3468 bool writethrough
, src_writethrough
;
3470 bool force_share
= false;
3473 Error
*local_err
= NULL
;
3474 bool image_opts
= false;
3476 /* Parse commandline parameters */
3478 cache
= BDRV_DEFAULT_CACHE
;
3479 src_cache
= BDRV_DEFAULT_CACHE
;
3483 static const struct option long_options
[] = {
3484 {"help", no_argument
, 0, 'h'},
3485 {"object", required_argument
, 0, OPTION_OBJECT
},
3486 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3487 {"force-share", no_argument
, 0, 'U'},
3490 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3491 long_options
, NULL
);
3497 missing_argument(argv
[optind
- 1]);
3500 unrecognized_option(argv
[optind
- 1]);
3509 out_basefmt
= optarg
;
3512 out_baseimg
= optarg
;
3530 user_creatable_process_cmdline(optarg
);
3532 case OPTION_IMAGE_OPTS
:
3545 if (optind
!= argc
- 1) {
3546 error_exit("Expecting one image file name");
3548 if (!unsafe
&& !out_baseimg
) {
3549 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3551 filename
= argv
[optind
++];
3553 qemu_progress_init(progress
, 2.0);
3554 qemu_progress_print(0, 100);
3556 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3557 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3559 error_report("Invalid cache option: %s", cache
);
3564 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3566 error_report("Invalid source cache option: %s", src_cache
);
3570 /* The source files are opened read-only, don't care about WCE */
3571 assert((src_flags
& BDRV_O_RDWR
) == 0);
3572 (void) src_writethrough
;
3577 * Ignore the old backing file for unsafe rebase in case we want to correct
3578 * the reference to a renamed or moved backing file.
3580 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3588 unfiltered_bs
= bdrv_skip_filters(bs
);
3590 if (out_basefmt
!= NULL
) {
3591 if (bdrv_find_format(out_basefmt
) == NULL
) {
3592 error_report("Invalid format name: '%s'", out_basefmt
);
3598 /* For safe rebasing we need to compare old and new backing file */
3600 QDict
*options
= NULL
;
3601 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3604 blk_old_backing
= blk_new(qemu_get_aio_context(),
3605 BLK_PERM_CONSISTENT_READ
,
3607 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3610 error_reportf_err(local_err
,
3611 "Could not reuse old backing file '%s': ",
3616 blk_old_backing
= NULL
;
3619 if (out_baseimg
[0]) {
3620 const char *overlay_filename
;
3621 char *out_real_path
;
3623 options
= qdict_new();
3625 qdict_put_str(options
, "driver", out_basefmt
);
3628 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3631 bdrv_refresh_filename(bs
);
3632 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3635 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3639 qobject_unref(options
);
3640 error_reportf_err(local_err
,
3641 "Could not resolve backing filename: ");
3647 * Find out whether we rebase an image on top of a previous image
3650 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3651 if (prefix_chain_bs
) {
3652 qobject_unref(options
);
3653 g_free(out_real_path
);
3655 blk_new_backing
= blk_new(qemu_get_aio_context(),
3656 BLK_PERM_CONSISTENT_READ
,
3658 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3661 error_reportf_err(local_err
,
3662 "Could not reuse backing file '%s': ",
3667 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3668 options
, src_flags
, &local_err
);
3669 g_free(out_real_path
);
3670 if (!blk_new_backing
) {
3671 error_reportf_err(local_err
,
3672 "Could not open new backing file '%s': ",
3682 * Check each unallocated cluster in the COW file. If it is unallocated,
3683 * accesses go to the backing file. We must therefore compare this cluster
3684 * in the old and new backing file, and if they differ we need to copy it
3685 * from the old backing file into the COW file.
3687 * If qemu-img crashes during this step, no harm is done. The content of
3688 * the image is the same as the original one at any time.
3692 int64_t old_backing_size
= 0;
3693 int64_t new_backing_size
= 0;
3696 float local_progress
= 0;
3698 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3699 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3701 size
= blk_getlength(blk
);
3703 error_report("Could not get size of '%s': %s",
3704 filename
, strerror(-size
));
3708 if (blk_old_backing
) {
3709 old_backing_size
= blk_getlength(blk_old_backing
);
3710 if (old_backing_size
< 0) {
3711 char backing_name
[PATH_MAX
];
3713 bdrv_get_backing_filename(bs
, backing_name
,
3714 sizeof(backing_name
));
3715 error_report("Could not get size of '%s': %s",
3716 backing_name
, strerror(-old_backing_size
));
3721 if (blk_new_backing
) {
3722 new_backing_size
= blk_getlength(blk_new_backing
);
3723 if (new_backing_size
< 0) {
3724 error_report("Could not get size of '%s': %s",
3725 out_baseimg
, strerror(-new_backing_size
));
3732 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3735 for (offset
= 0; offset
< size
; offset
+= n
) {
3736 bool buf_old_is_zero
= false;
3738 /* How many bytes can we handle with the next read? */
3739 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3741 /* If the cluster is allocated, we don't need to take action */
3742 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3744 error_report("error while reading image metadata: %s",
3752 if (prefix_chain_bs
) {
3754 * If cluster wasn't changed since prefix_chain, we don't need
3757 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3758 prefix_chain_bs
, false,
3761 error_report("error while reading image metadata: %s",
3771 * Read old and new backing file and take into consideration that
3772 * backing files may be smaller than the COW image.
3774 if (offset
>= old_backing_size
) {
3775 memset(buf_old
, 0, n
);
3776 buf_old_is_zero
= true;
3778 if (offset
+ n
> old_backing_size
) {
3779 n
= old_backing_size
- offset
;
3782 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3784 error_report("error while reading from old backing file");
3789 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3790 memset(buf_new
, 0, n
);
3792 if (offset
+ n
> new_backing_size
) {
3793 n
= new_backing_size
- offset
;
3796 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3798 error_report("error while reading from new backing file");
3803 /* If they differ, we need to write to the COW file */
3804 uint64_t written
= 0;
3806 while (written
< n
) {
3809 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3810 n
- written
, &pnum
))
3812 if (buf_old_is_zero
) {
3813 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3815 ret
= blk_pwrite(blk
, offset
+ written
,
3816 buf_old
+ written
, pnum
, 0);
3819 error_report("Error while writing to COW image: %s",
3827 qemu_progress_print(local_progress
, 100);
3832 * Change the backing file. All clusters that are different from the old
3833 * backing file are overwritten in the COW file now, so the visible content
3834 * doesn't change when we switch the backing file.
3836 if (out_baseimg
&& *out_baseimg
) {
3837 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3840 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3843 if (ret
== -ENOSPC
) {
3844 error_report("Could not change the backing file to '%s': No "
3845 "space left in the file header", out_baseimg
);
3846 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3847 error_report("Could not change the backing file to '%s': backing "
3848 "format must be specified", out_baseimg
);
3849 } else if (ret
< 0) {
3850 error_report("Could not change the backing file to '%s': %s",
3851 out_baseimg
, strerror(-ret
));
3854 qemu_progress_print(100, 0);
3856 * TODO At this point it is possible to check if any clusters that are
3857 * allocated in the COW file are the same in the backing file. If so, they
3858 * could be dropped from the COW file. Don't do this before switching the
3859 * backing file, in case of a crash this would lead to corruption.
3862 qemu_progress_end();
3865 blk_unref(blk_old_backing
);
3866 blk_unref(blk_new_backing
);
3868 qemu_vfree(buf_old
);
3869 qemu_vfree(buf_new
);
3878 static int img_resize(int argc
, char **argv
)
3881 int c
, ret
, relative
;
3882 const char *filename
, *fmt
, *size
;
3883 int64_t n
, total_size
, current_size
;
3885 BlockBackend
*blk
= NULL
;
3886 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3889 static QemuOptsList resize_options
= {
3890 .name
= "resize_options",
3891 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3894 .name
= BLOCK_OPT_SIZE
,
3895 .type
= QEMU_OPT_SIZE
,
3896 .help
= "Virtual disk size"
3902 bool image_opts
= false;
3903 bool shrink
= false;
3905 /* Remove size from argv manually so that negative numbers are not treated
3906 * as options by getopt. */
3908 error_exit("Not enough arguments");
3912 size
= argv
[--argc
];
3914 /* Parse getopt arguments */
3917 static const struct option long_options
[] = {
3918 {"help", no_argument
, 0, 'h'},
3919 {"object", required_argument
, 0, OPTION_OBJECT
},
3920 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3921 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3922 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3925 c
= getopt_long(argc
, argv
, ":f:hq",
3926 long_options
, NULL
);
3932 missing_argument(argv
[optind
- 1]);
3935 unrecognized_option(argv
[optind
- 1]);
3947 user_creatable_process_cmdline(optarg
);
3949 case OPTION_IMAGE_OPTS
:
3952 case OPTION_PREALLOCATION
:
3953 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3954 PREALLOC_MODE__MAX
, NULL
);
3955 if (prealloc
== PREALLOC_MODE__MAX
) {
3956 error_report("Invalid preallocation mode '%s'", optarg
);
3965 if (optind
!= argc
- 1) {
3966 error_exit("Expecting image file name and size");
3968 filename
= argv
[optind
++];
3970 /* Choose grow, shrink, or absolute resize mode */
3986 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3987 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3988 error_report_err(err
);
3990 qemu_opts_del(param
);
3993 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3994 qemu_opts_del(param
);
3996 blk
= img_open(image_opts
, filename
, fmt
,
3997 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4004 current_size
= blk_getlength(blk
);
4005 if (current_size
< 0) {
4006 error_report("Failed to inquire current image length: %s",
4007 strerror(-current_size
));
4013 total_size
= current_size
+ n
* relative
;
4017 if (total_size
<= 0) {
4018 error_report("New image size must be positive");
4023 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4024 error_report("Preallocation can only be used for growing images");
4029 if (total_size
< current_size
&& !shrink
) {
4030 error_report("Use the --shrink option to perform a shrink operation.");
4031 warn_report("Shrinking an image will delete all data beyond the "
4032 "shrunken image's end. Before performing such an "
4033 "operation, make sure there is no important data there.");
4039 * The user expects the image to have the desired size after
4040 * resizing, so pass @exact=true. It is of no use to report
4041 * success when the image has not actually been resized.
4043 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4045 qprintf(quiet
, "Image resized.\n");
4047 error_report_err(err
);
4057 static void amend_status_cb(BlockDriverState
*bs
,
4058 int64_t offset
, int64_t total_work_size
,
4061 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4064 static int print_amend_option_help(const char *format
)
4068 /* Find driver and parse its options */
4069 drv
= bdrv_find_format(format
);
4071 error_report("Unknown file format '%s'", format
);
4075 if (!drv
->bdrv_amend_options
) {
4076 error_report("Format driver '%s' does not support option amendment",
4081 /* Every driver supporting amendment must have amend_opts */
4082 assert(drv
->amend_opts
);
4084 printf("Amend options for '%s':\n", format
);
4085 qemu_opts_print_help(drv
->amend_opts
, false);
4089 static int img_amend(int argc
, char **argv
)
4093 char *options
= NULL
;
4094 QemuOptsList
*amend_opts
= NULL
;
4095 QemuOpts
*opts
= NULL
;
4096 const char *fmt
= NULL
, *filename
, *cache
;
4099 bool quiet
= false, progress
= false;
4100 BlockBackend
*blk
= NULL
;
4101 BlockDriverState
*bs
= NULL
;
4102 bool image_opts
= false;
4105 cache
= BDRV_DEFAULT_CACHE
;
4107 static const struct option long_options
[] = {
4108 {"help", no_argument
, 0, 'h'},
4109 {"object", required_argument
, 0, OPTION_OBJECT
},
4110 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4111 {"force", no_argument
, 0, OPTION_FORCE
},
4114 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4115 long_options
, NULL
);
4122 missing_argument(argv
[optind
- 1]);
4125 unrecognized_option(argv
[optind
- 1]);
4131 if (accumulate_options(&options
, optarg
) < 0) {
4133 goto out_no_progress
;
4149 user_creatable_process_cmdline(optarg
);
4151 case OPTION_IMAGE_OPTS
:
4161 error_exit("Must specify options (-o)");
4167 qemu_progress_init(progress
, 1.0);
4169 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4170 if (fmt
&& has_help_option(options
)) {
4171 /* If a format is explicitly specified (and possibly no filename is
4172 * given), print option help here */
4173 ret
= print_amend_option_help(fmt
);
4177 if (optind
!= argc
- 1) {
4178 error_report("Expecting one image file name");
4183 flags
= BDRV_O_RDWR
;
4184 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4186 error_report("Invalid cache option: %s", cache
);
4190 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4198 fmt
= bs
->drv
->format_name
;
4200 if (has_help_option(options
)) {
4201 /* If the format was auto-detected, print option help here */
4202 ret
= print_amend_option_help(fmt
);
4206 if (!bs
->drv
->bdrv_amend_options
) {
4207 error_report("Format driver '%s' does not support option amendment",
4213 /* Every driver supporting amendment must have amend_opts */
4214 assert(bs
->drv
->amend_opts
);
4216 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4217 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4218 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4219 /* Try to parse options using the create options */
4220 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4221 qemu_opts_del(opts
);
4222 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4223 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4224 error_append_hint(&err
,
4225 "This option is only supported for image creation\n");
4228 error_report_err(err
);
4233 /* In case the driver does not call amend_status_cb() */
4234 qemu_progress_print(0.f
, 0);
4235 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4236 qemu_progress_print(100.f
, 0);
4238 error_report_err(err
);
4243 qemu_progress_end();
4247 qemu_opts_del(opts
);
4248 qemu_opts_free(amend_opts
);
4257 typedef struct BenchData
{
4259 uint64_t image_size
;
4266 bool drain_on_flush
;
4275 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4278 error_report("Failed flush request: %s", strerror(-ret
));
4283 static void bench_cb(void *opaque
, int ret
)
4285 BenchData
*b
= opaque
;
4289 error_report("Failed request: %s", strerror(-ret
));
4294 /* Just finished a flush with drained queue: Start next requests */
4295 assert(b
->in_flight
== 0);
4296 b
->in_flush
= false;
4297 } else if (b
->in_flight
> 0) {
4298 int remaining
= b
->n
- b
->in_flight
;
4303 /* Time for flush? Drain queue if requested, then flush */
4304 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4305 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4306 BlockCompletionFunc
*cb
;
4308 if (b
->drain_on_flush
) {
4312 cb
= bench_undrained_flush_cb
;
4315 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4317 error_report("Failed to issue flush request");
4321 if (b
->drain_on_flush
) {
4327 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4328 int64_t offset
= b
->offset
;
4329 /* blk_aio_* might look for completed I/Os and kick bench_cb
4330 * again, so make sure this operation is counted by in_flight
4331 * and b->offset is ready for the next submission.
4334 b
->offset
+= b
->step
;
4335 b
->offset
%= b
->image_size
;
4337 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4339 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4342 error_report("Failed to issue request");
4348 static int img_bench(int argc
, char **argv
)
4351 const char *fmt
= NULL
, *filename
;
4353 bool image_opts
= false;
4354 bool is_write
= false;
4358 size_t bufsize
= 4096;
4361 int flush_interval
= 0;
4362 bool drain_on_flush
= true;
4364 BlockBackend
*blk
= NULL
;
4365 BenchData data
= {};
4367 bool writethrough
= false;
4368 struct timeval t1
, t2
;
4370 bool force_share
= false;
4374 static const struct option long_options
[] = {
4375 {"help", no_argument
, 0, 'h'},
4376 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4377 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4378 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4379 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4380 {"force-share", no_argument
, 0, 'U'},
4383 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4391 missing_argument(argv
[optind
- 1]);
4394 unrecognized_option(argv
[optind
- 1]);
4403 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4404 error_report("Invalid request count specified");
4414 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4415 error_report("Invalid queue depth specified");
4425 flags
|= BDRV_O_NATIVE_AIO
;
4428 ret
= bdrv_parse_aio(optarg
, &flags
);
4430 error_report("Invalid aio option: %s", optarg
);
4437 offset
= cvtnum("offset", optarg
);
4451 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4463 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4472 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4474 error_report("Invalid cache mode");
4480 flags
|= BDRV_O_RDWR
;
4486 case OPTION_PATTERN
:
4490 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4491 error_report("Invalid pattern byte specified");
4497 case OPTION_FLUSH_INTERVAL
:
4501 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4502 error_report("Invalid flush interval specified");
4505 flush_interval
= res
;
4508 case OPTION_NO_DRAIN
:
4509 drain_on_flush
= false;
4511 case OPTION_IMAGE_OPTS
:
4517 if (optind
!= argc
- 1) {
4518 error_exit("Expecting one image file name");
4520 filename
= argv
[argc
- 1];
4522 if (!is_write
&& flush_interval
) {
4523 error_report("--flush-interval is only available in write tests");
4527 if (flush_interval
&& flush_interval
< depth
) {
4528 error_report("Flush interval can't be smaller than depth");
4533 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4540 image_size
= blk_getlength(blk
);
4541 if (image_size
< 0) {
4546 data
= (BenchData
) {
4548 .image_size
= image_size
,
4550 .step
= step
?: bufsize
,
4555 .flush_interval
= flush_interval
,
4556 .drain_on_flush
= drain_on_flush
,
4558 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4559 "(starting at offset %" PRId64
", step size %d)\n",
4560 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4561 data
.offset
, data
.step
);
4562 if (flush_interval
) {
4563 printf("Sending flush every %d requests\n", flush_interval
);
4566 buf_size
= data
.nrreq
* data
.bufsize
;
4567 data
.buf
= blk_blockalign(blk
, buf_size
);
4568 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4570 blk_register_buf(blk
, data
.buf
, buf_size
);
4572 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4573 for (i
= 0; i
< data
.nrreq
; i
++) {
4574 qemu_iovec_init(&data
.qiov
[i
], 1);
4575 qemu_iovec_add(&data
.qiov
[i
],
4576 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4579 gettimeofday(&t1
, NULL
);
4582 while (data
.n
> 0) {
4583 main_loop_wait(false);
4585 gettimeofday(&t2
, NULL
);
4587 printf("Run completed in %3.3f seconds.\n",
4588 (t2
.tv_sec
- t1
.tv_sec
)
4589 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4593 blk_unregister_buf(blk
, data
.buf
);
4595 qemu_vfree(data
.buf
);
4612 typedef struct ImgBitmapAction
{
4613 enum ImgBitmapAct act
;
4614 const char *src
; /* only used for merge */
4615 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4618 static int img_bitmap(int argc
, char **argv
)
4622 QemuOpts
*opts
= NULL
;
4623 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4624 const char *filename
, *bitmap
;
4625 BlockBackend
*blk
= NULL
, *src
= NULL
;
4626 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4627 bool image_opts
= false;
4628 int64_t granularity
= 0;
4629 bool add
= false, merge
= false;
4630 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4631 ImgBitmapAction
*act
, *act_next
;
4634 QSIMPLEQ_INIT(&actions
);
4637 static const struct option long_options
[] = {
4638 {"help", no_argument
, 0, 'h'},
4639 {"object", required_argument
, 0, OPTION_OBJECT
},
4640 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4641 {"add", no_argument
, 0, OPTION_ADD
},
4642 {"remove", no_argument
, 0, OPTION_REMOVE
},
4643 {"clear", no_argument
, 0, OPTION_CLEAR
},
4644 {"enable", no_argument
, 0, OPTION_ENABLE
},
4645 {"disable", no_argument
, 0, OPTION_DISABLE
},
4646 {"merge", required_argument
, 0, OPTION_MERGE
},
4647 {"granularity", required_argument
, 0, 'g'},
4648 {"source-file", required_argument
, 0, 'b'},
4649 {"source-format", required_argument
, 0, 'F'},
4652 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4659 missing_argument(argv
[optind
- 1]);
4662 unrecognized_option(argv
[optind
- 1]);
4668 src_filename
= optarg
;
4677 granularity
= cvtnum("granularity", optarg
);
4678 if (granularity
< 0) {
4683 act
= g_new0(ImgBitmapAction
, 1);
4684 act
->act
= BITMAP_ADD
;
4685 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4689 act
= g_new0(ImgBitmapAction
, 1);
4690 act
->act
= BITMAP_REMOVE
;
4691 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4694 act
= g_new0(ImgBitmapAction
, 1);
4695 act
->act
= BITMAP_CLEAR
;
4696 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4699 act
= g_new0(ImgBitmapAction
, 1);
4700 act
->act
= BITMAP_ENABLE
;
4701 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4703 case OPTION_DISABLE
:
4704 act
= g_new0(ImgBitmapAction
, 1);
4705 act
->act
= BITMAP_DISABLE
;
4706 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4709 act
= g_new0(ImgBitmapAction
, 1);
4710 act
->act
= BITMAP_MERGE
;
4712 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4716 user_creatable_process_cmdline(optarg
);
4718 case OPTION_IMAGE_OPTS
:
4724 if (QSIMPLEQ_EMPTY(&actions
)) {
4725 error_report("Need at least one of --add, --remove, --clear, "
4726 "--enable, --disable, or --merge");
4730 if (granularity
&& !add
) {
4731 error_report("granularity only supported with --add");
4734 if (src_fmt
&& !src_filename
) {
4735 error_report("-F only supported with -b");
4738 if (src_filename
&& !merge
) {
4739 error_report("Merge bitmap source file only supported with "
4744 if (optind
!= argc
- 2) {
4745 error_report("Expecting filename and bitmap name");
4749 filename
= argv
[optind
];
4750 bitmap
= argv
[optind
+ 1];
4753 * No need to open backing chains; we will be manipulating bitmaps
4754 * directly in this image without reference to image contents.
4756 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4757 false, false, false);
4763 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4764 false, false, false);
4768 src_bs
= blk_bs(src
);
4773 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4776 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4777 !!granularity
, granularity
, true, true,
4778 false, false, &err
);
4782 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4786 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4790 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4793 case BITMAP_DISABLE
:
4794 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4798 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4803 g_assert_not_reached();
4807 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4819 qemu_opts_del(opts
);
4835 int bsz
; /* Block size */
4843 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4847 static int img_dd_bs(const char *arg
,
4848 struct DdIo
*in
, struct DdIo
*out
,
4853 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4858 in
->bsz
= out
->bsz
= res
;
4863 static int img_dd_count(const char *arg
,
4864 struct DdIo
*in
, struct DdIo
*out
,
4867 dd
->count
= cvtnum("count", arg
);
4869 if (dd
->count
< 0) {
4876 static int img_dd_if(const char *arg
,
4877 struct DdIo
*in
, struct DdIo
*out
,
4880 in
->filename
= g_strdup(arg
);
4885 static int img_dd_of(const char *arg
,
4886 struct DdIo
*in
, struct DdIo
*out
,
4889 out
->filename
= g_strdup(arg
);
4894 static int img_dd_skip(const char *arg
,
4895 struct DdIo
*in
, struct DdIo
*out
,
4898 in
->offset
= cvtnum("skip", arg
);
4900 if (in
->offset
< 0) {
4907 static int img_dd(int argc
, char **argv
)
4912 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4913 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4914 QemuOpts
*opts
= NULL
;
4915 QemuOptsList
*create_opts
= NULL
;
4916 Error
*local_err
= NULL
;
4917 bool image_opts
= false;
4919 const char *out_fmt
= "raw";
4920 const char *fmt
= NULL
;
4922 int64_t block_count
= 0, out_pos
, in_pos
;
4923 bool force_share
= false;
4924 struct DdInfo dd
= {
4929 .bsz
= 512, /* Block size is by default 512 bytes */
4941 const struct DdOpts options
[] = {
4942 { "bs", img_dd_bs
, C_BS
},
4943 { "count", img_dd_count
, C_COUNT
},
4944 { "if", img_dd_if
, C_IF
},
4945 { "of", img_dd_of
, C_OF
},
4946 { "skip", img_dd_skip
, C_SKIP
},
4949 const struct option long_options
[] = {
4950 { "help", no_argument
, 0, 'h'},
4951 { "object", required_argument
, 0, OPTION_OBJECT
},
4952 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4953 { "force-share", no_argument
, 0, 'U'},
4957 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4969 missing_argument(argv
[optind
- 1]);
4972 unrecognized_option(argv
[optind
- 1]);
4981 user_creatable_process_cmdline(optarg
);
4983 case OPTION_IMAGE_OPTS
:
4989 for (i
= optind
; i
< argc
; i
++) {
4991 arg
= g_strdup(argv
[i
]);
4993 tmp
= strchr(arg
, '=');
4995 error_report("unrecognized operand %s", arg
);
5002 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5003 if (!strcmp(arg
, options
[j
].name
)) {
5007 if (options
[j
].name
== NULL
) {
5008 error_report("unrecognized operand %s", arg
);
5013 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5017 dd
.flags
|= options
[j
].flag
;
5022 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5023 error_report("Must specify both input and output files");
5028 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5036 drv
= bdrv_find_format(out_fmt
);
5038 error_report("Unknown file format");
5042 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5045 error_report_err(local_err
);
5049 if (!drv
->create_opts
) {
5050 error_report("Format driver '%s' does not support image creation",
5055 if (!proto_drv
->create_opts
) {
5056 error_report("Protocol driver '%s' does not support image creation",
5057 proto_drv
->format_name
);
5061 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5062 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5064 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5066 size
= blk_getlength(blk1
);
5068 error_report("Failed to get size for '%s'", in
.filename
);
5073 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5074 dd
.count
* in
.bsz
< size
) {
5075 size
= dd
.count
* in
.bsz
;
5078 /* Overflow means the specified offset is beyond input image's size */
5079 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5080 size
< in
.bsz
* in
.offset
)) {
5081 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5083 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5084 size
- in
.bsz
* in
.offset
, &error_abort
);
5087 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5089 error_reportf_err(local_err
,
5090 "%s: error while creating output image: ",
5096 /* TODO, we can't honour --image-opts for the target,
5097 * since it needs to be given in a format compatible
5098 * with the bdrv_create() call above which does not
5099 * support image-opts style.
5101 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5102 false, false, false);
5109 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5110 size
< in
.offset
* in
.bsz
)) {
5111 /* We give a warning if the skip option is bigger than the input
5112 * size and create an empty output disk image (i.e. like dd(1)).
5114 error_report("%s: cannot skip to specified offset", in
.filename
);
5117 in_pos
= in
.offset
* in
.bsz
;
5120 in
.buf
= g_new(uint8_t, in
.bsz
);
5122 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5123 int in_ret
, out_ret
;
5125 if (in_pos
+ in
.bsz
> size
) {
5126 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5128 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5131 error_report("error while reading from input image file: %s",
5138 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5141 error_report("error while writing to output image file: %s",
5142 strerror(-out_ret
));
5151 qemu_opts_del(opts
);
5152 qemu_opts_free(create_opts
);
5155 g_free(in
.filename
);
5156 g_free(out
.filename
);
5166 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5170 Visitor
*v
= qobject_output_visitor_new(&obj
);
5172 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5173 visit_complete(v
, &obj
);
5174 str
= qobject_to_json_pretty(obj
, true);
5175 assert(str
!= NULL
);
5176 printf("%s\n", str
->str
);
5179 g_string_free(str
, true);
5182 static int img_measure(int argc
, char **argv
)
5184 static const struct option long_options
[] = {
5185 {"help", no_argument
, 0, 'h'},
5186 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5187 {"object", required_argument
, 0, OPTION_OBJECT
},
5188 {"output", required_argument
, 0, OPTION_OUTPUT
},
5189 {"size", required_argument
, 0, OPTION_SIZE
},
5190 {"force-share", no_argument
, 0, 'U'},
5193 OutputFormat output_format
= OFORMAT_HUMAN
;
5194 BlockBackend
*in_blk
= NULL
;
5196 const char *filename
= NULL
;
5197 const char *fmt
= NULL
;
5198 const char *out_fmt
= "raw";
5199 char *options
= NULL
;
5200 char *snapshot_name
= NULL
;
5201 bool force_share
= false;
5202 QemuOpts
*opts
= NULL
;
5203 QemuOpts
*object_opts
= NULL
;
5204 QemuOpts
*sn_opts
= NULL
;
5205 QemuOptsList
*create_opts
= NULL
;
5206 bool image_opts
= false;
5207 uint64_t img_size
= UINT64_MAX
;
5208 BlockMeasureInfo
*info
= NULL
;
5209 Error
*local_err
= NULL
;
5213 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5214 long_options
, NULL
)) != -1) {
5227 if (accumulate_options(&options
, optarg
) < 0) {
5232 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5233 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5236 error_report("Failed in parsing snapshot param '%s'",
5241 snapshot_name
= optarg
;
5248 user_creatable_process_cmdline(optarg
);
5250 case OPTION_IMAGE_OPTS
:
5254 if (!strcmp(optarg
, "json")) {
5255 output_format
= OFORMAT_JSON
;
5256 } else if (!strcmp(optarg
, "human")) {
5257 output_format
= OFORMAT_HUMAN
;
5259 error_report("--output must be used with human or json "
5268 sval
= cvtnum("image size", optarg
);
5272 img_size
= (uint64_t)sval
;
5278 if (argc
- optind
> 1) {
5279 error_report("At most one filename argument is allowed.");
5281 } else if (argc
- optind
== 1) {
5282 filename
= argv
[optind
];
5285 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5286 error_report("--image-opts, -f, and -l require a filename argument.");
5289 if (filename
&& img_size
!= UINT64_MAX
) {
5290 error_report("--size N cannot be used together with a filename.");
5293 if (!filename
&& img_size
== UINT64_MAX
) {
5294 error_report("Either --size N or one filename must be specified.");
5299 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5300 false, false, force_share
);
5306 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5307 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5308 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5310 } else if (snapshot_name
!= NULL
) {
5311 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5312 snapshot_name
, &local_err
);
5315 error_reportf_err(local_err
, "Failed to load snapshot: ");
5320 drv
= bdrv_find_format(out_fmt
);
5322 error_report("Unknown file format '%s'", out_fmt
);
5325 if (!drv
->create_opts
) {
5326 error_report("Format driver '%s' does not support image creation",
5331 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5332 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5333 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5335 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5336 error_report_err(local_err
);
5337 error_report("Invalid options for file format '%s'", out_fmt
);
5341 if (img_size
!= UINT64_MAX
) {
5342 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5345 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5347 error_report_err(local_err
);
5351 if (output_format
== OFORMAT_HUMAN
) {
5352 printf("required size: %" PRIu64
"\n", info
->required
);
5353 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5354 if (info
->has_bitmaps
) {
5355 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5358 dump_json_block_measure_info(info
);
5364 qapi_free_BlockMeasureInfo(info
);
5365 qemu_opts_del(object_opts
);
5366 qemu_opts_del(opts
);
5367 qemu_opts_del(sn_opts
);
5368 qemu_opts_free(create_opts
);
5374 static const img_cmd_t img_cmds
[] = {
5375 #define DEF(option, callback, arg_string) \
5376 { option, callback },
5377 #include "qemu-img-cmds.h"
5382 int main(int argc
, char **argv
)
5384 const img_cmd_t
*cmd
;
5385 const char *cmdname
;
5387 static const struct option long_options
[] = {
5388 {"help", no_argument
, 0, 'h'},
5389 {"version", no_argument
, 0, 'V'},
5390 {"trace", required_argument
, NULL
, 'T'},
5395 signal(SIGPIPE
, SIG_IGN
);
5399 error_init(argv
[0]);
5400 module_call_init(MODULE_INIT_TRACE
);
5401 qemu_init_exec_dir(argv
[0]);
5403 qemu_init_main_loop(&error_fatal
);
5405 qcrypto_init(&error_fatal
);
5407 module_call_init(MODULE_INIT_QOM
);
5410 error_exit("Not enough arguments");
5413 qemu_add_opts(&qemu_source_opts
);
5414 qemu_add_opts(&qemu_trace_opts
);
5416 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5419 missing_argument(argv
[optind
- 1]);
5422 unrecognized_option(argv
[optind
- 1]);
5428 printf(QEMU_IMG_VERSION
);
5431 trace_opt_parse(optarg
);
5436 cmdname
= argv
[optind
];
5438 /* reset getopt_long scanning */
5444 qemu_reset_optind();
5446 if (!trace_init_backends()) {
5450 qemu_set_log(LOG_TRACE
, &error_fatal
);
5452 /* find the command */
5453 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5454 if (!strcmp(cmdname
, cmd
->name
)) {
5455 return cmd
->handler(argc
, argv
);
5460 error_exit("Command not found: %s", cmdname
);