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 uint64_t progress_current
, progress_total
;
904 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
907 aio_context_acquire(aio_context
);
910 float progress
= 0.0f
;
911 aio_poll(aio_context
, true);
913 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
915 if (progress_total
) {
916 progress
= (float)progress_current
/ progress_total
* 100.f
;
918 qemu_progress_print(progress
, 0);
919 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
921 if (!job_is_completed(&job
->job
)) {
922 ret
= job_complete_sync(&job
->job
, errp
);
926 job_unref(&job
->job
);
927 aio_context_release(aio_context
);
929 /* publish completion progress only when success */
931 qemu_progress_print(100.f
, 0);
935 static int img_commit(int argc
, char **argv
)
938 const char *filename
, *fmt
, *cache
, *base
;
940 BlockDriverState
*bs
, *base_bs
;
942 bool progress
= false, quiet
= false, drop
= false;
944 Error
*local_err
= NULL
;
945 CommonBlockJobCBInfo cbi
;
946 bool image_opts
= false;
947 AioContext
*aio_context
;
948 int64_t rate_limit
= 0;
951 cache
= BDRV_DEFAULT_CACHE
;
954 static const struct option long_options
[] = {
955 {"help", no_argument
, 0, 'h'},
956 {"object", required_argument
, 0, OPTION_OBJECT
},
957 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
960 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
967 missing_argument(argv
[optind
- 1]);
970 unrecognized_option(argv
[optind
- 1]);
996 rate_limit
= cvtnum("rate limit", optarg
);
997 if (rate_limit
< 0) {
1002 user_creatable_process_cmdline(optarg
);
1004 case OPTION_IMAGE_OPTS
:
1010 /* Progress is not shown in Quiet mode */
1015 if (optind
!= argc
- 1) {
1016 error_exit("Expecting one image file name");
1018 filename
= argv
[optind
++];
1020 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1021 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1023 error_report("Invalid cache option: %s", cache
);
1027 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1034 qemu_progress_init(progress
, 1.f
);
1035 qemu_progress_print(0.f
, 100);
1038 base_bs
= bdrv_find_backing_image(bs
, base
);
1040 error_setg(&local_err
,
1041 "Did not find '%s' in the backing chain of '%s'",
1046 /* This is different from QMP, which by default uses the deepest file in
1047 * the backing chain (i.e., the very base); however, the traditional
1048 * behavior of qemu-img commit is using the immediate backing file. */
1049 base_bs
= bdrv_backing_chain_next(bs
);
1051 error_setg(&local_err
, "Image does not have a backing file");
1056 cbi
= (CommonBlockJobCBInfo
){
1061 aio_context
= bdrv_get_aio_context(bs
);
1062 aio_context_acquire(aio_context
);
1063 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1064 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1065 &cbi
, false, &local_err
);
1066 aio_context_release(aio_context
);
1071 /* When the block job completes, the BlockBackend reference will point to
1072 * the old backing file. In order to avoid that the top image is already
1073 * deleted, so we can still empty it afterwards, increment the reference
1074 * counter here preemptively. */
1079 job
= block_job_get("commit");
1081 run_block_job(job
, &local_err
);
1087 BlockBackend
*old_backing_blk
;
1089 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1091 if (!old_backing_blk
) {
1094 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1095 blk_unref(old_backing_blk
);
1096 if (ret
== -ENOTSUP
) {
1097 error_free(local_err
);
1099 } else if (ret
< 0) {
1110 qemu_progress_end();
1115 error_report_err(local_err
);
1119 qprintf(quiet
, "Image committed.\n");
1124 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1125 * of the first sector boundary within buf where the sector contains a
1126 * non-zero byte. This function is robust to a buffer that is not
1129 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1132 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1134 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1135 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1139 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1146 * Returns true iff the first sector pointed to by 'buf' contains at least
1149 * 'pnum' is set to the number of sectors (including and immediately following
1150 * the first one) that are known to be in the same allocated/unallocated state.
1151 * The function will try to align the end offset to alignment boundaries so
1152 * that the request will at least end aligned and consecutive requests will
1153 * also start at an aligned offset.
1155 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1156 int64_t sector_num
, int alignment
)
1165 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1166 for(i
= 1; i
< n
; i
++) {
1167 buf
+= BDRV_SECTOR_SIZE
;
1168 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1173 tail
= (sector_num
+ i
) & (alignment
- 1);
1175 if (is_zero
&& i
<= tail
) {
1176 /* treat unallocated areas which only consist
1177 * of a small tail as allocated. */
1181 /* align up end offset of allocated areas. */
1182 i
+= alignment
- tail
;
1185 /* align down end offset of zero areas. */
1194 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1195 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1196 * breaking up write requests for only small sparse areas.
1198 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1199 int min
, int64_t sector_num
, int alignment
)
1202 int num_checked
, num_used
;
1208 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1214 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1216 sector_num
+= *pnum
;
1217 num_checked
= num_used
;
1220 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1222 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1224 sector_num
+= *pnum
;
1225 num_checked
+= *pnum
;
1227 num_used
= num_checked
;
1228 } else if (*pnum
>= min
) {
1238 * Compares two buffers sector by sector. Returns 0 if the first
1239 * sector of each buffer matches, non-zero otherwise.
1241 * pnum is set to the sector-aligned size of the buffer prefix that
1242 * has the same matching status as the first sector.
1244 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1245 int64_t bytes
, int64_t *pnum
)
1248 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1252 res
= !!memcmp(buf1
, buf2
, i
);
1254 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1256 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1266 #define IO_BUF_SIZE (2 * MiB)
1269 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1271 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1272 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1273 * failure), and 4 on error (the exit status for read errors), after emitting
1276 * @param blk: BlockBackend for the image
1277 * @param offset: Starting offset to check
1278 * @param bytes: Number of bytes to check
1279 * @param filename: Name of disk file we are checking (logging purpose)
1280 * @param buffer: Allocated buffer for storing read data
1281 * @param quiet: Flag for quiet mode
1283 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1284 int64_t bytes
, const char *filename
,
1285 uint8_t *buffer
, bool quiet
)
1290 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1292 error_report("Error while reading offset %" PRId64
" of %s: %s",
1293 offset
, filename
, strerror(-ret
));
1296 idx
= find_nonzero(buffer
, bytes
);
1298 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1307 * Compares two images. Exit codes:
1309 * 0 - Images are identical or the requested help was printed
1311 * >1 - Error occurred
1313 static int img_compare(int argc
, char **argv
)
1315 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1316 BlockBackend
*blk1
, *blk2
;
1317 BlockDriverState
*bs1
, *bs2
;
1318 int64_t total_size1
, total_size2
;
1319 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1320 int64_t pnum1
, pnum2
;
1321 int allocated1
, allocated2
;
1322 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1323 bool progress
= false, quiet
= false, strict
= false;
1330 uint64_t progress_base
;
1331 bool image_opts
= false;
1332 bool force_share
= false;
1334 cache
= BDRV_DEFAULT_CACHE
;
1336 static const struct option long_options
[] = {
1337 {"help", no_argument
, 0, 'h'},
1338 {"object", required_argument
, 0, OPTION_OBJECT
},
1339 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1340 {"force-share", no_argument
, 0, 'U'},
1343 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1344 long_options
, NULL
);
1350 missing_argument(argv
[optind
- 1]);
1353 unrecognized_option(argv
[optind
- 1]);
1381 Error
*local_err
= NULL
;
1383 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1385 error_report_err(local_err
);
1388 /* Help was printed */
1394 case OPTION_IMAGE_OPTS
:
1400 /* Progress is not shown in Quiet mode */
1406 if (optind
!= argc
- 2) {
1407 error_exit("Expecting two image file names");
1409 filename1
= argv
[optind
++];
1410 filename2
= argv
[optind
++];
1412 /* Initialize before goto out */
1413 qemu_progress_init(progress
, 2.0);
1416 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1418 error_report("Invalid source cache option: %s", cache
);
1423 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1430 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1439 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1440 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1441 total_size1
= blk_getlength(blk1
);
1442 if (total_size1
< 0) {
1443 error_report("Can't get size of %s: %s",
1444 filename1
, strerror(-total_size1
));
1448 total_size2
= blk_getlength(blk2
);
1449 if (total_size2
< 0) {
1450 error_report("Can't get size of %s: %s",
1451 filename2
, strerror(-total_size2
));
1455 total_size
= MIN(total_size1
, total_size2
);
1456 progress_base
= MAX(total_size1
, total_size2
);
1458 qemu_progress_print(0, 100);
1460 if (strict
&& total_size1
!= total_size2
) {
1462 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1466 while (offset
< total_size
) {
1467 int status1
, status2
;
1469 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1470 total_size1
- offset
, &pnum1
, NULL
,
1474 error_report("Sector allocation test failed for %s", filename1
);
1477 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1479 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1480 total_size2
- offset
, &pnum2
, NULL
,
1484 error_report("Sector allocation test failed for %s", filename2
);
1487 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1489 assert(pnum1
&& pnum2
);
1490 chunk
= MIN(pnum1
, pnum2
);
1493 if (status1
!= status2
) {
1495 qprintf(quiet
, "Strict mode: Offset %" PRId64
1496 " block status mismatch!\n", offset
);
1500 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1502 } else if (allocated1
== allocated2
) {
1506 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1507 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1509 error_report("Error while reading offset %" PRId64
1511 offset
, filename1
, strerror(-ret
));
1515 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1517 error_report("Error while reading offset %" PRId64
1519 offset
, filename2
, strerror(-ret
));
1523 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1524 if (ret
|| pnum
!= chunk
) {
1525 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1526 offset
+ (ret
? 0 : pnum
));
1532 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1534 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1535 filename1
, buf1
, quiet
);
1537 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1538 filename2
, buf1
, quiet
);
1545 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1548 if (total_size1
!= total_size2
) {
1549 BlockBackend
*blk_over
;
1550 const char *filename_over
;
1552 qprintf(quiet
, "Warning: Image size mismatch!\n");
1553 if (total_size1
> total_size2
) {
1555 filename_over
= filename1
;
1558 filename_over
= filename2
;
1561 while (offset
< progress_base
) {
1562 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1563 progress_base
- offset
, &chunk
,
1567 error_report("Sector allocation test failed for %s",
1572 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1573 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1574 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1575 filename_over
, buf1
, quiet
);
1581 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1585 qprintf(quiet
, "Images are identical.\n");
1595 qemu_progress_end();
1599 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1600 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1601 const char *src_node
, const char *src_name
,
1604 BlockDirtyBitmapMergeSource
*merge_src
;
1605 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1607 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1608 merge_src
->type
= QTYPE_QDICT
;
1609 merge_src
->u
.external
.node
= g_strdup(src_node
);
1610 merge_src
->u
.external
.name
= g_strdup(src_name
);
1611 QAPI_LIST_PREPEND(list
, merge_src
);
1612 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1613 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1616 enum ImgConvertBlockStatus
{
1622 #define MAX_COROUTINES 16
1623 #define CONVERT_THROTTLE_GROUP "img_convert"
1625 typedef struct ImgConvertState
{
1627 int64_t *src_sectors
;
1630 int64_t total_sectors
;
1631 int64_t allocated_sectors
;
1632 int64_t allocated_done
;
1635 enum ImgConvertBlockStatus status
;
1636 int64_t sector_next_status
;
1637 BlockBackend
*target
;
1641 bool target_has_backing
;
1642 int64_t target_backing_sectors
; /* negative if unknown */
1649 size_t cluster_sectors
;
1651 long num_coroutines
;
1652 int running_coroutines
;
1653 Coroutine
*co
[MAX_COROUTINES
];
1654 int64_t wait_sector_num
[MAX_COROUTINES
];
1659 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1660 int *src_cur
, int64_t *src_cur_offset
)
1663 *src_cur_offset
= 0;
1664 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1665 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1667 assert(*src_cur
< s
->src_num
);
1671 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1673 int64_t src_cur_offset
;
1674 int ret
, n
, src_cur
;
1675 bool post_backing_zero
= false;
1677 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1679 assert(s
->total_sectors
> sector_num
);
1680 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1682 if (s
->target_backing_sectors
>= 0) {
1683 if (sector_num
>= s
->target_backing_sectors
) {
1684 post_backing_zero
= true;
1685 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1686 /* Split requests around target_backing_sectors (because
1687 * starting from there, zeros are handled differently) */
1688 n
= s
->target_backing_sectors
- sector_num
;
1692 if (s
->sector_next_status
<= sector_num
) {
1693 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1696 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1697 BlockDriverState
*base
;
1699 if (s
->target_has_backing
) {
1700 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1706 count
= n
* BDRV_SECTOR_SIZE
;
1708 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1715 warn_report("error while reading block status at "
1716 "offset %" PRIu64
": %s", offset
,
1719 /* Just try to read the data, then */
1720 ret
= BDRV_BLOCK_DATA
;
1721 count
= BDRV_SECTOR_SIZE
;
1723 /* Retry on a shorter range */
1724 n
= DIV_ROUND_UP(n
, 4);
1727 error_report("error while reading block status at offset "
1728 "%" PRIu64
": %s", offset
, strerror(-ret
));
1734 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1737 * Avoid that s->sector_next_status becomes unaligned to the source
1738 * request alignment and/or cluster size to avoid unnecessary read
1741 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1746 if (ret
& BDRV_BLOCK_ZERO
) {
1747 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1748 } else if (ret
& BDRV_BLOCK_DATA
) {
1749 s
->status
= BLK_DATA
;
1751 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1754 s
->sector_next_status
= sector_num
+ n
;
1757 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1758 if (s
->status
== BLK_DATA
) {
1759 n
= MIN(n
, s
->buf_sectors
);
1762 /* We need to write complete clusters for compressed images, so if an
1763 * unallocated area is shorter than that, we must consider the whole
1764 * cluster allocated. */
1765 if (s
->compressed
) {
1766 if (n
< s
->cluster_sectors
) {
1767 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1768 s
->status
= BLK_DATA
;
1770 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1777 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1778 int nb_sectors
, uint8_t *buf
)
1780 uint64_t single_read_until
= 0;
1783 assert(nb_sectors
<= s
->buf_sectors
);
1784 while (nb_sectors
> 0) {
1787 int64_t bs_sectors
, src_cur_offset
;
1790 /* In the case of compression with multiple source files, we can get a
1791 * nb_sectors that spreads into the next part. So we must be able to
1792 * read across multiple BDSes for one convert_read() call. */
1793 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1794 blk
= s
->src
[src_cur
];
1795 bs_sectors
= s
->src_sectors
[src_cur
];
1797 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1799 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1800 if (single_read_until
> offset
) {
1804 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1808 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1812 warn_report("error while reading offset %" PRIu64
1813 ": %s", offset
, strerror(-ret
));
1815 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1824 buf
+= n
* BDRV_SECTOR_SIZE
;
1831 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1832 int nb_sectors
, uint8_t *buf
,
1833 enum ImgConvertBlockStatus status
)
1837 while (nb_sectors
> 0) {
1839 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1842 case BLK_BACKING_FILE
:
1843 /* If we have a backing file, leave clusters unallocated that are
1844 * unallocated in the source image, so that the backing file is
1845 * visible at the respective offset. */
1846 assert(s
->target_has_backing
);
1850 /* If we're told to keep the target fully allocated (-S 0) or there
1851 * is real non-zero data, we must write it. Otherwise we can treat
1852 * it as zero sectors.
1853 * Compressed clusters need to be written as a whole, so in that
1854 * case we can only save the write if the buffer is completely
1856 if (!s
->min_sparse
||
1858 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1859 sector_num
, s
->alignment
)) ||
1861 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1863 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1864 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1873 if (s
->has_zero_init
) {
1874 assert(!s
->target_has_backing
);
1877 ret
= blk_co_pwrite_zeroes(s
->target
,
1878 sector_num
<< BDRV_SECTOR_BITS
,
1879 n
<< BDRV_SECTOR_BITS
,
1880 BDRV_REQ_MAY_UNMAP
);
1889 buf
+= n
* BDRV_SECTOR_SIZE
;
1895 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1900 while (nb_sectors
> 0) {
1903 int64_t bs_sectors
, src_cur_offset
;
1906 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1907 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1908 blk
= s
->src
[src_cur
];
1909 bs_sectors
= s
->src_sectors
[src_cur
];
1911 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1913 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1914 sector_num
<< BDRV_SECTOR_BITS
,
1915 n
<< BDRV_SECTOR_BITS
, 0, 0);
1926 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1928 ImgConvertState
*s
= opaque
;
1929 uint8_t *buf
= NULL
;
1933 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1934 if (s
->co
[i
] == qemu_coroutine_self()) {
1941 s
->running_coroutines
++;
1942 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1947 enum ImgConvertBlockStatus status
;
1950 qemu_co_mutex_lock(&s
->lock
);
1951 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1952 qemu_co_mutex_unlock(&s
->lock
);
1955 n
= convert_iteration_sectors(s
, s
->sector_num
);
1957 qemu_co_mutex_unlock(&s
->lock
);
1961 /* save current sector and allocation status to local variables */
1962 sector_num
= s
->sector_num
;
1964 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1965 n
= MIN(n
, s
->buf_sectors
);
1967 /* increment global sector counter so that other coroutines can
1968 * already continue reading beyond this request */
1970 qemu_co_mutex_unlock(&s
->lock
);
1972 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1973 s
->allocated_done
+= n
;
1974 qemu_progress_print(100.0 * s
->allocated_done
/
1975 s
->allocated_sectors
, 0);
1979 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1980 if (status
== BLK_DATA
&& !copy_range
) {
1981 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1983 error_report("error while reading at byte %lld: %s",
1984 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
1987 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1989 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1992 if (s
->wr_in_order
) {
1993 /* keep writes in order */
1994 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1995 s
->wait_sector_num
[index
] = sector_num
;
1996 qemu_coroutine_yield();
1998 s
->wait_sector_num
[index
] = -1;
2001 if (s
->ret
== -EINPROGRESS
) {
2003 ret
= convert_co_copy_range(s
, sector_num
, n
);
2005 s
->copy_range
= false;
2009 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2012 error_report("error while writing at byte %lld: %s",
2013 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2018 if (s
->wr_in_order
) {
2019 /* reenter the coroutine that might have waited
2020 * for this write to complete */
2021 s
->wr_offs
= sector_num
+ n
;
2022 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2023 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2025 * A -> B -> A cannot occur because A has
2026 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2027 * B will never enter A during this time window.
2029 qemu_coroutine_enter(s
->co
[i
]);
2037 s
->co
[index
] = NULL
;
2038 s
->running_coroutines
--;
2039 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2040 /* the convert job finished successfully */
2045 static int convert_do_copy(ImgConvertState
*s
)
2048 int64_t sector_num
= 0;
2050 /* Check whether we have zero initialisation or can get it efficiently */
2051 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2052 !s
->target_has_backing
) {
2053 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2056 /* Allocate buffer for copied data. For compressed images, only one cluster
2057 * can be copied at a time. */
2058 if (s
->compressed
) {
2059 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2060 error_report("invalid cluster size");
2063 s
->buf_sectors
= s
->cluster_sectors
;
2066 while (sector_num
< s
->total_sectors
) {
2067 n
= convert_iteration_sectors(s
, sector_num
);
2071 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2073 s
->allocated_sectors
+= n
;
2079 s
->sector_next_status
= 0;
2080 s
->ret
= -EINPROGRESS
;
2082 qemu_co_mutex_init(&s
->lock
);
2083 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2084 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2085 s
->wait_sector_num
[i
] = -1;
2086 qemu_coroutine_enter(s
->co
[i
]);
2089 while (s
->running_coroutines
) {
2090 main_loop_wait(false);
2093 if (s
->compressed
&& !s
->ret
) {
2094 /* signal EOF to align */
2095 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2104 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
)
2106 BdrvDirtyBitmap
*bm
;
2109 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2112 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2115 name
= bdrv_dirty_bitmap_name(bm
);
2116 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2117 true, bdrv_dirty_bitmap_granularity(bm
),
2119 true, !bdrv_dirty_bitmap_enabled(bm
),
2122 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2126 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2129 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2137 #define MAX_BUF_SECTORS 32768
2139 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2143 throttle_config_init(&cfg
);
2144 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2146 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2147 blk_set_io_limits(blk
, &cfg
);
2150 static int img_convert(int argc
, char **argv
)
2152 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2153 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2154 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2155 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2156 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2157 BlockDriverInfo bdi
;
2158 BlockDriverState
*out_bs
;
2159 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2160 QemuOptsList
*create_opts
= NULL
;
2161 QDict
*open_opts
= NULL
;
2162 char *options
= NULL
;
2163 Error
*local_err
= NULL
;
2164 bool writethrough
, src_writethrough
, image_opts
= false,
2165 skip_create
= false, progress
= false, tgt_image_opts
= false;
2166 int64_t ret
= -EINVAL
;
2167 bool force_share
= false;
2168 bool explict_min_sparse
= false;
2169 bool bitmaps
= false;
2170 int64_t rate_limit
= 0;
2172 ImgConvertState s
= (ImgConvertState
) {
2173 /* Need at least 4k of zeros for sparse detection */
2175 .copy_range
= false,
2176 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2177 .wr_in_order
= true,
2178 .num_coroutines
= 8,
2182 static const struct option long_options
[] = {
2183 {"help", no_argument
, 0, 'h'},
2184 {"object", required_argument
, 0, OPTION_OBJECT
},
2185 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2186 {"force-share", no_argument
, 0, 'U'},
2187 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2188 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2189 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2190 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2193 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
2194 long_options
, NULL
);
2200 missing_argument(argv
[optind
- 1]);
2203 unrecognized_option(argv
[optind
- 1]);
2215 out_baseimg
= optarg
;
2218 s
.copy_range
= true;
2221 s
.compressed
= true;
2224 if (accumulate_options(&options
, optarg
) < 0) {
2229 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2230 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2233 error_report("Failed in parsing snapshot param '%s'",
2238 snapshot_name
= optarg
;
2245 sval
= cvtnum("buffer size for sparse output", optarg
);
2248 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2249 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2250 error_report("Invalid buffer size for sparse output specified. "
2251 "Valid sizes are multiples of %llu up to %llu. Select "
2252 "0 to disable sparse detection (fully allocates output).",
2253 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2257 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2258 explict_min_sparse
= true;
2277 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2278 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2279 error_report("Invalid number of coroutines. Allowed number of"
2280 " coroutines is between 1 and %d", MAX_COROUTINES
);
2285 s
.wr_in_order
= false;
2291 rate_limit
= cvtnum("rate limit", optarg
);
2292 if (rate_limit
< 0) {
2297 user_creatable_process_cmdline(optarg
);
2299 case OPTION_IMAGE_OPTS
:
2302 case OPTION_SALVAGE
:
2305 case OPTION_TARGET_IMAGE_OPTS
:
2306 tgt_image_opts
= true;
2308 case OPTION_TARGET_IS_ZERO
:
2310 * The user asserting that the target is blank has the
2311 * same effect as the target driver supporting zero
2314 s
.has_zero_init
= true;
2316 case OPTION_BITMAPS
:
2322 if (!out_fmt
&& !tgt_image_opts
) {
2326 if (s
.compressed
&& s
.copy_range
) {
2327 error_report("Cannot enable copy offloading when -c is used");
2331 if (explict_min_sparse
&& s
.copy_range
) {
2332 error_report("Cannot enable copy offloading when -S is used");
2336 if (s
.copy_range
&& s
.salvage
) {
2337 error_report("Cannot use copy offloading in salvaging mode");
2341 if (tgt_image_opts
&& !skip_create
) {
2342 error_report("--target-image-opts requires use of -n flag");
2346 if (skip_create
&& options
) {
2347 error_report("-o has no effect when skipping image creation");
2351 if (s
.has_zero_init
&& !skip_create
) {
2352 error_report("--target-is-zero requires use of -n flag");
2356 s
.src_num
= argc
- optind
- 1;
2357 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2359 if (options
&& has_help_option(options
)) {
2361 ret
= print_block_option_help(out_filename
, out_fmt
);
2364 error_report("Option help requires a format be specified");
2369 if (s
.src_num
< 1) {
2370 error_report("Must specify image file name");
2374 /* ret is still -EINVAL until here */
2375 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2377 error_report("Invalid source cache option: %s", src_cache
);
2381 /* Initialize before goto out */
2385 qemu_progress_init(progress
, 1.0);
2386 qemu_progress_print(0, 100);
2388 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2389 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2390 s
.src_alignment
= g_new(int, s
.src_num
);
2392 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2393 BlockDriverState
*src_bs
;
2394 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2395 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2401 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2402 if (s
.src_sectors
[bs_i
] < 0) {
2403 error_report("Could not get size of %s: %s",
2404 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2408 src_bs
= blk_bs(s
.src
[bs_i
]);
2409 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2411 if (!bdrv_get_info(src_bs
, &bdi
)) {
2412 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2413 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2415 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2419 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2420 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2421 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2423 } else if (snapshot_name
!= NULL
) {
2424 if (s
.src_num
> 1) {
2425 error_report("No support for concatenating multiple snapshot");
2430 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2434 error_reportf_err(local_err
, "Failed to load snapshot: ");
2440 /* Find driver and parse its options */
2441 drv
= bdrv_find_format(out_fmt
);
2443 error_report("Unknown file format '%s'", out_fmt
);
2448 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2450 error_report_err(local_err
);
2455 if (!drv
->create_opts
) {
2456 error_report("Format driver '%s' does not support image creation",
2462 if (!proto_drv
->create_opts
) {
2463 error_report("Protocol driver '%s' does not support image creation",
2464 proto_drv
->format_name
);
2469 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2470 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2472 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2474 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2475 error_report_err(local_err
);
2481 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2482 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2483 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2489 /* Get backing file name if -o backing_file was used */
2490 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2491 if (out_baseimg_param
) {
2492 out_baseimg
= out_baseimg_param
;
2494 s
.target_has_backing
= (bool) out_baseimg
;
2496 if (s
.has_zero_init
&& s
.target_has_backing
) {
2497 error_report("Cannot use --target-is-zero when the destination "
2498 "image has a backing file");
2502 if (s
.src_num
> 1 && out_baseimg
) {
2503 error_report("Having a backing file for the target makes no sense when "
2504 "concatenating multiple input images");
2509 if (out_baseimg_param
) {
2510 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2511 error_report("Use of backing file requires explicit "
2518 /* Check if compression is supported */
2521 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2522 const char *encryptfmt
=
2523 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2524 const char *preallocation
=
2525 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2527 if (drv
&& !block_driver_can_compress(drv
)) {
2528 error_report("Compression not supported for this file format");
2533 if (encryption
|| encryptfmt
) {
2534 error_report("Compression and encryption not supported at "
2541 && strcmp(preallocation
, "off"))
2543 error_report("Compression and preallocation not supported at "
2550 /* Determine if bitmaps need copying */
2552 if (s
.src_num
> 1) {
2553 error_report("Copying bitmaps only possible with single source");
2557 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s
.src
[0]))) {
2558 error_report("Source lacks bitmap support");
2565 * The later open call will need any decryption secrets, and
2566 * bdrv_create() will purge "opts", so extract them now before
2570 open_opts
= qdict_new();
2571 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2573 /* Create the new image */
2574 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2576 error_reportf_err(local_err
, "%s: error while converting %s: ",
2577 out_filename
, out_fmt
);
2582 s
.target_is_new
= !skip_create
;
2584 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2585 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2587 error_report("Invalid cache option: %s", cache
);
2592 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2593 flags
, writethrough
, s
.quiet
, false);
2595 /* TODO ultimately we should allow --target-image-opts
2596 * to be used even when -n is not given.
2597 * That has to wait for bdrv_create to be improved
2598 * to allow filenames in option syntax
2600 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2601 flags
, writethrough
, s
.quiet
, false);
2602 open_opts
= NULL
; /* blk_new_open will have freed it */
2608 out_bs
= blk_bs(s
.target
);
2610 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2611 error_report("Format driver '%s' does not support bitmaps",
2612 out_bs
->drv
->format_name
);
2617 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2618 error_report("Compression not supported for this file format");
2623 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2624 * or discard_alignment of the out_bs is greater. Limit to
2625 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2626 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2628 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2629 out_bs
->bl
.pdiscard_alignment
>>
2630 BDRV_SECTOR_BITS
)));
2632 /* try to align the write requests to the destination to avoid unnecessary
2634 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2635 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2637 assert(is_power_of_2(s
.alignment
));
2640 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2641 if (output_sectors
< 0) {
2642 error_report("unable to get output image length: %s",
2643 strerror(-output_sectors
));
2646 } else if (output_sectors
< s
.total_sectors
) {
2647 error_report("output file is smaller than input file");
2653 if (s
.target_has_backing
&& s
.target_is_new
) {
2654 /* Errors are treated as "backing length unknown" (which means
2655 * s.target_backing_sectors has to be negative, which it will
2656 * be automatically). The backing file length is used only
2657 * for optimizations, so such a case is not fatal. */
2658 s
.target_backing_sectors
=
2659 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2661 s
.target_backing_sectors
= -1;
2664 ret
= bdrv_get_info(out_bs
, &bdi
);
2667 error_report("could not get block driver info");
2671 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2672 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2676 set_rate_limit(s
.target
, rate_limit
);
2679 ret
= convert_do_copy(&s
);
2681 /* Now copy the bitmaps */
2682 if (bitmaps
&& ret
== 0) {
2683 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
);
2688 qemu_progress_print(100, 0);
2690 qemu_progress_end();
2691 qemu_opts_del(opts
);
2692 qemu_opts_free(create_opts
);
2693 qobject_unref(open_opts
);
2694 blk_unref(s
.target
);
2696 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2697 blk_unref(s
.src
[bs_i
]);
2701 g_free(s
.src_sectors
);
2702 g_free(s
.src_alignment
);
2704 qemu_opts_del(sn_opts
);
2711 static void dump_snapshots(BlockDriverState
*bs
)
2713 QEMUSnapshotInfo
*sn_tab
, *sn
;
2716 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2719 printf("Snapshot list:\n");
2720 bdrv_snapshot_dump(NULL
);
2722 for(i
= 0; i
< nb_sns
; i
++) {
2724 bdrv_snapshot_dump(sn
);
2730 static void dump_json_image_info_list(ImageInfoList
*list
)
2734 Visitor
*v
= qobject_output_visitor_new(&obj
);
2736 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2737 visit_complete(v
, &obj
);
2738 str
= qobject_to_json_pretty(obj
, true);
2739 assert(str
!= NULL
);
2740 printf("%s\n", str
->str
);
2743 g_string_free(str
, true);
2746 static void dump_json_image_info(ImageInfo
*info
)
2750 Visitor
*v
= qobject_output_visitor_new(&obj
);
2752 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2753 visit_complete(v
, &obj
);
2754 str
= qobject_to_json_pretty(obj
, true);
2755 assert(str
!= NULL
);
2756 printf("%s\n", str
->str
);
2759 g_string_free(str
, true);
2762 static void dump_human_image_info_list(ImageInfoList
*list
)
2764 ImageInfoList
*elem
;
2767 for (elem
= list
; elem
; elem
= elem
->next
) {
2773 bdrv_image_info_dump(elem
->value
);
2777 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2779 return strcmp(a
, b
) == 0;
2783 * Open an image file chain and return an ImageInfoList
2785 * @filename: topmost image filename
2786 * @fmt: topmost image format (may be NULL to autodetect)
2787 * @chain: true - enumerate entire backing file chain
2788 * false - only topmost image file
2790 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2791 * image file. If there was an error a message will have been printed to
2794 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2795 const char *filename
,
2797 bool chain
, bool force_share
)
2799 ImageInfoList
*head
= NULL
;
2800 ImageInfoList
**tail
= &head
;
2801 GHashTable
*filenames
;
2804 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2808 BlockDriverState
*bs
;
2811 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2812 error_report("Backing file '%s' creates an infinite loop.",
2816 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2818 blk
= img_open(image_opts
, filename
, fmt
,
2819 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2826 bdrv_query_image_info(bs
, &info
, &err
);
2828 error_report_err(err
);
2833 QAPI_LIST_APPEND(tail
, info
);
2837 /* Clear parameters that only apply to the topmost image */
2838 filename
= fmt
= NULL
;
2842 if (info
->has_full_backing_filename
) {
2843 filename
= info
->full_backing_filename
;
2844 } else if (info
->has_backing_filename
) {
2845 error_report("Could not determine absolute backing filename,"
2846 " but backing filename '%s' present",
2847 info
->backing_filename
);
2850 if (info
->has_backing_filename_format
) {
2851 fmt
= info
->backing_filename_format
;
2855 g_hash_table_destroy(filenames
);
2859 qapi_free_ImageInfoList(head
);
2860 g_hash_table_destroy(filenames
);
2864 static int img_info(int argc
, char **argv
)
2867 OutputFormat output_format
= OFORMAT_HUMAN
;
2869 const char *filename
, *fmt
, *output
;
2870 ImageInfoList
*list
;
2871 bool image_opts
= false;
2872 bool force_share
= false;
2877 int option_index
= 0;
2878 static const struct option long_options
[] = {
2879 {"help", no_argument
, 0, 'h'},
2880 {"format", required_argument
, 0, 'f'},
2881 {"output", required_argument
, 0, OPTION_OUTPUT
},
2882 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2883 {"object", required_argument
, 0, OPTION_OBJECT
},
2884 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2885 {"force-share", no_argument
, 0, 'U'},
2888 c
= getopt_long(argc
, argv
, ":f:hU",
2889 long_options
, &option_index
);
2895 missing_argument(argv
[optind
- 1]);
2898 unrecognized_option(argv
[optind
- 1]);
2912 case OPTION_BACKING_CHAIN
:
2916 user_creatable_process_cmdline(optarg
);
2918 case OPTION_IMAGE_OPTS
:
2923 if (optind
!= argc
- 1) {
2924 error_exit("Expecting one image file name");
2926 filename
= argv
[optind
++];
2928 if (output
&& !strcmp(output
, "json")) {
2929 output_format
= OFORMAT_JSON
;
2930 } else if (output
&& !strcmp(output
, "human")) {
2931 output_format
= OFORMAT_HUMAN
;
2932 } else if (output
) {
2933 error_report("--output must be used with human or json as argument.");
2937 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2943 switch (output_format
) {
2945 dump_human_image_info_list(list
);
2949 dump_json_image_info_list(list
);
2951 dump_json_image_info(list
->value
);
2956 qapi_free_ImageInfoList(list
);
2960 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2963 switch (output_format
) {
2965 if (e
->data
&& !e
->has_offset
) {
2966 error_report("File contains external, encrypted or compressed clusters.");
2969 if (e
->data
&& !e
->zero
) {
2970 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2971 e
->start
, e
->length
,
2972 e
->has_offset
? e
->offset
: 0,
2973 e
->has_filename
? e
->filename
: "");
2975 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2976 * Modify the flags here to allow more coalescing.
2978 if (next
&& (!next
->data
|| next
->zero
)) {
2984 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2985 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
2986 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
2987 e
->present
? "true" : "false",
2988 e
->zero
? "true" : "false",
2989 e
->data
? "true" : "false");
2990 if (e
->has_offset
) {
2991 printf(", \"offset\": %"PRId64
"", e
->offset
);
3003 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3004 int64_t bytes
, MapEntry
*e
)
3008 BlockDriverState
*file
;
3011 char *filename
= NULL
;
3013 /* As an optimization, we could cache the current range of unallocated
3014 * clusters in each file of the chain, and avoid querying the same
3020 bs
= bdrv_skip_filters(bs
);
3021 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3026 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3029 bs
= bdrv_cow_bs(bs
);
3038 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3040 if (file
&& has_offset
) {
3041 bdrv_refresh_filename(file
);
3042 filename
= file
->filename
;
3048 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3049 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3051 .has_offset
= has_offset
,
3053 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3054 .has_filename
= filename
,
3055 .filename
= filename
,
3061 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3063 if (curr
->length
== 0) {
3066 if (curr
->zero
!= next
->zero
||
3067 curr
->data
!= next
->data
||
3068 curr
->depth
!= next
->depth
||
3069 curr
->present
!= next
->present
||
3070 curr
->has_filename
!= next
->has_filename
||
3071 curr
->has_offset
!= next
->has_offset
) {
3074 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3077 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3083 static int img_map(int argc
, char **argv
)
3086 OutputFormat output_format
= OFORMAT_HUMAN
;
3088 BlockDriverState
*bs
;
3089 const char *filename
, *fmt
, *output
;
3091 MapEntry curr
= { .length
= 0 }, next
;
3093 bool image_opts
= false;
3094 bool force_share
= false;
3095 int64_t start_offset
= 0;
3096 int64_t max_length
= -1;
3101 int option_index
= 0;
3102 static const struct option long_options
[] = {
3103 {"help", no_argument
, 0, 'h'},
3104 {"format", required_argument
, 0, 'f'},
3105 {"output", required_argument
, 0, OPTION_OUTPUT
},
3106 {"object", required_argument
, 0, OPTION_OBJECT
},
3107 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3108 {"force-share", no_argument
, 0, 'U'},
3109 {"start-offset", required_argument
, 0, 's'},
3110 {"max-length", required_argument
, 0, 'l'},
3113 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3114 long_options
, &option_index
);
3120 missing_argument(argv
[optind
- 1]);
3123 unrecognized_option(argv
[optind
- 1]);
3138 start_offset
= cvtnum("start offset", optarg
);
3139 if (start_offset
< 0) {
3144 max_length
= cvtnum("max length", optarg
);
3145 if (max_length
< 0) {
3150 user_creatable_process_cmdline(optarg
);
3152 case OPTION_IMAGE_OPTS
:
3157 if (optind
!= argc
- 1) {
3158 error_exit("Expecting one image file name");
3160 filename
= argv
[optind
];
3162 if (output
&& !strcmp(output
, "json")) {
3163 output_format
= OFORMAT_JSON
;
3164 } else if (output
&& !strcmp(output
, "human")) {
3165 output_format
= OFORMAT_HUMAN
;
3166 } else if (output
) {
3167 error_report("--output must be used with human or json as argument.");
3171 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3177 if (output_format
== OFORMAT_HUMAN
) {
3178 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3179 } else if (output_format
== OFORMAT_JSON
) {
3183 length
= blk_getlength(blk
);
3185 error_report("Failed to get size for '%s'", filename
);
3188 if (max_length
!= -1) {
3189 length
= MIN(start_offset
+ max_length
, length
);
3192 curr
.start
= start_offset
;
3193 while (curr
.start
+ curr
.length
< length
) {
3194 int64_t offset
= curr
.start
+ curr
.length
;
3195 int64_t n
= length
- offset
;
3197 ret
= get_block_status(bs
, offset
, n
, &next
);
3199 error_report("Could not read file metadata: %s", strerror(-ret
));
3203 if (entry_mergeable(&curr
, &next
)) {
3204 curr
.length
+= next
.length
;
3208 if (curr
.length
> 0) {
3209 ret
= dump_map_entry(output_format
, &curr
, &next
);
3217 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3218 if (output_format
== OFORMAT_JSON
) {
3227 #define SNAPSHOT_LIST 1
3228 #define SNAPSHOT_CREATE 2
3229 #define SNAPSHOT_APPLY 3
3230 #define SNAPSHOT_DELETE 4
3232 static int img_snapshot(int argc
, char **argv
)
3235 BlockDriverState
*bs
;
3236 QEMUSnapshotInfo sn
;
3237 char *filename
, *snapshot_name
= NULL
;
3238 int c
, ret
= 0, bdrv_oflags
;
3243 bool image_opts
= false;
3244 bool force_share
= false;
3246 bdrv_oflags
= BDRV_O_RDWR
;
3247 /* Parse commandline parameters */
3249 static const struct option long_options
[] = {
3250 {"help", no_argument
, 0, 'h'},
3251 {"object", required_argument
, 0, OPTION_OBJECT
},
3252 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3253 {"force-share", no_argument
, 0, 'U'},
3256 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3257 long_options
, NULL
);
3263 missing_argument(argv
[optind
- 1]);
3266 unrecognized_option(argv
[optind
- 1]);
3273 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3276 action
= SNAPSHOT_LIST
;
3277 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3281 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3284 action
= SNAPSHOT_APPLY
;
3285 snapshot_name
= optarg
;
3289 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3292 action
= SNAPSHOT_CREATE
;
3293 snapshot_name
= optarg
;
3297 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3300 action
= SNAPSHOT_DELETE
;
3301 snapshot_name
= optarg
;
3310 user_creatable_process_cmdline(optarg
);
3312 case OPTION_IMAGE_OPTS
:
3318 if (optind
!= argc
- 1) {
3319 error_exit("Expecting one image file name");
3321 filename
= argv
[optind
++];
3323 /* Open the image */
3324 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3331 /* Perform the requested action */
3337 case SNAPSHOT_CREATE
:
3338 memset(&sn
, 0, sizeof(sn
));
3339 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3341 qemu_gettimeofday(&tv
);
3342 sn
.date_sec
= tv
.tv_sec
;
3343 sn
.date_nsec
= tv
.tv_usec
* 1000;
3345 ret
= bdrv_snapshot_create(bs
, &sn
);
3347 error_report("Could not create snapshot '%s': %d (%s)",
3348 snapshot_name
, ret
, strerror(-ret
));
3352 case SNAPSHOT_APPLY
:
3353 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3355 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3360 case SNAPSHOT_DELETE
:
3361 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3363 error_report("Could not delete snapshot '%s': snapshot not "
3364 "found", snapshot_name
);
3367 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3369 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3385 static int img_rebase(int argc
, char **argv
)
3387 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3388 uint8_t *buf_old
= NULL
;
3389 uint8_t *buf_new
= NULL
;
3390 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3391 BlockDriverState
*unfiltered_bs
;
3393 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3394 int c
, flags
, src_flags
, ret
;
3395 bool writethrough
, src_writethrough
;
3397 bool force_share
= false;
3400 Error
*local_err
= NULL
;
3401 bool image_opts
= false;
3403 /* Parse commandline parameters */
3405 cache
= BDRV_DEFAULT_CACHE
;
3406 src_cache
= BDRV_DEFAULT_CACHE
;
3410 static const struct option long_options
[] = {
3411 {"help", no_argument
, 0, 'h'},
3412 {"object", required_argument
, 0, OPTION_OBJECT
},
3413 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3414 {"force-share", no_argument
, 0, 'U'},
3417 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3418 long_options
, NULL
);
3424 missing_argument(argv
[optind
- 1]);
3427 unrecognized_option(argv
[optind
- 1]);
3436 out_basefmt
= optarg
;
3439 out_baseimg
= optarg
;
3457 user_creatable_process_cmdline(optarg
);
3459 case OPTION_IMAGE_OPTS
:
3472 if (optind
!= argc
- 1) {
3473 error_exit("Expecting one image file name");
3475 if (!unsafe
&& !out_baseimg
) {
3476 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3478 filename
= argv
[optind
++];
3480 qemu_progress_init(progress
, 2.0);
3481 qemu_progress_print(0, 100);
3483 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3484 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3486 error_report("Invalid cache option: %s", cache
);
3491 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3493 error_report("Invalid source cache option: %s", src_cache
);
3497 /* The source files are opened read-only, don't care about WCE */
3498 assert((src_flags
& BDRV_O_RDWR
) == 0);
3499 (void) src_writethrough
;
3504 * Ignore the old backing file for unsafe rebase in case we want to correct
3505 * the reference to a renamed or moved backing file.
3507 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3515 unfiltered_bs
= bdrv_skip_filters(bs
);
3517 if (out_basefmt
!= NULL
) {
3518 if (bdrv_find_format(out_basefmt
) == NULL
) {
3519 error_report("Invalid format name: '%s'", out_basefmt
);
3525 /* For safe rebasing we need to compare old and new backing file */
3527 QDict
*options
= NULL
;
3528 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3531 blk_old_backing
= blk_new(qemu_get_aio_context(),
3532 BLK_PERM_CONSISTENT_READ
,
3534 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3537 error_reportf_err(local_err
,
3538 "Could not reuse old backing file '%s': ",
3543 blk_old_backing
= NULL
;
3546 if (out_baseimg
[0]) {
3547 const char *overlay_filename
;
3548 char *out_real_path
;
3550 options
= qdict_new();
3552 qdict_put_str(options
, "driver", out_basefmt
);
3555 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3558 bdrv_refresh_filename(bs
);
3559 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3562 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3566 qobject_unref(options
);
3567 error_reportf_err(local_err
,
3568 "Could not resolve backing filename: ");
3574 * Find out whether we rebase an image on top of a previous image
3577 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3578 if (prefix_chain_bs
) {
3579 qobject_unref(options
);
3580 g_free(out_real_path
);
3582 blk_new_backing
= blk_new(qemu_get_aio_context(),
3583 BLK_PERM_CONSISTENT_READ
,
3585 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3588 error_reportf_err(local_err
,
3589 "Could not reuse backing file '%s': ",
3594 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3595 options
, src_flags
, &local_err
);
3596 g_free(out_real_path
);
3597 if (!blk_new_backing
) {
3598 error_reportf_err(local_err
,
3599 "Could not open new backing file '%s': ",
3609 * Check each unallocated cluster in the COW file. If it is unallocated,
3610 * accesses go to the backing file. We must therefore compare this cluster
3611 * in the old and new backing file, and if they differ we need to copy it
3612 * from the old backing file into the COW file.
3614 * If qemu-img crashes during this step, no harm is done. The content of
3615 * the image is the same as the original one at any time.
3619 int64_t old_backing_size
= 0;
3620 int64_t new_backing_size
= 0;
3623 float local_progress
= 0;
3625 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3626 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3628 size
= blk_getlength(blk
);
3630 error_report("Could not get size of '%s': %s",
3631 filename
, strerror(-size
));
3635 if (blk_old_backing
) {
3636 old_backing_size
= blk_getlength(blk_old_backing
);
3637 if (old_backing_size
< 0) {
3638 char backing_name
[PATH_MAX
];
3640 bdrv_get_backing_filename(bs
, backing_name
,
3641 sizeof(backing_name
));
3642 error_report("Could not get size of '%s': %s",
3643 backing_name
, strerror(-old_backing_size
));
3648 if (blk_new_backing
) {
3649 new_backing_size
= blk_getlength(blk_new_backing
);
3650 if (new_backing_size
< 0) {
3651 error_report("Could not get size of '%s': %s",
3652 out_baseimg
, strerror(-new_backing_size
));
3659 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3662 for (offset
= 0; offset
< size
; offset
+= n
) {
3663 bool buf_old_is_zero
= false;
3665 /* How many bytes can we handle with the next read? */
3666 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3668 /* If the cluster is allocated, we don't need to take action */
3669 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3671 error_report("error while reading image metadata: %s",
3679 if (prefix_chain_bs
) {
3681 * If cluster wasn't changed since prefix_chain, we don't need
3684 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3685 prefix_chain_bs
, false,
3688 error_report("error while reading image metadata: %s",
3698 * Read old and new backing file and take into consideration that
3699 * backing files may be smaller than the COW image.
3701 if (offset
>= old_backing_size
) {
3702 memset(buf_old
, 0, n
);
3703 buf_old_is_zero
= true;
3705 if (offset
+ n
> old_backing_size
) {
3706 n
= old_backing_size
- offset
;
3709 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3711 error_report("error while reading from old backing file");
3716 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3717 memset(buf_new
, 0, n
);
3719 if (offset
+ n
> new_backing_size
) {
3720 n
= new_backing_size
- offset
;
3723 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3725 error_report("error while reading from new backing file");
3730 /* If they differ, we need to write to the COW file */
3731 uint64_t written
= 0;
3733 while (written
< n
) {
3736 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3737 n
- written
, &pnum
))
3739 if (buf_old_is_zero
) {
3740 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3742 ret
= blk_pwrite(blk
, offset
+ written
,
3743 buf_old
+ written
, pnum
, 0);
3746 error_report("Error while writing to COW image: %s",
3754 qemu_progress_print(local_progress
, 100);
3759 * Change the backing file. All clusters that are different from the old
3760 * backing file are overwritten in the COW file now, so the visible content
3761 * doesn't change when we switch the backing file.
3763 if (out_baseimg
&& *out_baseimg
) {
3764 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3767 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3770 if (ret
== -ENOSPC
) {
3771 error_report("Could not change the backing file to '%s': No "
3772 "space left in the file header", out_baseimg
);
3773 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3774 error_report("Could not change the backing file to '%s': backing "
3775 "format must be specified", out_baseimg
);
3776 } else if (ret
< 0) {
3777 error_report("Could not change the backing file to '%s': %s",
3778 out_baseimg
, strerror(-ret
));
3781 qemu_progress_print(100, 0);
3783 * TODO At this point it is possible to check if any clusters that are
3784 * allocated in the COW file are the same in the backing file. If so, they
3785 * could be dropped from the COW file. Don't do this before switching the
3786 * backing file, in case of a crash this would lead to corruption.
3789 qemu_progress_end();
3792 blk_unref(blk_old_backing
);
3793 blk_unref(blk_new_backing
);
3795 qemu_vfree(buf_old
);
3796 qemu_vfree(buf_new
);
3805 static int img_resize(int argc
, char **argv
)
3808 int c
, ret
, relative
;
3809 const char *filename
, *fmt
, *size
;
3810 int64_t n
, total_size
, current_size
;
3812 BlockBackend
*blk
= NULL
;
3813 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3816 static QemuOptsList resize_options
= {
3817 .name
= "resize_options",
3818 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3821 .name
= BLOCK_OPT_SIZE
,
3822 .type
= QEMU_OPT_SIZE
,
3823 .help
= "Virtual disk size"
3829 bool image_opts
= false;
3830 bool shrink
= false;
3832 /* Remove size from argv manually so that negative numbers are not treated
3833 * as options by getopt. */
3835 error_exit("Not enough arguments");
3839 size
= argv
[--argc
];
3841 /* Parse getopt arguments */
3844 static const struct option long_options
[] = {
3845 {"help", no_argument
, 0, 'h'},
3846 {"object", required_argument
, 0, OPTION_OBJECT
},
3847 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3848 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3849 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3852 c
= getopt_long(argc
, argv
, ":f:hq",
3853 long_options
, NULL
);
3859 missing_argument(argv
[optind
- 1]);
3862 unrecognized_option(argv
[optind
- 1]);
3874 user_creatable_process_cmdline(optarg
);
3876 case OPTION_IMAGE_OPTS
:
3879 case OPTION_PREALLOCATION
:
3880 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3881 PREALLOC_MODE__MAX
, NULL
);
3882 if (prealloc
== PREALLOC_MODE__MAX
) {
3883 error_report("Invalid preallocation mode '%s'", optarg
);
3892 if (optind
!= argc
- 1) {
3893 error_exit("Expecting image file name and size");
3895 filename
= argv
[optind
++];
3897 /* Choose grow, shrink, or absolute resize mode */
3913 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3914 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3915 error_report_err(err
);
3917 qemu_opts_del(param
);
3920 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3921 qemu_opts_del(param
);
3923 blk
= img_open(image_opts
, filename
, fmt
,
3924 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3931 current_size
= blk_getlength(blk
);
3932 if (current_size
< 0) {
3933 error_report("Failed to inquire current image length: %s",
3934 strerror(-current_size
));
3940 total_size
= current_size
+ n
* relative
;
3944 if (total_size
<= 0) {
3945 error_report("New image size must be positive");
3950 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3951 error_report("Preallocation can only be used for growing images");
3956 if (total_size
< current_size
&& !shrink
) {
3957 error_report("Use the --shrink option to perform a shrink operation.");
3958 warn_report("Shrinking an image will delete all data beyond the "
3959 "shrunken image's end. Before performing such an "
3960 "operation, make sure there is no important data there.");
3966 * The user expects the image to have the desired size after
3967 * resizing, so pass @exact=true. It is of no use to report
3968 * success when the image has not actually been resized.
3970 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
3972 qprintf(quiet
, "Image resized.\n");
3974 error_report_err(err
);
3984 static void amend_status_cb(BlockDriverState
*bs
,
3985 int64_t offset
, int64_t total_work_size
,
3988 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3991 static int print_amend_option_help(const char *format
)
3995 /* Find driver and parse its options */
3996 drv
= bdrv_find_format(format
);
3998 error_report("Unknown file format '%s'", format
);
4002 if (!drv
->bdrv_amend_options
) {
4003 error_report("Format driver '%s' does not support option amendment",
4008 /* Every driver supporting amendment must have amend_opts */
4009 assert(drv
->amend_opts
);
4011 printf("Amend options for '%s':\n", format
);
4012 qemu_opts_print_help(drv
->amend_opts
, false);
4016 static int img_amend(int argc
, char **argv
)
4020 char *options
= NULL
;
4021 QemuOptsList
*amend_opts
= NULL
;
4022 QemuOpts
*opts
= NULL
;
4023 const char *fmt
= NULL
, *filename
, *cache
;
4026 bool quiet
= false, progress
= false;
4027 BlockBackend
*blk
= NULL
;
4028 BlockDriverState
*bs
= NULL
;
4029 bool image_opts
= false;
4032 cache
= BDRV_DEFAULT_CACHE
;
4034 static const struct option long_options
[] = {
4035 {"help", no_argument
, 0, 'h'},
4036 {"object", required_argument
, 0, OPTION_OBJECT
},
4037 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4038 {"force", no_argument
, 0, OPTION_FORCE
},
4041 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4042 long_options
, NULL
);
4049 missing_argument(argv
[optind
- 1]);
4052 unrecognized_option(argv
[optind
- 1]);
4058 if (accumulate_options(&options
, optarg
) < 0) {
4060 goto out_no_progress
;
4076 user_creatable_process_cmdline(optarg
);
4078 case OPTION_IMAGE_OPTS
:
4088 error_exit("Must specify options (-o)");
4094 qemu_progress_init(progress
, 1.0);
4096 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4097 if (fmt
&& has_help_option(options
)) {
4098 /* If a format is explicitly specified (and possibly no filename is
4099 * given), print option help here */
4100 ret
= print_amend_option_help(fmt
);
4104 if (optind
!= argc
- 1) {
4105 error_report("Expecting one image file name");
4110 flags
= BDRV_O_RDWR
;
4111 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4113 error_report("Invalid cache option: %s", cache
);
4117 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4125 fmt
= bs
->drv
->format_name
;
4127 if (has_help_option(options
)) {
4128 /* If the format was auto-detected, print option help here */
4129 ret
= print_amend_option_help(fmt
);
4133 if (!bs
->drv
->bdrv_amend_options
) {
4134 error_report("Format driver '%s' does not support option amendment",
4140 /* Every driver supporting amendment must have amend_opts */
4141 assert(bs
->drv
->amend_opts
);
4143 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4144 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4145 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4146 /* Try to parse options using the create options */
4147 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4148 qemu_opts_del(opts
);
4149 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4150 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4151 error_append_hint(&err
,
4152 "This option is only supported for image creation\n");
4155 error_report_err(err
);
4160 /* In case the driver does not call amend_status_cb() */
4161 qemu_progress_print(0.f
, 0);
4162 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4163 qemu_progress_print(100.f
, 0);
4165 error_report_err(err
);
4170 qemu_progress_end();
4174 qemu_opts_del(opts
);
4175 qemu_opts_free(amend_opts
);
4184 typedef struct BenchData
{
4186 uint64_t image_size
;
4193 bool drain_on_flush
;
4202 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4205 error_report("Failed flush request: %s", strerror(-ret
));
4210 static void bench_cb(void *opaque
, int ret
)
4212 BenchData
*b
= opaque
;
4216 error_report("Failed request: %s", strerror(-ret
));
4221 /* Just finished a flush with drained queue: Start next requests */
4222 assert(b
->in_flight
== 0);
4223 b
->in_flush
= false;
4224 } else if (b
->in_flight
> 0) {
4225 int remaining
= b
->n
- b
->in_flight
;
4230 /* Time for flush? Drain queue if requested, then flush */
4231 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4232 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4233 BlockCompletionFunc
*cb
;
4235 if (b
->drain_on_flush
) {
4239 cb
= bench_undrained_flush_cb
;
4242 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4244 error_report("Failed to issue flush request");
4248 if (b
->drain_on_flush
) {
4254 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4255 int64_t offset
= b
->offset
;
4256 /* blk_aio_* might look for completed I/Os and kick bench_cb
4257 * again, so make sure this operation is counted by in_flight
4258 * and b->offset is ready for the next submission.
4261 b
->offset
+= b
->step
;
4262 b
->offset
%= b
->image_size
;
4264 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4266 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4269 error_report("Failed to issue request");
4275 static int img_bench(int argc
, char **argv
)
4278 const char *fmt
= NULL
, *filename
;
4280 bool image_opts
= false;
4281 bool is_write
= false;
4285 size_t bufsize
= 4096;
4288 int flush_interval
= 0;
4289 bool drain_on_flush
= true;
4291 BlockBackend
*blk
= NULL
;
4292 BenchData data
= {};
4294 bool writethrough
= false;
4295 struct timeval t1
, t2
;
4297 bool force_share
= false;
4301 static const struct option long_options
[] = {
4302 {"help", no_argument
, 0, 'h'},
4303 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4304 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4305 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4306 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4307 {"force-share", no_argument
, 0, 'U'},
4310 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4318 missing_argument(argv
[optind
- 1]);
4321 unrecognized_option(argv
[optind
- 1]);
4330 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4331 error_report("Invalid request count specified");
4341 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4342 error_report("Invalid queue depth specified");
4352 flags
|= BDRV_O_NATIVE_AIO
;
4355 ret
= bdrv_parse_aio(optarg
, &flags
);
4357 error_report("Invalid aio option: %s", optarg
);
4364 offset
= cvtnum("offset", optarg
);
4378 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4390 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4399 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4401 error_report("Invalid cache mode");
4407 flags
|= BDRV_O_RDWR
;
4413 case OPTION_PATTERN
:
4417 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4418 error_report("Invalid pattern byte specified");
4424 case OPTION_FLUSH_INTERVAL
:
4428 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4429 error_report("Invalid flush interval specified");
4432 flush_interval
= res
;
4435 case OPTION_NO_DRAIN
:
4436 drain_on_flush
= false;
4438 case OPTION_IMAGE_OPTS
:
4444 if (optind
!= argc
- 1) {
4445 error_exit("Expecting one image file name");
4447 filename
= argv
[argc
- 1];
4449 if (!is_write
&& flush_interval
) {
4450 error_report("--flush-interval is only available in write tests");
4454 if (flush_interval
&& flush_interval
< depth
) {
4455 error_report("Flush interval can't be smaller than depth");
4460 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4467 image_size
= blk_getlength(blk
);
4468 if (image_size
< 0) {
4473 data
= (BenchData
) {
4475 .image_size
= image_size
,
4477 .step
= step
?: bufsize
,
4482 .flush_interval
= flush_interval
,
4483 .drain_on_flush
= drain_on_flush
,
4485 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4486 "(starting at offset %" PRId64
", step size %d)\n",
4487 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4488 data
.offset
, data
.step
);
4489 if (flush_interval
) {
4490 printf("Sending flush every %d requests\n", flush_interval
);
4493 buf_size
= data
.nrreq
* data
.bufsize
;
4494 data
.buf
= blk_blockalign(blk
, buf_size
);
4495 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4497 blk_register_buf(blk
, data
.buf
, buf_size
);
4499 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4500 for (i
= 0; i
< data
.nrreq
; i
++) {
4501 qemu_iovec_init(&data
.qiov
[i
], 1);
4502 qemu_iovec_add(&data
.qiov
[i
],
4503 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4506 gettimeofday(&t1
, NULL
);
4509 while (data
.n
> 0) {
4510 main_loop_wait(false);
4512 gettimeofday(&t2
, NULL
);
4514 printf("Run completed in %3.3f seconds.\n",
4515 (t2
.tv_sec
- t1
.tv_sec
)
4516 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4520 blk_unregister_buf(blk
, data
.buf
);
4522 qemu_vfree(data
.buf
);
4539 typedef struct ImgBitmapAction
{
4540 enum ImgBitmapAct act
;
4541 const char *src
; /* only used for merge */
4542 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4545 static int img_bitmap(int argc
, char **argv
)
4549 QemuOpts
*opts
= NULL
;
4550 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4551 const char *filename
, *bitmap
;
4552 BlockBackend
*blk
= NULL
, *src
= NULL
;
4553 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4554 bool image_opts
= false;
4555 int64_t granularity
= 0;
4556 bool add
= false, merge
= false;
4557 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4558 ImgBitmapAction
*act
, *act_next
;
4561 QSIMPLEQ_INIT(&actions
);
4564 static const struct option long_options
[] = {
4565 {"help", no_argument
, 0, 'h'},
4566 {"object", required_argument
, 0, OPTION_OBJECT
},
4567 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4568 {"add", no_argument
, 0, OPTION_ADD
},
4569 {"remove", no_argument
, 0, OPTION_REMOVE
},
4570 {"clear", no_argument
, 0, OPTION_CLEAR
},
4571 {"enable", no_argument
, 0, OPTION_ENABLE
},
4572 {"disable", no_argument
, 0, OPTION_DISABLE
},
4573 {"merge", required_argument
, 0, OPTION_MERGE
},
4574 {"granularity", required_argument
, 0, 'g'},
4575 {"source-file", required_argument
, 0, 'b'},
4576 {"source-format", required_argument
, 0, 'F'},
4579 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4586 missing_argument(argv
[optind
- 1]);
4589 unrecognized_option(argv
[optind
- 1]);
4595 src_filename
= optarg
;
4604 granularity
= cvtnum("granularity", optarg
);
4605 if (granularity
< 0) {
4610 act
= g_new0(ImgBitmapAction
, 1);
4611 act
->act
= BITMAP_ADD
;
4612 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4616 act
= g_new0(ImgBitmapAction
, 1);
4617 act
->act
= BITMAP_REMOVE
;
4618 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4621 act
= g_new0(ImgBitmapAction
, 1);
4622 act
->act
= BITMAP_CLEAR
;
4623 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4626 act
= g_new0(ImgBitmapAction
, 1);
4627 act
->act
= BITMAP_ENABLE
;
4628 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4630 case OPTION_DISABLE
:
4631 act
= g_new0(ImgBitmapAction
, 1);
4632 act
->act
= BITMAP_DISABLE
;
4633 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4636 act
= g_new0(ImgBitmapAction
, 1);
4637 act
->act
= BITMAP_MERGE
;
4639 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4643 user_creatable_process_cmdline(optarg
);
4645 case OPTION_IMAGE_OPTS
:
4651 if (QSIMPLEQ_EMPTY(&actions
)) {
4652 error_report("Need at least one of --add, --remove, --clear, "
4653 "--enable, --disable, or --merge");
4657 if (granularity
&& !add
) {
4658 error_report("granularity only supported with --add");
4661 if (src_fmt
&& !src_filename
) {
4662 error_report("-F only supported with -b");
4665 if (src_filename
&& !merge
) {
4666 error_report("Merge bitmap source file only supported with "
4671 if (optind
!= argc
- 2) {
4672 error_report("Expecting filename and bitmap name");
4676 filename
= argv
[optind
];
4677 bitmap
= argv
[optind
+ 1];
4680 * No need to open backing chains; we will be manipulating bitmaps
4681 * directly in this image without reference to image contents.
4683 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4684 false, false, false);
4690 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4691 false, false, false);
4695 src_bs
= blk_bs(src
);
4700 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4703 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4704 !!granularity
, granularity
, true, true,
4705 false, false, &err
);
4709 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4713 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4717 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4720 case BITMAP_DISABLE
:
4721 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4725 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4730 g_assert_not_reached();
4734 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4746 qemu_opts_del(opts
);
4762 int bsz
; /* Block size */
4770 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4774 static int img_dd_bs(const char *arg
,
4775 struct DdIo
*in
, struct DdIo
*out
,
4780 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4785 in
->bsz
= out
->bsz
= res
;
4790 static int img_dd_count(const char *arg
,
4791 struct DdIo
*in
, struct DdIo
*out
,
4794 dd
->count
= cvtnum("count", arg
);
4796 if (dd
->count
< 0) {
4803 static int img_dd_if(const char *arg
,
4804 struct DdIo
*in
, struct DdIo
*out
,
4807 in
->filename
= g_strdup(arg
);
4812 static int img_dd_of(const char *arg
,
4813 struct DdIo
*in
, struct DdIo
*out
,
4816 out
->filename
= g_strdup(arg
);
4821 static int img_dd_skip(const char *arg
,
4822 struct DdIo
*in
, struct DdIo
*out
,
4825 in
->offset
= cvtnum("skip", arg
);
4827 if (in
->offset
< 0) {
4834 static int img_dd(int argc
, char **argv
)
4839 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4840 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4841 QemuOpts
*opts
= NULL
;
4842 QemuOptsList
*create_opts
= NULL
;
4843 Error
*local_err
= NULL
;
4844 bool image_opts
= false;
4846 const char *out_fmt
= "raw";
4847 const char *fmt
= NULL
;
4849 int64_t block_count
= 0, out_pos
, in_pos
;
4850 bool force_share
= false;
4851 struct DdInfo dd
= {
4856 .bsz
= 512, /* Block size is by default 512 bytes */
4868 const struct DdOpts options
[] = {
4869 { "bs", img_dd_bs
, C_BS
},
4870 { "count", img_dd_count
, C_COUNT
},
4871 { "if", img_dd_if
, C_IF
},
4872 { "of", img_dd_of
, C_OF
},
4873 { "skip", img_dd_skip
, C_SKIP
},
4876 const struct option long_options
[] = {
4877 { "help", no_argument
, 0, 'h'},
4878 { "object", required_argument
, 0, OPTION_OBJECT
},
4879 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4880 { "force-share", no_argument
, 0, 'U'},
4884 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4896 missing_argument(argv
[optind
- 1]);
4899 unrecognized_option(argv
[optind
- 1]);
4908 user_creatable_process_cmdline(optarg
);
4910 case OPTION_IMAGE_OPTS
:
4916 for (i
= optind
; i
< argc
; i
++) {
4918 arg
= g_strdup(argv
[i
]);
4920 tmp
= strchr(arg
, '=');
4922 error_report("unrecognized operand %s", arg
);
4929 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4930 if (!strcmp(arg
, options
[j
].name
)) {
4934 if (options
[j
].name
== NULL
) {
4935 error_report("unrecognized operand %s", arg
);
4940 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4944 dd
.flags
|= options
[j
].flag
;
4949 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4950 error_report("Must specify both input and output files");
4955 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4963 drv
= bdrv_find_format(out_fmt
);
4965 error_report("Unknown file format");
4969 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4972 error_report_err(local_err
);
4976 if (!drv
->create_opts
) {
4977 error_report("Format driver '%s' does not support image creation",
4982 if (!proto_drv
->create_opts
) {
4983 error_report("Protocol driver '%s' does not support image creation",
4984 proto_drv
->format_name
);
4988 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4989 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4991 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4993 size
= blk_getlength(blk1
);
4995 error_report("Failed to get size for '%s'", in
.filename
);
5000 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5001 dd
.count
* in
.bsz
< size
) {
5002 size
= dd
.count
* in
.bsz
;
5005 /* Overflow means the specified offset is beyond input image's size */
5006 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5007 size
< in
.bsz
* in
.offset
)) {
5008 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5010 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5011 size
- in
.bsz
* in
.offset
, &error_abort
);
5014 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5016 error_reportf_err(local_err
,
5017 "%s: error while creating output image: ",
5023 /* TODO, we can't honour --image-opts for the target,
5024 * since it needs to be given in a format compatible
5025 * with the bdrv_create() call above which does not
5026 * support image-opts style.
5028 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5029 false, false, false);
5036 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5037 size
< in
.offset
* in
.bsz
)) {
5038 /* We give a warning if the skip option is bigger than the input
5039 * size and create an empty output disk image (i.e. like dd(1)).
5041 error_report("%s: cannot skip to specified offset", in
.filename
);
5044 in_pos
= in
.offset
* in
.bsz
;
5047 in
.buf
= g_new(uint8_t, in
.bsz
);
5049 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5050 int in_ret
, out_ret
;
5052 if (in_pos
+ in
.bsz
> size
) {
5053 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5055 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5058 error_report("error while reading from input image file: %s",
5065 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5068 error_report("error while writing to output image file: %s",
5069 strerror(-out_ret
));
5078 qemu_opts_del(opts
);
5079 qemu_opts_free(create_opts
);
5082 g_free(in
.filename
);
5083 g_free(out
.filename
);
5093 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5097 Visitor
*v
= qobject_output_visitor_new(&obj
);
5099 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5100 visit_complete(v
, &obj
);
5101 str
= qobject_to_json_pretty(obj
, true);
5102 assert(str
!= NULL
);
5103 printf("%s\n", str
->str
);
5106 g_string_free(str
, true);
5109 static int img_measure(int argc
, char **argv
)
5111 static const struct option long_options
[] = {
5112 {"help", no_argument
, 0, 'h'},
5113 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5114 {"object", required_argument
, 0, OPTION_OBJECT
},
5115 {"output", required_argument
, 0, OPTION_OUTPUT
},
5116 {"size", required_argument
, 0, OPTION_SIZE
},
5117 {"force-share", no_argument
, 0, 'U'},
5120 OutputFormat output_format
= OFORMAT_HUMAN
;
5121 BlockBackend
*in_blk
= NULL
;
5123 const char *filename
= NULL
;
5124 const char *fmt
= NULL
;
5125 const char *out_fmt
= "raw";
5126 char *options
= NULL
;
5127 char *snapshot_name
= NULL
;
5128 bool force_share
= false;
5129 QemuOpts
*opts
= NULL
;
5130 QemuOpts
*object_opts
= NULL
;
5131 QemuOpts
*sn_opts
= NULL
;
5132 QemuOptsList
*create_opts
= NULL
;
5133 bool image_opts
= false;
5134 uint64_t img_size
= UINT64_MAX
;
5135 BlockMeasureInfo
*info
= NULL
;
5136 Error
*local_err
= NULL
;
5140 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5141 long_options
, NULL
)) != -1) {
5154 if (accumulate_options(&options
, optarg
) < 0) {
5159 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5160 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5163 error_report("Failed in parsing snapshot param '%s'",
5168 snapshot_name
= optarg
;
5175 user_creatable_process_cmdline(optarg
);
5177 case OPTION_IMAGE_OPTS
:
5181 if (!strcmp(optarg
, "json")) {
5182 output_format
= OFORMAT_JSON
;
5183 } else if (!strcmp(optarg
, "human")) {
5184 output_format
= OFORMAT_HUMAN
;
5186 error_report("--output must be used with human or json "
5195 sval
= cvtnum("image size", optarg
);
5199 img_size
= (uint64_t)sval
;
5205 if (argc
- optind
> 1) {
5206 error_report("At most one filename argument is allowed.");
5208 } else if (argc
- optind
== 1) {
5209 filename
= argv
[optind
];
5212 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5213 error_report("--image-opts, -f, and -l require a filename argument.");
5216 if (filename
&& img_size
!= UINT64_MAX
) {
5217 error_report("--size N cannot be used together with a filename.");
5220 if (!filename
&& img_size
== UINT64_MAX
) {
5221 error_report("Either --size N or one filename must be specified.");
5226 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5227 false, false, force_share
);
5233 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5234 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5235 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5237 } else if (snapshot_name
!= NULL
) {
5238 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5239 snapshot_name
, &local_err
);
5242 error_reportf_err(local_err
, "Failed to load snapshot: ");
5247 drv
= bdrv_find_format(out_fmt
);
5249 error_report("Unknown file format '%s'", out_fmt
);
5252 if (!drv
->create_opts
) {
5253 error_report("Format driver '%s' does not support image creation",
5258 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5259 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5260 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5262 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5263 error_report_err(local_err
);
5264 error_report("Invalid options for file format '%s'", out_fmt
);
5268 if (img_size
!= UINT64_MAX
) {
5269 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5272 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5274 error_report_err(local_err
);
5278 if (output_format
== OFORMAT_HUMAN
) {
5279 printf("required size: %" PRIu64
"\n", info
->required
);
5280 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5281 if (info
->has_bitmaps
) {
5282 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5285 dump_json_block_measure_info(info
);
5291 qapi_free_BlockMeasureInfo(info
);
5292 qemu_opts_del(object_opts
);
5293 qemu_opts_del(opts
);
5294 qemu_opts_del(sn_opts
);
5295 qemu_opts_free(create_opts
);
5301 static const img_cmd_t img_cmds
[] = {
5302 #define DEF(option, callback, arg_string) \
5303 { option, callback },
5304 #include "qemu-img-cmds.h"
5309 int main(int argc
, char **argv
)
5311 const img_cmd_t
*cmd
;
5312 const char *cmdname
;
5313 Error
*local_error
= NULL
;
5315 static const struct option long_options
[] = {
5316 {"help", no_argument
, 0, 'h'},
5317 {"version", no_argument
, 0, 'V'},
5318 {"trace", required_argument
, NULL
, 'T'},
5323 signal(SIGPIPE
, SIG_IGN
);
5327 error_init(argv
[0]);
5328 module_call_init(MODULE_INIT_TRACE
);
5329 qemu_init_exec_dir(argv
[0]);
5331 if (qemu_init_main_loop(&local_error
)) {
5332 error_report_err(local_error
);
5336 qcrypto_init(&error_fatal
);
5338 module_call_init(MODULE_INIT_QOM
);
5341 error_exit("Not enough arguments");
5344 qemu_add_opts(&qemu_source_opts
);
5345 qemu_add_opts(&qemu_trace_opts
);
5347 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5350 missing_argument(argv
[optind
- 1]);
5353 unrecognized_option(argv
[optind
- 1]);
5359 printf(QEMU_IMG_VERSION
);
5362 trace_opt_parse(optarg
);
5367 cmdname
= argv
[optind
];
5369 /* reset getopt_long scanning */
5375 qemu_reset_optind();
5377 if (!trace_init_backends()) {
5381 qemu_set_log(LOG_TRACE
);
5383 /* find the command */
5384 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5385 if (!strcmp(cmdname
, cmd
->name
)) {
5386 return cmd
->handler(argc
, argv
);
5391 error_exit("Command not found: %s", cmdname
);