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 "qemu/memalign.h"
46 #include "qom/object_interfaces.h"
47 #include "sysemu/block-backend.h"
48 #include "block/block_int.h"
49 #include "block/blockjob.h"
50 #include "block/qapi.h"
51 #include "crypto/init.h"
52 #include "trace/control.h"
53 #include "qemu/throttle.h"
54 #include "block/throttle-groups.h"
56 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
57 "\n" QEMU_COPYRIGHT "\n"
59 typedef struct img_cmd_t
{
61 int (*handler
)(int argc
, char **argv
);
66 OPTION_BACKING_CHAIN
= 257,
68 OPTION_IMAGE_OPTS
= 259,
70 OPTION_FLUSH_INTERVAL
= 261,
71 OPTION_NO_DRAIN
= 262,
72 OPTION_TARGET_IMAGE_OPTS
= 263,
74 OPTION_PREALLOCATION
= 265,
77 OPTION_TARGET_IS_ZERO
= 268,
86 OPTION_SKIP_BROKEN
= 277,
89 typedef enum OutputFormat
{
94 /* Default to cache=writeback as data integrity is not important for qemu-img */
95 #define BDRV_DEFAULT_CACHE "writeback"
97 static void format_print(void *opaque
, const char *name
)
102 static void QEMU_NORETURN
G_GNUC_PRINTF(1, 2) error_exit(const char *fmt
, ...)
107 error_vreport(fmt
, ap
);
110 error_printf("Try 'qemu-img --help' for more information\n");
114 static void QEMU_NORETURN
missing_argument(const char *option
)
116 error_exit("missing argument for option '%s'", option
);
119 static void QEMU_NORETURN
unrecognized_option(const char *option
)
121 error_exit("unrecognized option '%s'", option
);
124 /* Please keep in synch with docs/tools/qemu-img.rst */
125 static void QEMU_NORETURN
help(void)
127 const char *help_msg
=
129 "usage: qemu-img [standard options] command [command options]\n"
130 "QEMU disk image utility\n"
132 " '-h', '--help' display this help and exit\n"
133 " '-V', '--version' output version information and exit\n"
134 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
135 " specify tracing options\n"
138 #define DEF(option, callback, arg_string) \
140 #include "qemu-img-cmds.h"
143 "Command parameters:\n"
144 " 'filename' is a disk image filename\n"
145 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
146 " manual page for a description of the object properties. The most common\n"
147 " object type is a 'secret', which is used to supply passwords and/or\n"
148 " encryption keys.\n"
149 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
150 " 'cache' is the cache mode used to write the output disk image, the valid\n"
151 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
152 " 'directsync' and 'unsafe' (default for convert)\n"
153 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
154 " options are the same as for the 'cache' option\n"
155 " 'size' is the disk image size in bytes. Optional suffixes\n"
156 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
157 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
158 " supported. 'b' is ignored.\n"
159 " 'output_filename' is the destination disk image filename\n"
160 " 'output_fmt' is the destination format\n"
161 " 'options' is a comma separated list of format specific options in a\n"
162 " name=value format. Use -o ? for an overview of the options supported by the\n"
164 " 'snapshot_param' is param used for internal snapshot, format\n"
165 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
167 " '-c' indicates that target image must be compressed (qcow format only)\n"
168 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
169 " new backing file match exactly. The image doesn't need a working\n"
170 " backing file before rebasing in this case (useful for renaming the\n"
171 " backing file). For image creation, allow creating without attempting\n"
172 " to open the backing file.\n"
173 " '-h' with or without a command shows this help and lists the supported formats\n"
174 " '-p' show progress of command (only certain commands)\n"
175 " '-q' use Quiet mode - do not print any output (except errors)\n"
176 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
177 " contain only zeros for qemu-img to create a sparse image during\n"
178 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
179 " unallocated or zero sectors, and the destination image will always be\n"
181 " '--output' takes the format in which the output must be done (human or json)\n"
182 " '-n' skips the target volume creation (useful if the volume is created\n"
183 " prior to running qemu-img)\n"
185 "Parameters to bitmap subcommand:\n"
186 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
187 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
188 " or '--merge source'\n"
189 " '-g granularity' sets the granularity for '--add' actions\n"
190 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
191 " bitmaps from an alternative file\n"
193 "Parameters to check subcommand:\n"
194 " '-r' tries to repair any inconsistencies that are found during the check.\n"
195 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
196 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
197 " hiding corruption that has already occurred.\n"
199 "Parameters to convert subcommand:\n"
200 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
201 " '-m' specifies how many coroutines work in parallel during the convert\n"
202 " process (defaults to 8)\n"
203 " '-W' allow to write to the target out of order rather than sequential\n"
205 "Parameters to snapshot subcommand:\n"
206 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
207 " '-a' applies a snapshot (revert disk to saved state)\n"
208 " '-c' creates a snapshot\n"
209 " '-d' deletes a snapshot\n"
210 " '-l' lists all snapshots in the given image\n"
212 "Parameters to compare subcommand:\n"
213 " '-f' first image format\n"
214 " '-F' second image format\n"
215 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
217 "Parameters to dd subcommand:\n"
218 " 'bs=BYTES' read and write up to BYTES bytes at a time "
220 " 'count=N' copy only N input blocks\n"
221 " 'if=FILE' read from FILE\n"
222 " 'of=FILE' write to FILE\n"
223 " 'skip=N' skip N bs-sized blocks at the start of input\n";
225 printf("%s\nSupported formats:", help_msg
);
226 bdrv_iterate_format(format_print
, NULL
, false);
227 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
232 * Is @optarg safe for accumulate_options()?
233 * It is when multiple of them can be joined together separated by ','.
234 * To make that work, @optarg must not start with ',' (or else a
235 * separating ',' preceding it gets escaped), and it must not end with
236 * an odd number of ',' (or else a separating ',' following it gets
237 * escaped), or be empty (or else a separating ',' preceding it can
238 * escape a separating ',' following it).
241 static bool is_valid_option_list(const char *optarg
)
243 size_t len
= strlen(optarg
);
246 if (!optarg
[0] || optarg
[0] == ',') {
250 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
259 static int accumulate_options(char **options
, char *optarg
)
263 if (!is_valid_option_list(optarg
)) {
264 error_report("Invalid option list: %s", optarg
);
269 *options
= g_strdup(optarg
);
271 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
273 *options
= new_options
;
278 static QemuOptsList qemu_source_opts
= {
280 .implied_opt_name
= "file",
281 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
287 static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
293 ret
= vprintf(fmt
, args
);
300 static int print_block_option_help(const char *filename
, const char *fmt
)
302 BlockDriver
*drv
, *proto_drv
;
303 QemuOptsList
*create_opts
= NULL
;
304 Error
*local_err
= NULL
;
306 /* Find driver and parse its options */
307 drv
= bdrv_find_format(fmt
);
309 error_report("Unknown file format '%s'", fmt
);
313 if (!drv
->create_opts
) {
314 error_report("Format driver '%s' does not support image creation", fmt
);
318 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
320 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
322 error_report_err(local_err
);
323 qemu_opts_free(create_opts
);
326 if (!proto_drv
->create_opts
) {
327 error_report("Protocol driver '%s' does not support image creation",
328 proto_drv
->format_name
);
329 qemu_opts_free(create_opts
);
332 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
336 printf("Supported options:\n");
338 printf("Supported %s options:\n", fmt
);
340 qemu_opts_print_help(create_opts
, false);
341 qemu_opts_free(create_opts
);
345 "The protocol level may support further options.\n"
346 "Specify the target filename to include those options.\n");
353 static BlockBackend
*img_open_opts(const char *optstr
,
354 QemuOpts
*opts
, int flags
, bool writethrough
,
355 bool quiet
, bool force_share
)
358 Error
*local_err
= NULL
;
360 options
= qemu_opts_to_qdict(opts
, NULL
);
362 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
363 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
364 error_report("--force-share/-U conflicts with image options");
365 qobject_unref(options
);
368 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
370 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
372 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
375 blk_set_enable_write_cache(blk
, !writethrough
);
380 static BlockBackend
*img_open_file(const char *filename
,
382 const char *fmt
, int flags
,
383 bool writethrough
, bool quiet
,
387 Error
*local_err
= NULL
;
390 options
= qdict_new();
393 qdict_put_str(options
, "driver", fmt
);
397 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
399 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
401 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
404 blk_set_enable_write_cache(blk
, !writethrough
);
410 static int img_add_key_secrets(void *opaque
,
411 const char *name
, const char *value
,
414 QDict
*options
= opaque
;
416 if (g_str_has_suffix(name
, "key-secret")) {
417 qdict_put_str(options
, name
, value
);
424 static BlockBackend
*img_open(bool image_opts
,
425 const char *filename
,
426 const char *fmt
, int flags
, bool writethrough
,
427 bool quiet
, bool force_share
)
433 error_report("--image-opts and --format are mutually exclusive");
436 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
441 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
444 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
451 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
452 const char *base_filename
,
453 const char *base_fmt
)
456 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
458 error_report("Backing file not supported for file format '%s'",
464 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
465 error_report("Backing file format not supported for file "
473 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
479 err
= qemu_strtosz(value
, NULL
, &res
);
480 if (err
< 0 && err
!= -ERANGE
) {
481 error_report("Invalid %s specified. You may use "
482 "k, M, G, T, P or E suffixes for", name
);
483 error_report("kilobytes, megabytes, gigabytes, terabytes, "
484 "petabytes and exabytes.");
487 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
488 error_report("Invalid %s specified. Must be between %" PRId64
489 " and %" PRId64
".", name
, min
, max
);
495 static int64_t cvtnum(const char *name
, const char *value
)
497 return cvtnum_full(name
, value
, 0, INT64_MAX
);
500 static int img_create(int argc
, char **argv
)
503 uint64_t img_size
= -1;
504 const char *fmt
= "raw";
505 const char *base_fmt
= NULL
;
506 const char *filename
;
507 const char *base_filename
= NULL
;
508 char *options
= NULL
;
509 Error
*local_err
= NULL
;
514 static const struct option long_options
[] = {
515 {"help", no_argument
, 0, 'h'},
516 {"object", required_argument
, 0, OPTION_OBJECT
},
519 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
526 missing_argument(argv
[optind
- 1]);
529 unrecognized_option(argv
[optind
- 1]);
538 base_filename
= optarg
;
544 if (accumulate_options(&options
, optarg
) < 0) {
552 flags
|= BDRV_O_NO_BACKING
;
555 user_creatable_process_cmdline(optarg
);
560 /* Get the filename */
561 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
562 if (options
&& has_help_option(options
)) {
564 return print_block_option_help(filename
, fmt
);
567 if (optind
>= argc
) {
568 error_exit("Expecting image file name");
572 /* Get image size, if specified */
576 sval
= cvtnum("image size", argv
[optind
++]);
580 img_size
= (uint64_t)sval
;
582 if (optind
!= argc
) {
583 error_exit("Unexpected argument: %s", argv
[optind
]);
586 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
587 options
, img_size
, flags
, quiet
, &local_err
);
589 error_reportf_err(local_err
, "%s: ", filename
);
601 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
605 Visitor
*v
= qobject_output_visitor_new(&obj
);
607 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
608 visit_complete(v
, &obj
);
609 str
= qobject_to_json_pretty(obj
, true);
611 qprintf(quiet
, "%s\n", str
->str
);
614 g_string_free(str
, true);
617 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
619 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
620 qprintf(quiet
, "No errors were found on the image.\n");
622 if (check
->corruptions
) {
623 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
624 "Data may be corrupted, or further writes to the image "
631 "\n%" PRId64
" leaked clusters were found on the image.\n"
632 "This means waste of disk space, but no harm to data.\n",
636 if (check
->check_errors
) {
639 " internal errors have occurred during the check.\n",
640 check
->check_errors
);
644 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
645 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
646 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
647 check
->allocated_clusters
, check
->total_clusters
,
648 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
649 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
650 check
->compressed_clusters
* 100.0 /
651 check
->allocated_clusters
);
654 if (check
->image_end_offset
) {
656 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
660 static int collect_image_check(BlockDriverState
*bs
,
662 const char *filename
,
667 BdrvCheckResult result
;
669 ret
= bdrv_check(bs
, &result
, fix
);
674 check
->filename
= g_strdup(filename
);
675 check
->format
= g_strdup(bdrv_get_format_name(bs
));
676 check
->check_errors
= result
.check_errors
;
677 check
->corruptions
= result
.corruptions
;
678 check
->has_corruptions
= result
.corruptions
!= 0;
679 check
->leaks
= result
.leaks
;
680 check
->has_leaks
= result
.leaks
!= 0;
681 check
->corruptions_fixed
= result
.corruptions_fixed
;
682 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
683 check
->leaks_fixed
= result
.leaks_fixed
;
684 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
685 check
->image_end_offset
= result
.image_end_offset
;
686 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
687 check
->total_clusters
= result
.bfi
.total_clusters
;
688 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
689 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
690 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
691 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
692 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
693 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
694 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
700 * Checks an image for consistency. Exit codes:
702 * 0 - Check completed, image is good
703 * 1 - Check not completed because of internal errors
704 * 2 - Check completed, image is corrupted
705 * 3 - Check completed, image has leaked clusters, but is good otherwise
706 * 63 - Checks are not supported by the image format
708 static int img_check(int argc
, char **argv
)
711 OutputFormat output_format
= OFORMAT_HUMAN
;
712 const char *filename
, *fmt
, *output
, *cache
;
714 BlockDriverState
*bs
;
716 int flags
= BDRV_O_CHECK
;
720 bool image_opts
= false;
721 bool force_share
= false;
725 cache
= BDRV_DEFAULT_CACHE
;
728 int option_index
= 0;
729 static const struct option long_options
[] = {
730 {"help", no_argument
, 0, 'h'},
731 {"format", required_argument
, 0, 'f'},
732 {"repair", required_argument
, 0, 'r'},
733 {"output", required_argument
, 0, OPTION_OUTPUT
},
734 {"object", required_argument
, 0, OPTION_OBJECT
},
735 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
736 {"force-share", no_argument
, 0, 'U'},
739 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
740 long_options
, &option_index
);
746 missing_argument(argv
[optind
- 1]);
749 unrecognized_option(argv
[optind
- 1]);
758 flags
|= BDRV_O_RDWR
;
760 if (!strcmp(optarg
, "leaks")) {
761 fix
= BDRV_FIX_LEAKS
;
762 } else if (!strcmp(optarg
, "all")) {
763 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
765 error_exit("Unknown option value for -r "
766 "(expecting 'leaks' or 'all'): %s", optarg
);
782 user_creatable_process_cmdline(optarg
);
784 case OPTION_IMAGE_OPTS
:
789 if (optind
!= argc
- 1) {
790 error_exit("Expecting one image file name");
792 filename
= argv
[optind
++];
794 if (output
&& !strcmp(output
, "json")) {
795 output_format
= OFORMAT_JSON
;
796 } else if (output
&& !strcmp(output
, "human")) {
797 output_format
= OFORMAT_HUMAN
;
799 error_report("--output must be used with human or json as argument.");
803 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
805 error_report("Invalid source cache option: %s", cache
);
809 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
816 check
= g_new0(ImageCheck
, 1);
817 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
819 if (ret
== -ENOTSUP
) {
820 error_report("This image format does not support checks");
825 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
826 int corruptions_fixed
, leaks_fixed
;
827 bool has_leaks_fixed
, has_corruptions_fixed
;
829 leaks_fixed
= check
->leaks_fixed
;
830 has_leaks_fixed
= check
->has_leaks_fixed
;
831 corruptions_fixed
= check
->corruptions_fixed
;
832 has_corruptions_fixed
= check
->has_corruptions_fixed
;
834 if (output_format
== OFORMAT_HUMAN
) {
836 "The following inconsistencies were found and repaired:\n\n"
837 " %" PRId64
" leaked clusters\n"
838 " %" PRId64
" corruptions\n\n"
839 "Double checking the fixed image now...\n",
841 check
->corruptions_fixed
);
844 qapi_free_ImageCheck(check
);
845 check
= g_new0(ImageCheck
, 1);
846 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
848 check
->leaks_fixed
= leaks_fixed
;
849 check
->has_leaks_fixed
= has_leaks_fixed
;
850 check
->corruptions_fixed
= corruptions_fixed
;
851 check
->has_corruptions_fixed
= has_corruptions_fixed
;
855 switch (output_format
) {
857 dump_human_image_check(check
, quiet
);
860 dump_json_image_check(check
, quiet
);
865 if (ret
|| check
->check_errors
) {
867 error_report("Check failed: %s", strerror(-ret
));
869 error_report("Check failed");
875 if (check
->corruptions
) {
877 } else if (check
->leaks
) {
884 qapi_free_ImageCheck(check
);
889 typedef struct CommonBlockJobCBInfo
{
890 BlockDriverState
*bs
;
892 } CommonBlockJobCBInfo
;
894 static void common_block_job_cb(void *opaque
, int ret
)
896 CommonBlockJobCBInfo
*cbi
= opaque
;
899 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
903 static void run_block_job(BlockJob
*job
, Error
**errp
)
905 uint64_t progress_current
, progress_total
;
906 AioContext
*aio_context
= block_job_get_aio_context(job
);
909 aio_context_acquire(aio_context
);
912 float progress
= 0.0f
;
913 aio_poll(aio_context
, true);
915 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
917 if (progress_total
) {
918 progress
= (float)progress_current
/ progress_total
* 100.f
;
920 qemu_progress_print(progress
, 0);
921 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
923 if (!job_is_completed(&job
->job
)) {
924 ret
= job_complete_sync(&job
->job
, errp
);
928 job_unref(&job
->job
);
929 aio_context_release(aio_context
);
931 /* publish completion progress only when success */
933 qemu_progress_print(100.f
, 0);
937 static int img_commit(int argc
, char **argv
)
940 const char *filename
, *fmt
, *cache
, *base
;
942 BlockDriverState
*bs
, *base_bs
;
944 bool progress
= false, quiet
= false, drop
= false;
946 Error
*local_err
= NULL
;
947 CommonBlockJobCBInfo cbi
;
948 bool image_opts
= false;
949 AioContext
*aio_context
;
950 int64_t rate_limit
= 0;
953 cache
= BDRV_DEFAULT_CACHE
;
956 static const struct option long_options
[] = {
957 {"help", no_argument
, 0, 'h'},
958 {"object", required_argument
, 0, OPTION_OBJECT
},
959 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
962 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
969 missing_argument(argv
[optind
- 1]);
972 unrecognized_option(argv
[optind
- 1]);
998 rate_limit
= cvtnum("rate limit", optarg
);
999 if (rate_limit
< 0) {
1004 user_creatable_process_cmdline(optarg
);
1006 case OPTION_IMAGE_OPTS
:
1012 /* Progress is not shown in Quiet mode */
1017 if (optind
!= argc
- 1) {
1018 error_exit("Expecting one image file name");
1020 filename
= argv
[optind
++];
1022 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1023 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1025 error_report("Invalid cache option: %s", cache
);
1029 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1036 qemu_progress_init(progress
, 1.f
);
1037 qemu_progress_print(0.f
, 100);
1040 base_bs
= bdrv_find_backing_image(bs
, base
);
1042 error_setg(&local_err
,
1043 "Did not find '%s' in the backing chain of '%s'",
1048 /* This is different from QMP, which by default uses the deepest file in
1049 * the backing chain (i.e., the very base); however, the traditional
1050 * behavior of qemu-img commit is using the immediate backing file. */
1051 base_bs
= bdrv_backing_chain_next(bs
);
1053 error_setg(&local_err
, "Image does not have a backing file");
1058 cbi
= (CommonBlockJobCBInfo
){
1063 aio_context
= bdrv_get_aio_context(bs
);
1064 aio_context_acquire(aio_context
);
1065 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1066 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1067 &cbi
, false, &local_err
);
1068 aio_context_release(aio_context
);
1073 /* When the block job completes, the BlockBackend reference will point to
1074 * the old backing file. In order to avoid that the top image is already
1075 * deleted, so we can still empty it afterwards, increment the reference
1076 * counter here preemptively. */
1081 job
= block_job_get("commit");
1083 run_block_job(job
, &local_err
);
1089 BlockBackend
*old_backing_blk
;
1091 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1093 if (!old_backing_blk
) {
1096 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1097 blk_unref(old_backing_blk
);
1098 if (ret
== -ENOTSUP
) {
1099 error_free(local_err
);
1101 } else if (ret
< 0) {
1112 qemu_progress_end();
1117 error_report_err(local_err
);
1121 qprintf(quiet
, "Image committed.\n");
1126 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1127 * of the first sector boundary within buf where the sector contains a
1128 * non-zero byte. This function is robust to a buffer that is not
1131 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1134 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1136 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1137 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1141 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1148 * Returns true iff the first sector pointed to by 'buf' contains at least
1151 * 'pnum' is set to the number of sectors (including and immediately following
1152 * the first one) that are known to be in the same allocated/unallocated state.
1153 * The function will try to align the end offset to alignment boundaries so
1154 * that the request will at least end aligned and consecutive requests will
1155 * also start at an aligned offset.
1157 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1158 int64_t sector_num
, int alignment
)
1167 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1168 for(i
= 1; i
< n
; i
++) {
1169 buf
+= BDRV_SECTOR_SIZE
;
1170 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1177 * The whole buf is the same.
1178 * No reason to split it into chunks, so return now.
1184 tail
= (sector_num
+ i
) & (alignment
- 1);
1186 if (is_zero
&& i
<= tail
) {
1188 * For sure next sector after i is data, and it will rewrite this
1189 * tail anyway due to RMW. So, let's just write data now.
1194 /* If possible, align up end offset of allocated areas. */
1195 i
+= alignment
- tail
;
1199 * For sure next sector after i is data, and it will rewrite this
1200 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1211 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1212 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1213 * breaking up write requests for only small sparse areas.
1215 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1216 int min
, int64_t sector_num
, int alignment
)
1219 int num_checked
, num_used
;
1225 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1231 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1233 sector_num
+= *pnum
;
1234 num_checked
= num_used
;
1237 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1239 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1241 sector_num
+= *pnum
;
1242 num_checked
+= *pnum
;
1244 num_used
= num_checked
;
1245 } else if (*pnum
>= min
) {
1255 * Compares two buffers sector by sector. Returns 0 if the first
1256 * sector of each buffer matches, non-zero otherwise.
1258 * pnum is set to the sector-aligned size of the buffer prefix that
1259 * has the same matching status as the first sector.
1261 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1262 int64_t bytes
, int64_t *pnum
)
1265 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1269 res
= !!memcmp(buf1
, buf2
, i
);
1271 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1273 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1283 #define IO_BUF_SIZE (2 * MiB)
1286 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1288 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1289 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1290 * failure), and 4 on error (the exit status for read errors), after emitting
1293 * @param blk: BlockBackend for the image
1294 * @param offset: Starting offset to check
1295 * @param bytes: Number of bytes to check
1296 * @param filename: Name of disk file we are checking (logging purpose)
1297 * @param buffer: Allocated buffer for storing read data
1298 * @param quiet: Flag for quiet mode
1300 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1301 int64_t bytes
, const char *filename
,
1302 uint8_t *buffer
, bool quiet
)
1307 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1309 error_report("Error while reading offset %" PRId64
" of %s: %s",
1310 offset
, filename
, strerror(-ret
));
1313 idx
= find_nonzero(buffer
, bytes
);
1315 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1324 * Compares two images. Exit codes:
1326 * 0 - Images are identical or the requested help was printed
1328 * >1 - Error occurred
1330 static int img_compare(int argc
, char **argv
)
1332 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1333 BlockBackend
*blk1
, *blk2
;
1334 BlockDriverState
*bs1
, *bs2
;
1335 int64_t total_size1
, total_size2
;
1336 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1337 int64_t pnum1
, pnum2
;
1338 int allocated1
, allocated2
;
1339 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1340 bool progress
= false, quiet
= false, strict
= false;
1347 uint64_t progress_base
;
1348 bool image_opts
= false;
1349 bool force_share
= false;
1351 cache
= BDRV_DEFAULT_CACHE
;
1353 static const struct option long_options
[] = {
1354 {"help", no_argument
, 0, 'h'},
1355 {"object", required_argument
, 0, OPTION_OBJECT
},
1356 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1357 {"force-share", no_argument
, 0, 'U'},
1360 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1361 long_options
, NULL
);
1367 missing_argument(argv
[optind
- 1]);
1370 unrecognized_option(argv
[optind
- 1]);
1398 Error
*local_err
= NULL
;
1400 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1402 error_report_err(local_err
);
1405 /* Help was printed */
1411 case OPTION_IMAGE_OPTS
:
1417 /* Progress is not shown in Quiet mode */
1423 if (optind
!= argc
- 2) {
1424 error_exit("Expecting two image file names");
1426 filename1
= argv
[optind
++];
1427 filename2
= argv
[optind
++];
1429 /* Initialize before goto out */
1430 qemu_progress_init(progress
, 2.0);
1433 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1435 error_report("Invalid source cache option: %s", cache
);
1440 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1447 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1456 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1457 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1458 total_size1
= blk_getlength(blk1
);
1459 if (total_size1
< 0) {
1460 error_report("Can't get size of %s: %s",
1461 filename1
, strerror(-total_size1
));
1465 total_size2
= blk_getlength(blk2
);
1466 if (total_size2
< 0) {
1467 error_report("Can't get size of %s: %s",
1468 filename2
, strerror(-total_size2
));
1472 total_size
= MIN(total_size1
, total_size2
);
1473 progress_base
= MAX(total_size1
, total_size2
);
1475 qemu_progress_print(0, 100);
1477 if (strict
&& total_size1
!= total_size2
) {
1479 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1483 while (offset
< total_size
) {
1484 int status1
, status2
;
1486 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1487 total_size1
- offset
, &pnum1
, NULL
,
1491 error_report("Sector allocation test failed for %s", filename1
);
1494 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1496 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1497 total_size2
- offset
, &pnum2
, NULL
,
1501 error_report("Sector allocation test failed for %s", filename2
);
1504 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1506 assert(pnum1
&& pnum2
);
1507 chunk
= MIN(pnum1
, pnum2
);
1510 if (status1
!= status2
) {
1512 qprintf(quiet
, "Strict mode: Offset %" PRId64
1513 " block status mismatch!\n", offset
);
1517 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1519 } else if (allocated1
== allocated2
) {
1523 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1524 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1526 error_report("Error while reading offset %" PRId64
1528 offset
, filename1
, strerror(-ret
));
1532 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1534 error_report("Error while reading offset %" PRId64
1536 offset
, filename2
, strerror(-ret
));
1540 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1541 if (ret
|| pnum
!= chunk
) {
1542 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1543 offset
+ (ret
? 0 : pnum
));
1549 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1551 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1552 filename1
, buf1
, quiet
);
1554 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1555 filename2
, buf1
, quiet
);
1562 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1565 if (total_size1
!= total_size2
) {
1566 BlockBackend
*blk_over
;
1567 const char *filename_over
;
1569 qprintf(quiet
, "Warning: Image size mismatch!\n");
1570 if (total_size1
> total_size2
) {
1572 filename_over
= filename1
;
1575 filename_over
= filename2
;
1578 while (offset
< progress_base
) {
1579 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1580 progress_base
- offset
, &chunk
,
1584 error_report("Sector allocation test failed for %s",
1589 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1590 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1591 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1592 filename_over
, buf1
, quiet
);
1598 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1602 qprintf(quiet
, "Images are identical.\n");
1612 qemu_progress_end();
1616 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1617 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1618 const char *src_node
, const char *src_name
,
1621 BlockDirtyBitmapMergeSource
*merge_src
;
1622 BlockDirtyBitmapMergeSourceList
*list
= NULL
;
1624 merge_src
= g_new0(BlockDirtyBitmapMergeSource
, 1);
1625 merge_src
->type
= QTYPE_QDICT
;
1626 merge_src
->u
.external
.node
= g_strdup(src_node
);
1627 merge_src
->u
.external
.name
= g_strdup(src_name
);
1628 QAPI_LIST_PREPEND(list
, merge_src
);
1629 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1630 qapi_free_BlockDirtyBitmapMergeSourceList(list
);
1633 enum ImgConvertBlockStatus
{
1639 #define MAX_COROUTINES 16
1640 #define CONVERT_THROTTLE_GROUP "img_convert"
1642 typedef struct ImgConvertState
{
1644 int64_t *src_sectors
;
1647 int64_t total_sectors
;
1648 int64_t allocated_sectors
;
1649 int64_t allocated_done
;
1652 enum ImgConvertBlockStatus status
;
1653 int64_t sector_next_status
;
1654 BlockBackend
*target
;
1658 bool target_has_backing
;
1659 int64_t target_backing_sectors
; /* negative if unknown */
1666 size_t cluster_sectors
;
1668 long num_coroutines
;
1669 int running_coroutines
;
1670 Coroutine
*co
[MAX_COROUTINES
];
1671 int64_t wait_sector_num
[MAX_COROUTINES
];
1676 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1677 int *src_cur
, int64_t *src_cur_offset
)
1680 *src_cur_offset
= 0;
1681 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1682 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1684 assert(*src_cur
< s
->src_num
);
1688 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1690 int64_t src_cur_offset
;
1691 int ret
, n
, src_cur
;
1692 bool post_backing_zero
= false;
1694 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1696 assert(s
->total_sectors
> sector_num
);
1697 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1699 if (s
->target_backing_sectors
>= 0) {
1700 if (sector_num
>= s
->target_backing_sectors
) {
1701 post_backing_zero
= true;
1702 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1703 /* Split requests around target_backing_sectors (because
1704 * starting from there, zeros are handled differently) */
1705 n
= s
->target_backing_sectors
- sector_num
;
1709 if (s
->sector_next_status
<= sector_num
) {
1710 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1713 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1714 BlockDriverState
*base
;
1716 if (s
->target_has_backing
) {
1717 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1723 count
= n
* BDRV_SECTOR_SIZE
;
1725 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1732 warn_report("error while reading block status at "
1733 "offset %" PRIu64
": %s", offset
,
1736 /* Just try to read the data, then */
1737 ret
= BDRV_BLOCK_DATA
;
1738 count
= BDRV_SECTOR_SIZE
;
1740 /* Retry on a shorter range */
1741 n
= DIV_ROUND_UP(n
, 4);
1744 error_report("error while reading block status at offset "
1745 "%" PRIu64
": %s", offset
, strerror(-ret
));
1751 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1754 * Avoid that s->sector_next_status becomes unaligned to the source
1755 * request alignment and/or cluster size to avoid unnecessary read
1758 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1763 if (ret
& BDRV_BLOCK_ZERO
) {
1764 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1765 } else if (ret
& BDRV_BLOCK_DATA
) {
1766 s
->status
= BLK_DATA
;
1768 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1771 s
->sector_next_status
= sector_num
+ n
;
1774 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1775 if (s
->status
== BLK_DATA
) {
1776 n
= MIN(n
, s
->buf_sectors
);
1779 /* We need to write complete clusters for compressed images, so if an
1780 * unallocated area is shorter than that, we must consider the whole
1781 * cluster allocated. */
1782 if (s
->compressed
) {
1783 if (n
< s
->cluster_sectors
) {
1784 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1785 s
->status
= BLK_DATA
;
1787 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1794 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1795 int nb_sectors
, uint8_t *buf
)
1797 uint64_t single_read_until
= 0;
1800 assert(nb_sectors
<= s
->buf_sectors
);
1801 while (nb_sectors
> 0) {
1804 int64_t bs_sectors
, src_cur_offset
;
1807 /* In the case of compression with multiple source files, we can get a
1808 * nb_sectors that spreads into the next part. So we must be able to
1809 * read across multiple BDSes for one convert_read() call. */
1810 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1811 blk
= s
->src
[src_cur
];
1812 bs_sectors
= s
->src_sectors
[src_cur
];
1814 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1816 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1817 if (single_read_until
> offset
) {
1821 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1825 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1829 warn_report("error while reading offset %" PRIu64
1830 ": %s", offset
, strerror(-ret
));
1832 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1841 buf
+= n
* BDRV_SECTOR_SIZE
;
1848 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1849 int nb_sectors
, uint8_t *buf
,
1850 enum ImgConvertBlockStatus status
)
1854 while (nb_sectors
> 0) {
1856 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1859 case BLK_BACKING_FILE
:
1860 /* If we have a backing file, leave clusters unallocated that are
1861 * unallocated in the source image, so that the backing file is
1862 * visible at the respective offset. */
1863 assert(s
->target_has_backing
);
1867 /* If we're told to keep the target fully allocated (-S 0) or there
1868 * is real non-zero data, we must write it. Otherwise we can treat
1869 * it as zero sectors.
1870 * Compressed clusters need to be written as a whole, so in that
1871 * case we can only save the write if the buffer is completely
1873 if (!s
->min_sparse
||
1875 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1876 sector_num
, s
->alignment
)) ||
1878 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1880 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1881 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1890 if (s
->has_zero_init
) {
1891 assert(!s
->target_has_backing
);
1894 ret
= blk_co_pwrite_zeroes(s
->target
,
1895 sector_num
<< BDRV_SECTOR_BITS
,
1896 n
<< BDRV_SECTOR_BITS
,
1897 BDRV_REQ_MAY_UNMAP
);
1906 buf
+= n
* BDRV_SECTOR_SIZE
;
1912 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1917 while (nb_sectors
> 0) {
1920 int64_t bs_sectors
, src_cur_offset
;
1923 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1924 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1925 blk
= s
->src
[src_cur
];
1926 bs_sectors
= s
->src_sectors
[src_cur
];
1928 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1930 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1931 sector_num
<< BDRV_SECTOR_BITS
,
1932 n
<< BDRV_SECTOR_BITS
, 0, 0);
1943 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1945 ImgConvertState
*s
= opaque
;
1946 uint8_t *buf
= NULL
;
1950 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1951 if (s
->co
[i
] == qemu_coroutine_self()) {
1958 s
->running_coroutines
++;
1959 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1964 enum ImgConvertBlockStatus status
;
1967 qemu_co_mutex_lock(&s
->lock
);
1968 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1969 qemu_co_mutex_unlock(&s
->lock
);
1972 n
= convert_iteration_sectors(s
, s
->sector_num
);
1974 qemu_co_mutex_unlock(&s
->lock
);
1978 /* save current sector and allocation status to local variables */
1979 sector_num
= s
->sector_num
;
1981 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1982 n
= MIN(n
, s
->buf_sectors
);
1984 /* increment global sector counter so that other coroutines can
1985 * already continue reading beyond this request */
1987 qemu_co_mutex_unlock(&s
->lock
);
1989 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1990 s
->allocated_done
+= n
;
1991 qemu_progress_print(100.0 * s
->allocated_done
/
1992 s
->allocated_sectors
, 0);
1996 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1997 if (status
== BLK_DATA
&& !copy_range
) {
1998 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2000 error_report("error while reading at byte %lld: %s",
2001 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2004 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2006 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2009 if (s
->wr_in_order
) {
2010 /* keep writes in order */
2011 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2012 s
->wait_sector_num
[index
] = sector_num
;
2013 qemu_coroutine_yield();
2015 s
->wait_sector_num
[index
] = -1;
2018 if (s
->ret
== -EINPROGRESS
) {
2020 ret
= convert_co_copy_range(s
, sector_num
, n
);
2022 s
->copy_range
= false;
2026 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2029 error_report("error while writing at byte %lld: %s",
2030 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2035 if (s
->wr_in_order
) {
2036 /* reenter the coroutine that might have waited
2037 * for this write to complete */
2038 s
->wr_offs
= sector_num
+ n
;
2039 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2040 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2042 * A -> B -> A cannot occur because A has
2043 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2044 * B will never enter A during this time window.
2046 qemu_coroutine_enter(s
->co
[i
]);
2054 s
->co
[index
] = NULL
;
2055 s
->running_coroutines
--;
2056 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2057 /* the convert job finished successfully */
2062 static int convert_do_copy(ImgConvertState
*s
)
2065 int64_t sector_num
= 0;
2067 /* Check whether we have zero initialisation or can get it efficiently */
2068 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2069 !s
->target_has_backing
) {
2070 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2073 /* Allocate buffer for copied data. For compressed images, only one cluster
2074 * can be copied at a time. */
2075 if (s
->compressed
) {
2076 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2077 error_report("invalid cluster size");
2080 s
->buf_sectors
= s
->cluster_sectors
;
2083 while (sector_num
< s
->total_sectors
) {
2084 n
= convert_iteration_sectors(s
, sector_num
);
2088 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2090 s
->allocated_sectors
+= n
;
2096 s
->sector_next_status
= 0;
2097 s
->ret
= -EINPROGRESS
;
2099 qemu_co_mutex_init(&s
->lock
);
2100 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2101 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2102 s
->wait_sector_num
[i
] = -1;
2103 qemu_coroutine_enter(s
->co
[i
]);
2106 while (s
->running_coroutines
) {
2107 main_loop_wait(false);
2110 if (s
->compressed
&& !s
->ret
) {
2111 /* signal EOF to align */
2112 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2121 /* Check that bitmaps can be copied, or output an error */
2122 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2124 BdrvDirtyBitmap
*bm
;
2126 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2127 error_report("Source lacks bitmap support");
2130 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2131 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2134 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2135 error_report("Cannot copy inconsistent bitmap '%s'",
2136 bdrv_dirty_bitmap_name(bm
));
2137 error_printf("Try --skip-broken-bitmaps, or "
2138 "use 'qemu-img bitmap --remove' to delete it\n");
2145 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2148 BdrvDirtyBitmap
*bm
;
2151 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2154 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2157 name
= bdrv_dirty_bitmap_name(bm
);
2158 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2159 warn_report("Skipping inconsistent bitmap '%s'", name
);
2162 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2163 true, bdrv_dirty_bitmap_granularity(bm
),
2165 true, !bdrv_dirty_bitmap_enabled(bm
),
2168 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2172 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2175 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2176 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2184 #define MAX_BUF_SECTORS 32768
2186 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2190 throttle_config_init(&cfg
);
2191 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2193 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2194 blk_set_io_limits(blk
, &cfg
);
2197 static int img_convert(int argc
, char **argv
)
2199 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2200 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2201 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2202 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2203 *backing_fmt
= NULL
;
2204 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2205 BlockDriverInfo bdi
;
2206 BlockDriverState
*out_bs
;
2207 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2208 QemuOptsList
*create_opts
= NULL
;
2209 QDict
*open_opts
= NULL
;
2210 char *options
= NULL
;
2211 Error
*local_err
= NULL
;
2212 bool writethrough
, src_writethrough
, image_opts
= false,
2213 skip_create
= false, progress
= false, tgt_image_opts
= false;
2214 int64_t ret
= -EINVAL
;
2215 bool force_share
= false;
2216 bool explict_min_sparse
= false;
2217 bool bitmaps
= false;
2218 bool skip_broken
= false;
2219 int64_t rate_limit
= 0;
2221 ImgConvertState s
= (ImgConvertState
) {
2222 /* Need at least 4k of zeros for sparse detection */
2224 .copy_range
= false,
2225 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2226 .wr_in_order
= true,
2227 .num_coroutines
= 8,
2231 static const struct option long_options
[] = {
2232 {"help", no_argument
, 0, 'h'},
2233 {"object", required_argument
, 0, OPTION_OBJECT
},
2234 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2235 {"force-share", no_argument
, 0, 'U'},
2236 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2237 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2238 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2239 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2240 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2243 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2244 long_options
, NULL
);
2250 missing_argument(argv
[optind
- 1]);
2253 unrecognized_option(argv
[optind
- 1]);
2265 out_baseimg
= optarg
;
2268 s
.copy_range
= true;
2271 s
.compressed
= true;
2274 backing_fmt
= optarg
;
2277 if (accumulate_options(&options
, optarg
) < 0) {
2282 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2283 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2286 error_report("Failed in parsing snapshot param '%s'",
2291 snapshot_name
= optarg
;
2298 sval
= cvtnum("buffer size for sparse output", optarg
);
2301 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2302 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2303 error_report("Invalid buffer size for sparse output specified. "
2304 "Valid sizes are multiples of %llu up to %llu. Select "
2305 "0 to disable sparse detection (fully allocates output).",
2306 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2310 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2311 explict_min_sparse
= true;
2330 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2331 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2332 error_report("Invalid number of coroutines. Allowed number of"
2333 " coroutines is between 1 and %d", MAX_COROUTINES
);
2338 s
.wr_in_order
= false;
2344 rate_limit
= cvtnum("rate limit", optarg
);
2345 if (rate_limit
< 0) {
2350 user_creatable_process_cmdline(optarg
);
2352 case OPTION_IMAGE_OPTS
:
2355 case OPTION_SALVAGE
:
2358 case OPTION_TARGET_IMAGE_OPTS
:
2359 tgt_image_opts
= true;
2361 case OPTION_TARGET_IS_ZERO
:
2363 * The user asserting that the target is blank has the
2364 * same effect as the target driver supporting zero
2367 s
.has_zero_init
= true;
2369 case OPTION_BITMAPS
:
2372 case OPTION_SKIP_BROKEN
:
2378 if (!out_fmt
&& !tgt_image_opts
) {
2382 if (skip_broken
&& !bitmaps
) {
2383 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2387 if (s
.compressed
&& s
.copy_range
) {
2388 error_report("Cannot enable copy offloading when -c is used");
2392 if (explict_min_sparse
&& s
.copy_range
) {
2393 error_report("Cannot enable copy offloading when -S is used");
2397 if (s
.copy_range
&& s
.salvage
) {
2398 error_report("Cannot use copy offloading in salvaging mode");
2402 if (tgt_image_opts
&& !skip_create
) {
2403 error_report("--target-image-opts requires use of -n flag");
2407 if (skip_create
&& options
) {
2408 error_report("-o has no effect when skipping image creation");
2412 if (s
.has_zero_init
&& !skip_create
) {
2413 error_report("--target-is-zero requires use of -n flag");
2417 s
.src_num
= argc
- optind
- 1;
2418 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2420 if (options
&& has_help_option(options
)) {
2422 ret
= print_block_option_help(out_filename
, out_fmt
);
2425 error_report("Option help requires a format be specified");
2430 if (s
.src_num
< 1) {
2431 error_report("Must specify image file name");
2435 /* ret is still -EINVAL until here */
2436 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2438 error_report("Invalid source cache option: %s", src_cache
);
2442 /* Initialize before goto out */
2446 qemu_progress_init(progress
, 1.0);
2447 qemu_progress_print(0, 100);
2449 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2450 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2451 s
.src_alignment
= g_new(int, s
.src_num
);
2453 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2454 BlockDriverState
*src_bs
;
2455 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2456 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2462 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2463 if (s
.src_sectors
[bs_i
] < 0) {
2464 error_report("Could not get size of %s: %s",
2465 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2469 src_bs
= blk_bs(s
.src
[bs_i
]);
2470 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2472 if (!bdrv_get_info(src_bs
, &bdi
)) {
2473 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2474 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2476 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2480 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2481 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2482 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2484 } else if (snapshot_name
!= NULL
) {
2485 if (s
.src_num
> 1) {
2486 error_report("No support for concatenating multiple snapshot");
2491 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2495 error_reportf_err(local_err
, "Failed to load snapshot: ");
2501 /* Find driver and parse its options */
2502 drv
= bdrv_find_format(out_fmt
);
2504 error_report("Unknown file format '%s'", out_fmt
);
2509 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2511 error_report_err(local_err
);
2516 if (!drv
->create_opts
) {
2517 error_report("Format driver '%s' does not support image creation",
2523 if (!proto_drv
->create_opts
) {
2524 error_report("Protocol driver '%s' does not support image creation",
2525 proto_drv
->format_name
);
2530 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2531 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2533 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2535 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2536 error_report_err(local_err
);
2542 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2543 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2544 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2550 /* Get backing file name if -o backing_file was used */
2551 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2552 if (out_baseimg_param
) {
2553 out_baseimg
= out_baseimg_param
;
2555 s
.target_has_backing
= (bool) out_baseimg
;
2557 if (s
.has_zero_init
&& s
.target_has_backing
) {
2558 error_report("Cannot use --target-is-zero when the destination "
2559 "image has a backing file");
2563 if (s
.src_num
> 1 && out_baseimg
) {
2564 error_report("Having a backing file for the target makes no sense when "
2565 "concatenating multiple input images");
2570 if (out_baseimg_param
) {
2571 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2572 error_report("Use of backing file requires explicit "
2579 /* Check if compression is supported */
2582 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2583 const char *encryptfmt
=
2584 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2585 const char *preallocation
=
2586 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2588 if (drv
&& !block_driver_can_compress(drv
)) {
2589 error_report("Compression not supported for this file format");
2594 if (encryption
|| encryptfmt
) {
2595 error_report("Compression and encryption not supported at "
2602 && strcmp(preallocation
, "off"))
2604 error_report("Compression and preallocation not supported at "
2611 /* Determine if bitmaps need copying */
2613 if (s
.src_num
> 1) {
2614 error_report("Copying bitmaps only possible with single source");
2618 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2625 * The later open call will need any decryption secrets, and
2626 * bdrv_create() will purge "opts", so extract them now before
2630 open_opts
= qdict_new();
2631 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2633 /* Create the new image */
2634 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2636 error_reportf_err(local_err
, "%s: error while converting %s: ",
2637 out_filename
, out_fmt
);
2642 s
.target_is_new
= !skip_create
;
2644 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2645 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2647 error_report("Invalid cache option: %s", cache
);
2651 if (flags
& BDRV_O_NOCACHE
) {
2653 * If we open the target with O_DIRECT, it may be necessary to
2654 * extend its size to align to the physical sector size.
2656 flags
|= BDRV_O_RESIZE
;
2660 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2661 flags
, writethrough
, s
.quiet
, false);
2663 /* TODO ultimately we should allow --target-image-opts
2664 * to be used even when -n is not given.
2665 * That has to wait for bdrv_create to be improved
2666 * to allow filenames in option syntax
2668 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2669 flags
, writethrough
, s
.quiet
, false);
2670 open_opts
= NULL
; /* blk_new_open will have freed it */
2676 out_bs
= blk_bs(s
.target
);
2678 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2679 error_report("Format driver '%s' does not support bitmaps",
2680 out_bs
->drv
->format_name
);
2685 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2686 error_report("Compression not supported for this file format");
2691 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2692 * or discard_alignment of the out_bs is greater. Limit to
2693 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2694 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2696 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2697 out_bs
->bl
.pdiscard_alignment
>>
2698 BDRV_SECTOR_BITS
)));
2700 /* try to align the write requests to the destination to avoid unnecessary
2702 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2703 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2705 assert(is_power_of_2(s
.alignment
));
2708 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2709 if (output_sectors
< 0) {
2710 error_report("unable to get output image length: %s",
2711 strerror(-output_sectors
));
2714 } else if (output_sectors
< s
.total_sectors
) {
2715 error_report("output file is smaller than input file");
2721 if (s
.target_has_backing
&& s
.target_is_new
) {
2722 /* Errors are treated as "backing length unknown" (which means
2723 * s.target_backing_sectors has to be negative, which it will
2724 * be automatically). The backing file length is used only
2725 * for optimizations, so such a case is not fatal. */
2726 s
.target_backing_sectors
=
2727 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2729 s
.target_backing_sectors
= -1;
2732 ret
= bdrv_get_info(out_bs
, &bdi
);
2735 error_report("could not get block driver info");
2739 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2740 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2744 set_rate_limit(s
.target
, rate_limit
);
2747 ret
= convert_do_copy(&s
);
2749 /* Now copy the bitmaps */
2750 if (bitmaps
&& ret
== 0) {
2751 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2756 qemu_progress_print(100, 0);
2758 qemu_progress_end();
2759 qemu_opts_del(opts
);
2760 qemu_opts_free(create_opts
);
2761 qobject_unref(open_opts
);
2762 blk_unref(s
.target
);
2764 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2765 blk_unref(s
.src
[bs_i
]);
2769 g_free(s
.src_sectors
);
2770 g_free(s
.src_alignment
);
2772 qemu_opts_del(sn_opts
);
2779 static void dump_snapshots(BlockDriverState
*bs
)
2781 QEMUSnapshotInfo
*sn_tab
, *sn
;
2784 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2787 printf("Snapshot list:\n");
2788 bdrv_snapshot_dump(NULL
);
2790 for(i
= 0; i
< nb_sns
; i
++) {
2792 bdrv_snapshot_dump(sn
);
2798 static void dump_json_image_info_list(ImageInfoList
*list
)
2802 Visitor
*v
= qobject_output_visitor_new(&obj
);
2804 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2805 visit_complete(v
, &obj
);
2806 str
= qobject_to_json_pretty(obj
, true);
2807 assert(str
!= NULL
);
2808 printf("%s\n", str
->str
);
2811 g_string_free(str
, true);
2814 static void dump_json_image_info(ImageInfo
*info
)
2818 Visitor
*v
= qobject_output_visitor_new(&obj
);
2820 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2821 visit_complete(v
, &obj
);
2822 str
= qobject_to_json_pretty(obj
, true);
2823 assert(str
!= NULL
);
2824 printf("%s\n", str
->str
);
2827 g_string_free(str
, true);
2830 static void dump_human_image_info_list(ImageInfoList
*list
)
2832 ImageInfoList
*elem
;
2835 for (elem
= list
; elem
; elem
= elem
->next
) {
2841 bdrv_image_info_dump(elem
->value
);
2845 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2847 return strcmp(a
, b
) == 0;
2851 * Open an image file chain and return an ImageInfoList
2853 * @filename: topmost image filename
2854 * @fmt: topmost image format (may be NULL to autodetect)
2855 * @chain: true - enumerate entire backing file chain
2856 * false - only topmost image file
2858 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2859 * image file. If there was an error a message will have been printed to
2862 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2863 const char *filename
,
2865 bool chain
, bool force_share
)
2867 ImageInfoList
*head
= NULL
;
2868 ImageInfoList
**tail
= &head
;
2869 GHashTable
*filenames
;
2872 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2876 BlockDriverState
*bs
;
2879 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2880 error_report("Backing file '%s' creates an infinite loop.",
2884 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2886 blk
= img_open(image_opts
, filename
, fmt
,
2887 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2894 bdrv_query_image_info(bs
, &info
, &err
);
2896 error_report_err(err
);
2901 QAPI_LIST_APPEND(tail
, info
);
2905 /* Clear parameters that only apply to the topmost image */
2906 filename
= fmt
= NULL
;
2910 if (info
->has_full_backing_filename
) {
2911 filename
= info
->full_backing_filename
;
2912 } else if (info
->has_backing_filename
) {
2913 error_report("Could not determine absolute backing filename,"
2914 " but backing filename '%s' present",
2915 info
->backing_filename
);
2918 if (info
->has_backing_filename_format
) {
2919 fmt
= info
->backing_filename_format
;
2923 g_hash_table_destroy(filenames
);
2927 qapi_free_ImageInfoList(head
);
2928 g_hash_table_destroy(filenames
);
2932 static int img_info(int argc
, char **argv
)
2935 OutputFormat output_format
= OFORMAT_HUMAN
;
2937 const char *filename
, *fmt
, *output
;
2938 ImageInfoList
*list
;
2939 bool image_opts
= false;
2940 bool force_share
= false;
2945 int option_index
= 0;
2946 static const struct option long_options
[] = {
2947 {"help", no_argument
, 0, 'h'},
2948 {"format", required_argument
, 0, 'f'},
2949 {"output", required_argument
, 0, OPTION_OUTPUT
},
2950 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2951 {"object", required_argument
, 0, OPTION_OBJECT
},
2952 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2953 {"force-share", no_argument
, 0, 'U'},
2956 c
= getopt_long(argc
, argv
, ":f:hU",
2957 long_options
, &option_index
);
2963 missing_argument(argv
[optind
- 1]);
2966 unrecognized_option(argv
[optind
- 1]);
2980 case OPTION_BACKING_CHAIN
:
2984 user_creatable_process_cmdline(optarg
);
2986 case OPTION_IMAGE_OPTS
:
2991 if (optind
!= argc
- 1) {
2992 error_exit("Expecting one image file name");
2994 filename
= argv
[optind
++];
2996 if (output
&& !strcmp(output
, "json")) {
2997 output_format
= OFORMAT_JSON
;
2998 } else if (output
&& !strcmp(output
, "human")) {
2999 output_format
= OFORMAT_HUMAN
;
3000 } else if (output
) {
3001 error_report("--output must be used with human or json as argument.");
3005 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3011 switch (output_format
) {
3013 dump_human_image_info_list(list
);
3017 dump_json_image_info_list(list
);
3019 dump_json_image_info(list
->value
);
3024 qapi_free_ImageInfoList(list
);
3028 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3031 switch (output_format
) {
3033 if (e
->data
&& !e
->has_offset
) {
3034 error_report("File contains external, encrypted or compressed clusters.");
3037 if (e
->data
&& !e
->zero
) {
3038 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3039 e
->start
, e
->length
,
3040 e
->has_offset
? e
->offset
: 0,
3041 e
->has_filename
? e
->filename
: "");
3043 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3044 * Modify the flags here to allow more coalescing.
3046 if (next
&& (!next
->data
|| next
->zero
)) {
3052 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3053 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3054 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
3055 e
->present
? "true" : "false",
3056 e
->zero
? "true" : "false",
3057 e
->data
? "true" : "false");
3058 if (e
->has_offset
) {
3059 printf(", \"offset\": %"PRId64
"", e
->offset
);
3071 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3072 int64_t bytes
, MapEntry
*e
)
3076 BlockDriverState
*file
;
3079 char *filename
= NULL
;
3081 /* As an optimization, we could cache the current range of unallocated
3082 * clusters in each file of the chain, and avoid querying the same
3088 bs
= bdrv_skip_filters(bs
);
3089 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3094 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3097 bs
= bdrv_cow_bs(bs
);
3106 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3108 if (file
&& has_offset
) {
3109 bdrv_refresh_filename(file
);
3110 filename
= file
->filename
;
3116 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3117 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3119 .has_offset
= has_offset
,
3121 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3122 .has_filename
= filename
,
3123 .filename
= filename
,
3129 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3131 if (curr
->length
== 0) {
3134 if (curr
->zero
!= next
->zero
||
3135 curr
->data
!= next
->data
||
3136 curr
->depth
!= next
->depth
||
3137 curr
->present
!= next
->present
||
3138 curr
->has_filename
!= next
->has_filename
||
3139 curr
->has_offset
!= next
->has_offset
) {
3142 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
3145 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3151 static int img_map(int argc
, char **argv
)
3154 OutputFormat output_format
= OFORMAT_HUMAN
;
3156 BlockDriverState
*bs
;
3157 const char *filename
, *fmt
, *output
;
3159 MapEntry curr
= { .length
= 0 }, next
;
3161 bool image_opts
= false;
3162 bool force_share
= false;
3163 int64_t start_offset
= 0;
3164 int64_t max_length
= -1;
3169 int option_index
= 0;
3170 static const struct option long_options
[] = {
3171 {"help", no_argument
, 0, 'h'},
3172 {"format", required_argument
, 0, 'f'},
3173 {"output", required_argument
, 0, OPTION_OUTPUT
},
3174 {"object", required_argument
, 0, OPTION_OBJECT
},
3175 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3176 {"force-share", no_argument
, 0, 'U'},
3177 {"start-offset", required_argument
, 0, 's'},
3178 {"max-length", required_argument
, 0, 'l'},
3181 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3182 long_options
, &option_index
);
3188 missing_argument(argv
[optind
- 1]);
3191 unrecognized_option(argv
[optind
- 1]);
3206 start_offset
= cvtnum("start offset", optarg
);
3207 if (start_offset
< 0) {
3212 max_length
= cvtnum("max length", optarg
);
3213 if (max_length
< 0) {
3218 user_creatable_process_cmdline(optarg
);
3220 case OPTION_IMAGE_OPTS
:
3225 if (optind
!= argc
- 1) {
3226 error_exit("Expecting one image file name");
3228 filename
= argv
[optind
];
3230 if (output
&& !strcmp(output
, "json")) {
3231 output_format
= OFORMAT_JSON
;
3232 } else if (output
&& !strcmp(output
, "human")) {
3233 output_format
= OFORMAT_HUMAN
;
3234 } else if (output
) {
3235 error_report("--output must be used with human or json as argument.");
3239 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3245 if (output_format
== OFORMAT_HUMAN
) {
3246 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3247 } else if (output_format
== OFORMAT_JSON
) {
3251 length
= blk_getlength(blk
);
3253 error_report("Failed to get size for '%s'", filename
);
3256 if (max_length
!= -1) {
3257 length
= MIN(start_offset
+ max_length
, length
);
3260 curr
.start
= start_offset
;
3261 while (curr
.start
+ curr
.length
< length
) {
3262 int64_t offset
= curr
.start
+ curr
.length
;
3263 int64_t n
= length
- offset
;
3265 ret
= get_block_status(bs
, offset
, n
, &next
);
3267 error_report("Could not read file metadata: %s", strerror(-ret
));
3271 if (entry_mergeable(&curr
, &next
)) {
3272 curr
.length
+= next
.length
;
3276 if (curr
.length
> 0) {
3277 ret
= dump_map_entry(output_format
, &curr
, &next
);
3285 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3286 if (output_format
== OFORMAT_JSON
) {
3295 #define SNAPSHOT_LIST 1
3296 #define SNAPSHOT_CREATE 2
3297 #define SNAPSHOT_APPLY 3
3298 #define SNAPSHOT_DELETE 4
3300 static int img_snapshot(int argc
, char **argv
)
3303 BlockDriverState
*bs
;
3304 QEMUSnapshotInfo sn
;
3305 char *filename
, *snapshot_name
= NULL
;
3306 int c
, ret
= 0, bdrv_oflags
;
3310 bool image_opts
= false;
3311 bool force_share
= false;
3314 bdrv_oflags
= BDRV_O_RDWR
;
3315 /* Parse commandline parameters */
3317 static const struct option long_options
[] = {
3318 {"help", no_argument
, 0, 'h'},
3319 {"object", required_argument
, 0, OPTION_OBJECT
},
3320 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3321 {"force-share", no_argument
, 0, 'U'},
3324 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3325 long_options
, NULL
);
3331 missing_argument(argv
[optind
- 1]);
3334 unrecognized_option(argv
[optind
- 1]);
3341 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3344 action
= SNAPSHOT_LIST
;
3345 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3349 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3352 action
= SNAPSHOT_APPLY
;
3353 snapshot_name
= optarg
;
3357 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3360 action
= SNAPSHOT_CREATE
;
3361 snapshot_name
= optarg
;
3365 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3368 action
= SNAPSHOT_DELETE
;
3369 snapshot_name
= optarg
;
3378 user_creatable_process_cmdline(optarg
);
3380 case OPTION_IMAGE_OPTS
:
3386 if (optind
!= argc
- 1) {
3387 error_exit("Expecting one image file name");
3389 filename
= argv
[optind
++];
3391 /* Open the image */
3392 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3399 /* Perform the requested action */
3405 case SNAPSHOT_CREATE
:
3406 memset(&sn
, 0, sizeof(sn
));
3407 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3409 rt
= g_get_real_time();
3410 sn
.date_sec
= rt
/ G_USEC_PER_SEC
;
3411 sn
.date_nsec
= (rt
% G_USEC_PER_SEC
) * 1000;
3413 ret
= bdrv_snapshot_create(bs
, &sn
);
3415 error_report("Could not create snapshot '%s': %d (%s)",
3416 snapshot_name
, ret
, strerror(-ret
));
3420 case SNAPSHOT_APPLY
:
3421 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3423 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3428 case SNAPSHOT_DELETE
:
3429 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3431 error_report("Could not delete snapshot '%s': snapshot not "
3432 "found", snapshot_name
);
3435 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3437 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3453 static int img_rebase(int argc
, char **argv
)
3455 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3456 uint8_t *buf_old
= NULL
;
3457 uint8_t *buf_new
= NULL
;
3458 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3459 BlockDriverState
*unfiltered_bs
;
3461 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3462 int c
, flags
, src_flags
, ret
;
3463 bool writethrough
, src_writethrough
;
3465 bool force_share
= false;
3468 Error
*local_err
= NULL
;
3469 bool image_opts
= false;
3471 /* Parse commandline parameters */
3473 cache
= BDRV_DEFAULT_CACHE
;
3474 src_cache
= BDRV_DEFAULT_CACHE
;
3478 static const struct option long_options
[] = {
3479 {"help", no_argument
, 0, 'h'},
3480 {"object", required_argument
, 0, OPTION_OBJECT
},
3481 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3482 {"force-share", no_argument
, 0, 'U'},
3485 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3486 long_options
, NULL
);
3492 missing_argument(argv
[optind
- 1]);
3495 unrecognized_option(argv
[optind
- 1]);
3504 out_basefmt
= optarg
;
3507 out_baseimg
= optarg
;
3525 user_creatable_process_cmdline(optarg
);
3527 case OPTION_IMAGE_OPTS
:
3540 if (optind
!= argc
- 1) {
3541 error_exit("Expecting one image file name");
3543 if (!unsafe
&& !out_baseimg
) {
3544 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3546 filename
= argv
[optind
++];
3548 qemu_progress_init(progress
, 2.0);
3549 qemu_progress_print(0, 100);
3551 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3552 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3554 error_report("Invalid cache option: %s", cache
);
3559 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3561 error_report("Invalid source cache option: %s", src_cache
);
3565 /* The source files are opened read-only, don't care about WCE */
3566 assert((src_flags
& BDRV_O_RDWR
) == 0);
3567 (void) src_writethrough
;
3572 * Ignore the old backing file for unsafe rebase in case we want to correct
3573 * the reference to a renamed or moved backing file.
3575 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3583 unfiltered_bs
= bdrv_skip_filters(bs
);
3585 if (out_basefmt
!= NULL
) {
3586 if (bdrv_find_format(out_basefmt
) == NULL
) {
3587 error_report("Invalid format name: '%s'", out_basefmt
);
3593 /* For safe rebasing we need to compare old and new backing file */
3595 QDict
*options
= NULL
;
3596 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3599 blk_old_backing
= blk_new(qemu_get_aio_context(),
3600 BLK_PERM_CONSISTENT_READ
,
3602 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3605 error_reportf_err(local_err
,
3606 "Could not reuse old backing file '%s': ",
3611 blk_old_backing
= NULL
;
3614 if (out_baseimg
[0]) {
3615 const char *overlay_filename
;
3616 char *out_real_path
;
3618 options
= qdict_new();
3620 qdict_put_str(options
, "driver", out_basefmt
);
3623 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3626 bdrv_refresh_filename(bs
);
3627 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3630 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3634 qobject_unref(options
);
3635 error_reportf_err(local_err
,
3636 "Could not resolve backing filename: ");
3642 * Find out whether we rebase an image on top of a previous image
3645 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3646 if (prefix_chain_bs
) {
3647 qobject_unref(options
);
3648 g_free(out_real_path
);
3650 blk_new_backing
= blk_new(qemu_get_aio_context(),
3651 BLK_PERM_CONSISTENT_READ
,
3653 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3656 error_reportf_err(local_err
,
3657 "Could not reuse backing file '%s': ",
3662 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3663 options
, src_flags
, &local_err
);
3664 g_free(out_real_path
);
3665 if (!blk_new_backing
) {
3666 error_reportf_err(local_err
,
3667 "Could not open new backing file '%s': ",
3677 * Check each unallocated cluster in the COW file. If it is unallocated,
3678 * accesses go to the backing file. We must therefore compare this cluster
3679 * in the old and new backing file, and if they differ we need to copy it
3680 * from the old backing file into the COW file.
3682 * If qemu-img crashes during this step, no harm is done. The content of
3683 * the image is the same as the original one at any time.
3687 int64_t old_backing_size
= 0;
3688 int64_t new_backing_size
= 0;
3691 float local_progress
= 0;
3693 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3694 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3696 size
= blk_getlength(blk
);
3698 error_report("Could not get size of '%s': %s",
3699 filename
, strerror(-size
));
3703 if (blk_old_backing
) {
3704 old_backing_size
= blk_getlength(blk_old_backing
);
3705 if (old_backing_size
< 0) {
3706 char backing_name
[PATH_MAX
];
3708 bdrv_get_backing_filename(bs
, backing_name
,
3709 sizeof(backing_name
));
3710 error_report("Could not get size of '%s': %s",
3711 backing_name
, strerror(-old_backing_size
));
3716 if (blk_new_backing
) {
3717 new_backing_size
= blk_getlength(blk_new_backing
);
3718 if (new_backing_size
< 0) {
3719 error_report("Could not get size of '%s': %s",
3720 out_baseimg
, strerror(-new_backing_size
));
3727 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3730 for (offset
= 0; offset
< size
; offset
+= n
) {
3731 bool buf_old_is_zero
= false;
3733 /* How many bytes can we handle with the next read? */
3734 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3736 /* If the cluster is allocated, we don't need to take action */
3737 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3739 error_report("error while reading image metadata: %s",
3747 if (prefix_chain_bs
) {
3749 * If cluster wasn't changed since prefix_chain, we don't need
3752 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3753 prefix_chain_bs
, false,
3756 error_report("error while reading image metadata: %s",
3766 * Read old and new backing file and take into consideration that
3767 * backing files may be smaller than the COW image.
3769 if (offset
>= old_backing_size
) {
3770 memset(buf_old
, 0, n
);
3771 buf_old_is_zero
= true;
3773 if (offset
+ n
> old_backing_size
) {
3774 n
= old_backing_size
- offset
;
3777 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3779 error_report("error while reading from old backing file");
3784 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3785 memset(buf_new
, 0, n
);
3787 if (offset
+ n
> new_backing_size
) {
3788 n
= new_backing_size
- offset
;
3791 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3793 error_report("error while reading from new backing file");
3798 /* If they differ, we need to write to the COW file */
3799 uint64_t written
= 0;
3801 while (written
< n
) {
3804 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3805 n
- written
, &pnum
))
3807 if (buf_old_is_zero
) {
3808 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3810 ret
= blk_pwrite(blk
, offset
+ written
,
3811 buf_old
+ written
, pnum
, 0);
3814 error_report("Error while writing to COW image: %s",
3822 qemu_progress_print(local_progress
, 100);
3827 * Change the backing file. All clusters that are different from the old
3828 * backing file are overwritten in the COW file now, so the visible content
3829 * doesn't change when we switch the backing file.
3831 if (out_baseimg
&& *out_baseimg
) {
3832 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3835 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3838 if (ret
== -ENOSPC
) {
3839 error_report("Could not change the backing file to '%s': No "
3840 "space left in the file header", out_baseimg
);
3841 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3842 error_report("Could not change the backing file to '%s': backing "
3843 "format must be specified", out_baseimg
);
3844 } else if (ret
< 0) {
3845 error_report("Could not change the backing file to '%s': %s",
3846 out_baseimg
, strerror(-ret
));
3849 qemu_progress_print(100, 0);
3851 * TODO At this point it is possible to check if any clusters that are
3852 * allocated in the COW file are the same in the backing file. If so, they
3853 * could be dropped from the COW file. Don't do this before switching the
3854 * backing file, in case of a crash this would lead to corruption.
3857 qemu_progress_end();
3860 blk_unref(blk_old_backing
);
3861 blk_unref(blk_new_backing
);
3863 qemu_vfree(buf_old
);
3864 qemu_vfree(buf_new
);
3873 static int img_resize(int argc
, char **argv
)
3876 int c
, ret
, relative
;
3877 const char *filename
, *fmt
, *size
;
3878 int64_t n
, total_size
, current_size
;
3880 BlockBackend
*blk
= NULL
;
3881 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3884 static QemuOptsList resize_options
= {
3885 .name
= "resize_options",
3886 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3889 .name
= BLOCK_OPT_SIZE
,
3890 .type
= QEMU_OPT_SIZE
,
3891 .help
= "Virtual disk size"
3897 bool image_opts
= false;
3898 bool shrink
= false;
3900 /* Remove size from argv manually so that negative numbers are not treated
3901 * as options by getopt. */
3903 error_exit("Not enough arguments");
3907 size
= argv
[--argc
];
3909 /* Parse getopt arguments */
3912 static const struct option long_options
[] = {
3913 {"help", no_argument
, 0, 'h'},
3914 {"object", required_argument
, 0, OPTION_OBJECT
},
3915 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3916 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3917 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3920 c
= getopt_long(argc
, argv
, ":f:hq",
3921 long_options
, NULL
);
3927 missing_argument(argv
[optind
- 1]);
3930 unrecognized_option(argv
[optind
- 1]);
3942 user_creatable_process_cmdline(optarg
);
3944 case OPTION_IMAGE_OPTS
:
3947 case OPTION_PREALLOCATION
:
3948 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3949 PREALLOC_MODE__MAX
, NULL
);
3950 if (prealloc
== PREALLOC_MODE__MAX
) {
3951 error_report("Invalid preallocation mode '%s'", optarg
);
3960 if (optind
!= argc
- 1) {
3961 error_exit("Expecting image file name and size");
3963 filename
= argv
[optind
++];
3965 /* Choose grow, shrink, or absolute resize mode */
3981 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3982 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
3983 error_report_err(err
);
3985 qemu_opts_del(param
);
3988 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3989 qemu_opts_del(param
);
3991 blk
= img_open(image_opts
, filename
, fmt
,
3992 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3999 current_size
= blk_getlength(blk
);
4000 if (current_size
< 0) {
4001 error_report("Failed to inquire current image length: %s",
4002 strerror(-current_size
));
4008 total_size
= current_size
+ n
* relative
;
4012 if (total_size
<= 0) {
4013 error_report("New image size must be positive");
4018 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4019 error_report("Preallocation can only be used for growing images");
4024 if (total_size
< current_size
&& !shrink
) {
4025 error_report("Use the --shrink option to perform a shrink operation.");
4026 warn_report("Shrinking an image will delete all data beyond the "
4027 "shrunken image's end. Before performing such an "
4028 "operation, make sure there is no important data there.");
4034 * The user expects the image to have the desired size after
4035 * resizing, so pass @exact=true. It is of no use to report
4036 * success when the image has not actually been resized.
4038 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4040 qprintf(quiet
, "Image resized.\n");
4042 error_report_err(err
);
4052 static void amend_status_cb(BlockDriverState
*bs
,
4053 int64_t offset
, int64_t total_work_size
,
4056 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4059 static int print_amend_option_help(const char *format
)
4063 /* Find driver and parse its options */
4064 drv
= bdrv_find_format(format
);
4066 error_report("Unknown file format '%s'", format
);
4070 if (!drv
->bdrv_amend_options
) {
4071 error_report("Format driver '%s' does not support option amendment",
4076 /* Every driver supporting amendment must have amend_opts */
4077 assert(drv
->amend_opts
);
4079 printf("Amend options for '%s':\n", format
);
4080 qemu_opts_print_help(drv
->amend_opts
, false);
4084 static int img_amend(int argc
, char **argv
)
4088 char *options
= NULL
;
4089 QemuOptsList
*amend_opts
= NULL
;
4090 QemuOpts
*opts
= NULL
;
4091 const char *fmt
= NULL
, *filename
, *cache
;
4094 bool quiet
= false, progress
= false;
4095 BlockBackend
*blk
= NULL
;
4096 BlockDriverState
*bs
= NULL
;
4097 bool image_opts
= false;
4100 cache
= BDRV_DEFAULT_CACHE
;
4102 static const struct option long_options
[] = {
4103 {"help", no_argument
, 0, 'h'},
4104 {"object", required_argument
, 0, OPTION_OBJECT
},
4105 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4106 {"force", no_argument
, 0, OPTION_FORCE
},
4109 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4110 long_options
, NULL
);
4117 missing_argument(argv
[optind
- 1]);
4120 unrecognized_option(argv
[optind
- 1]);
4126 if (accumulate_options(&options
, optarg
) < 0) {
4128 goto out_no_progress
;
4144 user_creatable_process_cmdline(optarg
);
4146 case OPTION_IMAGE_OPTS
:
4156 error_exit("Must specify options (-o)");
4162 qemu_progress_init(progress
, 1.0);
4164 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4165 if (fmt
&& has_help_option(options
)) {
4166 /* If a format is explicitly specified (and possibly no filename is
4167 * given), print option help here */
4168 ret
= print_amend_option_help(fmt
);
4172 if (optind
!= argc
- 1) {
4173 error_report("Expecting one image file name");
4178 flags
= BDRV_O_RDWR
;
4179 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4181 error_report("Invalid cache option: %s", cache
);
4185 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4193 fmt
= bs
->drv
->format_name
;
4195 if (has_help_option(options
)) {
4196 /* If the format was auto-detected, print option help here */
4197 ret
= print_amend_option_help(fmt
);
4201 if (!bs
->drv
->bdrv_amend_options
) {
4202 error_report("Format driver '%s' does not support option amendment",
4208 /* Every driver supporting amendment must have amend_opts */
4209 assert(bs
->drv
->amend_opts
);
4211 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4212 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4213 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4214 /* Try to parse options using the create options */
4215 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4216 qemu_opts_del(opts
);
4217 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4218 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4219 error_append_hint(&err
,
4220 "This option is only supported for image creation\n");
4223 error_report_err(err
);
4228 /* In case the driver does not call amend_status_cb() */
4229 qemu_progress_print(0.f
, 0);
4230 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4231 qemu_progress_print(100.f
, 0);
4233 error_report_err(err
);
4238 qemu_progress_end();
4242 qemu_opts_del(opts
);
4243 qemu_opts_free(amend_opts
);
4252 typedef struct BenchData
{
4254 uint64_t image_size
;
4261 bool drain_on_flush
;
4270 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4273 error_report("Failed flush request: %s", strerror(-ret
));
4278 static void bench_cb(void *opaque
, int ret
)
4280 BenchData
*b
= opaque
;
4284 error_report("Failed request: %s", strerror(-ret
));
4289 /* Just finished a flush with drained queue: Start next requests */
4290 assert(b
->in_flight
== 0);
4291 b
->in_flush
= false;
4292 } else if (b
->in_flight
> 0) {
4293 int remaining
= b
->n
- b
->in_flight
;
4298 /* Time for flush? Drain queue if requested, then flush */
4299 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4300 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4301 BlockCompletionFunc
*cb
;
4303 if (b
->drain_on_flush
) {
4307 cb
= bench_undrained_flush_cb
;
4310 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4312 error_report("Failed to issue flush request");
4316 if (b
->drain_on_flush
) {
4322 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4323 int64_t offset
= b
->offset
;
4324 /* blk_aio_* might look for completed I/Os and kick bench_cb
4325 * again, so make sure this operation is counted by in_flight
4326 * and b->offset is ready for the next submission.
4329 b
->offset
+= b
->step
;
4330 b
->offset
%= b
->image_size
;
4332 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4334 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4337 error_report("Failed to issue request");
4343 static int img_bench(int argc
, char **argv
)
4346 const char *fmt
= NULL
, *filename
;
4348 bool image_opts
= false;
4349 bool is_write
= false;
4353 size_t bufsize
= 4096;
4356 int flush_interval
= 0;
4357 bool drain_on_flush
= true;
4359 BlockBackend
*blk
= NULL
;
4360 BenchData data
= {};
4362 bool writethrough
= false;
4363 struct timeval t1
, t2
;
4365 bool force_share
= false;
4369 static const struct option long_options
[] = {
4370 {"help", no_argument
, 0, 'h'},
4371 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4372 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4373 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4374 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4375 {"force-share", no_argument
, 0, 'U'},
4378 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4386 missing_argument(argv
[optind
- 1]);
4389 unrecognized_option(argv
[optind
- 1]);
4398 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4399 error_report("Invalid request count specified");
4409 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4410 error_report("Invalid queue depth specified");
4420 flags
|= BDRV_O_NATIVE_AIO
;
4423 ret
= bdrv_parse_aio(optarg
, &flags
);
4425 error_report("Invalid aio option: %s", optarg
);
4432 offset
= cvtnum("offset", optarg
);
4446 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4458 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4467 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4469 error_report("Invalid cache mode");
4475 flags
|= BDRV_O_RDWR
;
4481 case OPTION_PATTERN
:
4485 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4486 error_report("Invalid pattern byte specified");
4492 case OPTION_FLUSH_INTERVAL
:
4496 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4497 error_report("Invalid flush interval specified");
4500 flush_interval
= res
;
4503 case OPTION_NO_DRAIN
:
4504 drain_on_flush
= false;
4506 case OPTION_IMAGE_OPTS
:
4512 if (optind
!= argc
- 1) {
4513 error_exit("Expecting one image file name");
4515 filename
= argv
[argc
- 1];
4517 if (!is_write
&& flush_interval
) {
4518 error_report("--flush-interval is only available in write tests");
4522 if (flush_interval
&& flush_interval
< depth
) {
4523 error_report("Flush interval can't be smaller than depth");
4528 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4535 image_size
= blk_getlength(blk
);
4536 if (image_size
< 0) {
4541 data
= (BenchData
) {
4543 .image_size
= image_size
,
4545 .step
= step
?: bufsize
,
4550 .flush_interval
= flush_interval
,
4551 .drain_on_flush
= drain_on_flush
,
4553 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4554 "(starting at offset %" PRId64
", step size %d)\n",
4555 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4556 data
.offset
, data
.step
);
4557 if (flush_interval
) {
4558 printf("Sending flush every %d requests\n", flush_interval
);
4561 buf_size
= data
.nrreq
* data
.bufsize
;
4562 data
.buf
= blk_blockalign(blk
, buf_size
);
4563 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4565 blk_register_buf(blk
, data
.buf
, buf_size
);
4567 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4568 for (i
= 0; i
< data
.nrreq
; i
++) {
4569 qemu_iovec_init(&data
.qiov
[i
], 1);
4570 qemu_iovec_add(&data
.qiov
[i
],
4571 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4574 gettimeofday(&t1
, NULL
);
4577 while (data
.n
> 0) {
4578 main_loop_wait(false);
4580 gettimeofday(&t2
, NULL
);
4582 printf("Run completed in %3.3f seconds.\n",
4583 (t2
.tv_sec
- t1
.tv_sec
)
4584 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4588 blk_unregister_buf(blk
, data
.buf
);
4590 qemu_vfree(data
.buf
);
4607 typedef struct ImgBitmapAction
{
4608 enum ImgBitmapAct act
;
4609 const char *src
; /* only used for merge */
4610 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4613 static int img_bitmap(int argc
, char **argv
)
4617 QemuOpts
*opts
= NULL
;
4618 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4619 const char *filename
, *bitmap
;
4620 BlockBackend
*blk
= NULL
, *src
= NULL
;
4621 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4622 bool image_opts
= false;
4623 int64_t granularity
= 0;
4624 bool add
= false, merge
= false;
4625 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4626 ImgBitmapAction
*act
, *act_next
;
4629 QSIMPLEQ_INIT(&actions
);
4632 static const struct option long_options
[] = {
4633 {"help", no_argument
, 0, 'h'},
4634 {"object", required_argument
, 0, OPTION_OBJECT
},
4635 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4636 {"add", no_argument
, 0, OPTION_ADD
},
4637 {"remove", no_argument
, 0, OPTION_REMOVE
},
4638 {"clear", no_argument
, 0, OPTION_CLEAR
},
4639 {"enable", no_argument
, 0, OPTION_ENABLE
},
4640 {"disable", no_argument
, 0, OPTION_DISABLE
},
4641 {"merge", required_argument
, 0, OPTION_MERGE
},
4642 {"granularity", required_argument
, 0, 'g'},
4643 {"source-file", required_argument
, 0, 'b'},
4644 {"source-format", required_argument
, 0, 'F'},
4647 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4654 missing_argument(argv
[optind
- 1]);
4657 unrecognized_option(argv
[optind
- 1]);
4663 src_filename
= optarg
;
4672 granularity
= cvtnum("granularity", optarg
);
4673 if (granularity
< 0) {
4678 act
= g_new0(ImgBitmapAction
, 1);
4679 act
->act
= BITMAP_ADD
;
4680 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4684 act
= g_new0(ImgBitmapAction
, 1);
4685 act
->act
= BITMAP_REMOVE
;
4686 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4689 act
= g_new0(ImgBitmapAction
, 1);
4690 act
->act
= BITMAP_CLEAR
;
4691 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4694 act
= g_new0(ImgBitmapAction
, 1);
4695 act
->act
= BITMAP_ENABLE
;
4696 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4698 case OPTION_DISABLE
:
4699 act
= g_new0(ImgBitmapAction
, 1);
4700 act
->act
= BITMAP_DISABLE
;
4701 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4704 act
= g_new0(ImgBitmapAction
, 1);
4705 act
->act
= BITMAP_MERGE
;
4707 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4711 user_creatable_process_cmdline(optarg
);
4713 case OPTION_IMAGE_OPTS
:
4719 if (QSIMPLEQ_EMPTY(&actions
)) {
4720 error_report("Need at least one of --add, --remove, --clear, "
4721 "--enable, --disable, or --merge");
4725 if (granularity
&& !add
) {
4726 error_report("granularity only supported with --add");
4729 if (src_fmt
&& !src_filename
) {
4730 error_report("-F only supported with -b");
4733 if (src_filename
&& !merge
) {
4734 error_report("Merge bitmap source file only supported with "
4739 if (optind
!= argc
- 2) {
4740 error_report("Expecting filename and bitmap name");
4744 filename
= argv
[optind
];
4745 bitmap
= argv
[optind
+ 1];
4748 * No need to open backing chains; we will be manipulating bitmaps
4749 * directly in this image without reference to image contents.
4751 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4752 false, false, false);
4758 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4759 false, false, false);
4763 src_bs
= blk_bs(src
);
4768 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4771 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4772 !!granularity
, granularity
, true, true,
4773 false, false, &err
);
4777 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4781 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4785 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4788 case BITMAP_DISABLE
:
4789 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4793 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4798 g_assert_not_reached();
4802 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4814 qemu_opts_del(opts
);
4830 int bsz
; /* Block size */
4838 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4842 static int img_dd_bs(const char *arg
,
4843 struct DdIo
*in
, struct DdIo
*out
,
4848 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4853 in
->bsz
= out
->bsz
= res
;
4858 static int img_dd_count(const char *arg
,
4859 struct DdIo
*in
, struct DdIo
*out
,
4862 dd
->count
= cvtnum("count", arg
);
4864 if (dd
->count
< 0) {
4871 static int img_dd_if(const char *arg
,
4872 struct DdIo
*in
, struct DdIo
*out
,
4875 in
->filename
= g_strdup(arg
);
4880 static int img_dd_of(const char *arg
,
4881 struct DdIo
*in
, struct DdIo
*out
,
4884 out
->filename
= g_strdup(arg
);
4889 static int img_dd_skip(const char *arg
,
4890 struct DdIo
*in
, struct DdIo
*out
,
4893 in
->offset
= cvtnum("skip", arg
);
4895 if (in
->offset
< 0) {
4902 static int img_dd(int argc
, char **argv
)
4907 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4908 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4909 QemuOpts
*opts
= NULL
;
4910 QemuOptsList
*create_opts
= NULL
;
4911 Error
*local_err
= NULL
;
4912 bool image_opts
= false;
4914 const char *out_fmt
= "raw";
4915 const char *fmt
= NULL
;
4917 int64_t block_count
= 0, out_pos
, in_pos
;
4918 bool force_share
= false;
4919 struct DdInfo dd
= {
4924 .bsz
= 512, /* Block size is by default 512 bytes */
4936 const struct DdOpts options
[] = {
4937 { "bs", img_dd_bs
, C_BS
},
4938 { "count", img_dd_count
, C_COUNT
},
4939 { "if", img_dd_if
, C_IF
},
4940 { "of", img_dd_of
, C_OF
},
4941 { "skip", img_dd_skip
, C_SKIP
},
4944 const struct option long_options
[] = {
4945 { "help", no_argument
, 0, 'h'},
4946 { "object", required_argument
, 0, OPTION_OBJECT
},
4947 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4948 { "force-share", no_argument
, 0, 'U'},
4952 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4964 missing_argument(argv
[optind
- 1]);
4967 unrecognized_option(argv
[optind
- 1]);
4976 user_creatable_process_cmdline(optarg
);
4978 case OPTION_IMAGE_OPTS
:
4984 for (i
= optind
; i
< argc
; i
++) {
4986 arg
= g_strdup(argv
[i
]);
4988 tmp
= strchr(arg
, '=');
4990 error_report("unrecognized operand %s", arg
);
4997 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4998 if (!strcmp(arg
, options
[j
].name
)) {
5002 if (options
[j
].name
== NULL
) {
5003 error_report("unrecognized operand %s", arg
);
5008 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5012 dd
.flags
|= options
[j
].flag
;
5017 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5018 error_report("Must specify both input and output files");
5023 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5031 drv
= bdrv_find_format(out_fmt
);
5033 error_report("Unknown file format");
5037 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5040 error_report_err(local_err
);
5044 if (!drv
->create_opts
) {
5045 error_report("Format driver '%s' does not support image creation",
5050 if (!proto_drv
->create_opts
) {
5051 error_report("Protocol driver '%s' does not support image creation",
5052 proto_drv
->format_name
);
5056 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5057 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5059 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5061 size
= blk_getlength(blk1
);
5063 error_report("Failed to get size for '%s'", in
.filename
);
5068 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5069 dd
.count
* in
.bsz
< size
) {
5070 size
= dd
.count
* in
.bsz
;
5073 /* Overflow means the specified offset is beyond input image's size */
5074 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5075 size
< in
.bsz
* in
.offset
)) {
5076 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5078 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5079 size
- in
.bsz
* in
.offset
, &error_abort
);
5082 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5084 error_reportf_err(local_err
,
5085 "%s: error while creating output image: ",
5091 /* TODO, we can't honour --image-opts for the target,
5092 * since it needs to be given in a format compatible
5093 * with the bdrv_create() call above which does not
5094 * support image-opts style.
5096 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5097 false, false, false);
5104 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5105 size
< in
.offset
* in
.bsz
)) {
5106 /* We give a warning if the skip option is bigger than the input
5107 * size and create an empty output disk image (i.e. like dd(1)).
5109 error_report("%s: cannot skip to specified offset", in
.filename
);
5112 in_pos
= in
.offset
* in
.bsz
;
5115 in
.buf
= g_new(uint8_t, in
.bsz
);
5117 for (out_pos
= 0; in_pos
< size
; block_count
++) {
5118 int in_ret
, out_ret
;
5120 if (in_pos
+ in
.bsz
> size
) {
5121 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
5123 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
5126 error_report("error while reading from input image file: %s",
5133 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
5136 error_report("error while writing to output image file: %s",
5137 strerror(-out_ret
));
5146 qemu_opts_del(opts
);
5147 qemu_opts_free(create_opts
);
5150 g_free(in
.filename
);
5151 g_free(out
.filename
);
5161 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5165 Visitor
*v
= qobject_output_visitor_new(&obj
);
5167 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5168 visit_complete(v
, &obj
);
5169 str
= qobject_to_json_pretty(obj
, true);
5170 assert(str
!= NULL
);
5171 printf("%s\n", str
->str
);
5174 g_string_free(str
, true);
5177 static int img_measure(int argc
, char **argv
)
5179 static const struct option long_options
[] = {
5180 {"help", no_argument
, 0, 'h'},
5181 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5182 {"object", required_argument
, 0, OPTION_OBJECT
},
5183 {"output", required_argument
, 0, OPTION_OUTPUT
},
5184 {"size", required_argument
, 0, OPTION_SIZE
},
5185 {"force-share", no_argument
, 0, 'U'},
5188 OutputFormat output_format
= OFORMAT_HUMAN
;
5189 BlockBackend
*in_blk
= NULL
;
5191 const char *filename
= NULL
;
5192 const char *fmt
= NULL
;
5193 const char *out_fmt
= "raw";
5194 char *options
= NULL
;
5195 char *snapshot_name
= NULL
;
5196 bool force_share
= false;
5197 QemuOpts
*opts
= NULL
;
5198 QemuOpts
*object_opts
= NULL
;
5199 QemuOpts
*sn_opts
= NULL
;
5200 QemuOptsList
*create_opts
= NULL
;
5201 bool image_opts
= false;
5202 uint64_t img_size
= UINT64_MAX
;
5203 BlockMeasureInfo
*info
= NULL
;
5204 Error
*local_err
= NULL
;
5208 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5209 long_options
, NULL
)) != -1) {
5222 if (accumulate_options(&options
, optarg
) < 0) {
5227 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5228 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5231 error_report("Failed in parsing snapshot param '%s'",
5236 snapshot_name
= optarg
;
5243 user_creatable_process_cmdline(optarg
);
5245 case OPTION_IMAGE_OPTS
:
5249 if (!strcmp(optarg
, "json")) {
5250 output_format
= OFORMAT_JSON
;
5251 } else if (!strcmp(optarg
, "human")) {
5252 output_format
= OFORMAT_HUMAN
;
5254 error_report("--output must be used with human or json "
5263 sval
= cvtnum("image size", optarg
);
5267 img_size
= (uint64_t)sval
;
5273 if (argc
- optind
> 1) {
5274 error_report("At most one filename argument is allowed.");
5276 } else if (argc
- optind
== 1) {
5277 filename
= argv
[optind
];
5280 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5281 error_report("--image-opts, -f, and -l require a filename argument.");
5284 if (filename
&& img_size
!= UINT64_MAX
) {
5285 error_report("--size N cannot be used together with a filename.");
5288 if (!filename
&& img_size
== UINT64_MAX
) {
5289 error_report("Either --size N or one filename must be specified.");
5294 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5295 false, false, force_share
);
5301 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5302 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5303 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5305 } else if (snapshot_name
!= NULL
) {
5306 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5307 snapshot_name
, &local_err
);
5310 error_reportf_err(local_err
, "Failed to load snapshot: ");
5315 drv
= bdrv_find_format(out_fmt
);
5317 error_report("Unknown file format '%s'", out_fmt
);
5320 if (!drv
->create_opts
) {
5321 error_report("Format driver '%s' does not support image creation",
5326 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5327 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5328 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5330 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5331 error_report_err(local_err
);
5332 error_report("Invalid options for file format '%s'", out_fmt
);
5336 if (img_size
!= UINT64_MAX
) {
5337 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5340 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5342 error_report_err(local_err
);
5346 if (output_format
== OFORMAT_HUMAN
) {
5347 printf("required size: %" PRIu64
"\n", info
->required
);
5348 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5349 if (info
->has_bitmaps
) {
5350 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5353 dump_json_block_measure_info(info
);
5359 qapi_free_BlockMeasureInfo(info
);
5360 qemu_opts_del(object_opts
);
5361 qemu_opts_del(opts
);
5362 qemu_opts_del(sn_opts
);
5363 qemu_opts_free(create_opts
);
5369 static const img_cmd_t img_cmds
[] = {
5370 #define DEF(option, callback, arg_string) \
5371 { option, callback },
5372 #include "qemu-img-cmds.h"
5377 int main(int argc
, char **argv
)
5379 const img_cmd_t
*cmd
;
5380 const char *cmdname
;
5382 static const struct option long_options
[] = {
5383 {"help", no_argument
, 0, 'h'},
5384 {"version", no_argument
, 0, 'V'},
5385 {"trace", required_argument
, NULL
, 'T'},
5390 signal(SIGPIPE
, SIG_IGN
);
5394 error_init(argv
[0]);
5395 module_call_init(MODULE_INIT_TRACE
);
5396 qemu_init_exec_dir(argv
[0]);
5398 qemu_init_main_loop(&error_fatal
);
5400 qcrypto_init(&error_fatal
);
5402 module_call_init(MODULE_INIT_QOM
);
5405 error_exit("Not enough arguments");
5408 qemu_add_opts(&qemu_source_opts
);
5409 qemu_add_opts(&qemu_trace_opts
);
5411 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5414 missing_argument(argv
[optind
- 1]);
5417 unrecognized_option(argv
[optind
- 1]);
5423 printf(QEMU_IMG_VERSION
);
5426 trace_opt_parse(optarg
);
5431 cmdname
= argv
[optind
];
5433 /* reset getopt_long scanning */
5439 qemu_reset_optind();
5441 if (!trace_init_backends()) {
5445 qemu_set_log(LOG_TRACE
);
5447 /* find the command */
5448 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5449 if (!strcmp(cmdname
, cmd
->name
)) {
5450 return cmd
->handler(argc
, argv
);
5455 error_exit("Command not found: %s", cmdname
);