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 help for an overview of the options supported by\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
);
916 job_ref_locked(&job
->job
);
918 float progress
= 0.0f
;
920 aio_poll(aio_context
, true);
922 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
924 if (progress_total
) {
925 progress
= (float)progress_current
/ progress_total
* 100.f
;
927 qemu_progress_print(progress
, 0);
929 } while (!job_is_ready_locked(&job
->job
) &&
930 !job_is_completed_locked(&job
->job
));
932 if (!job_is_completed_locked(&job
->job
)) {
933 ret
= job_complete_sync_locked(&job
->job
, errp
);
937 job_unref_locked(&job
->job
);
939 aio_context_release(aio_context
);
941 /* publish completion progress only when success */
943 qemu_progress_print(100.f
, 0);
947 static int img_commit(int argc
, char **argv
)
950 const char *filename
, *fmt
, *cache
, *base
;
952 BlockDriverState
*bs
, *base_bs
;
954 bool progress
= false, quiet
= false, drop
= false;
956 Error
*local_err
= NULL
;
957 CommonBlockJobCBInfo cbi
;
958 bool image_opts
= false;
959 AioContext
*aio_context
;
960 int64_t rate_limit
= 0;
963 cache
= BDRV_DEFAULT_CACHE
;
966 static const struct option long_options
[] = {
967 {"help", no_argument
, 0, 'h'},
968 {"object", required_argument
, 0, OPTION_OBJECT
},
969 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
972 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
979 missing_argument(argv
[optind
- 1]);
982 unrecognized_option(argv
[optind
- 1]);
1008 rate_limit
= cvtnum("rate limit", optarg
);
1009 if (rate_limit
< 0) {
1014 user_creatable_process_cmdline(optarg
);
1016 case OPTION_IMAGE_OPTS
:
1022 /* Progress is not shown in Quiet mode */
1027 if (optind
!= argc
- 1) {
1028 error_exit("Expecting one image file name");
1030 filename
= argv
[optind
++];
1032 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1033 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1035 error_report("Invalid cache option: %s", cache
);
1039 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1046 qemu_progress_init(progress
, 1.f
);
1047 qemu_progress_print(0.f
, 100);
1050 base_bs
= bdrv_find_backing_image(bs
, base
);
1052 error_setg(&local_err
,
1053 "Did not find '%s' in the backing chain of '%s'",
1058 /* This is different from QMP, which by default uses the deepest file in
1059 * the backing chain (i.e., the very base); however, the traditional
1060 * behavior of qemu-img commit is using the immediate backing file. */
1061 base_bs
= bdrv_backing_chain_next(bs
);
1063 error_setg(&local_err
, "Image does not have a backing file");
1068 cbi
= (CommonBlockJobCBInfo
){
1073 aio_context
= bdrv_get_aio_context(bs
);
1074 aio_context_acquire(aio_context
);
1075 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1076 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1077 &cbi
, false, &local_err
);
1078 aio_context_release(aio_context
);
1083 /* When the block job completes, the BlockBackend reference will point to
1084 * the old backing file. In order to avoid that the top image is already
1085 * deleted, so we can still empty it afterwards, increment the reference
1086 * counter here preemptively. */
1091 job
= block_job_get("commit");
1093 run_block_job(job
, &local_err
);
1099 BlockBackend
*old_backing_blk
;
1101 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1103 if (!old_backing_blk
) {
1106 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1107 blk_unref(old_backing_blk
);
1108 if (ret
== -ENOTSUP
) {
1109 error_free(local_err
);
1111 } else if (ret
< 0) {
1122 qemu_progress_end();
1127 error_report_err(local_err
);
1131 qprintf(quiet
, "Image committed.\n");
1136 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1137 * of the first sector boundary within buf where the sector contains a
1138 * non-zero byte. This function is robust to a buffer that is not
1141 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1144 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1146 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1147 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1151 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1158 * Returns true iff the first sector pointed to by 'buf' contains at least
1161 * 'pnum' is set to the number of sectors (including and immediately following
1162 * the first one) that are known to be in the same allocated/unallocated state.
1163 * The function will try to align the end offset to alignment boundaries so
1164 * that the request will at least end aligned and consecutive requests will
1165 * also start at an aligned offset.
1167 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1168 int64_t sector_num
, int alignment
)
1177 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1178 for(i
= 1; i
< n
; i
++) {
1179 buf
+= BDRV_SECTOR_SIZE
;
1180 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1187 * The whole buf is the same.
1188 * No reason to split it into chunks, so return now.
1194 tail
= (sector_num
+ i
) & (alignment
- 1);
1196 if (is_zero
&& i
<= tail
) {
1198 * For sure next sector after i is data, and it will rewrite this
1199 * tail anyway due to RMW. So, let's just write data now.
1204 /* If possible, align up end offset of allocated areas. */
1205 i
+= alignment
- tail
;
1209 * For sure next sector after i is data, and it will rewrite this
1210 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1221 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1222 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1223 * breaking up write requests for only small sparse areas.
1225 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1226 int min
, int64_t sector_num
, int alignment
)
1229 int num_checked
, num_used
;
1235 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1241 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1243 sector_num
+= *pnum
;
1244 num_checked
= num_used
;
1247 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1249 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1251 sector_num
+= *pnum
;
1252 num_checked
+= *pnum
;
1254 num_used
= num_checked
;
1255 } else if (*pnum
>= min
) {
1265 * Compares two buffers sector by sector. Returns 0 if the first
1266 * sector of each buffer matches, non-zero otherwise.
1268 * pnum is set to the sector-aligned size of the buffer prefix that
1269 * has the same matching status as the first sector.
1271 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1272 int64_t bytes
, int64_t *pnum
)
1275 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1279 res
= !!memcmp(buf1
, buf2
, i
);
1281 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1283 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1293 #define IO_BUF_SIZE (2 * MiB)
1296 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1298 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1299 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1300 * failure), and 4 on error (the exit status for read errors), after emitting
1303 * @param blk: BlockBackend for the image
1304 * @param offset: Starting offset to check
1305 * @param bytes: Number of bytes to check
1306 * @param filename: Name of disk file we are checking (logging purpose)
1307 * @param buffer: Allocated buffer for storing read data
1308 * @param quiet: Flag for quiet mode
1310 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1311 int64_t bytes
, const char *filename
,
1312 uint8_t *buffer
, bool quiet
)
1317 ret
= blk_pread(blk
, offset
, bytes
, buffer
, 0);
1319 error_report("Error while reading offset %" PRId64
" of %s: %s",
1320 offset
, filename
, strerror(-ret
));
1323 idx
= find_nonzero(buffer
, bytes
);
1325 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1334 * Compares two images. Exit codes:
1336 * 0 - Images are identical or the requested help was printed
1338 * >1 - Error occurred
1340 static int img_compare(int argc
, char **argv
)
1342 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1343 BlockBackend
*blk1
, *blk2
;
1344 BlockDriverState
*bs1
, *bs2
;
1345 int64_t total_size1
, total_size2
;
1346 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1347 int64_t pnum1
, pnum2
;
1348 int allocated1
, allocated2
;
1349 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1350 bool progress
= false, quiet
= false, strict
= false;
1357 uint64_t progress_base
;
1358 bool image_opts
= false;
1359 bool force_share
= false;
1361 cache
= BDRV_DEFAULT_CACHE
;
1363 static const struct option long_options
[] = {
1364 {"help", no_argument
, 0, 'h'},
1365 {"object", required_argument
, 0, OPTION_OBJECT
},
1366 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1367 {"force-share", no_argument
, 0, 'U'},
1370 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1371 long_options
, NULL
);
1377 missing_argument(argv
[optind
- 1]);
1380 unrecognized_option(argv
[optind
- 1]);
1408 Error
*local_err
= NULL
;
1410 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1412 error_report_err(local_err
);
1415 /* Help was printed */
1421 case OPTION_IMAGE_OPTS
:
1427 /* Progress is not shown in Quiet mode */
1433 if (optind
!= argc
- 2) {
1434 error_exit("Expecting two image file names");
1436 filename1
= argv
[optind
++];
1437 filename2
= argv
[optind
++];
1439 /* Initialize before goto out */
1440 qemu_progress_init(progress
, 2.0);
1443 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1445 error_report("Invalid source cache option: %s", cache
);
1450 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1457 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1466 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1467 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1468 total_size1
= blk_getlength(blk1
);
1469 if (total_size1
< 0) {
1470 error_report("Can't get size of %s: %s",
1471 filename1
, strerror(-total_size1
));
1475 total_size2
= blk_getlength(blk2
);
1476 if (total_size2
< 0) {
1477 error_report("Can't get size of %s: %s",
1478 filename2
, strerror(-total_size2
));
1482 total_size
= MIN(total_size1
, total_size2
);
1483 progress_base
= MAX(total_size1
, total_size2
);
1485 qemu_progress_print(0, 100);
1487 if (strict
&& total_size1
!= total_size2
) {
1489 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1493 while (offset
< total_size
) {
1494 int status1
, status2
;
1496 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1497 total_size1
- offset
, &pnum1
, NULL
,
1501 error_report("Sector allocation test failed for %s", filename1
);
1504 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1506 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1507 total_size2
- offset
, &pnum2
, NULL
,
1511 error_report("Sector allocation test failed for %s", filename2
);
1514 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1516 assert(pnum1
&& pnum2
);
1517 chunk
= MIN(pnum1
, pnum2
);
1520 if (status1
!= status2
) {
1522 qprintf(quiet
, "Strict mode: Offset %" PRId64
1523 " block status mismatch!\n", offset
);
1527 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1529 } else if (allocated1
== allocated2
) {
1533 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1534 ret
= blk_pread(blk1
, offset
, chunk
, buf1
, 0);
1536 error_report("Error while reading offset %" PRId64
1538 offset
, filename1
, strerror(-ret
));
1542 ret
= blk_pread(blk2
, offset
, chunk
, buf2
, 0);
1544 error_report("Error while reading offset %" PRId64
1546 offset
, filename2
, strerror(-ret
));
1550 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1551 if (ret
|| pnum
!= chunk
) {
1552 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1553 offset
+ (ret
? 0 : pnum
));
1559 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1561 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1562 filename1
, buf1
, quiet
);
1564 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1565 filename2
, buf1
, quiet
);
1572 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1575 if (total_size1
!= total_size2
) {
1576 BlockBackend
*blk_over
;
1577 const char *filename_over
;
1579 qprintf(quiet
, "Warning: Image size mismatch!\n");
1580 if (total_size1
> total_size2
) {
1582 filename_over
= filename1
;
1585 filename_over
= filename2
;
1588 while (offset
< progress_base
) {
1589 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1590 progress_base
- offset
, &chunk
,
1594 error_report("Sector allocation test failed for %s",
1599 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1600 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1601 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1602 filename_over
, buf1
, quiet
);
1608 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1612 qprintf(quiet
, "Images are identical.\n");
1622 qemu_progress_end();
1626 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1627 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1628 const char *src_node
, const char *src_name
,
1631 BlockDirtyBitmapOrStr
*merge_src
;
1632 BlockDirtyBitmapOrStrList
*list
= NULL
;
1634 merge_src
= g_new0(BlockDirtyBitmapOrStr
, 1);
1635 merge_src
->type
= QTYPE_QDICT
;
1636 merge_src
->u
.external
.node
= g_strdup(src_node
);
1637 merge_src
->u
.external
.name
= g_strdup(src_name
);
1638 QAPI_LIST_PREPEND(list
, merge_src
);
1639 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1640 qapi_free_BlockDirtyBitmapOrStrList(list
);
1643 enum ImgConvertBlockStatus
{
1649 #define MAX_COROUTINES 16
1650 #define CONVERT_THROTTLE_GROUP "img_convert"
1652 typedef struct ImgConvertState
{
1654 int64_t *src_sectors
;
1657 int64_t total_sectors
;
1658 int64_t allocated_sectors
;
1659 int64_t allocated_done
;
1662 enum ImgConvertBlockStatus status
;
1663 int64_t sector_next_status
;
1664 BlockBackend
*target
;
1668 bool target_has_backing
;
1669 int64_t target_backing_sectors
; /* negative if unknown */
1676 size_t cluster_sectors
;
1678 long num_coroutines
;
1679 int running_coroutines
;
1680 Coroutine
*co
[MAX_COROUTINES
];
1681 int64_t wait_sector_num
[MAX_COROUTINES
];
1686 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1687 int *src_cur
, int64_t *src_cur_offset
)
1690 *src_cur_offset
= 0;
1691 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1692 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1694 assert(*src_cur
< s
->src_num
);
1698 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1700 int64_t src_cur_offset
;
1701 int ret
, n
, src_cur
;
1702 bool post_backing_zero
= false;
1704 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1706 assert(s
->total_sectors
> sector_num
);
1707 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1709 if (s
->target_backing_sectors
>= 0) {
1710 if (sector_num
>= s
->target_backing_sectors
) {
1711 post_backing_zero
= true;
1712 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1713 /* Split requests around target_backing_sectors (because
1714 * starting from there, zeros are handled differently) */
1715 n
= s
->target_backing_sectors
- sector_num
;
1719 if (s
->sector_next_status
<= sector_num
) {
1720 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1723 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1724 BlockDriverState
*base
;
1726 if (s
->target_has_backing
) {
1727 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1733 count
= n
* BDRV_SECTOR_SIZE
;
1735 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1742 warn_report("error while reading block status at "
1743 "offset %" PRIu64
": %s", offset
,
1746 /* Just try to read the data, then */
1747 ret
= BDRV_BLOCK_DATA
;
1748 count
= BDRV_SECTOR_SIZE
;
1750 /* Retry on a shorter range */
1751 n
= DIV_ROUND_UP(n
, 4);
1754 error_report("error while reading block status at offset "
1755 "%" PRIu64
": %s", offset
, strerror(-ret
));
1761 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1764 * Avoid that s->sector_next_status becomes unaligned to the source
1765 * request alignment and/or cluster size to avoid unnecessary read
1768 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1773 if (ret
& BDRV_BLOCK_ZERO
) {
1774 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1775 } else if (ret
& BDRV_BLOCK_DATA
) {
1776 s
->status
= BLK_DATA
;
1778 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1781 s
->sector_next_status
= sector_num
+ n
;
1784 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1785 if (s
->status
== BLK_DATA
) {
1786 n
= MIN(n
, s
->buf_sectors
);
1789 /* We need to write complete clusters for compressed images, so if an
1790 * unallocated area is shorter than that, we must consider the whole
1791 * cluster allocated. */
1792 if (s
->compressed
) {
1793 if (n
< s
->cluster_sectors
) {
1794 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1795 s
->status
= BLK_DATA
;
1797 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1804 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1805 int nb_sectors
, uint8_t *buf
)
1807 uint64_t single_read_until
= 0;
1810 assert(nb_sectors
<= s
->buf_sectors
);
1811 while (nb_sectors
> 0) {
1814 int64_t bs_sectors
, src_cur_offset
;
1817 /* In the case of compression with multiple source files, we can get a
1818 * nb_sectors that spreads into the next part. So we must be able to
1819 * read across multiple BDSes for one convert_read() call. */
1820 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1821 blk
= s
->src
[src_cur
];
1822 bs_sectors
= s
->src_sectors
[src_cur
];
1824 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1826 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1827 if (single_read_until
> offset
) {
1831 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1835 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1839 warn_report("error while reading offset %" PRIu64
1840 ": %s", offset
, strerror(-ret
));
1842 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1851 buf
+= n
* BDRV_SECTOR_SIZE
;
1858 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1859 int nb_sectors
, uint8_t *buf
,
1860 enum ImgConvertBlockStatus status
)
1864 while (nb_sectors
> 0) {
1866 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1869 case BLK_BACKING_FILE
:
1870 /* If we have a backing file, leave clusters unallocated that are
1871 * unallocated in the source image, so that the backing file is
1872 * visible at the respective offset. */
1873 assert(s
->target_has_backing
);
1877 /* If we're told to keep the target fully allocated (-S 0) or there
1878 * is real non-zero data, we must write it. Otherwise we can treat
1879 * it as zero sectors.
1880 * Compressed clusters need to be written as a whole, so in that
1881 * case we can only save the write if the buffer is completely
1883 if (!s
->min_sparse
||
1885 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1886 sector_num
, s
->alignment
)) ||
1888 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1890 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1891 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1900 if (s
->has_zero_init
) {
1901 assert(!s
->target_has_backing
);
1904 ret
= blk_co_pwrite_zeroes(s
->target
,
1905 sector_num
<< BDRV_SECTOR_BITS
,
1906 n
<< BDRV_SECTOR_BITS
,
1907 BDRV_REQ_MAY_UNMAP
);
1916 buf
+= n
* BDRV_SECTOR_SIZE
;
1922 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1927 while (nb_sectors
> 0) {
1930 int64_t bs_sectors
, src_cur_offset
;
1933 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1934 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1935 blk
= s
->src
[src_cur
];
1936 bs_sectors
= s
->src_sectors
[src_cur
];
1938 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1940 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1941 sector_num
<< BDRV_SECTOR_BITS
,
1942 n
<< BDRV_SECTOR_BITS
, 0, 0);
1953 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1955 ImgConvertState
*s
= opaque
;
1956 uint8_t *buf
= NULL
;
1960 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1961 if (s
->co
[i
] == qemu_coroutine_self()) {
1968 s
->running_coroutines
++;
1969 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1974 enum ImgConvertBlockStatus status
;
1977 qemu_co_mutex_lock(&s
->lock
);
1978 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1979 qemu_co_mutex_unlock(&s
->lock
);
1982 n
= convert_iteration_sectors(s
, s
->sector_num
);
1984 qemu_co_mutex_unlock(&s
->lock
);
1988 /* save current sector and allocation status to local variables */
1989 sector_num
= s
->sector_num
;
1991 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1992 n
= MIN(n
, s
->buf_sectors
);
1994 /* increment global sector counter so that other coroutines can
1995 * already continue reading beyond this request */
1997 qemu_co_mutex_unlock(&s
->lock
);
1999 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2000 s
->allocated_done
+= n
;
2001 qemu_progress_print(100.0 * s
->allocated_done
/
2002 s
->allocated_sectors
, 0);
2006 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2007 if (status
== BLK_DATA
&& !copy_range
) {
2008 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2010 error_report("error while reading at byte %lld: %s",
2011 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2014 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2016 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2019 if (s
->wr_in_order
) {
2020 /* keep writes in order */
2021 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2022 s
->wait_sector_num
[index
] = sector_num
;
2023 qemu_coroutine_yield();
2025 s
->wait_sector_num
[index
] = -1;
2028 if (s
->ret
== -EINPROGRESS
) {
2030 ret
= convert_co_copy_range(s
, sector_num
, n
);
2032 s
->copy_range
= false;
2036 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2039 error_report("error while writing at byte %lld: %s",
2040 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2045 if (s
->wr_in_order
) {
2046 /* reenter the coroutine that might have waited
2047 * for this write to complete */
2048 s
->wr_offs
= sector_num
+ n
;
2049 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2050 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2052 * A -> B -> A cannot occur because A has
2053 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2054 * B will never enter A during this time window.
2056 qemu_coroutine_enter(s
->co
[i
]);
2064 s
->co
[index
] = NULL
;
2065 s
->running_coroutines
--;
2066 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2067 /* the convert job finished successfully */
2072 static int convert_do_copy(ImgConvertState
*s
)
2075 int64_t sector_num
= 0;
2077 /* Check whether we have zero initialisation or can get it efficiently */
2078 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2079 !s
->target_has_backing
) {
2080 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2083 /* Allocate buffer for copied data. For compressed images, only one cluster
2084 * can be copied at a time. */
2085 if (s
->compressed
) {
2086 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2087 error_report("invalid cluster size");
2090 s
->buf_sectors
= s
->cluster_sectors
;
2093 while (sector_num
< s
->total_sectors
) {
2094 n
= convert_iteration_sectors(s
, sector_num
);
2098 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2100 s
->allocated_sectors
+= n
;
2106 s
->sector_next_status
= 0;
2107 s
->ret
= -EINPROGRESS
;
2109 qemu_co_mutex_init(&s
->lock
);
2110 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2111 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2112 s
->wait_sector_num
[i
] = -1;
2113 qemu_coroutine_enter(s
->co
[i
]);
2116 while (s
->running_coroutines
) {
2117 main_loop_wait(false);
2120 if (s
->compressed
&& !s
->ret
) {
2121 /* signal EOF to align */
2122 ret
= blk_pwrite_compressed(s
->target
, 0, 0, NULL
);
2131 /* Check that bitmaps can be copied, or output an error */
2132 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2134 BdrvDirtyBitmap
*bm
;
2136 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2137 error_report("Source lacks bitmap support");
2140 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2141 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2144 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2145 error_report("Cannot copy inconsistent bitmap '%s'",
2146 bdrv_dirty_bitmap_name(bm
));
2147 error_printf("Try --skip-broken-bitmaps, or "
2148 "use 'qemu-img bitmap --remove' to delete it\n");
2155 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2158 BdrvDirtyBitmap
*bm
;
2161 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2164 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2167 name
= bdrv_dirty_bitmap_name(bm
);
2168 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2169 warn_report("Skipping inconsistent bitmap '%s'", name
);
2172 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2173 true, bdrv_dirty_bitmap_granularity(bm
),
2175 true, !bdrv_dirty_bitmap_enabled(bm
),
2178 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2182 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2185 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2186 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2194 #define MAX_BUF_SECTORS 32768
2196 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2200 throttle_config_init(&cfg
);
2201 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2203 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2204 blk_set_io_limits(blk
, &cfg
);
2207 static int img_convert(int argc
, char **argv
)
2209 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2210 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2211 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2212 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2213 *backing_fmt
= NULL
;
2214 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2215 BlockDriverInfo bdi
;
2216 BlockDriverState
*out_bs
;
2217 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2218 QemuOptsList
*create_opts
= NULL
;
2219 QDict
*open_opts
= NULL
;
2220 char *options
= NULL
;
2221 Error
*local_err
= NULL
;
2222 bool writethrough
, src_writethrough
, image_opts
= false,
2223 skip_create
= false, progress
= false, tgt_image_opts
= false;
2224 int64_t ret
= -EINVAL
;
2225 bool force_share
= false;
2226 bool explict_min_sparse
= false;
2227 bool bitmaps
= false;
2228 bool skip_broken
= false;
2229 int64_t rate_limit
= 0;
2231 ImgConvertState s
= (ImgConvertState
) {
2232 /* Need at least 4k of zeros for sparse detection */
2234 .copy_range
= false,
2235 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2236 .wr_in_order
= true,
2237 .num_coroutines
= 8,
2241 static const struct option long_options
[] = {
2242 {"help", no_argument
, 0, 'h'},
2243 {"object", required_argument
, 0, OPTION_OBJECT
},
2244 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2245 {"force-share", no_argument
, 0, 'U'},
2246 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2247 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2248 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2249 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2250 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2253 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2254 long_options
, NULL
);
2260 missing_argument(argv
[optind
- 1]);
2263 unrecognized_option(argv
[optind
- 1]);
2275 out_baseimg
= optarg
;
2278 s
.copy_range
= true;
2281 s
.compressed
= true;
2284 backing_fmt
= optarg
;
2287 if (accumulate_options(&options
, optarg
) < 0) {
2292 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2293 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2296 error_report("Failed in parsing snapshot param '%s'",
2301 snapshot_name
= optarg
;
2308 sval
= cvtnum("buffer size for sparse output", optarg
);
2311 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2312 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2313 error_report("Invalid buffer size for sparse output specified. "
2314 "Valid sizes are multiples of %llu up to %llu. Select "
2315 "0 to disable sparse detection (fully allocates output).",
2316 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2320 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2321 explict_min_sparse
= true;
2340 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2341 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2342 error_report("Invalid number of coroutines. Allowed number of"
2343 " coroutines is between 1 and %d", MAX_COROUTINES
);
2348 s
.wr_in_order
= false;
2354 rate_limit
= cvtnum("rate limit", optarg
);
2355 if (rate_limit
< 0) {
2360 user_creatable_process_cmdline(optarg
);
2362 case OPTION_IMAGE_OPTS
:
2365 case OPTION_SALVAGE
:
2368 case OPTION_TARGET_IMAGE_OPTS
:
2369 tgt_image_opts
= true;
2371 case OPTION_TARGET_IS_ZERO
:
2373 * The user asserting that the target is blank has the
2374 * same effect as the target driver supporting zero
2377 s
.has_zero_init
= true;
2379 case OPTION_BITMAPS
:
2382 case OPTION_SKIP_BROKEN
:
2388 if (!out_fmt
&& !tgt_image_opts
) {
2392 if (skip_broken
&& !bitmaps
) {
2393 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2397 if (s
.compressed
&& s
.copy_range
) {
2398 error_report("Cannot enable copy offloading when -c is used");
2402 if (explict_min_sparse
&& s
.copy_range
) {
2403 error_report("Cannot enable copy offloading when -S is used");
2407 if (s
.copy_range
&& s
.salvage
) {
2408 error_report("Cannot use copy offloading in salvaging mode");
2412 if (tgt_image_opts
&& !skip_create
) {
2413 error_report("--target-image-opts requires use of -n flag");
2417 if (skip_create
&& options
) {
2418 error_report("-o has no effect when skipping image creation");
2422 if (s
.has_zero_init
&& !skip_create
) {
2423 error_report("--target-is-zero requires use of -n flag");
2427 s
.src_num
= argc
- optind
- 1;
2428 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2430 if (options
&& has_help_option(options
)) {
2432 ret
= print_block_option_help(out_filename
, out_fmt
);
2435 error_report("Option help requires a format be specified");
2440 if (s
.src_num
< 1) {
2441 error_report("Must specify image file name");
2445 /* ret is still -EINVAL until here */
2446 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2448 error_report("Invalid source cache option: %s", src_cache
);
2452 /* Initialize before goto out */
2456 qemu_progress_init(progress
, 1.0);
2457 qemu_progress_print(0, 100);
2459 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2460 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2461 s
.src_alignment
= g_new(int, s
.src_num
);
2463 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2464 BlockDriverState
*src_bs
;
2465 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2466 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2472 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2473 if (s
.src_sectors
[bs_i
] < 0) {
2474 error_report("Could not get size of %s: %s",
2475 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2479 src_bs
= blk_bs(s
.src
[bs_i
]);
2480 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2482 if (!bdrv_get_info(src_bs
, &bdi
)) {
2483 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2484 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2486 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2490 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2491 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2492 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2494 } else if (snapshot_name
!= NULL
) {
2495 if (s
.src_num
> 1) {
2496 error_report("No support for concatenating multiple snapshot");
2501 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2505 error_reportf_err(local_err
, "Failed to load snapshot: ");
2511 /* Find driver and parse its options */
2512 drv
= bdrv_find_format(out_fmt
);
2514 error_report("Unknown file format '%s'", out_fmt
);
2519 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2521 error_report_err(local_err
);
2526 if (!drv
->create_opts
) {
2527 error_report("Format driver '%s' does not support image creation",
2533 if (!proto_drv
->create_opts
) {
2534 error_report("Protocol driver '%s' does not support image creation",
2535 proto_drv
->format_name
);
2540 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2541 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2543 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2545 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2546 error_report_err(local_err
);
2552 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2553 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2554 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2560 /* Get backing file name if -o backing_file was used */
2561 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2562 if (out_baseimg_param
) {
2563 out_baseimg
= out_baseimg_param
;
2565 s
.target_has_backing
= (bool) out_baseimg
;
2567 if (s
.has_zero_init
&& s
.target_has_backing
) {
2568 error_report("Cannot use --target-is-zero when the destination "
2569 "image has a backing file");
2573 if (s
.src_num
> 1 && out_baseimg
) {
2574 error_report("Having a backing file for the target makes no sense when "
2575 "concatenating multiple input images");
2580 if (out_baseimg_param
) {
2581 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2582 error_report("Use of backing file requires explicit "
2589 /* Check if compression is supported */
2592 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2593 const char *encryptfmt
=
2594 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2595 const char *preallocation
=
2596 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2598 if (drv
&& !block_driver_can_compress(drv
)) {
2599 error_report("Compression not supported for this file format");
2604 if (encryption
|| encryptfmt
) {
2605 error_report("Compression and encryption not supported at "
2612 && strcmp(preallocation
, "off"))
2614 error_report("Compression and preallocation not supported at "
2621 /* Determine if bitmaps need copying */
2623 if (s
.src_num
> 1) {
2624 error_report("Copying bitmaps only possible with single source");
2628 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2635 * The later open call will need any decryption secrets, and
2636 * bdrv_create() will purge "opts", so extract them now before
2640 open_opts
= qdict_new();
2641 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2643 /* Create the new image */
2644 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2646 error_reportf_err(local_err
, "%s: error while converting %s: ",
2647 out_filename
, out_fmt
);
2652 s
.target_is_new
= !skip_create
;
2654 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2655 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2657 error_report("Invalid cache option: %s", cache
);
2661 if (flags
& BDRV_O_NOCACHE
) {
2663 * If we open the target with O_DIRECT, it may be necessary to
2664 * extend its size to align to the physical sector size.
2666 flags
|= BDRV_O_RESIZE
;
2670 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2671 flags
, writethrough
, s
.quiet
, false);
2673 /* TODO ultimately we should allow --target-image-opts
2674 * to be used even when -n is not given.
2675 * That has to wait for bdrv_create to be improved
2676 * to allow filenames in option syntax
2678 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2679 flags
, writethrough
, s
.quiet
, false);
2680 open_opts
= NULL
; /* blk_new_open will have freed it */
2686 out_bs
= blk_bs(s
.target
);
2688 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2689 error_report("Format driver '%s' does not support bitmaps",
2690 out_bs
->drv
->format_name
);
2695 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2696 error_report("Compression not supported for this file format");
2701 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2702 * or discard_alignment of the out_bs is greater. Limit to
2703 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2704 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2706 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2707 out_bs
->bl
.pdiscard_alignment
>>
2708 BDRV_SECTOR_BITS
)));
2710 /* try to align the write requests to the destination to avoid unnecessary
2712 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2713 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2715 assert(is_power_of_2(s
.alignment
));
2718 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2719 if (output_sectors
< 0) {
2720 error_report("unable to get output image length: %s",
2721 strerror(-output_sectors
));
2724 } else if (output_sectors
< s
.total_sectors
) {
2725 error_report("output file is smaller than input file");
2731 if (s
.target_has_backing
&& s
.target_is_new
) {
2732 /* Errors are treated as "backing length unknown" (which means
2733 * s.target_backing_sectors has to be negative, which it will
2734 * be automatically). The backing file length is used only
2735 * for optimizations, so such a case is not fatal. */
2736 s
.target_backing_sectors
=
2737 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2739 s
.target_backing_sectors
= -1;
2742 ret
= bdrv_get_info(out_bs
, &bdi
);
2745 error_report("could not get block driver info");
2749 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2750 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2754 set_rate_limit(s
.target
, rate_limit
);
2757 ret
= convert_do_copy(&s
);
2759 /* Now copy the bitmaps */
2760 if (bitmaps
&& ret
== 0) {
2761 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2766 qemu_progress_print(100, 0);
2768 qemu_progress_end();
2769 qemu_opts_del(opts
);
2770 qemu_opts_free(create_opts
);
2771 qobject_unref(open_opts
);
2772 blk_unref(s
.target
);
2774 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2775 blk_unref(s
.src
[bs_i
]);
2779 g_free(s
.src_sectors
);
2780 g_free(s
.src_alignment
);
2782 qemu_opts_del(sn_opts
);
2789 static void dump_snapshots(BlockDriverState
*bs
)
2791 QEMUSnapshotInfo
*sn_tab
, *sn
;
2794 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2797 printf("Snapshot list:\n");
2798 bdrv_snapshot_dump(NULL
);
2800 for(i
= 0; i
< nb_sns
; i
++) {
2802 bdrv_snapshot_dump(sn
);
2808 static void dump_json_image_info_list(ImageInfoList
*list
)
2812 Visitor
*v
= qobject_output_visitor_new(&obj
);
2814 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2815 visit_complete(v
, &obj
);
2816 str
= qobject_to_json_pretty(obj
, true);
2817 assert(str
!= NULL
);
2818 printf("%s\n", str
->str
);
2821 g_string_free(str
, true);
2824 static void dump_json_image_info(ImageInfo
*info
)
2828 Visitor
*v
= qobject_output_visitor_new(&obj
);
2830 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2831 visit_complete(v
, &obj
);
2832 str
= qobject_to_json_pretty(obj
, true);
2833 assert(str
!= NULL
);
2834 printf("%s\n", str
->str
);
2837 g_string_free(str
, true);
2840 static void dump_human_image_info_list(ImageInfoList
*list
)
2842 ImageInfoList
*elem
;
2845 for (elem
= list
; elem
; elem
= elem
->next
) {
2851 bdrv_image_info_dump(elem
->value
);
2855 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2857 return strcmp(a
, b
) == 0;
2861 * Open an image file chain and return an ImageInfoList
2863 * @filename: topmost image filename
2864 * @fmt: topmost image format (may be NULL to autodetect)
2865 * @chain: true - enumerate entire backing file chain
2866 * false - only topmost image file
2868 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2869 * image file. If there was an error a message will have been printed to
2872 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2873 const char *filename
,
2875 bool chain
, bool force_share
)
2877 ImageInfoList
*head
= NULL
;
2878 ImageInfoList
**tail
= &head
;
2879 GHashTable
*filenames
;
2882 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2886 BlockDriverState
*bs
;
2889 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2890 error_report("Backing file '%s' creates an infinite loop.",
2894 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2896 blk
= img_open(image_opts
, filename
, fmt
,
2897 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2904 bdrv_query_image_info(bs
, &info
, &err
);
2906 error_report_err(err
);
2911 QAPI_LIST_APPEND(tail
, info
);
2915 /* Clear parameters that only apply to the topmost image */
2916 filename
= fmt
= NULL
;
2920 if (info
->has_full_backing_filename
) {
2921 filename
= info
->full_backing_filename
;
2922 } else if (info
->has_backing_filename
) {
2923 error_report("Could not determine absolute backing filename,"
2924 " but backing filename '%s' present",
2925 info
->backing_filename
);
2928 if (info
->has_backing_filename_format
) {
2929 fmt
= info
->backing_filename_format
;
2933 g_hash_table_destroy(filenames
);
2937 qapi_free_ImageInfoList(head
);
2938 g_hash_table_destroy(filenames
);
2942 static int img_info(int argc
, char **argv
)
2945 OutputFormat output_format
= OFORMAT_HUMAN
;
2947 const char *filename
, *fmt
, *output
;
2948 ImageInfoList
*list
;
2949 bool image_opts
= false;
2950 bool force_share
= false;
2955 int option_index
= 0;
2956 static const struct option long_options
[] = {
2957 {"help", no_argument
, 0, 'h'},
2958 {"format", required_argument
, 0, 'f'},
2959 {"output", required_argument
, 0, OPTION_OUTPUT
},
2960 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2961 {"object", required_argument
, 0, OPTION_OBJECT
},
2962 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2963 {"force-share", no_argument
, 0, 'U'},
2966 c
= getopt_long(argc
, argv
, ":f:hU",
2967 long_options
, &option_index
);
2973 missing_argument(argv
[optind
- 1]);
2976 unrecognized_option(argv
[optind
- 1]);
2990 case OPTION_BACKING_CHAIN
:
2994 user_creatable_process_cmdline(optarg
);
2996 case OPTION_IMAGE_OPTS
:
3001 if (optind
!= argc
- 1) {
3002 error_exit("Expecting one image file name");
3004 filename
= argv
[optind
++];
3006 if (output
&& !strcmp(output
, "json")) {
3007 output_format
= OFORMAT_JSON
;
3008 } else if (output
&& !strcmp(output
, "human")) {
3009 output_format
= OFORMAT_HUMAN
;
3010 } else if (output
) {
3011 error_report("--output must be used with human or json as argument.");
3015 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3021 switch (output_format
) {
3023 dump_human_image_info_list(list
);
3027 dump_json_image_info_list(list
);
3029 dump_json_image_info(list
->value
);
3034 qapi_free_ImageInfoList(list
);
3038 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3041 switch (output_format
) {
3043 if (e
->data
&& !e
->has_offset
) {
3044 error_report("File contains external, encrypted or compressed clusters.");
3047 if (e
->data
&& !e
->zero
) {
3048 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3049 e
->start
, e
->length
,
3050 e
->has_offset
? e
->offset
: 0,
3051 e
->has_filename
? e
->filename
: "");
3053 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3054 * Modify the flags here to allow more coalescing.
3056 if (next
&& (!next
->data
|| next
->zero
)) {
3062 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3063 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3064 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
3065 e
->present
? "true" : "false",
3066 e
->zero
? "true" : "false",
3067 e
->data
? "true" : "false");
3068 if (e
->has_offset
) {
3069 printf(", \"offset\": %"PRId64
"", e
->offset
);
3081 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3082 int64_t bytes
, MapEntry
*e
)
3086 BlockDriverState
*file
;
3089 char *filename
= NULL
;
3091 /* As an optimization, we could cache the current range of unallocated
3092 * clusters in each file of the chain, and avoid querying the same
3098 bs
= bdrv_skip_filters(bs
);
3099 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3104 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3107 bs
= bdrv_cow_bs(bs
);
3116 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3118 if (file
&& has_offset
) {
3119 bdrv_refresh_filename(file
);
3120 filename
= file
->filename
;
3126 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3127 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3129 .has_offset
= has_offset
,
3131 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3132 .has_filename
= filename
,
3133 .filename
= filename
,
3139 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3141 if (curr
->length
== 0) {
3144 if (curr
->zero
!= next
->zero
||
3145 curr
->data
!= next
->data
||
3146 curr
->depth
!= next
->depth
||
3147 curr
->present
!= next
->present
||
3148 curr
->has_filename
!= next
->has_filename
||
3149 curr
->has_offset
!= next
->has_offset
) {
3152 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3155 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3161 static int img_map(int argc
, char **argv
)
3164 OutputFormat output_format
= OFORMAT_HUMAN
;
3166 BlockDriverState
*bs
;
3167 const char *filename
, *fmt
, *output
;
3169 MapEntry curr
= { .length
= 0 }, next
;
3171 bool image_opts
= false;
3172 bool force_share
= false;
3173 int64_t start_offset
= 0;
3174 int64_t max_length
= -1;
3179 int option_index
= 0;
3180 static const struct option long_options
[] = {
3181 {"help", no_argument
, 0, 'h'},
3182 {"format", required_argument
, 0, 'f'},
3183 {"output", required_argument
, 0, OPTION_OUTPUT
},
3184 {"object", required_argument
, 0, OPTION_OBJECT
},
3185 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3186 {"force-share", no_argument
, 0, 'U'},
3187 {"start-offset", required_argument
, 0, 's'},
3188 {"max-length", required_argument
, 0, 'l'},
3191 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3192 long_options
, &option_index
);
3198 missing_argument(argv
[optind
- 1]);
3201 unrecognized_option(argv
[optind
- 1]);
3216 start_offset
= cvtnum("start offset", optarg
);
3217 if (start_offset
< 0) {
3222 max_length
= cvtnum("max length", optarg
);
3223 if (max_length
< 0) {
3228 user_creatable_process_cmdline(optarg
);
3230 case OPTION_IMAGE_OPTS
:
3235 if (optind
!= argc
- 1) {
3236 error_exit("Expecting one image file name");
3238 filename
= argv
[optind
];
3240 if (output
&& !strcmp(output
, "json")) {
3241 output_format
= OFORMAT_JSON
;
3242 } else if (output
&& !strcmp(output
, "human")) {
3243 output_format
= OFORMAT_HUMAN
;
3244 } else if (output
) {
3245 error_report("--output must be used with human or json as argument.");
3249 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3255 if (output_format
== OFORMAT_HUMAN
) {
3256 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3257 } else if (output_format
== OFORMAT_JSON
) {
3261 length
= blk_getlength(blk
);
3263 error_report("Failed to get size for '%s'", filename
);
3266 if (max_length
!= -1) {
3267 length
= MIN(start_offset
+ max_length
, length
);
3270 curr
.start
= start_offset
;
3271 while (curr
.start
+ curr
.length
< length
) {
3272 int64_t offset
= curr
.start
+ curr
.length
;
3273 int64_t n
= length
- offset
;
3275 ret
= get_block_status(bs
, offset
, n
, &next
);
3277 error_report("Could not read file metadata: %s", strerror(-ret
));
3281 if (entry_mergeable(&curr
, &next
)) {
3282 curr
.length
+= next
.length
;
3286 if (curr
.length
> 0) {
3287 ret
= dump_map_entry(output_format
, &curr
, &next
);
3295 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3296 if (output_format
== OFORMAT_JSON
) {
3305 #define SNAPSHOT_LIST 1
3306 #define SNAPSHOT_CREATE 2
3307 #define SNAPSHOT_APPLY 3
3308 #define SNAPSHOT_DELETE 4
3310 static int img_snapshot(int argc
, char **argv
)
3313 BlockDriverState
*bs
;
3314 QEMUSnapshotInfo sn
;
3315 char *filename
, *snapshot_name
= NULL
;
3316 int c
, ret
= 0, bdrv_oflags
;
3320 bool image_opts
= false;
3321 bool force_share
= false;
3324 bdrv_oflags
= BDRV_O_RDWR
;
3325 /* Parse commandline parameters */
3327 static const struct option long_options
[] = {
3328 {"help", no_argument
, 0, 'h'},
3329 {"object", required_argument
, 0, OPTION_OBJECT
},
3330 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3331 {"force-share", no_argument
, 0, 'U'},
3334 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3335 long_options
, NULL
);
3341 missing_argument(argv
[optind
- 1]);
3344 unrecognized_option(argv
[optind
- 1]);
3351 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3354 action
= SNAPSHOT_LIST
;
3355 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3359 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3362 action
= SNAPSHOT_APPLY
;
3363 snapshot_name
= optarg
;
3367 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3370 action
= SNAPSHOT_CREATE
;
3371 snapshot_name
= optarg
;
3375 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3378 action
= SNAPSHOT_DELETE
;
3379 snapshot_name
= optarg
;
3388 user_creatable_process_cmdline(optarg
);
3390 case OPTION_IMAGE_OPTS
:
3396 if (optind
!= argc
- 1) {
3397 error_exit("Expecting one image file name");
3399 filename
= argv
[optind
++];
3401 /* Open the image */
3402 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3409 /* Perform the requested action */
3415 case SNAPSHOT_CREATE
:
3416 memset(&sn
, 0, sizeof(sn
));
3417 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3419 rt
= g_get_real_time();
3420 sn
.date_sec
= rt
/ G_USEC_PER_SEC
;
3421 sn
.date_nsec
= (rt
% G_USEC_PER_SEC
) * 1000;
3423 ret
= bdrv_snapshot_create(bs
, &sn
);
3425 error_report("Could not create snapshot '%s': %d (%s)",
3426 snapshot_name
, ret
, strerror(-ret
));
3430 case SNAPSHOT_APPLY
:
3431 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3433 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3438 case SNAPSHOT_DELETE
:
3439 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3441 error_report("Could not delete snapshot '%s': snapshot not "
3442 "found", snapshot_name
);
3445 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3447 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3463 static int img_rebase(int argc
, char **argv
)
3465 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3466 uint8_t *buf_old
= NULL
;
3467 uint8_t *buf_new
= NULL
;
3468 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3469 BlockDriverState
*unfiltered_bs
;
3471 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3472 int c
, flags
, src_flags
, ret
;
3473 bool writethrough
, src_writethrough
;
3475 bool force_share
= false;
3478 Error
*local_err
= NULL
;
3479 bool image_opts
= false;
3481 /* Parse commandline parameters */
3483 cache
= BDRV_DEFAULT_CACHE
;
3484 src_cache
= BDRV_DEFAULT_CACHE
;
3488 static const struct option long_options
[] = {
3489 {"help", no_argument
, 0, 'h'},
3490 {"object", required_argument
, 0, OPTION_OBJECT
},
3491 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3492 {"force-share", no_argument
, 0, 'U'},
3495 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3496 long_options
, NULL
);
3502 missing_argument(argv
[optind
- 1]);
3505 unrecognized_option(argv
[optind
- 1]);
3514 out_basefmt
= optarg
;
3517 out_baseimg
= optarg
;
3535 user_creatable_process_cmdline(optarg
);
3537 case OPTION_IMAGE_OPTS
:
3550 if (optind
!= argc
- 1) {
3551 error_exit("Expecting one image file name");
3553 if (!unsafe
&& !out_baseimg
) {
3554 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3556 filename
= argv
[optind
++];
3558 qemu_progress_init(progress
, 2.0);
3559 qemu_progress_print(0, 100);
3561 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3562 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3564 error_report("Invalid cache option: %s", cache
);
3569 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3571 error_report("Invalid source cache option: %s", src_cache
);
3575 /* The source files are opened read-only, don't care about WCE */
3576 assert((src_flags
& BDRV_O_RDWR
) == 0);
3577 (void) src_writethrough
;
3582 * Ignore the old backing file for unsafe rebase in case we want to correct
3583 * the reference to a renamed or moved backing file.
3585 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3593 unfiltered_bs
= bdrv_skip_filters(bs
);
3595 if (out_basefmt
!= NULL
) {
3596 if (bdrv_find_format(out_basefmt
) == NULL
) {
3597 error_report("Invalid format name: '%s'", out_basefmt
);
3603 /* For safe rebasing we need to compare old and new backing file */
3605 QDict
*options
= NULL
;
3606 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3609 blk_old_backing
= blk_new(qemu_get_aio_context(),
3610 BLK_PERM_CONSISTENT_READ
,
3612 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3615 error_reportf_err(local_err
,
3616 "Could not reuse old backing file '%s': ",
3621 blk_old_backing
= NULL
;
3624 if (out_baseimg
[0]) {
3625 const char *overlay_filename
;
3626 char *out_real_path
;
3628 options
= qdict_new();
3630 qdict_put_str(options
, "driver", out_basefmt
);
3633 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3636 bdrv_refresh_filename(bs
);
3637 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3640 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3644 qobject_unref(options
);
3645 error_reportf_err(local_err
,
3646 "Could not resolve backing filename: ");
3652 * Find out whether we rebase an image on top of a previous image
3655 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3656 if (prefix_chain_bs
) {
3657 qobject_unref(options
);
3658 g_free(out_real_path
);
3660 blk_new_backing
= blk_new(qemu_get_aio_context(),
3661 BLK_PERM_CONSISTENT_READ
,
3663 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3666 error_reportf_err(local_err
,
3667 "Could not reuse backing file '%s': ",
3672 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3673 options
, src_flags
, &local_err
);
3674 g_free(out_real_path
);
3675 if (!blk_new_backing
) {
3676 error_reportf_err(local_err
,
3677 "Could not open new backing file '%s': ",
3687 * Check each unallocated cluster in the COW file. If it is unallocated,
3688 * accesses go to the backing file. We must therefore compare this cluster
3689 * in the old and new backing file, and if they differ we need to copy it
3690 * from the old backing file into the COW file.
3692 * If qemu-img crashes during this step, no harm is done. The content of
3693 * the image is the same as the original one at any time.
3697 int64_t old_backing_size
= 0;
3698 int64_t new_backing_size
= 0;
3701 float local_progress
= 0;
3703 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3704 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3706 size
= blk_getlength(blk
);
3708 error_report("Could not get size of '%s': %s",
3709 filename
, strerror(-size
));
3713 if (blk_old_backing
) {
3714 old_backing_size
= blk_getlength(blk_old_backing
);
3715 if (old_backing_size
< 0) {
3716 char backing_name
[PATH_MAX
];
3718 bdrv_get_backing_filename(bs
, backing_name
,
3719 sizeof(backing_name
));
3720 error_report("Could not get size of '%s': %s",
3721 backing_name
, strerror(-old_backing_size
));
3726 if (blk_new_backing
) {
3727 new_backing_size
= blk_getlength(blk_new_backing
);
3728 if (new_backing_size
< 0) {
3729 error_report("Could not get size of '%s': %s",
3730 out_baseimg
, strerror(-new_backing_size
));
3737 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3740 for (offset
= 0; offset
< size
; offset
+= n
) {
3741 bool buf_old_is_zero
= false;
3743 /* How many bytes can we handle with the next read? */
3744 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3746 /* If the cluster is allocated, we don't need to take action */
3747 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3749 error_report("error while reading image metadata: %s",
3757 if (prefix_chain_bs
) {
3759 * If cluster wasn't changed since prefix_chain, we don't need
3762 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3763 prefix_chain_bs
, false,
3766 error_report("error while reading image metadata: %s",
3776 * Read old and new backing file and take into consideration that
3777 * backing files may be smaller than the COW image.
3779 if (offset
>= old_backing_size
) {
3780 memset(buf_old
, 0, n
);
3781 buf_old_is_zero
= true;
3783 if (offset
+ n
> old_backing_size
) {
3784 n
= old_backing_size
- offset
;
3787 ret
= blk_pread(blk_old_backing
, offset
, n
, buf_old
, 0);
3789 error_report("error while reading from old backing file");
3794 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3795 memset(buf_new
, 0, n
);
3797 if (offset
+ n
> new_backing_size
) {
3798 n
= new_backing_size
- offset
;
3801 ret
= blk_pread(blk_new_backing
, offset
, n
, buf_new
, 0);
3803 error_report("error while reading from new backing file");
3808 /* If they differ, we need to write to the COW file */
3809 uint64_t written
= 0;
3811 while (written
< n
) {
3814 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3815 n
- written
, &pnum
))
3817 if (buf_old_is_zero
) {
3818 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3820 ret
= blk_pwrite(blk
, offset
+ written
, pnum
,
3821 buf_old
+ written
, 0);
3824 error_report("Error while writing to COW image: %s",
3832 qemu_progress_print(local_progress
, 100);
3837 * Change the backing file. All clusters that are different from the old
3838 * backing file are overwritten in the COW file now, so the visible content
3839 * doesn't change when we switch the backing file.
3841 if (out_baseimg
&& *out_baseimg
) {
3842 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3845 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3848 if (ret
== -ENOSPC
) {
3849 error_report("Could not change the backing file to '%s': No "
3850 "space left in the file header", out_baseimg
);
3851 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3852 error_report("Could not change the backing file to '%s': backing "
3853 "format must be specified", out_baseimg
);
3854 } else if (ret
< 0) {
3855 error_report("Could not change the backing file to '%s': %s",
3856 out_baseimg
, strerror(-ret
));
3859 qemu_progress_print(100, 0);
3861 * TODO At this point it is possible to check if any clusters that are
3862 * allocated in the COW file are the same in the backing file. If so, they
3863 * could be dropped from the COW file. Don't do this before switching the
3864 * backing file, in case of a crash this would lead to corruption.
3867 qemu_progress_end();
3870 blk_unref(blk_old_backing
);
3871 blk_unref(blk_new_backing
);
3873 qemu_vfree(buf_old
);
3874 qemu_vfree(buf_new
);
3883 static int img_resize(int argc
, char **argv
)
3886 int c
, ret
, relative
;
3887 const char *filename
, *fmt
, *size
;
3888 int64_t n
, total_size
, current_size
;
3890 BlockBackend
*blk
= NULL
;
3891 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3894 static QemuOptsList resize_options
= {
3895 .name
= "resize_options",
3896 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3899 .name
= BLOCK_OPT_SIZE
,
3900 .type
= QEMU_OPT_SIZE
,
3901 .help
= "Virtual disk size"
3907 bool image_opts
= false;
3908 bool shrink
= false;
3910 /* Remove size from argv manually so that negative numbers are not treated
3911 * as options by getopt. */
3913 error_exit("Not enough arguments");
3917 size
= argv
[--argc
];
3919 /* Parse getopt arguments */
3922 static const struct option long_options
[] = {
3923 {"help", no_argument
, 0, 'h'},
3924 {"object", required_argument
, 0, OPTION_OBJECT
},
3925 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3926 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3927 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3930 c
= getopt_long(argc
, argv
, ":f:hq",
3931 long_options
, NULL
);
3937 missing_argument(argv
[optind
- 1]);
3940 unrecognized_option(argv
[optind
- 1]);
3952 user_creatable_process_cmdline(optarg
);
3954 case OPTION_IMAGE_OPTS
:
3957 case OPTION_PREALLOCATION
:
3958 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3959 PREALLOC_MODE__MAX
, NULL
);
3960 if (prealloc
== PREALLOC_MODE__MAX
) {
3961 error_report("Invalid preallocation mode '%s'", optarg
);
3970 if (optind
!= argc
- 1) {
3971 error_exit("Expecting image file name and size");
3973 filename
= argv
[optind
++];
3975 /* Choose grow, shrink, or absolute resize mode */
3991 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3992 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3993 error_report_err(err
);
3995 qemu_opts_del(param
);
3998 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3999 qemu_opts_del(param
);
4001 blk
= img_open(image_opts
, filename
, fmt
,
4002 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4009 current_size
= blk_getlength(blk
);
4010 if (current_size
< 0) {
4011 error_report("Failed to inquire current image length: %s",
4012 strerror(-current_size
));
4018 total_size
= current_size
+ n
* relative
;
4022 if (total_size
<= 0) {
4023 error_report("New image size must be positive");
4028 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4029 error_report("Preallocation can only be used for growing images");
4034 if (total_size
< current_size
&& !shrink
) {
4035 error_report("Use the --shrink option to perform a shrink operation.");
4036 warn_report("Shrinking an image will delete all data beyond the "
4037 "shrunken image's end. Before performing such an "
4038 "operation, make sure there is no important data there.");
4044 * The user expects the image to have the desired size after
4045 * resizing, so pass @exact=true. It is of no use to report
4046 * success when the image has not actually been resized.
4048 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4050 qprintf(quiet
, "Image resized.\n");
4052 error_report_err(err
);
4062 static void amend_status_cb(BlockDriverState
*bs
,
4063 int64_t offset
, int64_t total_work_size
,
4066 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4069 static int print_amend_option_help(const char *format
)
4073 /* Find driver and parse its options */
4074 drv
= bdrv_find_format(format
);
4076 error_report("Unknown file format '%s'", format
);
4080 if (!drv
->bdrv_amend_options
) {
4081 error_report("Format driver '%s' does not support option amendment",
4086 /* Every driver supporting amendment must have amend_opts */
4087 assert(drv
->amend_opts
);
4089 printf("Amend options for '%s':\n", format
);
4090 qemu_opts_print_help(drv
->amend_opts
, false);
4094 static int img_amend(int argc
, char **argv
)
4098 char *options
= NULL
;
4099 QemuOptsList
*amend_opts
= NULL
;
4100 QemuOpts
*opts
= NULL
;
4101 const char *fmt
= NULL
, *filename
, *cache
;
4104 bool quiet
= false, progress
= false;
4105 BlockBackend
*blk
= NULL
;
4106 BlockDriverState
*bs
= NULL
;
4107 bool image_opts
= false;
4110 cache
= BDRV_DEFAULT_CACHE
;
4112 static const struct option long_options
[] = {
4113 {"help", no_argument
, 0, 'h'},
4114 {"object", required_argument
, 0, OPTION_OBJECT
},
4115 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4116 {"force", no_argument
, 0, OPTION_FORCE
},
4119 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4120 long_options
, NULL
);
4127 missing_argument(argv
[optind
- 1]);
4130 unrecognized_option(argv
[optind
- 1]);
4136 if (accumulate_options(&options
, optarg
) < 0) {
4138 goto out_no_progress
;
4154 user_creatable_process_cmdline(optarg
);
4156 case OPTION_IMAGE_OPTS
:
4166 error_exit("Must specify options (-o)");
4172 qemu_progress_init(progress
, 1.0);
4174 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4175 if (fmt
&& has_help_option(options
)) {
4176 /* If a format is explicitly specified (and possibly no filename is
4177 * given), print option help here */
4178 ret
= print_amend_option_help(fmt
);
4182 if (optind
!= argc
- 1) {
4183 error_report("Expecting one image file name");
4188 flags
= BDRV_O_RDWR
;
4189 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4191 error_report("Invalid cache option: %s", cache
);
4195 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4203 fmt
= bs
->drv
->format_name
;
4205 if (has_help_option(options
)) {
4206 /* If the format was auto-detected, print option help here */
4207 ret
= print_amend_option_help(fmt
);
4211 if (!bs
->drv
->bdrv_amend_options
) {
4212 error_report("Format driver '%s' does not support option amendment",
4218 /* Every driver supporting amendment must have amend_opts */
4219 assert(bs
->drv
->amend_opts
);
4221 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4222 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4223 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4224 /* Try to parse options using the create options */
4225 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4226 qemu_opts_del(opts
);
4227 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4228 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4229 error_append_hint(&err
,
4230 "This option is only supported for image creation\n");
4233 error_report_err(err
);
4238 /* In case the driver does not call amend_status_cb() */
4239 qemu_progress_print(0.f
, 0);
4240 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4241 qemu_progress_print(100.f
, 0);
4243 error_report_err(err
);
4248 qemu_progress_end();
4252 qemu_opts_del(opts
);
4253 qemu_opts_free(amend_opts
);
4262 typedef struct BenchData
{
4264 uint64_t image_size
;
4271 bool drain_on_flush
;
4280 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4283 error_report("Failed flush request: %s", strerror(-ret
));
4288 static void bench_cb(void *opaque
, int ret
)
4290 BenchData
*b
= opaque
;
4294 error_report("Failed request: %s", strerror(-ret
));
4299 /* Just finished a flush with drained queue: Start next requests */
4300 assert(b
->in_flight
== 0);
4301 b
->in_flush
= false;
4302 } else if (b
->in_flight
> 0) {
4303 int remaining
= b
->n
- b
->in_flight
;
4308 /* Time for flush? Drain queue if requested, then flush */
4309 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4310 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4311 BlockCompletionFunc
*cb
;
4313 if (b
->drain_on_flush
) {
4317 cb
= bench_undrained_flush_cb
;
4320 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4322 error_report("Failed to issue flush request");
4326 if (b
->drain_on_flush
) {
4332 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4333 int64_t offset
= b
->offset
;
4334 /* blk_aio_* might look for completed I/Os and kick bench_cb
4335 * again, so make sure this operation is counted by in_flight
4336 * and b->offset is ready for the next submission.
4339 b
->offset
+= b
->step
;
4340 b
->offset
%= b
->image_size
;
4342 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4344 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4347 error_report("Failed to issue request");
4353 static int img_bench(int argc
, char **argv
)
4356 const char *fmt
= NULL
, *filename
;
4358 bool image_opts
= false;
4359 bool is_write
= false;
4363 size_t bufsize
= 4096;
4366 int flush_interval
= 0;
4367 bool drain_on_flush
= true;
4369 BlockBackend
*blk
= NULL
;
4370 BenchData data
= {};
4372 bool writethrough
= false;
4373 struct timeval t1
, t2
;
4375 bool force_share
= false;
4379 static const struct option long_options
[] = {
4380 {"help", no_argument
, 0, 'h'},
4381 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4382 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4383 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4384 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4385 {"force-share", no_argument
, 0, 'U'},
4388 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4396 missing_argument(argv
[optind
- 1]);
4399 unrecognized_option(argv
[optind
- 1]);
4408 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4409 error_report("Invalid request count specified");
4419 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4420 error_report("Invalid queue depth specified");
4430 flags
|= BDRV_O_NATIVE_AIO
;
4433 ret
= bdrv_parse_aio(optarg
, &flags
);
4435 error_report("Invalid aio option: %s", optarg
);
4442 offset
= cvtnum("offset", optarg
);
4456 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4468 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4477 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4479 error_report("Invalid cache mode");
4485 flags
|= BDRV_O_RDWR
;
4491 case OPTION_PATTERN
:
4495 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4496 error_report("Invalid pattern byte specified");
4502 case OPTION_FLUSH_INTERVAL
:
4506 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4507 error_report("Invalid flush interval specified");
4510 flush_interval
= res
;
4513 case OPTION_NO_DRAIN
:
4514 drain_on_flush
= false;
4516 case OPTION_IMAGE_OPTS
:
4522 if (optind
!= argc
- 1) {
4523 error_exit("Expecting one image file name");
4525 filename
= argv
[argc
- 1];
4527 if (!is_write
&& flush_interval
) {
4528 error_report("--flush-interval is only available in write tests");
4532 if (flush_interval
&& flush_interval
< depth
) {
4533 error_report("Flush interval can't be smaller than depth");
4538 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4545 image_size
= blk_getlength(blk
);
4546 if (image_size
< 0) {
4551 data
= (BenchData
) {
4553 .image_size
= image_size
,
4555 .step
= step
?: bufsize
,
4560 .flush_interval
= flush_interval
,
4561 .drain_on_flush
= drain_on_flush
,
4563 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4564 "(starting at offset %" PRId64
", step size %d)\n",
4565 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4566 data
.offset
, data
.step
);
4567 if (flush_interval
) {
4568 printf("Sending flush every %d requests\n", flush_interval
);
4571 buf_size
= data
.nrreq
* data
.bufsize
;
4572 data
.buf
= blk_blockalign(blk
, buf_size
);
4573 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4575 blk_register_buf(blk
, data
.buf
, buf_size
);
4577 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4578 for (i
= 0; i
< data
.nrreq
; i
++) {
4579 qemu_iovec_init(&data
.qiov
[i
], 1);
4580 qemu_iovec_add(&data
.qiov
[i
],
4581 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4584 gettimeofday(&t1
, NULL
);
4587 while (data
.n
> 0) {
4588 main_loop_wait(false);
4590 gettimeofday(&t2
, NULL
);
4592 printf("Run completed in %3.3f seconds.\n",
4593 (t2
.tv_sec
- t1
.tv_sec
)
4594 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4598 blk_unregister_buf(blk
, data
.buf
);
4600 qemu_vfree(data
.buf
);
4617 typedef struct ImgBitmapAction
{
4618 enum ImgBitmapAct act
;
4619 const char *src
; /* only used for merge */
4620 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4623 static int img_bitmap(int argc
, char **argv
)
4627 QemuOpts
*opts
= NULL
;
4628 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4629 const char *filename
, *bitmap
;
4630 BlockBackend
*blk
= NULL
, *src
= NULL
;
4631 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4632 bool image_opts
= false;
4633 int64_t granularity
= 0;
4634 bool add
= false, merge
= false;
4635 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4636 ImgBitmapAction
*act
, *act_next
;
4639 QSIMPLEQ_INIT(&actions
);
4642 static const struct option long_options
[] = {
4643 {"help", no_argument
, 0, 'h'},
4644 {"object", required_argument
, 0, OPTION_OBJECT
},
4645 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4646 {"add", no_argument
, 0, OPTION_ADD
},
4647 {"remove", no_argument
, 0, OPTION_REMOVE
},
4648 {"clear", no_argument
, 0, OPTION_CLEAR
},
4649 {"enable", no_argument
, 0, OPTION_ENABLE
},
4650 {"disable", no_argument
, 0, OPTION_DISABLE
},
4651 {"merge", required_argument
, 0, OPTION_MERGE
},
4652 {"granularity", required_argument
, 0, 'g'},
4653 {"source-file", required_argument
, 0, 'b'},
4654 {"source-format", required_argument
, 0, 'F'},
4657 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4664 missing_argument(argv
[optind
- 1]);
4667 unrecognized_option(argv
[optind
- 1]);
4673 src_filename
= optarg
;
4682 granularity
= cvtnum("granularity", optarg
);
4683 if (granularity
< 0) {
4688 act
= g_new0(ImgBitmapAction
, 1);
4689 act
->act
= BITMAP_ADD
;
4690 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4694 act
= g_new0(ImgBitmapAction
, 1);
4695 act
->act
= BITMAP_REMOVE
;
4696 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4699 act
= g_new0(ImgBitmapAction
, 1);
4700 act
->act
= BITMAP_CLEAR
;
4701 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4704 act
= g_new0(ImgBitmapAction
, 1);
4705 act
->act
= BITMAP_ENABLE
;
4706 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4708 case OPTION_DISABLE
:
4709 act
= g_new0(ImgBitmapAction
, 1);
4710 act
->act
= BITMAP_DISABLE
;
4711 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4714 act
= g_new0(ImgBitmapAction
, 1);
4715 act
->act
= BITMAP_MERGE
;
4717 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4721 user_creatable_process_cmdline(optarg
);
4723 case OPTION_IMAGE_OPTS
:
4729 if (QSIMPLEQ_EMPTY(&actions
)) {
4730 error_report("Need at least one of --add, --remove, --clear, "
4731 "--enable, --disable, or --merge");
4735 if (granularity
&& !add
) {
4736 error_report("granularity only supported with --add");
4739 if (src_fmt
&& !src_filename
) {
4740 error_report("-F only supported with -b");
4743 if (src_filename
&& !merge
) {
4744 error_report("Merge bitmap source file only supported with "
4749 if (optind
!= argc
- 2) {
4750 error_report("Expecting filename and bitmap name");
4754 filename
= argv
[optind
];
4755 bitmap
= argv
[optind
+ 1];
4758 * No need to open backing chains; we will be manipulating bitmaps
4759 * directly in this image without reference to image contents.
4761 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4762 false, false, false);
4768 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4769 false, false, false);
4773 src_bs
= blk_bs(src
);
4778 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4781 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4782 !!granularity
, granularity
, true, true,
4783 false, false, &err
);
4787 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4791 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4795 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4798 case BITMAP_DISABLE
:
4799 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4803 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4808 g_assert_not_reached();
4812 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4824 qemu_opts_del(opts
);
4840 int bsz
; /* Block size */
4848 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4852 static int img_dd_bs(const char *arg
,
4853 struct DdIo
*in
, struct DdIo
*out
,
4858 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4863 in
->bsz
= out
->bsz
= res
;
4868 static int img_dd_count(const char *arg
,
4869 struct DdIo
*in
, struct DdIo
*out
,
4872 dd
->count
= cvtnum("count", arg
);
4874 if (dd
->count
< 0) {
4881 static int img_dd_if(const char *arg
,
4882 struct DdIo
*in
, struct DdIo
*out
,
4885 in
->filename
= g_strdup(arg
);
4890 static int img_dd_of(const char *arg
,
4891 struct DdIo
*in
, struct DdIo
*out
,
4894 out
->filename
= g_strdup(arg
);
4899 static int img_dd_skip(const char *arg
,
4900 struct DdIo
*in
, struct DdIo
*out
,
4903 in
->offset
= cvtnum("skip", arg
);
4905 if (in
->offset
< 0) {
4912 static int img_dd(int argc
, char **argv
)
4917 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4918 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4919 QemuOpts
*opts
= NULL
;
4920 QemuOptsList
*create_opts
= NULL
;
4921 Error
*local_err
= NULL
;
4922 bool image_opts
= false;
4924 const char *out_fmt
= "raw";
4925 const char *fmt
= NULL
;
4927 int64_t block_count
= 0, out_pos
, in_pos
;
4928 bool force_share
= false;
4929 struct DdInfo dd
= {
4934 .bsz
= 512, /* Block size is by default 512 bytes */
4946 const struct DdOpts options
[] = {
4947 { "bs", img_dd_bs
, C_BS
},
4948 { "count", img_dd_count
, C_COUNT
},
4949 { "if", img_dd_if
, C_IF
},
4950 { "of", img_dd_of
, C_OF
},
4951 { "skip", img_dd_skip
, C_SKIP
},
4954 const struct option long_options
[] = {
4955 { "help", no_argument
, 0, 'h'},
4956 { "object", required_argument
, 0, OPTION_OBJECT
},
4957 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4958 { "force-share", no_argument
, 0, 'U'},
4962 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4974 missing_argument(argv
[optind
- 1]);
4977 unrecognized_option(argv
[optind
- 1]);
4986 user_creatable_process_cmdline(optarg
);
4988 case OPTION_IMAGE_OPTS
:
4994 for (i
= optind
; i
< argc
; i
++) {
4996 arg
= g_strdup(argv
[i
]);
4998 tmp
= strchr(arg
, '=');
5000 error_report("unrecognized operand %s", arg
);
5007 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5008 if (!strcmp(arg
, options
[j
].name
)) {
5012 if (options
[j
].name
== NULL
) {
5013 error_report("unrecognized operand %s", arg
);
5018 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5022 dd
.flags
|= options
[j
].flag
;
5027 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5028 error_report("Must specify both input and output files");
5033 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5041 drv
= bdrv_find_format(out_fmt
);
5043 error_report("Unknown file format");
5047 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5050 error_report_err(local_err
);
5054 if (!drv
->create_opts
) {
5055 error_report("Format driver '%s' does not support image creation",
5060 if (!proto_drv
->create_opts
) {
5061 error_report("Protocol driver '%s' does not support image creation",
5062 proto_drv
->format_name
);
5066 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5067 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5069 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5071 size
= blk_getlength(blk1
);
5073 error_report("Failed to get size for '%s'", in
.filename
);
5078 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5079 dd
.count
* in
.bsz
< size
) {
5080 size
= dd
.count
* in
.bsz
;
5083 /* Overflow means the specified offset is beyond input image's size */
5084 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5085 size
< in
.bsz
* in
.offset
)) {
5086 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5088 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5089 size
- in
.bsz
* in
.offset
, &error_abort
);
5092 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5094 error_reportf_err(local_err
,
5095 "%s: error while creating output image: ",
5101 /* TODO, we can't honour --image-opts for the target,
5102 * since it needs to be given in a format compatible
5103 * with the bdrv_create() call above which does not
5104 * support image-opts style.
5106 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5107 false, false, false);
5114 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5115 size
< in
.offset
* in
.bsz
)) {
5116 /* We give a warning if the skip option is bigger than the input
5117 * size and create an empty output disk image (i.e. like dd(1)).
5119 error_report("%s: cannot skip to specified offset", in
.filename
);
5122 in_pos
= in
.offset
* in
.bsz
;
5125 in
.buf
= g_new(uint8_t, in
.bsz
);
5127 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5128 int bytes
= (in_pos
+ in
.bsz
> size
) ? size
- in_pos
: in
.bsz
;
5130 ret
= blk_pread(blk1
, in_pos
, bytes
, in
.buf
, 0);
5132 error_report("error while reading from input image file: %s",
5138 ret
= blk_pwrite(blk2
, out_pos
, bytes
, in
.buf
, 0);
5140 error_report("error while writing to output image file: %s",
5149 qemu_opts_del(opts
);
5150 qemu_opts_free(create_opts
);
5153 g_free(in
.filename
);
5154 g_free(out
.filename
);
5164 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5168 Visitor
*v
= qobject_output_visitor_new(&obj
);
5170 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5171 visit_complete(v
, &obj
);
5172 str
= qobject_to_json_pretty(obj
, true);
5173 assert(str
!= NULL
);
5174 printf("%s\n", str
->str
);
5177 g_string_free(str
, true);
5180 static int img_measure(int argc
, char **argv
)
5182 static const struct option long_options
[] = {
5183 {"help", no_argument
, 0, 'h'},
5184 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5185 {"object", required_argument
, 0, OPTION_OBJECT
},
5186 {"output", required_argument
, 0, OPTION_OUTPUT
},
5187 {"size", required_argument
, 0, OPTION_SIZE
},
5188 {"force-share", no_argument
, 0, 'U'},
5191 OutputFormat output_format
= OFORMAT_HUMAN
;
5192 BlockBackend
*in_blk
= NULL
;
5194 const char *filename
= NULL
;
5195 const char *fmt
= NULL
;
5196 const char *out_fmt
= "raw";
5197 char *options
= NULL
;
5198 char *snapshot_name
= NULL
;
5199 bool force_share
= false;
5200 QemuOpts
*opts
= NULL
;
5201 QemuOpts
*object_opts
= NULL
;
5202 QemuOpts
*sn_opts
= NULL
;
5203 QemuOptsList
*create_opts
= NULL
;
5204 bool image_opts
= false;
5205 uint64_t img_size
= UINT64_MAX
;
5206 BlockMeasureInfo
*info
= NULL
;
5207 Error
*local_err
= NULL
;
5211 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5212 long_options
, NULL
)) != -1) {
5225 if (accumulate_options(&options
, optarg
) < 0) {
5230 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5231 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5234 error_report("Failed in parsing snapshot param '%s'",
5239 snapshot_name
= optarg
;
5246 user_creatable_process_cmdline(optarg
);
5248 case OPTION_IMAGE_OPTS
:
5252 if (!strcmp(optarg
, "json")) {
5253 output_format
= OFORMAT_JSON
;
5254 } else if (!strcmp(optarg
, "human")) {
5255 output_format
= OFORMAT_HUMAN
;
5257 error_report("--output must be used with human or json "
5266 sval
= cvtnum("image size", optarg
);
5270 img_size
= (uint64_t)sval
;
5276 if (argc
- optind
> 1) {
5277 error_report("At most one filename argument is allowed.");
5279 } else if (argc
- optind
== 1) {
5280 filename
= argv
[optind
];
5283 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5284 error_report("--image-opts, -f, and -l require a filename argument.");
5287 if (filename
&& img_size
!= UINT64_MAX
) {
5288 error_report("--size N cannot be used together with a filename.");
5291 if (!filename
&& img_size
== UINT64_MAX
) {
5292 error_report("Either --size N or one filename must be specified.");
5297 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5298 false, false, force_share
);
5304 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5305 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5306 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5308 } else if (snapshot_name
!= NULL
) {
5309 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5310 snapshot_name
, &local_err
);
5313 error_reportf_err(local_err
, "Failed to load snapshot: ");
5318 drv
= bdrv_find_format(out_fmt
);
5320 error_report("Unknown file format '%s'", out_fmt
);
5323 if (!drv
->create_opts
) {
5324 error_report("Format driver '%s' does not support image creation",
5329 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5330 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5331 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5333 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5334 error_report_err(local_err
);
5335 error_report("Invalid options for file format '%s'", out_fmt
);
5339 if (img_size
!= UINT64_MAX
) {
5340 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5343 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5345 error_report_err(local_err
);
5349 if (output_format
== OFORMAT_HUMAN
) {
5350 printf("required size: %" PRIu64
"\n", info
->required
);
5351 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5352 if (info
->has_bitmaps
) {
5353 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5356 dump_json_block_measure_info(info
);
5362 qapi_free_BlockMeasureInfo(info
);
5363 qemu_opts_del(object_opts
);
5364 qemu_opts_del(opts
);
5365 qemu_opts_del(sn_opts
);
5366 qemu_opts_free(create_opts
);
5372 static const img_cmd_t img_cmds
[] = {
5373 #define DEF(option, callback, arg_string) \
5374 { option, callback },
5375 #include "qemu-img-cmds.h"
5380 int main(int argc
, char **argv
)
5382 const img_cmd_t
*cmd
;
5383 const char *cmdname
;
5385 static const struct option long_options
[] = {
5386 {"help", no_argument
, 0, 'h'},
5387 {"version", no_argument
, 0, 'V'},
5388 {"trace", required_argument
, NULL
, 'T'},
5393 signal(SIGPIPE
, SIG_IGN
);
5397 error_init(argv
[0]);
5398 module_call_init(MODULE_INIT_TRACE
);
5399 qemu_init_exec_dir(argv
[0]);
5401 qemu_init_main_loop(&error_fatal
);
5403 qcrypto_init(&error_fatal
);
5405 module_call_init(MODULE_INIT_QOM
);
5408 error_exit("Not enough arguments");
5411 qemu_add_opts(&qemu_source_opts
);
5412 qemu_add_opts(&qemu_trace_opts
);
5414 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5417 missing_argument(argv
[optind
- 1]);
5420 unrecognized_option(argv
[optind
- 1]);
5426 printf(QEMU_IMG_VERSION
);
5429 trace_opt_parse(optarg
);
5434 cmdname
= argv
[optind
];
5436 /* reset getopt_long scanning */
5442 qemu_reset_optind();
5444 if (!trace_init_backends()) {
5448 qemu_set_log(LOG_TRACE
, &error_fatal
);
5450 /* find the command */
5451 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5452 if (!strcmp(cmdname
, cmd
->name
)) {
5453 return cmd
->handler(argc
, argv
);
5458 error_exit("Command not found: %s", cmdname
);