2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/sockets.h"
44 #include "qemu/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
52 #include "qemu/throttle.h"
53 #include "block/throttle-groups.h"
55 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
56 "\n" QEMU_COPYRIGHT "\n"
58 typedef struct img_cmd_t
{
60 int (*handler
)(int argc
, char **argv
);
65 OPTION_BACKING_CHAIN
= 257,
67 OPTION_IMAGE_OPTS
= 259,
69 OPTION_FLUSH_INTERVAL
= 261,
70 OPTION_NO_DRAIN
= 262,
71 OPTION_TARGET_IMAGE_OPTS
= 263,
73 OPTION_PREALLOCATION
= 265,
76 OPTION_TARGET_IS_ZERO
= 268,
87 typedef enum OutputFormat
{
92 /* Default to cache=writeback as data integrity is not important for qemu-img */
93 #define BDRV_DEFAULT_CACHE "writeback"
95 static void format_print(void *opaque
, const char *name
)
100 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
105 error_vreport(fmt
, ap
);
108 error_printf("Try 'qemu-img --help' for more information\n");
112 static void QEMU_NORETURN
missing_argument(const char *option
)
114 error_exit("missing argument for option '%s'", option
);
117 static void QEMU_NORETURN
unrecognized_option(const char *option
)
119 error_exit("unrecognized option '%s'", option
);
122 /* Please keep in synch with docs/tools/qemu-img.rst */
123 static void QEMU_NORETURN
help(void)
125 const char *help_msg
=
127 "usage: qemu-img [standard options] command [command options]\n"
128 "QEMU disk image utility\n"
130 " '-h', '--help' display this help and exit\n"
131 " '-V', '--version' output version information and exit\n"
132 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
133 " specify tracing options\n"
136 #define DEF(option, callback, arg_string) \
138 #include "qemu-img-cmds.h"
141 "Command parameters:\n"
142 " 'filename' is a disk image filename\n"
143 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
144 " manual page for a description of the object properties. The most common\n"
145 " object type is a 'secret', which is used to supply passwords and/or\n"
146 " encryption keys.\n"
147 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
148 " 'cache' is the cache mode used to write the output disk image, the valid\n"
149 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
150 " 'directsync' and 'unsafe' (default for convert)\n"
151 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
152 " options are the same as for the 'cache' option\n"
153 " 'size' is the disk image size in bytes. Optional suffixes\n"
154 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
155 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
156 " supported. 'b' is ignored.\n"
157 " 'output_filename' is the destination disk image filename\n"
158 " 'output_fmt' is the destination format\n"
159 " 'options' is a comma separated list of format specific options in a\n"
160 " name=value format. Use -o ? for an overview of the options supported by the\n"
162 " 'snapshot_param' is param used for internal snapshot, format\n"
163 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
165 " '-c' indicates that target image must be compressed (qcow format only)\n"
166 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
167 " new backing file match exactly. The image doesn't need a working\n"
168 " backing file before rebasing in this case (useful for renaming the\n"
169 " backing file). For image creation, allow creating without attempting\n"
170 " to open the backing file.\n"
171 " '-h' with or without a command shows this help and lists the supported formats\n"
172 " '-p' show progress of command (only certain commands)\n"
173 " '-q' use Quiet mode - do not print any output (except errors)\n"
174 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
175 " contain only zeros for qemu-img to create a sparse image during\n"
176 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
177 " unallocated or zero sectors, and the destination image will always be\n"
179 " '--output' takes the format in which the output must be done (human or json)\n"
180 " '-n' skips the target volume creation (useful if the volume is created\n"
181 " prior to running qemu-img)\n"
183 "Parameters to bitmap subcommand:\n"
184 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
185 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
186 " or '--merge source'\n"
187 " '-g granularity' sets the granularity for '--add' actions\n"
188 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
189 " bitmaps from an alternative file\n"
191 "Parameters to check subcommand:\n"
192 " '-r' tries to repair any inconsistencies that are found during the check.\n"
193 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
194 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
195 " hiding corruption that has already occurred.\n"
197 "Parameters to convert subcommand:\n"
198 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
199 " '-m' specifies how many coroutines work in parallel during the convert\n"
200 " process (defaults to 8)\n"
201 " '-W' allow to write to the target out of order rather than sequential\n"
203 "Parameters to snapshot subcommand:\n"
204 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
205 " '-a' applies a snapshot (revert disk to saved state)\n"
206 " '-c' creates a snapshot\n"
207 " '-d' deletes a snapshot\n"
208 " '-l' lists all snapshots in the given image\n"
210 "Parameters to compare subcommand:\n"
211 " '-f' first image format\n"
212 " '-F' second image format\n"
213 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
215 "Parameters to dd subcommand:\n"
216 " 'bs=BYTES' read and write up to BYTES bytes at a time "
218 " 'count=N' copy only N input blocks\n"
219 " 'if=FILE' read from FILE\n"
220 " 'of=FILE' write to FILE\n"
221 " 'skip=N' skip N bs-sized blocks at the start of input\n";
223 printf("%s\nSupported formats:", help_msg
);
224 bdrv_iterate_format(format_print
, NULL
, false);
225 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
230 * Is @optarg safe for accumulate_options()?
231 * It is when multiple of them can be joined together separated by ','.
232 * To make that work, @optarg must not start with ',' (or else a
233 * separating ',' preceding it gets escaped), and it must not end with
234 * an odd number of ',' (or else a separating ',' following it gets
235 * escaped), or be empty (or else a separating ',' preceding it can
236 * escape a separating ',' following it).
239 static bool is_valid_option_list(const char *optarg
)
241 size_t len
= strlen(optarg
);
244 if (!optarg
[0] || optarg
[0] == ',') {
248 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
257 static int accumulate_options(char **options
, char *optarg
)
261 if (!is_valid_option_list(optarg
)) {
262 error_report("Invalid option list: %s", optarg
);
267 *options
= g_strdup(optarg
);
269 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
271 *options
= new_options
;
276 static QemuOptsList qemu_source_opts
= {
278 .implied_opt_name
= "file",
279 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
285 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
291 ret
= vprintf(fmt
, args
);
298 static int print_block_option_help(const char *filename
, const char *fmt
)
300 BlockDriver
*drv
, *proto_drv
;
301 QemuOptsList
*create_opts
= NULL
;
302 Error
*local_err
= NULL
;
304 /* Find driver and parse its options */
305 drv
= bdrv_find_format(fmt
);
307 error_report("Unknown file format '%s'", fmt
);
311 if (!drv
->create_opts
) {
312 error_report("Format driver '%s' does not support image creation", fmt
);
316 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
318 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
320 error_report_err(local_err
);
321 qemu_opts_free(create_opts
);
324 if (!proto_drv
->create_opts
) {
325 error_report("Protocol driver '%s' does not support image creation",
326 proto_drv
->format_name
);
327 qemu_opts_free(create_opts
);
330 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
334 printf("Supported options:\n");
336 printf("Supported %s options:\n", fmt
);
338 qemu_opts_print_help(create_opts
, false);
339 qemu_opts_free(create_opts
);
343 "The protocol level may support further options.\n"
344 "Specify the target filename to include those options.\n");
351 static BlockBackend
*img_open_opts(const char *optstr
,
352 QemuOpts
*opts
, int flags
, bool writethrough
,
353 bool quiet
, bool force_share
)
356 Error
*local_err
= NULL
;
358 options
= qemu_opts_to_qdict(opts
, NULL
);
360 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
361 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
362 error_report("--force-share/-U conflicts with image options");
363 qobject_unref(options
);
366 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
368 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
370 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
373 blk_set_enable_write_cache(blk
, !writethrough
);
378 static BlockBackend
*img_open_file(const char *filename
,
380 const char *fmt
, int flags
,
381 bool writethrough
, bool quiet
,
385 Error
*local_err
= NULL
;
388 options
= qdict_new();
391 qdict_put_str(options
, "driver", fmt
);
395 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
397 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
399 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
402 blk_set_enable_write_cache(blk
, !writethrough
);
408 static int img_add_key_secrets(void *opaque
,
409 const char *name
, const char *value
,
412 QDict
*options
= opaque
;
414 if (g_str_has_suffix(name
, "key-secret")) {
415 qdict_put_str(options
, name
, value
);
422 static BlockBackend
*img_open(bool image_opts
,
423 const char *filename
,
424 const char *fmt
, int flags
, bool writethrough
,
425 bool quiet
, bool force_share
)
431 error_report("--image-opts and --format are mutually exclusive");
434 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
439 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
442 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
449 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
450 const char *base_filename
,
451 const char *base_fmt
)
454 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
456 error_report("Backing file not supported for file format '%s'",
462 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
463 error_report("Backing file format not supported for file "
471 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
477 err
= qemu_strtosz(value
, NULL
, &res
);
478 if (err
< 0 && err
!= -ERANGE
) {
479 error_report("Invalid %s specified. You may use "
480 "k, M, G, T, P or E suffixes for", name
);
481 error_report("kilobytes, megabytes, gigabytes, terabytes, "
482 "petabytes and exabytes.");
485 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
486 error_report("Invalid %s specified. Must be between %" PRId64
487 " and %" PRId64
".", name
, min
, max
);
493 static int64_t cvtnum(const char *name
, const char *value
)
495 return cvtnum_full(name
, value
, 0, INT64_MAX
);
498 static int img_create(int argc
, char **argv
)
501 uint64_t img_size
= -1;
502 const char *fmt
= "raw";
503 const char *base_fmt
= NULL
;
504 const char *filename
;
505 const char *base_filename
= NULL
;
506 char *options
= NULL
;
507 Error
*local_err
= NULL
;
512 static const struct option long_options
[] = {
513 {"help", no_argument
, 0, 'h'},
514 {"object", required_argument
, 0, OPTION_OBJECT
},
517 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
524 missing_argument(argv
[optind
- 1]);
527 unrecognized_option(argv
[optind
- 1]);
536 base_filename
= optarg
;
542 if (accumulate_options(&options
, optarg
) < 0) {
550 flags
|= BDRV_O_NO_BACKING
;
553 user_creatable_process_cmdline(optarg
);
558 /* Get the filename */
559 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
560 if (options
&& has_help_option(options
)) {
562 return print_block_option_help(filename
, fmt
);
565 if (optind
>= argc
) {
566 error_exit("Expecting image file name");
570 /* Get image size, if specified */
574 sval
= cvtnum("image size", argv
[optind
++]);
578 img_size
= (uint64_t)sval
;
580 if (optind
!= argc
) {
581 error_exit("Unexpected argument: %s", argv
[optind
]);
584 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
585 options
, img_size
, flags
, quiet
, &local_err
);
587 error_reportf_err(local_err
, "%s: ", filename
);
599 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
603 Visitor
*v
= qobject_output_visitor_new(&obj
);
605 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
606 visit_complete(v
, &obj
);
607 str
= qobject_to_json_pretty(obj
, true);
609 qprintf(quiet
, "%s\n", str
->str
);
612 g_string_free(str
, true);
615 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
617 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
618 qprintf(quiet
, "No errors were found on the image.\n");
620 if (check
->corruptions
) {
621 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
622 "Data may be corrupted, or further writes to the image "
629 "\n%" PRId64
" leaked clusters were found on the image.\n"
630 "This means waste of disk space, but no harm to data.\n",
634 if (check
->check_errors
) {
637 " internal errors have occurred during the check.\n",
638 check
->check_errors
);
642 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
643 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
644 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
645 check
->allocated_clusters
, check
->total_clusters
,
646 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
647 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
648 check
->compressed_clusters
* 100.0 /
649 check
->allocated_clusters
);
652 if (check
->image_end_offset
) {
654 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
658 static int collect_image_check(BlockDriverState
*bs
,
660 const char *filename
,
665 BdrvCheckResult result
;
667 ret
= bdrv_check(bs
, &result
, fix
);
672 check
->filename
= g_strdup(filename
);
673 check
->format
= g_strdup(bdrv_get_format_name(bs
));
674 check
->check_errors
= result
.check_errors
;
675 check
->corruptions
= result
.corruptions
;
676 check
->has_corruptions
= result
.corruptions
!= 0;
677 check
->leaks
= result
.leaks
;
678 check
->has_leaks
= result
.leaks
!= 0;
679 check
->corruptions_fixed
= result
.corruptions_fixed
;
680 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
681 check
->leaks_fixed
= result
.leaks_fixed
;
682 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
683 check
->image_end_offset
= result
.image_end_offset
;
684 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
685 check
->total_clusters
= result
.bfi
.total_clusters
;
686 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
687 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
688 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
689 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
690 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
691 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
692 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
698 * Checks an image for consistency. Exit codes:
700 * 0 - Check completed, image is good
701 * 1 - Check not completed because of internal errors
702 * 2 - Check completed, image is corrupted
703 * 3 - Check completed, image has leaked clusters, but is good otherwise
704 * 63 - Checks are not supported by the image format
706 static int img_check(int argc
, char **argv
)
709 OutputFormat output_format
= OFORMAT_HUMAN
;
710 const char *filename
, *fmt
, *output
, *cache
;
712 BlockDriverState
*bs
;
714 int flags
= BDRV_O_CHECK
;
718 bool image_opts
= false;
719 bool force_share
= false;
723 cache
= BDRV_DEFAULT_CACHE
;
726 int option_index
= 0;
727 static const struct option long_options
[] = {
728 {"help", no_argument
, 0, 'h'},
729 {"format", required_argument
, 0, 'f'},
730 {"repair", required_argument
, 0, 'r'},
731 {"output", required_argument
, 0, OPTION_OUTPUT
},
732 {"object", required_argument
, 0, OPTION_OBJECT
},
733 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
734 {"force-share", no_argument
, 0, 'U'},
737 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
738 long_options
, &option_index
);
744 missing_argument(argv
[optind
- 1]);
747 unrecognized_option(argv
[optind
- 1]);
756 flags
|= BDRV_O_RDWR
;
758 if (!strcmp(optarg
, "leaks")) {
759 fix
= BDRV_FIX_LEAKS
;
760 } else if (!strcmp(optarg
, "all")) {
761 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
763 error_exit("Unknown option value for -r "
764 "(expecting 'leaks' or 'all'): %s", optarg
);
780 user_creatable_process_cmdline(optarg
);
782 case OPTION_IMAGE_OPTS
:
787 if (optind
!= argc
- 1) {
788 error_exit("Expecting one image file name");
790 filename
= argv
[optind
++];
792 if (output
&& !strcmp(output
, "json")) {
793 output_format
= OFORMAT_JSON
;
794 } else if (output
&& !strcmp(output
, "human")) {
795 output_format
= OFORMAT_HUMAN
;
797 error_report("--output must be used with human or json as argument.");
801 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
803 error_report("Invalid source cache option: %s", cache
);
807 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
814 check
= g_new0(ImageCheck
, 1);
815 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
817 if (ret
== -ENOTSUP
) {
818 error_report("This image format does not support checks");
823 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
824 int corruptions_fixed
, leaks_fixed
;
825 bool has_leaks_fixed
, has_corruptions_fixed
;
827 leaks_fixed
= check
->leaks_fixed
;
828 has_leaks_fixed
= check
->has_leaks_fixed
;
829 corruptions_fixed
= check
->corruptions_fixed
;
830 has_corruptions_fixed
= check
->has_corruptions_fixed
;
832 if (output_format
== OFORMAT_HUMAN
) {
834 "The following inconsistencies were found and repaired:\n\n"
835 " %" PRId64
" leaked clusters\n"
836 " %" PRId64
" corruptions\n\n"
837 "Double checking the fixed image now...\n",
839 check
->corruptions_fixed
);
842 qapi_free_ImageCheck(check
);
843 check
= g_new0(ImageCheck
, 1);
844 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
846 check
->leaks_fixed
= leaks_fixed
;
847 check
->has_leaks_fixed
= has_leaks_fixed
;
848 check
->corruptions_fixed
= corruptions_fixed
;
849 check
->has_corruptions_fixed
= has_corruptions_fixed
;
853 switch (output_format
) {
855 dump_human_image_check(check
, quiet
);
858 dump_json_image_check(check
, quiet
);
863 if (ret
|| check
->check_errors
) {
865 error_report("Check failed: %s", strerror(-ret
));
867 error_report("Check failed");
873 if (check
->corruptions
) {
875 } else if (check
->leaks
) {
882 qapi_free_ImageCheck(check
);
887 typedef struct CommonBlockJobCBInfo
{
888 BlockDriverState
*bs
;
890 } CommonBlockJobCBInfo
;
892 static void common_block_job_cb(void *opaque
, int ret
)
894 CommonBlockJobCBInfo
*cbi
= opaque
;
897 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
901 static void run_block_job(BlockJob
*job
, Error
**errp
)
903 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
906 aio_context_acquire(aio_context
);
909 float progress
= 0.0f
;
910 aio_poll(aio_context
, true);
911 if (job
->job
.progress
.total
) {
912 progress
= (float)job
->job
.progress
.current
/
913 job
->job
.progress
.total
* 100.f
;
915 qemu_progress_print(progress
, 0);
916 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
918 if (!job_is_completed(&job
->job
)) {
919 ret
= job_complete_sync(&job
->job
, errp
);
923 job_unref(&job
->job
);
924 aio_context_release(aio_context
);
926 /* publish completion progress only when success */
928 qemu_progress_print(100.f
, 0);
932 static int img_commit(int argc
, char **argv
)
935 const char *filename
, *fmt
, *cache
, *base
;
937 BlockDriverState
*bs
, *base_bs
;
939 bool progress
= false, quiet
= false, drop
= false;
941 Error
*local_err
= NULL
;
942 CommonBlockJobCBInfo cbi
;
943 bool image_opts
= false;
944 AioContext
*aio_context
;
945 int64_t rate_limit
= 0;
948 cache
= BDRV_DEFAULT_CACHE
;
951 static const struct option long_options
[] = {
952 {"help", no_argument
, 0, 'h'},
953 {"object", required_argument
, 0, OPTION_OBJECT
},
954 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
957 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
964 missing_argument(argv
[optind
- 1]);
967 unrecognized_option(argv
[optind
- 1]);
993 rate_limit
= cvtnum("rate limit", optarg
);
994 if (rate_limit
< 0) {
999 user_creatable_process_cmdline(optarg
);
1001 case OPTION_IMAGE_OPTS
:
1007 /* Progress is not shown in Quiet mode */
1012 if (optind
!= argc
- 1) {
1013 error_exit("Expecting one image file name");
1015 filename
= argv
[optind
++];
1017 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1018 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1020 error_report("Invalid cache option: %s", cache
);
1024 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1031 qemu_progress_init(progress
, 1.f
);
1032 qemu_progress_print(0.f
, 100);
1035 base_bs
= bdrv_find_backing_image(bs
, base
);
1037 error_setg(&local_err
,
1038 "Did not find '%s' in the backing chain of '%s'",
1043 /* This is different from QMP, which by default uses the deepest file in
1044 * the backing chain (i.e., the very base); however, the traditional
1045 * behavior of qemu-img commit is using the immediate backing file. */
1046 base_bs
= bdrv_backing_chain_next(bs
);
1048 error_setg(&local_err
, "Image does not have a backing file");
1053 cbi
= (CommonBlockJobCBInfo
){
1058 aio_context
= bdrv_get_aio_context(bs
);
1059 aio_context_acquire(aio_context
);
1060 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1061 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1062 &cbi
, false, &local_err
);
1063 aio_context_release(aio_context
);
1068 /* When the block job completes, the BlockBackend reference will point to
1069 * the old backing file. In order to avoid that the top image is already
1070 * deleted, so we can still empty it afterwards, increment the reference
1071 * counter here preemptively. */
1076 job
= block_job_get("commit");
1078 run_block_job(job
, &local_err
);
1084 BlockBackend
*old_backing_blk
;
1086 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1088 if (!old_backing_blk
) {
1091 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1092 blk_unref(old_backing_blk
);
1093 if (ret
== -ENOTSUP
) {
1094 error_free(local_err
);
1096 } else if (ret
< 0) {
1107 qemu_progress_end();
1112 error_report_err(local_err
);
1116 qprintf(quiet
, "Image committed.\n");
1121 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1122 * of the first sector boundary within buf where the sector contains a
1123 * non-zero byte. This function is robust to a buffer that is not
1126 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1129 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1131 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1132 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1136 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1143 * Returns true iff the first sector pointed to by 'buf' contains at least
1146 * 'pnum' is set to the number of sectors (including and immediately following
1147 * the first one) that are known to be in the same allocated/unallocated state.
1148 * The function will try to align the end offset to alignment boundaries so
1149 * that the request will at least end aligned and consecutive requests will
1150 * also start at an aligned offset.
1152 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1153 int64_t sector_num
, int alignment
)
1162 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1163 for(i
= 1; i
< n
; i
++) {
1164 buf
+= BDRV_SECTOR_SIZE
;
1165 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1170 tail
= (sector_num
+ i
) & (alignment
- 1);
1172 if (is_zero
&& i
<= tail
) {
1173 /* treat unallocated areas which only consist
1174 * of a small tail as allocated. */
1178 /* align up end offset of allocated areas. */
1179 i
+= alignment
- tail
;
1182 /* align down end offset of zero areas. */
1191 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1192 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1193 * breaking up write requests for only small sparse areas.
1195 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1196 int min
, int64_t sector_num
, int alignment
)
1199 int num_checked
, num_used
;
1205 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1211 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1213 sector_num
+= *pnum
;
1214 num_checked
= num_used
;
1217 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1219 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1221 sector_num
+= *pnum
;
1222 num_checked
+= *pnum
;
1224 num_used
= num_checked
;
1225 } else if (*pnum
>= min
) {
1235 * Compares two buffers sector by sector. Returns 0 if the first
1236 * sector of each buffer matches, non-zero otherwise.
1238 * pnum is set to the sector-aligned size of the buffer prefix that
1239 * has the same matching status as the first sector.
1241 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1242 int64_t bytes
, int64_t *pnum
)
1245 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1249 res
= !!memcmp(buf1
, buf2
, i
);
1251 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1253 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1263 #define IO_BUF_SIZE (2 * MiB)
1266 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1268 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1269 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1270 * failure), and 4 on error (the exit status for read errors), after emitting
1273 * @param blk: BlockBackend for the image
1274 * @param offset: Starting offset to check
1275 * @param bytes: Number of bytes to check
1276 * @param filename: Name of disk file we are checking (logging purpose)
1277 * @param buffer: Allocated buffer for storing read data
1278 * @param quiet: Flag for quiet mode
1280 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1281 int64_t bytes
, const char *filename
,
1282 uint8_t *buffer
, bool quiet
)
1287 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1289 error_report("Error while reading offset %" PRId64
" of %s: %s",
1290 offset
, filename
, strerror(-ret
));
1293 idx
= find_nonzero(buffer
, bytes
);
1295 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1304 * Compares two images. Exit codes:
1306 * 0 - Images are identical or the requested help was printed
1308 * >1 - Error occurred
1310 static int img_compare(int argc
, char **argv
)
1312 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1313 BlockBackend
*blk1
, *blk2
;
1314 BlockDriverState
*bs1
, *bs2
;
1315 int64_t total_size1
, total_size2
;
1316 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1317 int64_t pnum1
, pnum2
;
1318 int allocated1
, allocated2
;
1319 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1320 bool progress
= false, quiet
= false, strict
= false;
1327 uint64_t progress_base
;
1328 bool image_opts
= false;
1329 bool force_share
= false;
1331 cache
= BDRV_DEFAULT_CACHE
;
1333 static const struct option long_options
[] = {
1334 {"help", no_argument
, 0, 'h'},
1335 {"object", required_argument
, 0, OPTION_OBJECT
},
1336 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1337 {"force-share", no_argument
, 0, 'U'},
1340 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1341 long_options
, NULL
);
1347 missing_argument(argv
[optind
- 1]);
1350 unrecognized_option(argv
[optind
- 1]);
1378 Error
*local_err
= NULL
;
1380 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1382 error_report_err(local_err
);
1385 /* Help was printed */
1391 case OPTION_IMAGE_OPTS
:
1397 /* Progress is not shown in Quiet mode */
1403 if (optind
!= argc
- 2) {
1404 error_exit("Expecting two image file names");
1406 filename1
= argv
[optind
++];
1407 filename2
= argv
[optind
++];
1409 /* Initialize before goto out */
1410 qemu_progress_init(progress
, 2.0);
1413 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1415 error_report("Invalid source cache option: %s", cache
);
1420 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1427 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1436 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1437 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1438 total_size1
= blk_getlength(blk1
);
1439 if (total_size1
< 0) {
1440 error_report("Can't get size of %s: %s",
1441 filename1
, strerror(-total_size1
));
1445 total_size2
= blk_getlength(blk2
);
1446 if (total_size2
< 0) {
1447 error_report("Can't get size of %s: %s",
1448 filename2
, strerror(-total_size2
));
1452 total_size
= MIN(total_size1
, total_size2
);
1453 progress_base
= MAX(total_size1
, total_size2
);
1455 qemu_progress_print(0, 100);
1457 if (strict
&& total_size1
!= total_size2
) {
1459 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1463 while (offset
< total_size
) {
1464 int status1
, status2
;
1466 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1467 total_size1
- offset
, &pnum1
, NULL
,
1471 error_report("Sector allocation test failed for %s", filename1
);
1474 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1476 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1477 total_size2
- offset
, &pnum2
, NULL
,
1481 error_report("Sector allocation test failed for %s", filename2
);
1484 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1486 assert(pnum1
&& pnum2
);
1487 chunk
= MIN(pnum1
, pnum2
);
1490 if (status1
!= status2
) {
1492 qprintf(quiet
, "Strict mode: Offset %" PRId64
1493 " block status mismatch!\n", offset
);
1497 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1499 } else if (allocated1
== allocated2
) {
1503 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1504 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1506 error_report("Error while reading offset %" PRId64
1508 offset
, filename1
, strerror(-ret
));
1512 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1514 error_report("Error while reading offset %" PRId64
1516 offset
, filename2
, strerror(-ret
));
1520 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1521 if (ret
|| pnum
!= chunk
) {
1522 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1523 offset
+ (ret
? 0 : pnum
));
1529 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1531 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1532 filename1
, buf1
, quiet
);
1534 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1535 filename2
, buf1
, quiet
);
1542 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1545 if (total_size1
!= total_size2
) {
1546 BlockBackend
*blk_over
;
1547 const char *filename_over
;
1549 qprintf(quiet
, "Warning: Image size mismatch!\n");
1550 if (total_size1
> total_size2
) {
1552 filename_over
= filename1
;
1555 filename_over
= filename2
;
1558 while (offset
< progress_base
) {
1559 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1560 progress_base
- offset
, &chunk
,
1564 error_report("Sector allocation test failed for %s",
1569 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1570 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1571 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1572 filename_over
, buf1
, quiet
);
1578 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1582 qprintf(quiet
, "Images are identical.\n");
1592 qemu_progress_end();
1596 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1597 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1598 const char *src_node
, const char *src_name
,
1601 BlockDirtyBitmapMergeSource
*merge_src
;
1602 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1604 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1605 merge_src
->type
= QTYPE_QDICT
;
1606 merge_src
->u
.external
.node
= g_strdup(src_node
);
1607 merge_src
->u
.external
.name
= g_strdup(src_name
);
1608 QAPI_LIST_PREPEND(list
, merge_src
);
1609 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1610 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1613 enum ImgConvertBlockStatus
{
1619 #define MAX_COROUTINES 16
1620 #define CONVERT_THROTTLE_GROUP "img_convert"
1622 typedef struct ImgConvertState
{
1624 int64_t *src_sectors
;
1627 int64_t total_sectors
;
1628 int64_t allocated_sectors
;
1629 int64_t allocated_done
;
1632 enum ImgConvertBlockStatus status
;
1633 int64_t sector_next_status
;
1634 BlockBackend
*target
;
1638 bool target_has_backing
;
1639 int64_t target_backing_sectors
; /* negative if unknown */
1646 size_t cluster_sectors
;
1648 long num_coroutines
;
1649 int running_coroutines
;
1650 Coroutine
*co
[MAX_COROUTINES
];
1651 int64_t wait_sector_num
[MAX_COROUTINES
];
1656 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1657 int *src_cur
, int64_t *src_cur_offset
)
1660 *src_cur_offset
= 0;
1661 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1662 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1664 assert(*src_cur
< s
->src_num
);
1668 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1670 int64_t src_cur_offset
;
1671 int ret
, n
, src_cur
;
1672 bool post_backing_zero
= false;
1674 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1676 assert(s
->total_sectors
> sector_num
);
1677 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1679 if (s
->target_backing_sectors
>= 0) {
1680 if (sector_num
>= s
->target_backing_sectors
) {
1681 post_backing_zero
= true;
1682 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1683 /* Split requests around target_backing_sectors (because
1684 * starting from there, zeros are handled differently) */
1685 n
= s
->target_backing_sectors
- sector_num
;
1689 if (s
->sector_next_status
<= sector_num
) {
1690 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1693 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1694 BlockDriverState
*base
;
1696 if (s
->target_has_backing
) {
1697 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1703 count
= n
* BDRV_SECTOR_SIZE
;
1705 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1712 warn_report("error while reading block status at "
1713 "offset %" PRIu64
": %s", offset
,
1716 /* Just try to read the data, then */
1717 ret
= BDRV_BLOCK_DATA
;
1718 count
= BDRV_SECTOR_SIZE
;
1720 /* Retry on a shorter range */
1721 n
= DIV_ROUND_UP(n
, 4);
1724 error_report("error while reading block status at offset "
1725 "%" PRIu64
": %s", offset
, strerror(-ret
));
1731 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1734 * Avoid that s->sector_next_status becomes unaligned to the source
1735 * request alignment and/or cluster size to avoid unnecessary read
1738 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1743 if (ret
& BDRV_BLOCK_ZERO
) {
1744 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1745 } else if (ret
& BDRV_BLOCK_DATA
) {
1746 s
->status
= BLK_DATA
;
1748 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1751 s
->sector_next_status
= sector_num
+ n
;
1754 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1755 if (s
->status
== BLK_DATA
) {
1756 n
= MIN(n
, s
->buf_sectors
);
1759 /* We need to write complete clusters for compressed images, so if an
1760 * unallocated area is shorter than that, we must consider the whole
1761 * cluster allocated. */
1762 if (s
->compressed
) {
1763 if (n
< s
->cluster_sectors
) {
1764 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1765 s
->status
= BLK_DATA
;
1767 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1774 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1775 int nb_sectors
, uint8_t *buf
)
1777 uint64_t single_read_until
= 0;
1780 assert(nb_sectors
<= s
->buf_sectors
);
1781 while (nb_sectors
> 0) {
1784 int64_t bs_sectors
, src_cur_offset
;
1787 /* In the case of compression with multiple source files, we can get a
1788 * nb_sectors that spreads into the next part. So we must be able to
1789 * read across multiple BDSes for one convert_read() call. */
1790 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1791 blk
= s
->src
[src_cur
];
1792 bs_sectors
= s
->src_sectors
[src_cur
];
1794 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1796 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1797 if (single_read_until
> offset
) {
1801 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1805 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1809 warn_report("error while reading offset %" PRIu64
1810 ": %s", offset
, strerror(-ret
));
1812 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1821 buf
+= n
* BDRV_SECTOR_SIZE
;
1828 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1829 int nb_sectors
, uint8_t *buf
,
1830 enum ImgConvertBlockStatus status
)
1834 while (nb_sectors
> 0) {
1836 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1839 case BLK_BACKING_FILE
:
1840 /* If we have a backing file, leave clusters unallocated that are
1841 * unallocated in the source image, so that the backing file is
1842 * visible at the respective offset. */
1843 assert(s
->target_has_backing
);
1847 /* If we're told to keep the target fully allocated (-S 0) or there
1848 * is real non-zero data, we must write it. Otherwise we can treat
1849 * it as zero sectors.
1850 * Compressed clusters need to be written as a whole, so in that
1851 * case we can only save the write if the buffer is completely
1853 if (!s
->min_sparse
||
1855 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1856 sector_num
, s
->alignment
)) ||
1858 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1860 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1861 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1870 if (s
->has_zero_init
) {
1871 assert(!s
->target_has_backing
);
1874 ret
= blk_co_pwrite_zeroes(s
->target
,
1875 sector_num
<< BDRV_SECTOR_BITS
,
1876 n
<< BDRV_SECTOR_BITS
,
1877 BDRV_REQ_MAY_UNMAP
);
1886 buf
+= n
* BDRV_SECTOR_SIZE
;
1892 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1897 while (nb_sectors
> 0) {
1900 int64_t bs_sectors
, src_cur_offset
;
1903 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1904 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1905 blk
= s
->src
[src_cur
];
1906 bs_sectors
= s
->src_sectors
[src_cur
];
1908 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1910 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1911 sector_num
<< BDRV_SECTOR_BITS
,
1912 n
<< BDRV_SECTOR_BITS
, 0, 0);
1923 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1925 ImgConvertState
*s
= opaque
;
1926 uint8_t *buf
= NULL
;
1930 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1931 if (s
->co
[i
] == qemu_coroutine_self()) {
1938 s
->running_coroutines
++;
1939 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1944 enum ImgConvertBlockStatus status
;
1947 qemu_co_mutex_lock(&s
->lock
);
1948 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1949 qemu_co_mutex_unlock(&s
->lock
);
1952 n
= convert_iteration_sectors(s
, s
->sector_num
);
1954 qemu_co_mutex_unlock(&s
->lock
);
1958 /* save current sector and allocation status to local variables */
1959 sector_num
= s
->sector_num
;
1961 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1962 n
= MIN(n
, s
->buf_sectors
);
1964 /* increment global sector counter so that other coroutines can
1965 * already continue reading beyond this request */
1967 qemu_co_mutex_unlock(&s
->lock
);
1969 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1970 s
->allocated_done
+= n
;
1971 qemu_progress_print(100.0 * s
->allocated_done
/
1972 s
->allocated_sectors
, 0);
1976 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1977 if (status
== BLK_DATA
&& !copy_range
) {
1978 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1980 error_report("error while reading at byte %lld: %s",
1981 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
1984 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1986 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1989 if (s
->wr_in_order
) {
1990 /* keep writes in order */
1991 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1992 s
->wait_sector_num
[index
] = sector_num
;
1993 qemu_coroutine_yield();
1995 s
->wait_sector_num
[index
] = -1;
1998 if (s
->ret
== -EINPROGRESS
) {
2000 ret
= convert_co_copy_range(s
, sector_num
, n
);
2002 s
->copy_range
= false;
2006 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2009 error_report("error while writing at byte %lld: %s",
2010 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2015 if (s
->wr_in_order
) {
2016 /* reenter the coroutine that might have waited
2017 * for this write to complete */
2018 s
->wr_offs
= sector_num
+ n
;
2019 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2020 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2022 * A -> B -> A cannot occur because A has
2023 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2024 * B will never enter A during this time window.
2026 qemu_coroutine_enter(s
->co
[i
]);
2034 s
->co
[index
] = NULL
;
2035 s
->running_coroutines
--;
2036 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2037 /* the convert job finished successfully */
2042 static int convert_do_copy(ImgConvertState
*s
)
2045 int64_t sector_num
= 0;
2047 /* Check whether we have zero initialisation or can get it efficiently */
2048 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2049 !s
->target_has_backing
) {
2050 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2053 /* Allocate buffer for copied data. For compressed images, only one cluster
2054 * can be copied at a time. */
2055 if (s
->compressed
) {
2056 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2057 error_report("invalid cluster size");
2060 s
->buf_sectors
= s
->cluster_sectors
;
2063 while (sector_num
< s
->total_sectors
) {
2064 n
= convert_iteration_sectors(s
, sector_num
);
2068 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2070 s
->allocated_sectors
+= n
;
2076 s
->sector_next_status
= 0;
2077 s
->ret
= -EINPROGRESS
;
2079 qemu_co_mutex_init(&s
->lock
);
2080 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2081 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2082 s
->wait_sector_num
[i
] = -1;
2083 qemu_coroutine_enter(s
->co
[i
]);
2086 while (s
->running_coroutines
) {
2087 main_loop_wait(false);
2090 if (s
->compressed
&& !s
->ret
) {
2091 /* signal EOF to align */
2092 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2101 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2103 BdrvDirtyBitmap
*bm
;
2106 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2109 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2112 name
= bdrv_dirty_bitmap_name(bm
);
2113 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2114 true, bdrv_dirty_bitmap_granularity(bm
),
2116 true, !bdrv_dirty_bitmap_enabled(bm
),
2119 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2123 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2126 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2134 #define MAX_BUF_SECTORS 32768
2136 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2140 throttle_config_init(&cfg
);
2141 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2143 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2144 blk_set_io_limits(blk
, &cfg
);
2147 static int img_convert(int argc
, char **argv
)
2149 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2150 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2151 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2152 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2153 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2154 BlockDriverInfo bdi
;
2155 BlockDriverState
*out_bs
;
2156 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2157 QemuOptsList
*create_opts
= NULL
;
2158 QDict
*open_opts
= NULL
;
2159 char *options
= NULL
;
2160 Error
*local_err
= NULL
;
2161 bool writethrough
, src_writethrough
, image_opts
= false,
2162 skip_create
= false, progress
= false, tgt_image_opts
= false;
2163 int64_t ret
= -EINVAL
;
2164 bool force_share
= false;
2165 bool explict_min_sparse
= false;
2166 bool bitmaps
= false;
2167 int64_t rate_limit
= 0;
2169 ImgConvertState s
= (ImgConvertState
) {
2170 /* Need at least 4k of zeros for sparse detection */
2172 .copy_range
= false,
2173 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2174 .wr_in_order
= true,
2175 .num_coroutines
= 8,
2179 static const struct option long_options
[] = {
2180 {"help", no_argument
, 0, 'h'},
2181 {"object", required_argument
, 0, OPTION_OBJECT
},
2182 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2183 {"force-share", no_argument
, 0, 'U'},
2184 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2185 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2186 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2187 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2190 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
2191 long_options
, NULL
);
2197 missing_argument(argv
[optind
- 1]);
2200 unrecognized_option(argv
[optind
- 1]);
2212 out_baseimg
= optarg
;
2215 s
.copy_range
= true;
2218 s
.compressed
= true;
2221 if (accumulate_options(&options
, optarg
) < 0) {
2226 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2227 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2230 error_report("Failed in parsing snapshot param '%s'",
2235 snapshot_name
= optarg
;
2242 sval
= cvtnum("buffer size for sparse output", optarg
);
2245 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2246 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2247 error_report("Invalid buffer size for sparse output specified. "
2248 "Valid sizes are multiples of %llu up to %llu. Select "
2249 "0 to disable sparse detection (fully allocates output).",
2250 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2254 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2255 explict_min_sparse
= true;
2274 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2275 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2276 error_report("Invalid number of coroutines. Allowed number of"
2277 " coroutines is between 1 and %d", MAX_COROUTINES
);
2282 s
.wr_in_order
= false;
2288 rate_limit
= cvtnum("rate limit", optarg
);
2289 if (rate_limit
< 0) {
2294 user_creatable_process_cmdline(optarg
);
2296 case OPTION_IMAGE_OPTS
:
2299 case OPTION_SALVAGE
:
2302 case OPTION_TARGET_IMAGE_OPTS
:
2303 tgt_image_opts
= true;
2305 case OPTION_TARGET_IS_ZERO
:
2307 * The user asserting that the target is blank has the
2308 * same effect as the target driver supporting zero
2311 s
.has_zero_init
= true;
2313 case OPTION_BITMAPS
:
2319 if (!out_fmt
&& !tgt_image_opts
) {
2323 if (s
.compressed
&& s
.copy_range
) {
2324 error_report("Cannot enable copy offloading when -c is used");
2328 if (explict_min_sparse
&& s
.copy_range
) {
2329 error_report("Cannot enable copy offloading when -S is used");
2333 if (s
.copy_range
&& s
.salvage
) {
2334 error_report("Cannot use copy offloading in salvaging mode");
2338 if (tgt_image_opts
&& !skip_create
) {
2339 error_report("--target-image-opts requires use of -n flag");
2343 if (skip_create
&& options
) {
2344 error_report("-o has no effect when skipping image creation");
2348 if (s
.has_zero_init
&& !skip_create
) {
2349 error_report("--target-is-zero requires use of -n flag");
2353 s
.src_num
= argc
- optind
- 1;
2354 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2356 if (options
&& has_help_option(options
)) {
2358 ret
= print_block_option_help(out_filename
, out_fmt
);
2361 error_report("Option help requires a format be specified");
2366 if (s
.src_num
< 1) {
2367 error_report("Must specify image file name");
2371 /* ret is still -EINVAL until here */
2372 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2374 error_report("Invalid source cache option: %s", src_cache
);
2378 /* Initialize before goto out */
2382 qemu_progress_init(progress
, 1.0);
2383 qemu_progress_print(0, 100);
2385 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2386 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2387 s
.src_alignment
= g_new(int, s
.src_num
);
2389 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2390 BlockDriverState
*src_bs
;
2391 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2392 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2398 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2399 if (s
.src_sectors
[bs_i
] < 0) {
2400 error_report("Could not get size of %s: %s",
2401 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2405 src_bs
= blk_bs(s
.src
[bs_i
]);
2406 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2408 if (!bdrv_get_info(src_bs
, &bdi
)) {
2409 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2410 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2412 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2416 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2417 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2418 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2420 } else if (snapshot_name
!= NULL
) {
2421 if (s
.src_num
> 1) {
2422 error_report("No support for concatenating multiple snapshot");
2427 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2431 error_reportf_err(local_err
, "Failed to load snapshot: ");
2437 /* Find driver and parse its options */
2438 drv
= bdrv_find_format(out_fmt
);
2440 error_report("Unknown file format '%s'", out_fmt
);
2445 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2447 error_report_err(local_err
);
2452 if (!drv
->create_opts
) {
2453 error_report("Format driver '%s' does not support image creation",
2459 if (!proto_drv
->create_opts
) {
2460 error_report("Protocol driver '%s' does not support image creation",
2461 proto_drv
->format_name
);
2466 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2467 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2469 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2471 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2472 error_report_err(local_err
);
2478 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2479 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2480 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2486 /* Get backing file name if -o backing_file was used */
2487 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2488 if (out_baseimg_param
) {
2489 out_baseimg
= out_baseimg_param
;
2491 s
.target_has_backing
= (bool) out_baseimg
;
2493 if (s
.has_zero_init
&& s
.target_has_backing
) {
2494 error_report("Cannot use --target-is-zero when the destination "
2495 "image has a backing file");
2499 if (s
.src_num
> 1 && out_baseimg
) {
2500 error_report("Having a backing file for the target makes no sense when "
2501 "concatenating multiple input images");
2506 if (out_baseimg_param
) {
2507 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2508 warn_report("Deprecated use of backing file without explicit "
2513 /* Check if compression is supported */
2516 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2517 const char *encryptfmt
=
2518 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2519 const char *preallocation
=
2520 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2522 if (drv
&& !block_driver_can_compress(drv
)) {
2523 error_report("Compression not supported for this file format");
2528 if (encryption
|| encryptfmt
) {
2529 error_report("Compression and encryption not supported at "
2536 && strcmp(preallocation
, "off"))
2538 error_report("Compression and preallocation not supported at "
2545 /* Determine if bitmaps need copying */
2547 if (s
.src_num
> 1) {
2548 error_report("Copying bitmaps only possible with single source");
2552 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2553 error_report("Source lacks bitmap support");
2560 * The later open call will need any decryption secrets, and
2561 * bdrv_create() will purge "opts", so extract them now before
2565 open_opts
= qdict_new();
2566 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2568 /* Create the new image */
2569 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2571 error_reportf_err(local_err
, "%s: error while converting %s: ",
2572 out_filename
, out_fmt
);
2577 s
.target_is_new
= !skip_create
;
2579 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2580 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2582 error_report("Invalid cache option: %s", cache
);
2587 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2588 flags
, writethrough
, s
.quiet
, false);
2590 /* TODO ultimately we should allow --target-image-opts
2591 * to be used even when -n is not given.
2592 * That has to wait for bdrv_create to be improved
2593 * to allow filenames in option syntax
2595 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2596 flags
, writethrough
, s
.quiet
, false);
2597 open_opts
= NULL
; /* blk_new_open will have freed it */
2603 out_bs
= blk_bs(s
.target
);
2605 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2606 error_report("Format driver '%s' does not support bitmaps",
2607 out_bs
->drv
->format_name
);
2612 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2613 error_report("Compression not supported for this file format");
2618 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2619 * or discard_alignment of the out_bs is greater. Limit to
2620 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2621 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2623 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2624 out_bs
->bl
.pdiscard_alignment
>>
2625 BDRV_SECTOR_BITS
)));
2627 /* try to align the write requests to the destination to avoid unnecessary
2629 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2630 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2632 assert(is_power_of_2(s
.alignment
));
2635 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2636 if (output_sectors
< 0) {
2637 error_report("unable to get output image length: %s",
2638 strerror(-output_sectors
));
2641 } else if (output_sectors
< s
.total_sectors
) {
2642 error_report("output file is smaller than input file");
2648 if (s
.target_has_backing
&& s
.target_is_new
) {
2649 /* Errors are treated as "backing length unknown" (which means
2650 * s.target_backing_sectors has to be negative, which it will
2651 * be automatically). The backing file length is used only
2652 * for optimizations, so such a case is not fatal. */
2653 s
.target_backing_sectors
=
2654 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2656 s
.target_backing_sectors
= -1;
2659 ret
= bdrv_get_info(out_bs
, &bdi
);
2662 error_report("could not get block driver info");
2666 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2667 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2671 set_rate_limit(s
.target
, rate_limit
);
2674 ret
= convert_do_copy(&s
);
2676 /* Now copy the bitmaps */
2677 if (bitmaps
&& ret
== 0) {
2678 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2683 qemu_progress_print(100, 0);
2685 qemu_progress_end();
2686 qemu_opts_del(opts
);
2687 qemu_opts_free(create_opts
);
2688 qobject_unref(open_opts
);
2689 blk_unref(s
.target
);
2691 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2692 blk_unref(s
.src
[bs_i
]);
2696 g_free(s
.src_sectors
);
2697 g_free(s
.src_alignment
);
2699 qemu_opts_del(sn_opts
);
2706 static void dump_snapshots(BlockDriverState
*bs
)
2708 QEMUSnapshotInfo
*sn_tab
, *sn
;
2711 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2714 printf("Snapshot list:\n");
2715 bdrv_snapshot_dump(NULL
);
2717 for(i
= 0; i
< nb_sns
; i
++) {
2719 bdrv_snapshot_dump(sn
);
2725 static void dump_json_image_info_list(ImageInfoList
*list
)
2729 Visitor
*v
= qobject_output_visitor_new(&obj
);
2731 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2732 visit_complete(v
, &obj
);
2733 str
= qobject_to_json_pretty(obj
, true);
2734 assert(str
!= NULL
);
2735 printf("%s\n", str
->str
);
2738 g_string_free(str
, true);
2741 static void dump_json_image_info(ImageInfo
*info
)
2745 Visitor
*v
= qobject_output_visitor_new(&obj
);
2747 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2748 visit_complete(v
, &obj
);
2749 str
= qobject_to_json_pretty(obj
, true);
2750 assert(str
!= NULL
);
2751 printf("%s\n", str
->str
);
2754 g_string_free(str
, true);
2757 static void dump_human_image_info_list(ImageInfoList
*list
)
2759 ImageInfoList
*elem
;
2762 for (elem
= list
; elem
; elem
= elem
->next
) {
2768 bdrv_image_info_dump(elem
->value
);
2772 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2774 return strcmp(a
, b
) == 0;
2778 * Open an image file chain and return an ImageInfoList
2780 * @filename: topmost image filename
2781 * @fmt: topmost image format (may be NULL to autodetect)
2782 * @chain: true - enumerate entire backing file chain
2783 * false - only topmost image file
2785 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2786 * image file. If there was an error a message will have been printed to
2789 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2790 const char *filename
,
2792 bool chain
, bool force_share
)
2794 ImageInfoList
*head
= NULL
;
2795 ImageInfoList
**tail
= &head
;
2796 GHashTable
*filenames
;
2799 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2803 BlockDriverState
*bs
;
2806 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2807 error_report("Backing file '%s' creates an infinite loop.",
2811 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2813 blk
= img_open(image_opts
, filename
, fmt
,
2814 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2821 bdrv_query_image_info(bs
, &info
, &err
);
2823 error_report_err(err
);
2828 QAPI_LIST_APPEND(tail
, info
);
2832 /* Clear parameters that only apply to the topmost image */
2833 filename
= fmt
= NULL
;
2837 if (info
->has_full_backing_filename
) {
2838 filename
= info
->full_backing_filename
;
2839 } else if (info
->has_backing_filename
) {
2840 error_report("Could not determine absolute backing filename,"
2841 " but backing filename '%s' present",
2842 info
->backing_filename
);
2845 if (info
->has_backing_filename_format
) {
2846 fmt
= info
->backing_filename_format
;
2850 g_hash_table_destroy(filenames
);
2854 qapi_free_ImageInfoList(head
);
2855 g_hash_table_destroy(filenames
);
2859 static int img_info(int argc
, char **argv
)
2862 OutputFormat output_format
= OFORMAT_HUMAN
;
2864 const char *filename
, *fmt
, *output
;
2865 ImageInfoList
*list
;
2866 bool image_opts
= false;
2867 bool force_share
= false;
2872 int option_index
= 0;
2873 static const struct option long_options
[] = {
2874 {"help", no_argument
, 0, 'h'},
2875 {"format", required_argument
, 0, 'f'},
2876 {"output", required_argument
, 0, OPTION_OUTPUT
},
2877 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2878 {"object", required_argument
, 0, OPTION_OBJECT
},
2879 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2880 {"force-share", no_argument
, 0, 'U'},
2883 c
= getopt_long(argc
, argv
, ":f:hU",
2884 long_options
, &option_index
);
2890 missing_argument(argv
[optind
- 1]);
2893 unrecognized_option(argv
[optind
- 1]);
2907 case OPTION_BACKING_CHAIN
:
2911 user_creatable_process_cmdline(optarg
);
2913 case OPTION_IMAGE_OPTS
:
2918 if (optind
!= argc
- 1) {
2919 error_exit("Expecting one image file name");
2921 filename
= argv
[optind
++];
2923 if (output
&& !strcmp(output
, "json")) {
2924 output_format
= OFORMAT_JSON
;
2925 } else if (output
&& !strcmp(output
, "human")) {
2926 output_format
= OFORMAT_HUMAN
;
2927 } else if (output
) {
2928 error_report("--output must be used with human or json as argument.");
2932 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2938 switch (output_format
) {
2940 dump_human_image_info_list(list
);
2944 dump_json_image_info_list(list
);
2946 dump_json_image_info(list
->value
);
2951 qapi_free_ImageInfoList(list
);
2955 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2958 switch (output_format
) {
2960 if (e
->data
&& !e
->has_offset
) {
2961 error_report("File contains external, encrypted or compressed clusters.");
2964 if (e
->data
&& !e
->zero
) {
2965 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2966 e
->start
, e
->length
,
2967 e
->has_offset
? e
->offset
: 0,
2968 e
->has_filename
? e
->filename
: "");
2970 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2971 * Modify the flags here to allow more coalescing.
2973 if (next
&& (!next
->data
|| next
->zero
)) {
2979 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2980 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2981 e
->start
, e
->length
, e
->depth
,
2982 e
->zero
? "true" : "false",
2983 e
->data
? "true" : "false");
2984 if (e
->has_offset
) {
2985 printf(", \"offset\": %"PRId64
"", e
->offset
);
2997 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2998 int64_t bytes
, MapEntry
*e
)
3002 BlockDriverState
*file
;
3005 char *filename
= NULL
;
3007 /* As an optimization, we could cache the current range of unallocated
3008 * clusters in each file of the chain, and avoid querying the same
3014 bs
= bdrv_skip_filters(bs
);
3015 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3020 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3023 bs
= bdrv_cow_bs(bs
);
3032 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3034 if (file
&& has_offset
) {
3035 bdrv_refresh_filename(file
);
3036 filename
= file
->filename
;
3042 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3043 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3045 .has_offset
= has_offset
,
3047 .has_filename
= filename
,
3048 .filename
= filename
,
3054 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3056 if (curr
->length
== 0) {
3059 if (curr
->zero
!= next
->zero
||
3060 curr
->data
!= next
->data
||
3061 curr
->depth
!= next
->depth
||
3062 curr
->has_filename
!= next
->has_filename
||
3063 curr
->has_offset
!= next
->has_offset
) {
3066 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3069 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3075 static int img_map(int argc
, char **argv
)
3078 OutputFormat output_format
= OFORMAT_HUMAN
;
3080 BlockDriverState
*bs
;
3081 const char *filename
, *fmt
, *output
;
3083 MapEntry curr
= { .length
= 0 }, next
;
3085 bool image_opts
= false;
3086 bool force_share
= false;
3087 int64_t start_offset
= 0;
3088 int64_t max_length
= -1;
3093 int option_index
= 0;
3094 static const struct option long_options
[] = {
3095 {"help", no_argument
, 0, 'h'},
3096 {"format", required_argument
, 0, 'f'},
3097 {"output", required_argument
, 0, OPTION_OUTPUT
},
3098 {"object", required_argument
, 0, OPTION_OBJECT
},
3099 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3100 {"force-share", no_argument
, 0, 'U'},
3101 {"start-offset", required_argument
, 0, 's'},
3102 {"max-length", required_argument
, 0, 'l'},
3105 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3106 long_options
, &option_index
);
3112 missing_argument(argv
[optind
- 1]);
3115 unrecognized_option(argv
[optind
- 1]);
3130 start_offset
= cvtnum("start offset", optarg
);
3131 if (start_offset
< 0) {
3136 max_length
= cvtnum("max length", optarg
);
3137 if (max_length
< 0) {
3142 user_creatable_process_cmdline(optarg
);
3144 case OPTION_IMAGE_OPTS
:
3149 if (optind
!= argc
- 1) {
3150 error_exit("Expecting one image file name");
3152 filename
= argv
[optind
];
3154 if (output
&& !strcmp(output
, "json")) {
3155 output_format
= OFORMAT_JSON
;
3156 } else if (output
&& !strcmp(output
, "human")) {
3157 output_format
= OFORMAT_HUMAN
;
3158 } else if (output
) {
3159 error_report("--output must be used with human or json as argument.");
3163 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3169 if (output_format
== OFORMAT_HUMAN
) {
3170 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3171 } else if (output_format
== OFORMAT_JSON
) {
3175 length
= blk_getlength(blk
);
3177 error_report("Failed to get size for '%s'", filename
);
3180 if (max_length
!= -1) {
3181 length
= MIN(start_offset
+ max_length
, length
);
3184 curr
.start
= start_offset
;
3185 while (curr
.start
+ curr
.length
< length
) {
3186 int64_t offset
= curr
.start
+ curr
.length
;
3187 int64_t n
= length
- offset
;
3189 ret
= get_block_status(bs
, offset
, n
, &next
);
3191 error_report("Could not read file metadata: %s", strerror(-ret
));
3195 if (entry_mergeable(&curr
, &next
)) {
3196 curr
.length
+= next
.length
;
3200 if (curr
.length
> 0) {
3201 ret
= dump_map_entry(output_format
, &curr
, &next
);
3209 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3210 if (output_format
== OFORMAT_JSON
) {
3219 #define SNAPSHOT_LIST 1
3220 #define SNAPSHOT_CREATE 2
3221 #define SNAPSHOT_APPLY 3
3222 #define SNAPSHOT_DELETE 4
3224 static int img_snapshot(int argc
, char **argv
)
3227 BlockDriverState
*bs
;
3228 QEMUSnapshotInfo sn
;
3229 char *filename
, *snapshot_name
= NULL
;
3230 int c
, ret
= 0, bdrv_oflags
;
3235 bool image_opts
= false;
3236 bool force_share
= false;
3238 bdrv_oflags
= BDRV_O_RDWR
;
3239 /* Parse commandline parameters */
3241 static const struct option long_options
[] = {
3242 {"help", no_argument
, 0, 'h'},
3243 {"object", required_argument
, 0, OPTION_OBJECT
},
3244 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3245 {"force-share", no_argument
, 0, 'U'},
3248 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3249 long_options
, NULL
);
3255 missing_argument(argv
[optind
- 1]);
3258 unrecognized_option(argv
[optind
- 1]);
3265 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3268 action
= SNAPSHOT_LIST
;
3269 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3273 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3276 action
= SNAPSHOT_APPLY
;
3277 snapshot_name
= optarg
;
3281 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3284 action
= SNAPSHOT_CREATE
;
3285 snapshot_name
= optarg
;
3289 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3292 action
= SNAPSHOT_DELETE
;
3293 snapshot_name
= optarg
;
3302 user_creatable_process_cmdline(optarg
);
3304 case OPTION_IMAGE_OPTS
:
3310 if (optind
!= argc
- 1) {
3311 error_exit("Expecting one image file name");
3313 filename
= argv
[optind
++];
3315 /* Open the image */
3316 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3323 /* Perform the requested action */
3329 case SNAPSHOT_CREATE
:
3330 memset(&sn
, 0, sizeof(sn
));
3331 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3333 qemu_gettimeofday(&tv
);
3334 sn
.date_sec
= tv
.tv_sec
;
3335 sn
.date_nsec
= tv
.tv_usec
* 1000;
3337 ret
= bdrv_snapshot_create(bs
, &sn
);
3339 error_report("Could not create snapshot '%s': %d (%s)",
3340 snapshot_name
, ret
, strerror(-ret
));
3344 case SNAPSHOT_APPLY
:
3345 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3347 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3352 case SNAPSHOT_DELETE
:
3353 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3355 error_report("Could not delete snapshot '%s': snapshot not "
3356 "found", snapshot_name
);
3359 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3361 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3377 static int img_rebase(int argc
, char **argv
)
3379 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3380 uint8_t *buf_old
= NULL
;
3381 uint8_t *buf_new
= NULL
;
3382 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3383 BlockDriverState
*unfiltered_bs
;
3385 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3386 int c
, flags
, src_flags
, ret
;
3387 bool writethrough
, src_writethrough
;
3389 bool force_share
= false;
3392 Error
*local_err
= NULL
;
3393 bool image_opts
= false;
3395 /* Parse commandline parameters */
3397 cache
= BDRV_DEFAULT_CACHE
;
3398 src_cache
= BDRV_DEFAULT_CACHE
;
3402 static const struct option long_options
[] = {
3403 {"help", no_argument
, 0, 'h'},
3404 {"object", required_argument
, 0, OPTION_OBJECT
},
3405 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3406 {"force-share", no_argument
, 0, 'U'},
3409 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3410 long_options
, NULL
);
3416 missing_argument(argv
[optind
- 1]);
3419 unrecognized_option(argv
[optind
- 1]);
3428 out_basefmt
= optarg
;
3431 out_baseimg
= optarg
;
3449 user_creatable_process_cmdline(optarg
);
3451 case OPTION_IMAGE_OPTS
:
3464 if (optind
!= argc
- 1) {
3465 error_exit("Expecting one image file name");
3467 if (!unsafe
&& !out_baseimg
) {
3468 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3470 filename
= argv
[optind
++];
3472 qemu_progress_init(progress
, 2.0);
3473 qemu_progress_print(0, 100);
3475 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3476 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3478 error_report("Invalid cache option: %s", cache
);
3483 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3485 error_report("Invalid source cache option: %s", src_cache
);
3489 /* The source files are opened read-only, don't care about WCE */
3490 assert((src_flags
& BDRV_O_RDWR
) == 0);
3491 (void) src_writethrough
;
3496 * Ignore the old backing file for unsafe rebase in case we want to correct
3497 * the reference to a renamed or moved backing file.
3499 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3507 unfiltered_bs
= bdrv_skip_filters(bs
);
3509 if (out_basefmt
!= NULL
) {
3510 if (bdrv_find_format(out_basefmt
) == NULL
) {
3511 error_report("Invalid format name: '%s'", out_basefmt
);
3517 /* For safe rebasing we need to compare old and new backing file */
3519 QDict
*options
= NULL
;
3520 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3523 blk_old_backing
= blk_new(qemu_get_aio_context(),
3524 BLK_PERM_CONSISTENT_READ
,
3526 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3529 error_reportf_err(local_err
,
3530 "Could not reuse old backing file '%s': ",
3535 blk_old_backing
= NULL
;
3538 if (out_baseimg
[0]) {
3539 const char *overlay_filename
;
3540 char *out_real_path
;
3542 options
= qdict_new();
3544 qdict_put_str(options
, "driver", out_basefmt
);
3547 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3550 bdrv_refresh_filename(bs
);
3551 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3554 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3558 qobject_unref(options
);
3559 error_reportf_err(local_err
,
3560 "Could not resolve backing filename: ");
3566 * Find out whether we rebase an image on top of a previous image
3569 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3570 if (prefix_chain_bs
) {
3571 qobject_unref(options
);
3572 g_free(out_real_path
);
3574 blk_new_backing
= blk_new(qemu_get_aio_context(),
3575 BLK_PERM_CONSISTENT_READ
,
3577 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3580 error_reportf_err(local_err
,
3581 "Could not reuse backing file '%s': ",
3586 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3587 options
, src_flags
, &local_err
);
3588 g_free(out_real_path
);
3589 if (!blk_new_backing
) {
3590 error_reportf_err(local_err
,
3591 "Could not open new backing file '%s': ",
3601 * Check each unallocated cluster in the COW file. If it is unallocated,
3602 * accesses go to the backing file. We must therefore compare this cluster
3603 * in the old and new backing file, and if they differ we need to copy it
3604 * from the old backing file into the COW file.
3606 * If qemu-img crashes during this step, no harm is done. The content of
3607 * the image is the same as the original one at any time.
3611 int64_t old_backing_size
= 0;
3612 int64_t new_backing_size
= 0;
3615 float local_progress
= 0;
3617 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3618 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3620 size
= blk_getlength(blk
);
3622 error_report("Could not get size of '%s': %s",
3623 filename
, strerror(-size
));
3627 if (blk_old_backing
) {
3628 old_backing_size
= blk_getlength(blk_old_backing
);
3629 if (old_backing_size
< 0) {
3630 char backing_name
[PATH_MAX
];
3632 bdrv_get_backing_filename(bs
, backing_name
,
3633 sizeof(backing_name
));
3634 error_report("Could not get size of '%s': %s",
3635 backing_name
, strerror(-old_backing_size
));
3640 if (blk_new_backing
) {
3641 new_backing_size
= blk_getlength(blk_new_backing
);
3642 if (new_backing_size
< 0) {
3643 error_report("Could not get size of '%s': %s",
3644 out_baseimg
, strerror(-new_backing_size
));
3651 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3654 for (offset
= 0; offset
< size
; offset
+= n
) {
3655 bool buf_old_is_zero
= false;
3657 /* How many bytes can we handle with the next read? */
3658 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3660 /* If the cluster is allocated, we don't need to take action */
3661 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3663 error_report("error while reading image metadata: %s",
3671 if (prefix_chain_bs
) {
3673 * If cluster wasn't changed since prefix_chain, we don't need
3676 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3677 prefix_chain_bs
, false,
3680 error_report("error while reading image metadata: %s",
3690 * Read old and new backing file and take into consideration that
3691 * backing files may be smaller than the COW image.
3693 if (offset
>= old_backing_size
) {
3694 memset(buf_old
, 0, n
);
3695 buf_old_is_zero
= true;
3697 if (offset
+ n
> old_backing_size
) {
3698 n
= old_backing_size
- offset
;
3701 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3703 error_report("error while reading from old backing file");
3708 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3709 memset(buf_new
, 0, n
);
3711 if (offset
+ n
> new_backing_size
) {
3712 n
= new_backing_size
- offset
;
3715 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3717 error_report("error while reading from new backing file");
3722 /* If they differ, we need to write to the COW file */
3723 uint64_t written
= 0;
3725 while (written
< n
) {
3728 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3729 n
- written
, &pnum
))
3731 if (buf_old_is_zero
) {
3732 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3734 ret
= blk_pwrite(blk
, offset
+ written
,
3735 buf_old
+ written
, pnum
, 0);
3738 error_report("Error while writing to COW image: %s",
3746 qemu_progress_print(local_progress
, 100);
3751 * Change the backing file. All clusters that are different from the old
3752 * backing file are overwritten in the COW file now, so the visible content
3753 * doesn't change when we switch the backing file.
3755 if (out_baseimg
&& *out_baseimg
) {
3756 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3759 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3762 if (ret
== -ENOSPC
) {
3763 error_report("Could not change the backing file to '%s': No "
3764 "space left in the file header", out_baseimg
);
3765 } else if (ret
< 0) {
3766 error_report("Could not change the backing file to '%s': %s",
3767 out_baseimg
, strerror(-ret
));
3770 qemu_progress_print(100, 0);
3772 * TODO At this point it is possible to check if any clusters that are
3773 * allocated in the COW file are the same in the backing file. If so, they
3774 * could be dropped from the COW file. Don't do this before switching the
3775 * backing file, in case of a crash this would lead to corruption.
3778 qemu_progress_end();
3781 blk_unref(blk_old_backing
);
3782 blk_unref(blk_new_backing
);
3784 qemu_vfree(buf_old
);
3785 qemu_vfree(buf_new
);
3794 static int img_resize(int argc
, char **argv
)
3797 int c
, ret
, relative
;
3798 const char *filename
, *fmt
, *size
;
3799 int64_t n
, total_size
, current_size
;
3801 BlockBackend
*blk
= NULL
;
3802 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3805 static QemuOptsList resize_options
= {
3806 .name
= "resize_options",
3807 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3810 .name
= BLOCK_OPT_SIZE
,
3811 .type
= QEMU_OPT_SIZE
,
3812 .help
= "Virtual disk size"
3818 bool image_opts
= false;
3819 bool shrink
= false;
3821 /* Remove size from argv manually so that negative numbers are not treated
3822 * as options by getopt. */
3824 error_exit("Not enough arguments");
3828 size
= argv
[--argc
];
3830 /* Parse getopt arguments */
3833 static const struct option long_options
[] = {
3834 {"help", no_argument
, 0, 'h'},
3835 {"object", required_argument
, 0, OPTION_OBJECT
},
3836 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3837 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3838 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3841 c
= getopt_long(argc
, argv
, ":f:hq",
3842 long_options
, NULL
);
3848 missing_argument(argv
[optind
- 1]);
3851 unrecognized_option(argv
[optind
- 1]);
3863 user_creatable_process_cmdline(optarg
);
3865 case OPTION_IMAGE_OPTS
:
3868 case OPTION_PREALLOCATION
:
3869 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3870 PREALLOC_MODE__MAX
, NULL
);
3871 if (prealloc
== PREALLOC_MODE__MAX
) {
3872 error_report("Invalid preallocation mode '%s'", optarg
);
3881 if (optind
!= argc
- 1) {
3882 error_exit("Expecting image file name and size");
3884 filename
= argv
[optind
++];
3886 /* Choose grow, shrink, or absolute resize mode */
3902 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3903 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3904 error_report_err(err
);
3906 qemu_opts_del(param
);
3909 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3910 qemu_opts_del(param
);
3912 blk
= img_open(image_opts
, filename
, fmt
,
3913 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3920 current_size
= blk_getlength(blk
);
3921 if (current_size
< 0) {
3922 error_report("Failed to inquire current image length: %s",
3923 strerror(-current_size
));
3929 total_size
= current_size
+ n
* relative
;
3933 if (total_size
<= 0) {
3934 error_report("New image size must be positive");
3939 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3940 error_report("Preallocation can only be used for growing images");
3945 if (total_size
< current_size
&& !shrink
) {
3946 error_report("Use the --shrink option to perform a shrink operation.");
3947 warn_report("Shrinking an image will delete all data beyond the "
3948 "shrunken image's end. Before performing such an "
3949 "operation, make sure there is no important data there.");
3955 * The user expects the image to have the desired size after
3956 * resizing, so pass @exact=true. It is of no use to report
3957 * success when the image has not actually been resized.
3959 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
3961 qprintf(quiet
, "Image resized.\n");
3963 error_report_err(err
);
3973 static void amend_status_cb(BlockDriverState
*bs
,
3974 int64_t offset
, int64_t total_work_size
,
3977 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3980 static int print_amend_option_help(const char *format
)
3984 /* Find driver and parse its options */
3985 drv
= bdrv_find_format(format
);
3987 error_report("Unknown file format '%s'", format
);
3991 if (!drv
->bdrv_amend_options
) {
3992 error_report("Format driver '%s' does not support option amendment",
3997 /* Every driver supporting amendment must have amend_opts */
3998 assert(drv
->amend_opts
);
4000 printf("Amend options for '%s':\n", format
);
4001 qemu_opts_print_help(drv
->amend_opts
, false);
4005 static int img_amend(int argc
, char **argv
)
4009 char *options
= NULL
;
4010 QemuOptsList
*amend_opts
= NULL
;
4011 QemuOpts
*opts
= NULL
;
4012 const char *fmt
= NULL
, *filename
, *cache
;
4015 bool quiet
= false, progress
= false;
4016 BlockBackend
*blk
= NULL
;
4017 BlockDriverState
*bs
= NULL
;
4018 bool image_opts
= false;
4021 cache
= BDRV_DEFAULT_CACHE
;
4023 static const struct option long_options
[] = {
4024 {"help", no_argument
, 0, 'h'},
4025 {"object", required_argument
, 0, OPTION_OBJECT
},
4026 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4027 {"force", no_argument
, 0, OPTION_FORCE
},
4030 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4031 long_options
, NULL
);
4038 missing_argument(argv
[optind
- 1]);
4041 unrecognized_option(argv
[optind
- 1]);
4047 if (accumulate_options(&options
, optarg
) < 0) {
4049 goto out_no_progress
;
4065 user_creatable_process_cmdline(optarg
);
4067 case OPTION_IMAGE_OPTS
:
4077 error_exit("Must specify options (-o)");
4083 qemu_progress_init(progress
, 1.0);
4085 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4086 if (fmt
&& has_help_option(options
)) {
4087 /* If a format is explicitly specified (and possibly no filename is
4088 * given), print option help here */
4089 ret
= print_amend_option_help(fmt
);
4093 if (optind
!= argc
- 1) {
4094 error_report("Expecting one image file name");
4099 flags
= BDRV_O_RDWR
;
4100 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4102 error_report("Invalid cache option: %s", cache
);
4106 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4114 fmt
= bs
->drv
->format_name
;
4116 if (has_help_option(options
)) {
4117 /* If the format was auto-detected, print option help here */
4118 ret
= print_amend_option_help(fmt
);
4122 if (!bs
->drv
->bdrv_amend_options
) {
4123 error_report("Format driver '%s' does not support option amendment",
4129 /* Every driver supporting amendment must have amend_opts */
4130 assert(bs
->drv
->amend_opts
);
4132 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4133 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4134 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4135 /* Try to parse options using the create options */
4136 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4137 qemu_opts_del(opts
);
4138 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4139 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4140 error_append_hint(&err
,
4141 "This option is only supported for image creation\n");
4144 error_report_err(err
);
4149 /* In case the driver does not call amend_status_cb() */
4150 qemu_progress_print(0.f
, 0);
4151 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4152 qemu_progress_print(100.f
, 0);
4154 error_report_err(err
);
4159 qemu_progress_end();
4163 qemu_opts_del(opts
);
4164 qemu_opts_free(amend_opts
);
4173 typedef struct BenchData
{
4175 uint64_t image_size
;
4182 bool drain_on_flush
;
4191 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4194 error_report("Failed flush request: %s", strerror(-ret
));
4199 static void bench_cb(void *opaque
, int ret
)
4201 BenchData
*b
= opaque
;
4205 error_report("Failed request: %s", strerror(-ret
));
4210 /* Just finished a flush with drained queue: Start next requests */
4211 assert(b
->in_flight
== 0);
4212 b
->in_flush
= false;
4213 } else if (b
->in_flight
> 0) {
4214 int remaining
= b
->n
- b
->in_flight
;
4219 /* Time for flush? Drain queue if requested, then flush */
4220 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4221 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4222 BlockCompletionFunc
*cb
;
4224 if (b
->drain_on_flush
) {
4228 cb
= bench_undrained_flush_cb
;
4231 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4233 error_report("Failed to issue flush request");
4237 if (b
->drain_on_flush
) {
4243 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4244 int64_t offset
= b
->offset
;
4245 /* blk_aio_* might look for completed I/Os and kick bench_cb
4246 * again, so make sure this operation is counted by in_flight
4247 * and b->offset is ready for the next submission.
4250 b
->offset
+= b
->step
;
4251 b
->offset
%= b
->image_size
;
4253 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4255 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4258 error_report("Failed to issue request");
4264 static int img_bench(int argc
, char **argv
)
4267 const char *fmt
= NULL
, *filename
;
4269 bool image_opts
= false;
4270 bool is_write
= false;
4274 size_t bufsize
= 4096;
4277 int flush_interval
= 0;
4278 bool drain_on_flush
= true;
4280 BlockBackend
*blk
= NULL
;
4281 BenchData data
= {};
4283 bool writethrough
= false;
4284 struct timeval t1
, t2
;
4286 bool force_share
= false;
4290 static const struct option long_options
[] = {
4291 {"help", no_argument
, 0, 'h'},
4292 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4293 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4294 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4295 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4296 {"force-share", no_argument
, 0, 'U'},
4299 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4307 missing_argument(argv
[optind
- 1]);
4310 unrecognized_option(argv
[optind
- 1]);
4319 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4320 error_report("Invalid request count specified");
4330 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4331 error_report("Invalid queue depth specified");
4341 flags
|= BDRV_O_NATIVE_AIO
;
4344 ret
= bdrv_parse_aio(optarg
, &flags
);
4346 error_report("Invalid aio option: %s", optarg
);
4353 offset
= cvtnum("offset", optarg
);
4367 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4379 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4388 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4390 error_report("Invalid cache mode");
4396 flags
|= BDRV_O_RDWR
;
4402 case OPTION_PATTERN
:
4406 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4407 error_report("Invalid pattern byte specified");
4413 case OPTION_FLUSH_INTERVAL
:
4417 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4418 error_report("Invalid flush interval specified");
4421 flush_interval
= res
;
4424 case OPTION_NO_DRAIN
:
4425 drain_on_flush
= false;
4427 case OPTION_IMAGE_OPTS
:
4433 if (optind
!= argc
- 1) {
4434 error_exit("Expecting one image file name");
4436 filename
= argv
[argc
- 1];
4438 if (!is_write
&& flush_interval
) {
4439 error_report("--flush-interval is only available in write tests");
4443 if (flush_interval
&& flush_interval
< depth
) {
4444 error_report("Flush interval can't be smaller than depth");
4449 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4456 image_size
= blk_getlength(blk
);
4457 if (image_size
< 0) {
4462 data
= (BenchData
) {
4464 .image_size
= image_size
,
4466 .step
= step
?: bufsize
,
4471 .flush_interval
= flush_interval
,
4472 .drain_on_flush
= drain_on_flush
,
4474 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4475 "(starting at offset %" PRId64
", step size %d)\n",
4476 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4477 data
.offset
, data
.step
);
4478 if (flush_interval
) {
4479 printf("Sending flush every %d requests\n", flush_interval
);
4482 buf_size
= data
.nrreq
* data
.bufsize
;
4483 data
.buf
= blk_blockalign(blk
, buf_size
);
4484 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4486 blk_register_buf(blk
, data
.buf
, buf_size
);
4488 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4489 for (i
= 0; i
< data
.nrreq
; i
++) {
4490 qemu_iovec_init(&data
.qiov
[i
], 1);
4491 qemu_iovec_add(&data
.qiov
[i
],
4492 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4495 gettimeofday(&t1
, NULL
);
4498 while (data
.n
> 0) {
4499 main_loop_wait(false);
4501 gettimeofday(&t2
, NULL
);
4503 printf("Run completed in %3.3f seconds.\n",
4504 (t2
.tv_sec
- t1
.tv_sec
)
4505 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4509 blk_unregister_buf(blk
, data
.buf
);
4511 qemu_vfree(data
.buf
);
4528 typedef struct ImgBitmapAction
{
4529 enum ImgBitmapAct act
;
4530 const char *src
; /* only used for merge */
4531 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4534 static int img_bitmap(int argc
, char **argv
)
4538 QemuOpts
*opts
= NULL
;
4539 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4540 const char *filename
, *bitmap
;
4541 BlockBackend
*blk
= NULL
, *src
= NULL
;
4542 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4543 bool image_opts
= false;
4544 int64_t granularity
= 0;
4545 bool add
= false, merge
= false;
4546 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4547 ImgBitmapAction
*act
, *act_next
;
4550 QSIMPLEQ_INIT(&actions
);
4553 static const struct option long_options
[] = {
4554 {"help", no_argument
, 0, 'h'},
4555 {"object", required_argument
, 0, OPTION_OBJECT
},
4556 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4557 {"add", no_argument
, 0, OPTION_ADD
},
4558 {"remove", no_argument
, 0, OPTION_REMOVE
},
4559 {"clear", no_argument
, 0, OPTION_CLEAR
},
4560 {"enable", no_argument
, 0, OPTION_ENABLE
},
4561 {"disable", no_argument
, 0, OPTION_DISABLE
},
4562 {"merge", required_argument
, 0, OPTION_MERGE
},
4563 {"granularity", required_argument
, 0, 'g'},
4564 {"source-file", required_argument
, 0, 'b'},
4565 {"source-format", required_argument
, 0, 'F'},
4568 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4575 missing_argument(argv
[optind
- 1]);
4578 unrecognized_option(argv
[optind
- 1]);
4584 src_filename
= optarg
;
4593 granularity
= cvtnum("granularity", optarg
);
4594 if (granularity
< 0) {
4599 act
= g_new0(ImgBitmapAction
, 1);
4600 act
->act
= BITMAP_ADD
;
4601 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4605 act
= g_new0(ImgBitmapAction
, 1);
4606 act
->act
= BITMAP_REMOVE
;
4607 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4610 act
= g_new0(ImgBitmapAction
, 1);
4611 act
->act
= BITMAP_CLEAR
;
4612 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4615 act
= g_new0(ImgBitmapAction
, 1);
4616 act
->act
= BITMAP_ENABLE
;
4617 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4619 case OPTION_DISABLE
:
4620 act
= g_new0(ImgBitmapAction
, 1);
4621 act
->act
= BITMAP_DISABLE
;
4622 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4625 act
= g_new0(ImgBitmapAction
, 1);
4626 act
->act
= BITMAP_MERGE
;
4628 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4632 user_creatable_process_cmdline(optarg
);
4634 case OPTION_IMAGE_OPTS
:
4640 if (QSIMPLEQ_EMPTY(&actions
)) {
4641 error_report("Need at least one of --add, --remove, --clear, "
4642 "--enable, --disable, or --merge");
4646 if (granularity
&& !add
) {
4647 error_report("granularity only supported with --add");
4650 if (src_fmt
&& !src_filename
) {
4651 error_report("-F only supported with -b");
4654 if (src_filename
&& !merge
) {
4655 error_report("Merge bitmap source file only supported with "
4660 if (optind
!= argc
- 2) {
4661 error_report("Expecting filename and bitmap name");
4665 filename
= argv
[optind
];
4666 bitmap
= argv
[optind
+ 1];
4669 * No need to open backing chains; we will be manipulating bitmaps
4670 * directly in this image without reference to image contents.
4672 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4673 false, false, false);
4679 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4680 false, false, false);
4684 src_bs
= blk_bs(src
);
4689 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4692 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4693 !!granularity
, granularity
, true, true,
4694 false, false, &err
);
4698 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4702 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4706 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4709 case BITMAP_DISABLE
:
4710 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4714 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4719 g_assert_not_reached();
4723 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4735 qemu_opts_del(opts
);
4751 int bsz
; /* Block size */
4759 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4763 static int img_dd_bs(const char *arg
,
4764 struct DdIo
*in
, struct DdIo
*out
,
4769 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4774 in
->bsz
= out
->bsz
= res
;
4779 static int img_dd_count(const char *arg
,
4780 struct DdIo
*in
, struct DdIo
*out
,
4783 dd
->count
= cvtnum("count", arg
);
4785 if (dd
->count
< 0) {
4792 static int img_dd_if(const char *arg
,
4793 struct DdIo
*in
, struct DdIo
*out
,
4796 in
->filename
= g_strdup(arg
);
4801 static int img_dd_of(const char *arg
,
4802 struct DdIo
*in
, struct DdIo
*out
,
4805 out
->filename
= g_strdup(arg
);
4810 static int img_dd_skip(const char *arg
,
4811 struct DdIo
*in
, struct DdIo
*out
,
4814 in
->offset
= cvtnum("skip", arg
);
4816 if (in
->offset
< 0) {
4823 static int img_dd(int argc
, char **argv
)
4828 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4829 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4830 QemuOpts
*opts
= NULL
;
4831 QemuOptsList
*create_opts
= NULL
;
4832 Error
*local_err
= NULL
;
4833 bool image_opts
= false;
4835 const char *out_fmt
= "raw";
4836 const char *fmt
= NULL
;
4838 int64_t block_count
= 0, out_pos
, in_pos
;
4839 bool force_share
= false;
4840 struct DdInfo dd
= {
4845 .bsz
= 512, /* Block size is by default 512 bytes */
4857 const struct DdOpts options
[] = {
4858 { "bs", img_dd_bs
, C_BS
},
4859 { "count", img_dd_count
, C_COUNT
},
4860 { "if", img_dd_if
, C_IF
},
4861 { "of", img_dd_of
, C_OF
},
4862 { "skip", img_dd_skip
, C_SKIP
},
4865 const struct option long_options
[] = {
4866 { "help", no_argument
, 0, 'h'},
4867 { "object", required_argument
, 0, OPTION_OBJECT
},
4868 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4869 { "force-share", no_argument
, 0, 'U'},
4873 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4885 missing_argument(argv
[optind
- 1]);
4888 unrecognized_option(argv
[optind
- 1]);
4897 user_creatable_process_cmdline(optarg
);
4899 case OPTION_IMAGE_OPTS
:
4905 for (i
= optind
; i
< argc
; i
++) {
4907 arg
= g_strdup(argv
[i
]);
4909 tmp
= strchr(arg
, '=');
4911 error_report("unrecognized operand %s", arg
);
4918 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4919 if (!strcmp(arg
, options
[j
].name
)) {
4923 if (options
[j
].name
== NULL
) {
4924 error_report("unrecognized operand %s", arg
);
4929 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4933 dd
.flags
|= options
[j
].flag
;
4938 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4939 error_report("Must specify both input and output files");
4944 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4952 drv
= bdrv_find_format(out_fmt
);
4954 error_report("Unknown file format");
4958 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4961 error_report_err(local_err
);
4965 if (!drv
->create_opts
) {
4966 error_report("Format driver '%s' does not support image creation",
4971 if (!proto_drv
->create_opts
) {
4972 error_report("Protocol driver '%s' does not support image creation",
4973 proto_drv
->format_name
);
4977 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4978 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4980 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4982 size
= blk_getlength(blk1
);
4984 error_report("Failed to get size for '%s'", in
.filename
);
4989 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4990 dd
.count
* in
.bsz
< size
) {
4991 size
= dd
.count
* in
.bsz
;
4994 /* Overflow means the specified offset is beyond input image's size */
4995 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4996 size
< in
.bsz
* in
.offset
)) {
4997 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4999 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5000 size
- in
.bsz
* in
.offset
, &error_abort
);
5003 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5005 error_reportf_err(local_err
,
5006 "%s: error while creating output image: ",
5012 /* TODO, we can't honour --image-opts for the target,
5013 * since it needs to be given in a format compatible
5014 * with the bdrv_create() call above which does not
5015 * support image-opts style.
5017 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5018 false, false, false);
5025 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5026 size
< in
.offset
* in
.bsz
)) {
5027 /* We give a warning if the skip option is bigger than the input
5028 * size and create an empty output disk image (i.e. like dd(1)).
5030 error_report("%s: cannot skip to specified offset", in
.filename
);
5033 in_pos
= in
.offset
* in
.bsz
;
5036 in
.buf
= g_new(uint8_t, in
.bsz
);
5038 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5039 int in_ret
, out_ret
;
5041 if (in_pos
+ in
.bsz
> size
) {
5042 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5044 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5047 error_report("error while reading from input image file: %s",
5054 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5057 error_report("error while writing to output image file: %s",
5058 strerror(-out_ret
));
5067 qemu_opts_del(opts
);
5068 qemu_opts_free(create_opts
);
5071 g_free(in
.filename
);
5072 g_free(out
.filename
);
5082 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5086 Visitor
*v
= qobject_output_visitor_new(&obj
);
5088 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5089 visit_complete(v
, &obj
);
5090 str
= qobject_to_json_pretty(obj
, true);
5091 assert(str
!= NULL
);
5092 printf("%s\n", str
->str
);
5095 g_string_free(str
, true);
5098 static int img_measure(int argc
, char **argv
)
5100 static const struct option long_options
[] = {
5101 {"help", no_argument
, 0, 'h'},
5102 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5103 {"object", required_argument
, 0, OPTION_OBJECT
},
5104 {"output", required_argument
, 0, OPTION_OUTPUT
},
5105 {"size", required_argument
, 0, OPTION_SIZE
},
5106 {"force-share", no_argument
, 0, 'U'},
5109 OutputFormat output_format
= OFORMAT_HUMAN
;
5110 BlockBackend
*in_blk
= NULL
;
5112 const char *filename
= NULL
;
5113 const char *fmt
= NULL
;
5114 const char *out_fmt
= "raw";
5115 char *options
= NULL
;
5116 char *snapshot_name
= NULL
;
5117 bool force_share
= false;
5118 QemuOpts
*opts
= NULL
;
5119 QemuOpts
*object_opts
= NULL
;
5120 QemuOpts
*sn_opts
= NULL
;
5121 QemuOptsList
*create_opts
= NULL
;
5122 bool image_opts
= false;
5123 uint64_t img_size
= UINT64_MAX
;
5124 BlockMeasureInfo
*info
= NULL
;
5125 Error
*local_err
= NULL
;
5129 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5130 long_options
, NULL
)) != -1) {
5143 if (accumulate_options(&options
, optarg
) < 0) {
5148 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5149 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5152 error_report("Failed in parsing snapshot param '%s'",
5157 snapshot_name
= optarg
;
5164 user_creatable_process_cmdline(optarg
);
5166 case OPTION_IMAGE_OPTS
:
5170 if (!strcmp(optarg
, "json")) {
5171 output_format
= OFORMAT_JSON
;
5172 } else if (!strcmp(optarg
, "human")) {
5173 output_format
= OFORMAT_HUMAN
;
5175 error_report("--output must be used with human or json "
5184 sval
= cvtnum("image size", optarg
);
5188 img_size
= (uint64_t)sval
;
5194 if (argc
- optind
> 1) {
5195 error_report("At most one filename argument is allowed.");
5197 } else if (argc
- optind
== 1) {
5198 filename
= argv
[optind
];
5201 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5202 error_report("--image-opts, -f, and -l require a filename argument.");
5205 if (filename
&& img_size
!= UINT64_MAX
) {
5206 error_report("--size N cannot be used together with a filename.");
5209 if (!filename
&& img_size
== UINT64_MAX
) {
5210 error_report("Either --size N or one filename must be specified.");
5215 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5216 false, false, force_share
);
5222 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5223 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5224 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5226 } else if (snapshot_name
!= NULL
) {
5227 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5228 snapshot_name
, &local_err
);
5231 error_reportf_err(local_err
, "Failed to load snapshot: ");
5236 drv
= bdrv_find_format(out_fmt
);
5238 error_report("Unknown file format '%s'", out_fmt
);
5241 if (!drv
->create_opts
) {
5242 error_report("Format driver '%s' does not support image creation",
5247 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5248 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5249 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5251 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5252 error_report_err(local_err
);
5253 error_report("Invalid options for file format '%s'", out_fmt
);
5257 if (img_size
!= UINT64_MAX
) {
5258 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5261 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5263 error_report_err(local_err
);
5267 if (output_format
== OFORMAT_HUMAN
) {
5268 printf("required size: %" PRIu64
"\n", info
->required
);
5269 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5270 if (info
->has_bitmaps
) {
5271 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5274 dump_json_block_measure_info(info
);
5280 qapi_free_BlockMeasureInfo(info
);
5281 qemu_opts_del(object_opts
);
5282 qemu_opts_del(opts
);
5283 qemu_opts_del(sn_opts
);
5284 qemu_opts_free(create_opts
);
5290 static const img_cmd_t img_cmds
[] = {
5291 #define DEF(option, callback, arg_string) \
5292 { option, callback },
5293 #include "qemu-img-cmds.h"
5298 int main(int argc
, char **argv
)
5300 const img_cmd_t
*cmd
;
5301 const char *cmdname
;
5302 Error
*local_error
= NULL
;
5304 static const struct option long_options
[] = {
5305 {"help", no_argument
, 0, 'h'},
5306 {"version", no_argument
, 0, 'V'},
5307 {"trace", required_argument
, NULL
, 'T'},
5312 signal(SIGPIPE
, SIG_IGN
);
5316 error_init(argv
[0]);
5317 module_call_init(MODULE_INIT_TRACE
);
5318 qemu_init_exec_dir(argv
[0]);
5320 if (qemu_init_main_loop(&local_error
)) {
5321 error_report_err(local_error
);
5325 qcrypto_init(&error_fatal
);
5327 module_call_init(MODULE_INIT_QOM
);
5330 error_exit("Not enough arguments");
5333 qemu_add_opts(&qemu_source_opts
);
5334 qemu_add_opts(&qemu_trace_opts
);
5336 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5339 missing_argument(argv
[optind
- 1]);
5342 unrecognized_option(argv
[optind
- 1]);
5348 printf(QEMU_IMG_VERSION
);
5351 trace_opt_parse(optarg
);
5356 cmdname
= argv
[optind
];
5358 /* reset getopt_long scanning */
5364 qemu_reset_optind();
5366 if (!trace_init_backends()) {
5370 qemu_set_log(LOG_TRACE
);
5372 /* find the command */
5373 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5374 if (!strcmp(cmdname
, cmd
->name
)) {
5375 return cmd
->handler(argc
, argv
);
5380 error_exit("Command not found: %s", cmdname
);