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-visit-block-core.h"
32 #include "qapi/qobject-output-visitor.h"
33 #include "qapi/qmp/qjson.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.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/units.h"
44 #include "qom/object_interfaces.h"
45 #include "sysemu/block-backend.h"
46 #include "block/block_int.h"
47 #include "block/blockjob.h"
48 #include "block/qapi.h"
49 #include "crypto/init.h"
50 #include "trace/control.h"
52 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
53 "\n" QEMU_COPYRIGHT "\n"
55 typedef struct img_cmd_t
{
57 int (*handler
)(int argc
, char **argv
);
62 OPTION_BACKING_CHAIN
= 257,
64 OPTION_IMAGE_OPTS
= 259,
66 OPTION_FLUSH_INTERVAL
= 261,
67 OPTION_NO_DRAIN
= 262,
68 OPTION_TARGET_IMAGE_OPTS
= 263,
70 OPTION_PREALLOCATION
= 265,
75 typedef enum OutputFormat
{
80 /* Default to cache=writeback as data integrity is not important for qemu-img */
81 #define BDRV_DEFAULT_CACHE "writeback"
83 static void format_print(void *opaque
, const char *name
)
88 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
93 error_vreport(fmt
, ap
);
96 error_printf("Try 'qemu-img --help' for more information\n");
100 static void QEMU_NORETURN
missing_argument(const char *option
)
102 error_exit("missing argument for option '%s'", option
);
105 static void QEMU_NORETURN
unrecognized_option(const char *option
)
107 error_exit("unrecognized option '%s'", option
);
110 /* Please keep in synch with qemu-img.texi */
111 static void QEMU_NORETURN
help(void)
113 const char *help_msg
=
115 "usage: qemu-img [standard options] command [command options]\n"
116 "QEMU disk image utility\n"
118 " '-h', '--help' display this help and exit\n"
119 " '-V', '--version' output version information and exit\n"
120 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121 " specify tracing options\n"
124 #define DEF(option, callback, arg_string) \
126 #include "qemu-img-cmds.h"
129 "Command parameters:\n"
130 " 'filename' is a disk image filename\n"
131 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
132 " manual page for a description of the object properties. The most common\n"
133 " object type is a 'secret', which is used to supply passwords and/or\n"
134 " encryption keys.\n"
135 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
136 " 'cache' is the cache mode used to write the output disk image, the valid\n"
137 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
138 " 'directsync' and 'unsafe' (default for convert)\n"
139 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
140 " options are the same as for the 'cache' option\n"
141 " 'size' is the disk image size in bytes. Optional suffixes\n"
142 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
143 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
144 " supported. 'b' is ignored.\n"
145 " 'output_filename' is the destination disk image filename\n"
146 " 'output_fmt' is the destination format\n"
147 " 'options' is a comma separated list of format specific options in a\n"
148 " name=value format. Use -o ? for an overview of the options supported by the\n"
150 " 'snapshot_param' is param used for internal snapshot, format\n"
151 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
153 " '-c' indicates that target image must be compressed (qcow format only)\n"
154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
159 " '-h' with or without a command shows this help and lists the supported formats\n"
160 " '-p' show progress of command (only certain commands)\n"
161 " '-q' use Quiet mode - do not print any output (except errors)\n"
162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
167 " '--output' takes the format in which the output must be done (human or json)\n"
168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
175 " hiding corruption that has already occurred.\n"
177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
187 " '-l' lists all snapshots in the given image\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
202 printf("%s\nSupported formats:", help_msg
);
203 bdrv_iterate_format(format_print
, NULL
, false);
204 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
208 static QemuOptsList qemu_object_opts
= {
210 .implied_opt_name
= "qom-type",
211 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
217 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
219 if (user_creatable_print_help(type
, opts
)) {
225 static QemuOptsList qemu_source_opts
= {
227 .implied_opt_name
= "file",
228 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
234 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
240 ret
= vprintf(fmt
, args
);
247 static int print_block_option_help(const char *filename
, const char *fmt
)
249 BlockDriver
*drv
, *proto_drv
;
250 QemuOptsList
*create_opts
= NULL
;
251 Error
*local_err
= NULL
;
253 /* Find driver and parse its options */
254 drv
= bdrv_find_format(fmt
);
256 error_report("Unknown file format '%s'", fmt
);
260 if (!drv
->create_opts
) {
261 error_report("Format driver '%s' does not support image creation", fmt
);
265 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
267 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
269 error_report_err(local_err
);
270 qemu_opts_free(create_opts
);
273 if (!proto_drv
->create_opts
) {
274 error_report("Protocol driver '%s' does not support image creation",
275 proto_drv
->format_name
);
276 qemu_opts_free(create_opts
);
279 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
283 printf("Supported options:\n");
285 printf("Supported %s options:\n", fmt
);
287 qemu_opts_print_help(create_opts
, false);
288 qemu_opts_free(create_opts
);
292 "The protocol level may support further options.\n"
293 "Specify the target filename to include those options.\n");
300 static BlockBackend
*img_open_opts(const char *optstr
,
301 QemuOpts
*opts
, int flags
, bool writethrough
,
302 bool quiet
, bool force_share
)
305 Error
*local_err
= NULL
;
307 options
= qemu_opts_to_qdict(opts
, NULL
);
309 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
310 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
311 error_report("--force-share/-U conflicts with image options");
312 qobject_unref(options
);
315 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
317 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
319 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
322 blk_set_enable_write_cache(blk
, !writethrough
);
327 static BlockBackend
*img_open_file(const char *filename
,
329 const char *fmt
, int flags
,
330 bool writethrough
, bool quiet
,
334 Error
*local_err
= NULL
;
337 options
= qdict_new();
340 qdict_put_str(options
, "driver", fmt
);
344 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
346 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
348 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
351 blk_set_enable_write_cache(blk
, !writethrough
);
357 static int img_add_key_secrets(void *opaque
,
358 const char *name
, const char *value
,
361 QDict
*options
= opaque
;
363 if (g_str_has_suffix(name
, "key-secret")) {
364 qdict_put_str(options
, name
, value
);
371 static BlockBackend
*img_open(bool image_opts
,
372 const char *filename
,
373 const char *fmt
, int flags
, bool writethrough
,
374 bool quiet
, bool force_share
)
380 error_report("--image-opts and --format are mutually exclusive");
383 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
388 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
391 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
398 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
399 const char *base_filename
,
400 const char *base_fmt
)
405 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
407 error_report("Backing file not supported for file format '%s'",
414 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
416 error_report("Backing file format not supported for file "
425 static int64_t cvtnum(const char *s
)
430 err
= qemu_strtosz(s
, NULL
, &value
);
434 if (value
> INT64_MAX
) {
440 static int img_create(int argc
, char **argv
)
443 uint64_t img_size
= -1;
444 const char *fmt
= "raw";
445 const char *base_fmt
= NULL
;
446 const char *filename
;
447 const char *base_filename
= NULL
;
448 char *options
= NULL
;
449 Error
*local_err
= NULL
;
454 static const struct option long_options
[] = {
455 {"help", no_argument
, 0, 'h'},
456 {"object", required_argument
, 0, OPTION_OBJECT
},
459 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
466 missing_argument(argv
[optind
- 1]);
469 unrecognized_option(argv
[optind
- 1]);
478 base_filename
= optarg
;
484 if (!is_valid_option_list(optarg
)) {
485 error_report("Invalid option list: %s", optarg
);
489 options
= g_strdup(optarg
);
491 char *old_options
= options
;
492 options
= g_strdup_printf("%s,%s", options
, optarg
);
500 flags
|= BDRV_O_NO_BACKING
;
502 case OPTION_OBJECT
: {
504 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
513 /* Get the filename */
514 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
515 if (options
&& has_help_option(options
)) {
517 return print_block_option_help(filename
, fmt
);
520 if (optind
>= argc
) {
521 error_exit("Expecting image file name");
525 if (qemu_opts_foreach(&qemu_object_opts
,
526 user_creatable_add_opts_foreach
,
527 qemu_img_object_print_help
, &error_fatal
)) {
531 /* Get image size, if specified */
535 sval
= cvtnum(argv
[optind
++]);
537 if (sval
== -ERANGE
) {
538 error_report("Image size must be less than 8 EiB!");
540 error_report("Invalid image size specified! You may use k, M, "
541 "G, T, P or E suffixes for ");
542 error_report("kilobytes, megabytes, gigabytes, terabytes, "
543 "petabytes and exabytes.");
547 img_size
= (uint64_t)sval
;
549 if (optind
!= argc
) {
550 error_exit("Unexpected argument: %s", argv
[optind
]);
553 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
554 options
, img_size
, flags
, quiet
, &local_err
);
556 error_reportf_err(local_err
, "%s: ", filename
);
568 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
572 Visitor
*v
= qobject_output_visitor_new(&obj
);
574 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
575 visit_complete(v
, &obj
);
576 str
= qobject_to_json_pretty(obj
);
578 qprintf(quiet
, "%s\n", qstring_get_str(str
));
584 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
586 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
587 qprintf(quiet
, "No errors were found on the image.\n");
589 if (check
->corruptions
) {
590 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
591 "Data may be corrupted, or further writes to the image "
598 "\n%" PRId64
" leaked clusters were found on the image.\n"
599 "This means waste of disk space, but no harm to data.\n",
603 if (check
->check_errors
) {
606 " internal errors have occurred during the check.\n",
607 check
->check_errors
);
611 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
612 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
613 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
614 check
->allocated_clusters
, check
->total_clusters
,
615 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
616 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
617 check
->compressed_clusters
* 100.0 /
618 check
->allocated_clusters
);
621 if (check
->image_end_offset
) {
623 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
627 static int collect_image_check(BlockDriverState
*bs
,
629 const char *filename
,
634 BdrvCheckResult result
;
636 ret
= bdrv_check(bs
, &result
, fix
);
641 check
->filename
= g_strdup(filename
);
642 check
->format
= g_strdup(bdrv_get_format_name(bs
));
643 check
->check_errors
= result
.check_errors
;
644 check
->corruptions
= result
.corruptions
;
645 check
->has_corruptions
= result
.corruptions
!= 0;
646 check
->leaks
= result
.leaks
;
647 check
->has_leaks
= result
.leaks
!= 0;
648 check
->corruptions_fixed
= result
.corruptions_fixed
;
649 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
650 check
->leaks_fixed
= result
.leaks_fixed
;
651 check
->has_leaks_fixed
= result
.leaks
!= 0;
652 check
->image_end_offset
= result
.image_end_offset
;
653 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
654 check
->total_clusters
= result
.bfi
.total_clusters
;
655 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
656 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
657 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
658 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
659 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
660 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
661 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
667 * Checks an image for consistency. Exit codes:
669 * 0 - Check completed, image is good
670 * 1 - Check not completed because of internal errors
671 * 2 - Check completed, image is corrupted
672 * 3 - Check completed, image has leaked clusters, but is good otherwise
673 * 63 - Checks are not supported by the image format
675 static int img_check(int argc
, char **argv
)
678 OutputFormat output_format
= OFORMAT_HUMAN
;
679 const char *filename
, *fmt
, *output
, *cache
;
681 BlockDriverState
*bs
;
683 int flags
= BDRV_O_CHECK
;
687 bool image_opts
= false;
688 bool force_share
= false;
692 cache
= BDRV_DEFAULT_CACHE
;
695 int option_index
= 0;
696 static const struct option long_options
[] = {
697 {"help", no_argument
, 0, 'h'},
698 {"format", required_argument
, 0, 'f'},
699 {"repair", required_argument
, 0, 'r'},
700 {"output", required_argument
, 0, OPTION_OUTPUT
},
701 {"object", required_argument
, 0, OPTION_OBJECT
},
702 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
703 {"force-share", no_argument
, 0, 'U'},
706 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
707 long_options
, &option_index
);
713 missing_argument(argv
[optind
- 1]);
716 unrecognized_option(argv
[optind
- 1]);
725 flags
|= BDRV_O_RDWR
;
727 if (!strcmp(optarg
, "leaks")) {
728 fix
= BDRV_FIX_LEAKS
;
729 } else if (!strcmp(optarg
, "all")) {
730 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
732 error_exit("Unknown option value for -r "
733 "(expecting 'leaks' or 'all'): %s", optarg
);
748 case OPTION_OBJECT
: {
750 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
756 case OPTION_IMAGE_OPTS
:
761 if (optind
!= argc
- 1) {
762 error_exit("Expecting one image file name");
764 filename
= argv
[optind
++];
766 if (output
&& !strcmp(output
, "json")) {
767 output_format
= OFORMAT_JSON
;
768 } else if (output
&& !strcmp(output
, "human")) {
769 output_format
= OFORMAT_HUMAN
;
771 error_report("--output must be used with human or json as argument.");
775 if (qemu_opts_foreach(&qemu_object_opts
,
776 user_creatable_add_opts_foreach
,
777 qemu_img_object_print_help
, &error_fatal
)) {
781 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
783 error_report("Invalid source cache option: %s", cache
);
787 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
794 check
= g_new0(ImageCheck
, 1);
795 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
797 if (ret
== -ENOTSUP
) {
798 error_report("This image format does not support checks");
803 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
804 int corruptions_fixed
, leaks_fixed
;
806 leaks_fixed
= check
->leaks_fixed
;
807 corruptions_fixed
= check
->corruptions_fixed
;
809 if (output_format
== OFORMAT_HUMAN
) {
811 "The following inconsistencies were found and repaired:\n\n"
812 " %" PRId64
" leaked clusters\n"
813 " %" PRId64
" corruptions\n\n"
814 "Double checking the fixed image now...\n",
816 check
->corruptions_fixed
);
819 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
821 check
->leaks_fixed
= leaks_fixed
;
822 check
->corruptions_fixed
= corruptions_fixed
;
826 switch (output_format
) {
828 dump_human_image_check(check
, quiet
);
831 dump_json_image_check(check
, quiet
);
836 if (ret
|| check
->check_errors
) {
838 error_report("Check failed: %s", strerror(-ret
));
840 error_report("Check failed");
846 if (check
->corruptions
) {
848 } else if (check
->leaks
) {
855 qapi_free_ImageCheck(check
);
860 typedef struct CommonBlockJobCBInfo
{
861 BlockDriverState
*bs
;
863 } CommonBlockJobCBInfo
;
865 static void common_block_job_cb(void *opaque
, int ret
)
867 CommonBlockJobCBInfo
*cbi
= opaque
;
870 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
874 static void run_block_job(BlockJob
*job
, Error
**errp
)
876 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
879 aio_context_acquire(aio_context
);
882 float progress
= 0.0f
;
883 aio_poll(aio_context
, true);
884 if (job
->job
.progress_total
) {
885 progress
= (float)job
->job
.progress_current
/
886 job
->job
.progress_total
* 100.f
;
888 qemu_progress_print(progress
, 0);
889 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
891 if (!job_is_completed(&job
->job
)) {
892 ret
= job_complete_sync(&job
->job
, errp
);
896 job_unref(&job
->job
);
897 aio_context_release(aio_context
);
899 /* publish completion progress only when success */
901 qemu_progress_print(100.f
, 0);
905 static int img_commit(int argc
, char **argv
)
908 const char *filename
, *fmt
, *cache
, *base
;
910 BlockDriverState
*bs
, *base_bs
;
912 bool progress
= false, quiet
= false, drop
= false;
914 Error
*local_err
= NULL
;
915 CommonBlockJobCBInfo cbi
;
916 bool image_opts
= false;
917 AioContext
*aio_context
;
920 cache
= BDRV_DEFAULT_CACHE
;
923 static const struct option long_options
[] = {
924 {"help", no_argument
, 0, 'h'},
925 {"object", required_argument
, 0, OPTION_OBJECT
},
926 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
929 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
936 missing_argument(argv
[optind
- 1]);
939 unrecognized_option(argv
[optind
- 1]);
964 case OPTION_OBJECT
: {
966 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
972 case OPTION_IMAGE_OPTS
:
978 /* Progress is not shown in Quiet mode */
983 if (optind
!= argc
- 1) {
984 error_exit("Expecting one image file name");
986 filename
= argv
[optind
++];
988 if (qemu_opts_foreach(&qemu_object_opts
,
989 user_creatable_add_opts_foreach
,
990 qemu_img_object_print_help
, &error_fatal
)) {
994 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
995 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
997 error_report("Invalid cache option: %s", cache
);
1001 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1008 qemu_progress_init(progress
, 1.f
);
1009 qemu_progress_print(0.f
, 100);
1012 base_bs
= bdrv_find_backing_image(bs
, base
);
1014 error_setg(&local_err
,
1015 "Did not find '%s' in the backing chain of '%s'",
1020 /* This is different from QMP, which by default uses the deepest file in
1021 * the backing chain (i.e., the very base); however, the traditional
1022 * behavior of qemu-img commit is using the immediate backing file. */
1023 base_bs
= backing_bs(bs
);
1025 error_setg(&local_err
, "Image does not have a backing file");
1030 cbi
= (CommonBlockJobCBInfo
){
1035 aio_context
= bdrv_get_aio_context(bs
);
1036 aio_context_acquire(aio_context
);
1037 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1038 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1039 &cbi
, false, &local_err
);
1040 aio_context_release(aio_context
);
1045 /* When the block job completes, the BlockBackend reference will point to
1046 * the old backing file. In order to avoid that the top image is already
1047 * deleted, so we can still empty it afterwards, increment the reference
1048 * counter here preemptively. */
1053 job
= block_job_get("commit");
1055 run_block_job(job
, &local_err
);
1060 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1061 ret
= bs
->drv
->bdrv_make_empty(bs
);
1063 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1075 qemu_progress_end();
1080 error_report_err(local_err
);
1084 qprintf(quiet
, "Image committed.\n");
1089 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1090 * of the first sector boundary within buf where the sector contains a
1091 * non-zero byte. This function is robust to a buffer that is not
1094 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1097 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1099 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1100 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1104 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1111 * Returns true iff the first sector pointed to by 'buf' contains at least
1114 * 'pnum' is set to the number of sectors (including and immediately following
1115 * the first one) that are known to be in the same allocated/unallocated state.
1116 * The function will try to align the end offset to alignment boundaries so
1117 * that the request will at least end aligned and consequtive requests will
1118 * also start at an aligned offset.
1120 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1121 int64_t sector_num
, int alignment
)
1130 is_zero
= buffer_is_zero(buf
, 512);
1131 for(i
= 1; i
< n
; i
++) {
1133 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1138 tail
= (sector_num
+ i
) & (alignment
- 1);
1140 if (is_zero
&& i
<= tail
) {
1141 /* treat unallocated areas which only consist
1142 * of a small tail as allocated. */
1146 /* align up end offset of allocated areas. */
1147 i
+= alignment
- tail
;
1150 /* align down end offset of zero areas. */
1159 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1160 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1161 * breaking up write requests for only small sparse areas.
1163 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1164 int min
, int64_t sector_num
, int alignment
)
1167 int num_checked
, num_used
;
1173 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1179 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1181 sector_num
+= *pnum
;
1182 num_checked
= num_used
;
1185 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1187 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1189 sector_num
+= *pnum
;
1190 num_checked
+= *pnum
;
1192 num_used
= num_checked
;
1193 } else if (*pnum
>= min
) {
1203 * Compares two buffers sector by sector. Returns 0 if the first
1204 * sector of each buffer matches, non-zero otherwise.
1206 * pnum is set to the sector-aligned size of the buffer prefix that
1207 * has the same matching status as the first sector.
1209 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1210 int64_t bytes
, int64_t *pnum
)
1213 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1217 res
= !!memcmp(buf1
, buf2
, i
);
1219 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1221 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1231 #define IO_BUF_SIZE (2 * MiB)
1234 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1236 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1237 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1238 * failure), and 4 on error (the exit status for read errors), after emitting
1241 * @param blk: BlockBackend for the image
1242 * @param offset: Starting offset to check
1243 * @param bytes: Number of bytes to check
1244 * @param filename: Name of disk file we are checking (logging purpose)
1245 * @param buffer: Allocated buffer for storing read data
1246 * @param quiet: Flag for quiet mode
1248 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1249 int64_t bytes
, const char *filename
,
1250 uint8_t *buffer
, bool quiet
)
1255 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1257 error_report("Error while reading offset %" PRId64
" of %s: %s",
1258 offset
, filename
, strerror(-ret
));
1261 idx
= find_nonzero(buffer
, bytes
);
1263 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1272 * Compares two images. Exit codes:
1274 * 0 - Images are identical
1276 * >1 - Error occurred
1278 static int img_compare(int argc
, char **argv
)
1280 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1281 BlockBackend
*blk1
, *blk2
;
1282 BlockDriverState
*bs1
, *bs2
;
1283 int64_t total_size1
, total_size2
;
1284 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1285 int64_t pnum1
, pnum2
;
1286 int allocated1
, allocated2
;
1287 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1288 bool progress
= false, quiet
= false, strict
= false;
1295 uint64_t progress_base
;
1296 bool image_opts
= false;
1297 bool force_share
= false;
1299 cache
= BDRV_DEFAULT_CACHE
;
1301 static const struct option long_options
[] = {
1302 {"help", no_argument
, 0, 'h'},
1303 {"object", required_argument
, 0, OPTION_OBJECT
},
1304 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1305 {"force-share", no_argument
, 0, 'U'},
1308 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1309 long_options
, NULL
);
1315 missing_argument(argv
[optind
- 1]);
1318 unrecognized_option(argv
[optind
- 1]);
1344 case OPTION_OBJECT
: {
1346 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1353 case OPTION_IMAGE_OPTS
:
1359 /* Progress is not shown in Quiet mode */
1365 if (optind
!= argc
- 2) {
1366 error_exit("Expecting two image file names");
1368 filename1
= argv
[optind
++];
1369 filename2
= argv
[optind
++];
1371 if (qemu_opts_foreach(&qemu_object_opts
,
1372 user_creatable_add_opts_foreach
,
1373 qemu_img_object_print_help
, &error_fatal
)) {
1378 /* Initialize before goto out */
1379 qemu_progress_init(progress
, 2.0);
1382 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1384 error_report("Invalid source cache option: %s", cache
);
1389 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1396 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1405 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1406 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1407 total_size1
= blk_getlength(blk1
);
1408 if (total_size1
< 0) {
1409 error_report("Can't get size of %s: %s",
1410 filename1
, strerror(-total_size1
));
1414 total_size2
= blk_getlength(blk2
);
1415 if (total_size2
< 0) {
1416 error_report("Can't get size of %s: %s",
1417 filename2
, strerror(-total_size2
));
1421 total_size
= MIN(total_size1
, total_size2
);
1422 progress_base
= MAX(total_size1
, total_size2
);
1424 qemu_progress_print(0, 100);
1426 if (strict
&& total_size1
!= total_size2
) {
1428 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1432 while (offset
< total_size
) {
1433 int status1
, status2
;
1435 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1436 total_size1
- offset
, &pnum1
, NULL
,
1440 error_report("Sector allocation test failed for %s", filename1
);
1443 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1445 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1446 total_size2
- offset
, &pnum2
, NULL
,
1450 error_report("Sector allocation test failed for %s", filename2
);
1453 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1455 assert(pnum1
&& pnum2
);
1456 chunk
= MIN(pnum1
, pnum2
);
1459 if (status1
!= status2
) {
1461 qprintf(quiet
, "Strict mode: Offset %" PRId64
1462 " block status mismatch!\n", offset
);
1466 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1468 } else if (allocated1
== allocated2
) {
1472 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1473 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1475 error_report("Error while reading offset %" PRId64
1477 offset
, filename1
, strerror(-ret
));
1481 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1483 error_report("Error while reading offset %" PRId64
1485 offset
, filename2
, strerror(-ret
));
1489 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1490 if (ret
|| pnum
!= chunk
) {
1491 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1492 offset
+ (ret
? 0 : pnum
));
1498 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1500 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1501 filename1
, buf1
, quiet
);
1503 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1504 filename2
, buf1
, quiet
);
1511 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1514 if (total_size1
!= total_size2
) {
1515 BlockBackend
*blk_over
;
1516 const char *filename_over
;
1518 qprintf(quiet
, "Warning: Image size mismatch!\n");
1519 if (total_size1
> total_size2
) {
1521 filename_over
= filename1
;
1524 filename_over
= filename2
;
1527 while (offset
< progress_base
) {
1528 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1529 progress_base
- offset
, &chunk
,
1533 error_report("Sector allocation test failed for %s",
1538 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1539 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1540 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1541 filename_over
, buf1
, quiet
);
1547 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1551 qprintf(quiet
, "Images are identical.\n");
1561 qemu_progress_end();
1566 enum ImgConvertBlockStatus
{
1572 #define MAX_COROUTINES 16
1574 typedef struct ImgConvertState
{
1576 int64_t *src_sectors
;
1578 int64_t total_sectors
;
1579 int64_t allocated_sectors
;
1580 int64_t allocated_done
;
1583 enum ImgConvertBlockStatus status
;
1584 int64_t sector_next_status
;
1585 BlockBackend
*target
;
1588 bool unallocated_blocks_are_zero
;
1590 bool target_has_backing
;
1591 int64_t target_backing_sectors
; /* negative if unknown */
1598 size_t cluster_sectors
;
1600 long num_coroutines
;
1601 int running_coroutines
;
1602 Coroutine
*co
[MAX_COROUTINES
];
1603 int64_t wait_sector_num
[MAX_COROUTINES
];
1608 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1609 int *src_cur
, int64_t *src_cur_offset
)
1612 *src_cur_offset
= 0;
1613 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1614 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1616 assert(*src_cur
< s
->src_num
);
1620 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1622 int64_t src_cur_offset
;
1623 int ret
, n
, src_cur
;
1624 bool post_backing_zero
= false;
1626 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1628 assert(s
->total_sectors
> sector_num
);
1629 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1631 if (s
->target_backing_sectors
>= 0) {
1632 if (sector_num
>= s
->target_backing_sectors
) {
1633 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1634 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1635 /* Split requests around target_backing_sectors (because
1636 * starting from there, zeros are handled differently) */
1637 n
= s
->target_backing_sectors
- sector_num
;
1641 if (s
->sector_next_status
<= sector_num
) {
1642 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1646 count
= n
* BDRV_SECTOR_SIZE
;
1648 if (s
->target_has_backing
) {
1649 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1650 count
, &count
, NULL
, NULL
);
1652 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1653 offset
, count
, &count
, NULL
,
1661 warn_report("error while reading block status at "
1662 "offset %" PRIu64
": %s", offset
,
1665 /* Just try to read the data, then */
1666 ret
= BDRV_BLOCK_DATA
;
1667 count
= BDRV_SECTOR_SIZE
;
1669 /* Retry on a shorter range */
1670 n
= DIV_ROUND_UP(n
, 4);
1673 error_report("error while reading block status at offset "
1674 "%" PRIu64
": %s", offset
, strerror(-ret
));
1680 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1682 if (ret
& BDRV_BLOCK_ZERO
) {
1683 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1684 } else if (ret
& BDRV_BLOCK_DATA
) {
1685 s
->status
= BLK_DATA
;
1687 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1690 s
->sector_next_status
= sector_num
+ n
;
1693 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1694 if (s
->status
== BLK_DATA
) {
1695 n
= MIN(n
, s
->buf_sectors
);
1698 /* We need to write complete clusters for compressed images, so if an
1699 * unallocated area is shorter than that, we must consider the whole
1700 * cluster allocated. */
1701 if (s
->compressed
) {
1702 if (n
< s
->cluster_sectors
) {
1703 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1704 s
->status
= BLK_DATA
;
1706 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1713 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1714 int nb_sectors
, uint8_t *buf
)
1716 uint64_t single_read_until
= 0;
1719 assert(nb_sectors
<= s
->buf_sectors
);
1720 while (nb_sectors
> 0) {
1723 int64_t bs_sectors
, src_cur_offset
;
1726 /* In the case of compression with multiple source files, we can get a
1727 * nb_sectors that spreads into the next part. So we must be able to
1728 * read across multiple BDSes for one convert_read() call. */
1729 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1730 blk
= s
->src
[src_cur
];
1731 bs_sectors
= s
->src_sectors
[src_cur
];
1733 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1735 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1736 if (single_read_until
> offset
) {
1740 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1744 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1748 warn_report("error while reading offset %" PRIu64
1749 ": %s", offset
, strerror(-ret
));
1751 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1760 buf
+= n
* BDRV_SECTOR_SIZE
;
1767 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1768 int nb_sectors
, uint8_t *buf
,
1769 enum ImgConvertBlockStatus status
)
1773 while (nb_sectors
> 0) {
1775 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1778 case BLK_BACKING_FILE
:
1779 /* If we have a backing file, leave clusters unallocated that are
1780 * unallocated in the source image, so that the backing file is
1781 * visible at the respective offset. */
1782 assert(s
->target_has_backing
);
1786 /* If we're told to keep the target fully allocated (-S 0) or there
1787 * is real non-zero data, we must write it. Otherwise we can treat
1788 * it as zero sectors.
1789 * Compressed clusters need to be written as a whole, so in that
1790 * case we can only save the write if the buffer is completely
1792 if (!s
->min_sparse
||
1794 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1795 sector_num
, s
->alignment
)) ||
1797 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1799 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1800 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1809 if (s
->has_zero_init
) {
1810 assert(!s
->target_has_backing
);
1813 ret
= blk_co_pwrite_zeroes(s
->target
,
1814 sector_num
<< BDRV_SECTOR_BITS
,
1815 n
<< BDRV_SECTOR_BITS
,
1816 BDRV_REQ_MAY_UNMAP
);
1825 buf
+= n
* BDRV_SECTOR_SIZE
;
1831 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1836 while (nb_sectors
> 0) {
1839 int64_t bs_sectors
, src_cur_offset
;
1842 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1843 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1844 blk
= s
->src
[src_cur
];
1845 bs_sectors
= s
->src_sectors
[src_cur
];
1847 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1849 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1850 sector_num
<< BDRV_SECTOR_BITS
,
1851 n
<< BDRV_SECTOR_BITS
, 0, 0);
1862 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1864 ImgConvertState
*s
= opaque
;
1865 uint8_t *buf
= NULL
;
1869 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1870 if (s
->co
[i
] == qemu_coroutine_self()) {
1877 s
->running_coroutines
++;
1878 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1883 enum ImgConvertBlockStatus status
;
1886 qemu_co_mutex_lock(&s
->lock
);
1887 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1888 qemu_co_mutex_unlock(&s
->lock
);
1891 n
= convert_iteration_sectors(s
, s
->sector_num
);
1893 qemu_co_mutex_unlock(&s
->lock
);
1897 /* save current sector and allocation status to local variables */
1898 sector_num
= s
->sector_num
;
1900 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1901 n
= MIN(n
, s
->buf_sectors
);
1903 /* increment global sector counter so that other coroutines can
1904 * already continue reading beyond this request */
1906 qemu_co_mutex_unlock(&s
->lock
);
1908 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1909 s
->allocated_done
+= n
;
1910 qemu_progress_print(100.0 * s
->allocated_done
/
1911 s
->allocated_sectors
, 0);
1915 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1916 if (status
== BLK_DATA
&& !copy_range
) {
1917 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1919 error_report("error while reading sector %" PRId64
1920 ": %s", sector_num
, strerror(-ret
));
1923 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1925 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1928 if (s
->wr_in_order
) {
1929 /* keep writes in order */
1930 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1931 s
->wait_sector_num
[index
] = sector_num
;
1932 qemu_coroutine_yield();
1934 s
->wait_sector_num
[index
] = -1;
1937 if (s
->ret
== -EINPROGRESS
) {
1939 ret
= convert_co_copy_range(s
, sector_num
, n
);
1941 s
->copy_range
= false;
1945 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1948 error_report("error while writing sector %" PRId64
1949 ": %s", sector_num
, strerror(-ret
));
1954 if (s
->wr_in_order
) {
1955 /* reenter the coroutine that might have waited
1956 * for this write to complete */
1957 s
->wr_offs
= sector_num
+ n
;
1958 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1959 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1961 * A -> B -> A cannot occur because A has
1962 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1963 * B will never enter A during this time window.
1965 qemu_coroutine_enter(s
->co
[i
]);
1973 s
->co
[index
] = NULL
;
1974 s
->running_coroutines
--;
1975 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1976 /* the convert job finished successfully */
1981 static int convert_do_copy(ImgConvertState
*s
)
1984 int64_t sector_num
= 0;
1986 /* Check whether we have zero initialisation or can get it efficiently */
1987 if (s
->target_is_new
&& s
->min_sparse
&& !s
->target_has_backing
) {
1988 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
1990 s
->has_zero_init
= false;
1993 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1994 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1996 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
1998 s
->has_zero_init
= true;
2002 /* Allocate buffer for copied data. For compressed images, only one cluster
2003 * can be copied at a time. */
2004 if (s
->compressed
) {
2005 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2006 error_report("invalid cluster size");
2009 s
->buf_sectors
= s
->cluster_sectors
;
2012 while (sector_num
< s
->total_sectors
) {
2013 n
= convert_iteration_sectors(s
, sector_num
);
2017 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2019 s
->allocated_sectors
+= n
;
2025 s
->sector_next_status
= 0;
2026 s
->ret
= -EINPROGRESS
;
2028 qemu_co_mutex_init(&s
->lock
);
2029 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2030 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2031 s
->wait_sector_num
[i
] = -1;
2032 qemu_coroutine_enter(s
->co
[i
]);
2035 while (s
->running_coroutines
) {
2036 main_loop_wait(false);
2039 if (s
->compressed
&& !s
->ret
) {
2040 /* signal EOF to align */
2041 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
2050 #define MAX_BUF_SECTORS 32768
2052 static int img_convert(int argc
, char **argv
)
2054 int c
, bs_i
, flags
, src_flags
= 0;
2055 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2056 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2057 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2058 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2059 BlockDriverInfo bdi
;
2060 BlockDriverState
*out_bs
;
2061 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2062 QemuOptsList
*create_opts
= NULL
;
2063 QDict
*open_opts
= NULL
;
2064 char *options
= NULL
;
2065 Error
*local_err
= NULL
;
2066 bool writethrough
, src_writethrough
, image_opts
= false,
2067 skip_create
= false, progress
= false, tgt_image_opts
= false;
2068 int64_t ret
= -EINVAL
;
2069 bool force_share
= false;
2070 bool explict_min_sparse
= false;
2072 ImgConvertState s
= (ImgConvertState
) {
2073 /* Need at least 4k of zeros for sparse detection */
2075 .copy_range
= false,
2076 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2077 .wr_in_order
= true,
2078 .num_coroutines
= 8,
2082 static const struct option long_options
[] = {
2083 {"help", no_argument
, 0, 'h'},
2084 {"object", required_argument
, 0, OPTION_OBJECT
},
2085 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2086 {"force-share", no_argument
, 0, 'U'},
2087 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2088 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2091 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2092 long_options
, NULL
);
2098 missing_argument(argv
[optind
- 1]);
2101 unrecognized_option(argv
[optind
- 1]);
2113 out_baseimg
= optarg
;
2116 s
.copy_range
= true;
2119 s
.compressed
= true;
2122 if (!is_valid_option_list(optarg
)) {
2123 error_report("Invalid option list: %s", optarg
);
2127 options
= g_strdup(optarg
);
2129 char *old_options
= options
;
2130 options
= g_strdup_printf("%s,%s", options
, optarg
);
2131 g_free(old_options
);
2135 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2136 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2139 error_report("Failed in parsing snapshot param '%s'",
2144 snapshot_name
= optarg
;
2151 sval
= cvtnum(optarg
);
2152 if (sval
< 0 || !QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2153 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2154 error_report("Invalid buffer size for sparse output specified. "
2155 "Valid sizes are multiples of %llu up to %llu. Select "
2156 "0 to disable sparse detection (fully allocates output).",
2157 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2161 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2162 explict_min_sparse
= true;
2181 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2182 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2183 error_report("Invalid number of coroutines. Allowed number of"
2184 " coroutines is between 1 and %d", MAX_COROUTINES
);
2189 s
.wr_in_order
= false;
2194 case OPTION_OBJECT
: {
2195 QemuOpts
*object_opts
;
2196 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2203 case OPTION_IMAGE_OPTS
:
2206 case OPTION_SALVAGE
:
2209 case OPTION_TARGET_IMAGE_OPTS
:
2210 tgt_image_opts
= true;
2215 if (!out_fmt
&& !tgt_image_opts
) {
2219 if (qemu_opts_foreach(&qemu_object_opts
,
2220 user_creatable_add_opts_foreach
,
2221 qemu_img_object_print_help
, &error_fatal
)) {
2225 if (s
.compressed
&& s
.copy_range
) {
2226 error_report("Cannot enable copy offloading when -c is used");
2230 if (explict_min_sparse
&& s
.copy_range
) {
2231 error_report("Cannot enable copy offloading when -S is used");
2235 if (s
.copy_range
&& s
.salvage
) {
2236 error_report("Cannot use copy offloading in salvaging mode");
2240 if (tgt_image_opts
&& !skip_create
) {
2241 error_report("--target-image-opts requires use of -n flag");
2245 if (skip_create
&& options
) {
2246 warn_report("-o has no effect when skipping image creation");
2247 warn_report("This will become an error in future QEMU versions.");
2250 s
.src_num
= argc
- optind
- 1;
2251 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2253 if (options
&& has_help_option(options
)) {
2255 ret
= print_block_option_help(out_filename
, out_fmt
);
2258 error_report("Option help requires a format be specified");
2263 if (s
.src_num
< 1) {
2264 error_report("Must specify image file name");
2269 /* ret is still -EINVAL until here */
2270 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2272 error_report("Invalid source cache option: %s", src_cache
);
2276 /* Initialize before goto out */
2280 qemu_progress_init(progress
, 1.0);
2281 qemu_progress_print(0, 100);
2283 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2284 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2286 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2287 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2288 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2294 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2295 if (s
.src_sectors
[bs_i
] < 0) {
2296 error_report("Could not get size of %s: %s",
2297 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2301 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2305 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2306 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2307 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2309 } else if (snapshot_name
!= NULL
) {
2310 if (s
.src_num
> 1) {
2311 error_report("No support for concatenating multiple snapshot");
2316 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2320 error_reportf_err(local_err
, "Failed to load snapshot: ");
2326 /* Find driver and parse its options */
2327 drv
= bdrv_find_format(out_fmt
);
2329 error_report("Unknown file format '%s'", out_fmt
);
2334 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2336 error_report_err(local_err
);
2341 if (!drv
->create_opts
) {
2342 error_report("Format driver '%s' does not support image creation",
2348 if (!proto_drv
->create_opts
) {
2349 error_report("Protocol driver '%s' does not support image creation",
2350 proto_drv
->format_name
);
2355 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2356 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2358 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2360 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2362 error_report_err(local_err
);
2368 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2370 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2376 /* Get backing file name if -o backing_file was used */
2377 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2378 if (out_baseimg_param
) {
2379 out_baseimg
= out_baseimg_param
;
2381 s
.target_has_backing
= (bool) out_baseimg
;
2383 if (s
.src_num
> 1 && out_baseimg
) {
2384 error_report("Having a backing file for the target makes no sense when "
2385 "concatenating multiple input images");
2390 /* Check if compression is supported */
2393 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2394 const char *encryptfmt
=
2395 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2396 const char *preallocation
=
2397 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2399 if (drv
&& !block_driver_can_compress(drv
)) {
2400 error_report("Compression not supported for this file format");
2405 if (encryption
|| encryptfmt
) {
2406 error_report("Compression and encryption not supported at "
2413 && strcmp(preallocation
, "off"))
2415 error_report("Compression and preallocation not supported at "
2423 * The later open call will need any decryption secrets, and
2424 * bdrv_create() will purge "opts", so extract them now before
2428 open_opts
= qdict_new();
2429 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2433 /* Create the new image */
2434 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2436 error_reportf_err(local_err
, "%s: error while converting %s: ",
2437 out_filename
, out_fmt
);
2442 s
.target_is_new
= !skip_create
;
2444 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2445 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2447 error_report("Invalid cache option: %s", cache
);
2452 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2453 flags
, writethrough
, s
.quiet
, false);
2455 /* TODO ultimately we should allow --target-image-opts
2456 * to be used even when -n is not given.
2457 * That has to wait for bdrv_create to be improved
2458 * to allow filenames in option syntax
2460 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2461 flags
, writethrough
, s
.quiet
, false);
2462 open_opts
= NULL
; /* blk_new_open will have freed it */
2468 out_bs
= blk_bs(s
.target
);
2470 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2471 error_report("Compression not supported for this file format");
2476 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2477 * or discard_alignment of the out_bs is greater. Limit to
2478 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2479 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2481 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2482 out_bs
->bl
.pdiscard_alignment
>>
2483 BDRV_SECTOR_BITS
)));
2485 /* try to align the write requests to the destination to avoid unnecessary
2487 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2488 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2490 assert(is_power_of_2(s
.alignment
));
2493 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2494 if (output_sectors
< 0) {
2495 error_report("unable to get output image length: %s",
2496 strerror(-output_sectors
));
2499 } else if (output_sectors
< s
.total_sectors
) {
2500 error_report("output file is smaller than input file");
2506 if (s
.target_has_backing
) {
2507 /* Errors are treated as "backing length unknown" (which means
2508 * s.target_backing_sectors has to be negative, which it will
2509 * be automatically). The backing file length is used only
2510 * for optimizations, so such a case is not fatal. */
2511 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2513 s
.target_backing_sectors
= -1;
2516 ret
= bdrv_get_info(out_bs
, &bdi
);
2519 error_report("could not get block driver info");
2523 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2524 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2525 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2528 ret
= convert_do_copy(&s
);
2531 qemu_progress_print(100, 0);
2533 qemu_progress_end();
2534 qemu_opts_del(opts
);
2535 qemu_opts_free(create_opts
);
2536 qemu_opts_del(sn_opts
);
2537 qobject_unref(open_opts
);
2538 blk_unref(s
.target
);
2540 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2541 blk_unref(s
.src
[bs_i
]);
2545 g_free(s
.src_sectors
);
2553 static void dump_snapshots(BlockDriverState
*bs
)
2555 QEMUSnapshotInfo
*sn_tab
, *sn
;
2558 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2561 printf("Snapshot list:\n");
2562 bdrv_snapshot_dump(NULL
);
2564 for(i
= 0; i
< nb_sns
; i
++) {
2566 bdrv_snapshot_dump(sn
);
2572 static void dump_json_image_info_list(ImageInfoList
*list
)
2576 Visitor
*v
= qobject_output_visitor_new(&obj
);
2578 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2579 visit_complete(v
, &obj
);
2580 str
= qobject_to_json_pretty(obj
);
2581 assert(str
!= NULL
);
2582 printf("%s\n", qstring_get_str(str
));
2588 static void dump_json_image_info(ImageInfo
*info
)
2592 Visitor
*v
= qobject_output_visitor_new(&obj
);
2594 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2595 visit_complete(v
, &obj
);
2596 str
= qobject_to_json_pretty(obj
);
2597 assert(str
!= NULL
);
2598 printf("%s\n", qstring_get_str(str
));
2604 static void dump_human_image_info_list(ImageInfoList
*list
)
2606 ImageInfoList
*elem
;
2609 for (elem
= list
; elem
; elem
= elem
->next
) {
2615 bdrv_image_info_dump(elem
->value
);
2619 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2621 return strcmp(a
, b
) == 0;
2625 * Open an image file chain and return an ImageInfoList
2627 * @filename: topmost image filename
2628 * @fmt: topmost image format (may be NULL to autodetect)
2629 * @chain: true - enumerate entire backing file chain
2630 * false - only topmost image file
2632 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2633 * image file. If there was an error a message will have been printed to
2636 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2637 const char *filename
,
2639 bool chain
, bool force_share
)
2641 ImageInfoList
*head
= NULL
;
2642 ImageInfoList
**last
= &head
;
2643 GHashTable
*filenames
;
2646 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2650 BlockDriverState
*bs
;
2652 ImageInfoList
*elem
;
2654 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2655 error_report("Backing file '%s' creates an infinite loop.",
2659 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2661 blk
= img_open(image_opts
, filename
, fmt
,
2662 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2669 bdrv_query_image_info(bs
, &info
, &err
);
2671 error_report_err(err
);
2676 elem
= g_new0(ImageInfoList
, 1);
2683 /* Clear parameters that only apply to the topmost image */
2684 filename
= fmt
= NULL
;
2688 if (info
->has_full_backing_filename
) {
2689 filename
= info
->full_backing_filename
;
2690 } else if (info
->has_backing_filename
) {
2691 error_report("Could not determine absolute backing filename,"
2692 " but backing filename '%s' present",
2693 info
->backing_filename
);
2696 if (info
->has_backing_filename_format
) {
2697 fmt
= info
->backing_filename_format
;
2701 g_hash_table_destroy(filenames
);
2705 qapi_free_ImageInfoList(head
);
2706 g_hash_table_destroy(filenames
);
2710 static int img_info(int argc
, char **argv
)
2713 OutputFormat output_format
= OFORMAT_HUMAN
;
2715 const char *filename
, *fmt
, *output
;
2716 ImageInfoList
*list
;
2717 bool image_opts
= false;
2718 bool force_share
= false;
2723 int option_index
= 0;
2724 static const struct option long_options
[] = {
2725 {"help", no_argument
, 0, 'h'},
2726 {"format", required_argument
, 0, 'f'},
2727 {"output", required_argument
, 0, OPTION_OUTPUT
},
2728 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2729 {"object", required_argument
, 0, OPTION_OBJECT
},
2730 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2731 {"force-share", no_argument
, 0, 'U'},
2734 c
= getopt_long(argc
, argv
, ":f:hU",
2735 long_options
, &option_index
);
2741 missing_argument(argv
[optind
- 1]);
2744 unrecognized_option(argv
[optind
- 1]);
2758 case OPTION_BACKING_CHAIN
:
2761 case OPTION_OBJECT
: {
2763 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2769 case OPTION_IMAGE_OPTS
:
2774 if (optind
!= argc
- 1) {
2775 error_exit("Expecting one image file name");
2777 filename
= argv
[optind
++];
2779 if (output
&& !strcmp(output
, "json")) {
2780 output_format
= OFORMAT_JSON
;
2781 } else if (output
&& !strcmp(output
, "human")) {
2782 output_format
= OFORMAT_HUMAN
;
2783 } else if (output
) {
2784 error_report("--output must be used with human or json as argument.");
2788 if (qemu_opts_foreach(&qemu_object_opts
,
2789 user_creatable_add_opts_foreach
,
2790 qemu_img_object_print_help
, &error_fatal
)) {
2794 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2800 switch (output_format
) {
2802 dump_human_image_info_list(list
);
2806 dump_json_image_info_list(list
);
2808 dump_json_image_info(list
->value
);
2813 qapi_free_ImageInfoList(list
);
2817 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2820 switch (output_format
) {
2822 if (e
->data
&& !e
->has_offset
) {
2823 error_report("File contains external, encrypted or compressed clusters.");
2826 if (e
->data
&& !e
->zero
) {
2827 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2828 e
->start
, e
->length
,
2829 e
->has_offset
? e
->offset
: 0,
2830 e
->has_filename
? e
->filename
: "");
2832 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2833 * Modify the flags here to allow more coalescing.
2835 if (next
&& (!next
->data
|| next
->zero
)) {
2841 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2842 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2843 (e
->start
== 0 ? "[" : ",\n"),
2844 e
->start
, e
->length
, e
->depth
,
2845 e
->zero
? "true" : "false",
2846 e
->data
? "true" : "false");
2847 if (e
->has_offset
) {
2848 printf(", \"offset\": %"PRId64
"", e
->offset
);
2860 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2861 int64_t bytes
, MapEntry
*e
)
2865 BlockDriverState
*file
;
2868 char *filename
= NULL
;
2870 /* As an optimization, we could cache the current range of unallocated
2871 * clusters in each file of the chain, and avoid querying the same
2877 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2882 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2885 bs
= backing_bs(bs
);
2894 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2896 if (file
&& has_offset
) {
2897 bdrv_refresh_filename(file
);
2898 filename
= file
->filename
;
2904 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2905 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2907 .has_offset
= has_offset
,
2909 .has_filename
= filename
,
2910 .filename
= filename
,
2916 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2918 if (curr
->length
== 0) {
2921 if (curr
->zero
!= next
->zero
||
2922 curr
->data
!= next
->data
||
2923 curr
->depth
!= next
->depth
||
2924 curr
->has_filename
!= next
->has_filename
||
2925 curr
->has_offset
!= next
->has_offset
) {
2928 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2931 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2937 static int img_map(int argc
, char **argv
)
2940 OutputFormat output_format
= OFORMAT_HUMAN
;
2942 BlockDriverState
*bs
;
2943 const char *filename
, *fmt
, *output
;
2945 MapEntry curr
= { .length
= 0 }, next
;
2947 bool image_opts
= false;
2948 bool force_share
= false;
2953 int option_index
= 0;
2954 static const struct option long_options
[] = {
2955 {"help", no_argument
, 0, 'h'},
2956 {"format", required_argument
, 0, 'f'},
2957 {"output", required_argument
, 0, OPTION_OUTPUT
},
2958 {"object", required_argument
, 0, OPTION_OBJECT
},
2959 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2960 {"force-share", no_argument
, 0, 'U'},
2963 c
= getopt_long(argc
, argv
, ":f:hU",
2964 long_options
, &option_index
);
2970 missing_argument(argv
[optind
- 1]);
2973 unrecognized_option(argv
[optind
- 1]);
2987 case OPTION_OBJECT
: {
2989 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2995 case OPTION_IMAGE_OPTS
:
3000 if (optind
!= argc
- 1) {
3001 error_exit("Expecting one image file name");
3003 filename
= argv
[optind
];
3005 if (output
&& !strcmp(output
, "json")) {
3006 output_format
= OFORMAT_JSON
;
3007 } else if (output
&& !strcmp(output
, "human")) {
3008 output_format
= OFORMAT_HUMAN
;
3009 } else if (output
) {
3010 error_report("--output must be used with human or json as argument.");
3014 if (qemu_opts_foreach(&qemu_object_opts
,
3015 user_creatable_add_opts_foreach
,
3016 qemu_img_object_print_help
, &error_fatal
)) {
3020 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3026 if (output_format
== OFORMAT_HUMAN
) {
3027 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3030 length
= blk_getlength(blk
);
3031 while (curr
.start
+ curr
.length
< length
) {
3032 int64_t offset
= curr
.start
+ curr
.length
;
3035 /* Probe up to 1 GiB at a time. */
3036 n
= MIN(1 * GiB
, length
- offset
);
3037 ret
= get_block_status(bs
, offset
, n
, &next
);
3040 error_report("Could not read file metadata: %s", strerror(-ret
));
3044 if (entry_mergeable(&curr
, &next
)) {
3045 curr
.length
+= next
.length
;
3049 if (curr
.length
> 0) {
3050 ret
= dump_map_entry(output_format
, &curr
, &next
);
3058 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3065 #define SNAPSHOT_LIST 1
3066 #define SNAPSHOT_CREATE 2
3067 #define SNAPSHOT_APPLY 3
3068 #define SNAPSHOT_DELETE 4
3070 static int img_snapshot(int argc
, char **argv
)
3073 BlockDriverState
*bs
;
3074 QEMUSnapshotInfo sn
;
3075 char *filename
, *snapshot_name
= NULL
;
3076 int c
, ret
= 0, bdrv_oflags
;
3081 bool image_opts
= false;
3082 bool force_share
= false;
3084 bdrv_oflags
= BDRV_O_RDWR
;
3085 /* Parse commandline parameters */
3087 static const struct option long_options
[] = {
3088 {"help", no_argument
, 0, 'h'},
3089 {"object", required_argument
, 0, OPTION_OBJECT
},
3090 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3091 {"force-share", no_argument
, 0, 'U'},
3094 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3095 long_options
, NULL
);
3101 missing_argument(argv
[optind
- 1]);
3104 unrecognized_option(argv
[optind
- 1]);
3111 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3114 action
= SNAPSHOT_LIST
;
3115 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3119 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3122 action
= SNAPSHOT_APPLY
;
3123 snapshot_name
= optarg
;
3127 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3130 action
= SNAPSHOT_CREATE
;
3131 snapshot_name
= optarg
;
3135 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3138 action
= SNAPSHOT_DELETE
;
3139 snapshot_name
= optarg
;
3147 case OPTION_OBJECT
: {
3149 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3155 case OPTION_IMAGE_OPTS
:
3161 if (optind
!= argc
- 1) {
3162 error_exit("Expecting one image file name");
3164 filename
= argv
[optind
++];
3166 if (qemu_opts_foreach(&qemu_object_opts
,
3167 user_creatable_add_opts_foreach
,
3168 qemu_img_object_print_help
, &error_fatal
)) {
3172 /* Open the image */
3173 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3180 /* Perform the requested action */
3186 case SNAPSHOT_CREATE
:
3187 memset(&sn
, 0, sizeof(sn
));
3188 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3190 qemu_gettimeofday(&tv
);
3191 sn
.date_sec
= tv
.tv_sec
;
3192 sn
.date_nsec
= tv
.tv_usec
* 1000;
3194 ret
= bdrv_snapshot_create(bs
, &sn
);
3196 error_report("Could not create snapshot '%s': %d (%s)",
3197 snapshot_name
, ret
, strerror(-ret
));
3201 case SNAPSHOT_APPLY
:
3202 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3204 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3209 case SNAPSHOT_DELETE
:
3210 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3212 error_report("Could not delete snapshot '%s': snapshot not "
3213 "found", snapshot_name
);
3216 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3218 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3234 static int img_rebase(int argc
, char **argv
)
3236 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3237 uint8_t *buf_old
= NULL
;
3238 uint8_t *buf_new
= NULL
;
3239 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3241 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3242 int c
, flags
, src_flags
, ret
;
3243 bool writethrough
, src_writethrough
;
3245 bool force_share
= false;
3248 Error
*local_err
= NULL
;
3249 bool image_opts
= false;
3251 /* Parse commandline parameters */
3253 cache
= BDRV_DEFAULT_CACHE
;
3254 src_cache
= BDRV_DEFAULT_CACHE
;
3258 static const struct option long_options
[] = {
3259 {"help", no_argument
, 0, 'h'},
3260 {"object", required_argument
, 0, OPTION_OBJECT
},
3261 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3262 {"force-share", no_argument
, 0, 'U'},
3265 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3266 long_options
, NULL
);
3272 missing_argument(argv
[optind
- 1]);
3275 unrecognized_option(argv
[optind
- 1]);
3284 out_basefmt
= optarg
;
3287 out_baseimg
= optarg
;
3304 case OPTION_OBJECT
: {
3306 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3312 case OPTION_IMAGE_OPTS
:
3325 if (optind
!= argc
- 1) {
3326 error_exit("Expecting one image file name");
3328 if (!unsafe
&& !out_baseimg
) {
3329 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3331 filename
= argv
[optind
++];
3333 if (qemu_opts_foreach(&qemu_object_opts
,
3334 user_creatable_add_opts_foreach
,
3335 qemu_img_object_print_help
, &error_fatal
)) {
3339 qemu_progress_init(progress
, 2.0);
3340 qemu_progress_print(0, 100);
3342 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3343 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3345 error_report("Invalid cache option: %s", cache
);
3350 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3352 error_report("Invalid source cache option: %s", src_cache
);
3356 /* The source files are opened read-only, don't care about WCE */
3357 assert((src_flags
& BDRV_O_RDWR
) == 0);
3358 (void) src_writethrough
;
3363 * Ignore the old backing file for unsafe rebase in case we want to correct
3364 * the reference to a renamed or moved backing file.
3366 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3374 if (out_basefmt
!= NULL
) {
3375 if (bdrv_find_format(out_basefmt
) == NULL
) {
3376 error_report("Invalid format name: '%s'", out_basefmt
);
3382 /* For safe rebasing we need to compare old and new backing file */
3384 QDict
*options
= NULL
;
3385 BlockDriverState
*base_bs
= backing_bs(bs
);
3388 blk_old_backing
= blk_new(qemu_get_aio_context(),
3389 BLK_PERM_CONSISTENT_READ
,
3391 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3394 error_reportf_err(local_err
,
3395 "Could not reuse old backing file '%s': ",
3400 blk_old_backing
= NULL
;
3403 if (out_baseimg
[0]) {
3404 const char *overlay_filename
;
3405 char *out_real_path
;
3407 options
= qdict_new();
3409 qdict_put_str(options
, "driver", out_basefmt
);
3412 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3415 bdrv_refresh_filename(bs
);
3416 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3419 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3423 qobject_unref(options
);
3424 error_reportf_err(local_err
,
3425 "Could not resolve backing filename: ");
3431 * Find out whether we rebase an image on top of a previous image
3434 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3435 if (prefix_chain_bs
) {
3436 qobject_unref(options
);
3437 g_free(out_real_path
);
3439 blk_new_backing
= blk_new(qemu_get_aio_context(),
3440 BLK_PERM_CONSISTENT_READ
,
3442 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3445 error_reportf_err(local_err
,
3446 "Could not reuse backing file '%s': ",
3451 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3452 options
, src_flags
, &local_err
);
3453 g_free(out_real_path
);
3454 if (!blk_new_backing
) {
3455 error_reportf_err(local_err
,
3456 "Could not open new backing file '%s': ",
3466 * Check each unallocated cluster in the COW file. If it is unallocated,
3467 * accesses go to the backing file. We must therefore compare this cluster
3468 * in the old and new backing file, and if they differ we need to copy it
3469 * from the old backing file into the COW file.
3471 * If qemu-img crashes during this step, no harm is done. The content of
3472 * the image is the same as the original one at any time.
3476 int64_t old_backing_size
= 0;
3477 int64_t new_backing_size
= 0;
3480 float local_progress
= 0;
3482 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3483 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3485 size
= blk_getlength(blk
);
3487 error_report("Could not get size of '%s': %s",
3488 filename
, strerror(-size
));
3492 if (blk_old_backing
) {
3493 old_backing_size
= blk_getlength(blk_old_backing
);
3494 if (old_backing_size
< 0) {
3495 char backing_name
[PATH_MAX
];
3497 bdrv_get_backing_filename(bs
, backing_name
,
3498 sizeof(backing_name
));
3499 error_report("Could not get size of '%s': %s",
3500 backing_name
, strerror(-old_backing_size
));
3505 if (blk_new_backing
) {
3506 new_backing_size
= blk_getlength(blk_new_backing
);
3507 if (new_backing_size
< 0) {
3508 error_report("Could not get size of '%s': %s",
3509 out_baseimg
, strerror(-new_backing_size
));
3516 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3519 for (offset
= 0; offset
< size
; offset
+= n
) {
3520 bool buf_old_is_zero
= false;
3522 /* How many bytes can we handle with the next read? */
3523 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3525 /* If the cluster is allocated, we don't need to take action */
3526 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3528 error_report("error while reading image metadata: %s",
3536 if (prefix_chain_bs
) {
3538 * If cluster wasn't changed since prefix_chain, we don't need
3541 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3542 false, offset
, n
, &n
);
3544 error_report("error while reading image metadata: %s",
3554 * Read old and new backing file and take into consideration that
3555 * backing files may be smaller than the COW image.
3557 if (offset
>= old_backing_size
) {
3558 memset(buf_old
, 0, n
);
3559 buf_old_is_zero
= true;
3561 if (offset
+ n
> old_backing_size
) {
3562 n
= old_backing_size
- offset
;
3565 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3567 error_report("error while reading from old backing file");
3572 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3573 memset(buf_new
, 0, n
);
3575 if (offset
+ n
> new_backing_size
) {
3576 n
= new_backing_size
- offset
;
3579 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3581 error_report("error while reading from new backing file");
3586 /* If they differ, we need to write to the COW file */
3587 uint64_t written
= 0;
3589 while (written
< n
) {
3592 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3593 n
- written
, &pnum
))
3595 if (buf_old_is_zero
) {
3596 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3598 ret
= blk_pwrite(blk
, offset
+ written
,
3599 buf_old
+ written
, pnum
, 0);
3602 error_report("Error while writing to COW image: %s",
3610 qemu_progress_print(local_progress
, 100);
3615 * Change the backing file. All clusters that are different from the old
3616 * backing file are overwritten in the COW file now, so the visible content
3617 * doesn't change when we switch the backing file.
3619 if (out_baseimg
&& *out_baseimg
) {
3620 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3622 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3625 if (ret
== -ENOSPC
) {
3626 error_report("Could not change the backing file to '%s': No "
3627 "space left in the file header", out_baseimg
);
3628 } else if (ret
< 0) {
3629 error_report("Could not change the backing file to '%s': %s",
3630 out_baseimg
, strerror(-ret
));
3633 qemu_progress_print(100, 0);
3635 * TODO At this point it is possible to check if any clusters that are
3636 * allocated in the COW file are the same in the backing file. If so, they
3637 * could be dropped from the COW file. Don't do this before switching the
3638 * backing file, in case of a crash this would lead to corruption.
3641 qemu_progress_end();
3644 blk_unref(blk_old_backing
);
3645 blk_unref(blk_new_backing
);
3647 qemu_vfree(buf_old
);
3648 qemu_vfree(buf_new
);
3657 static int img_resize(int argc
, char **argv
)
3660 int c
, ret
, relative
;
3661 const char *filename
, *fmt
, *size
;
3662 int64_t n
, total_size
, current_size
;
3664 BlockBackend
*blk
= NULL
;
3665 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3668 static QemuOptsList resize_options
= {
3669 .name
= "resize_options",
3670 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3673 .name
= BLOCK_OPT_SIZE
,
3674 .type
= QEMU_OPT_SIZE
,
3675 .help
= "Virtual disk size"
3681 bool image_opts
= false;
3682 bool shrink
= false;
3684 /* Remove size from argv manually so that negative numbers are not treated
3685 * as options by getopt. */
3687 error_exit("Not enough arguments");
3691 size
= argv
[--argc
];
3693 /* Parse getopt arguments */
3696 static const struct option long_options
[] = {
3697 {"help", no_argument
, 0, 'h'},
3698 {"object", required_argument
, 0, OPTION_OBJECT
},
3699 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3700 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3701 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3704 c
= getopt_long(argc
, argv
, ":f:hq",
3705 long_options
, NULL
);
3711 missing_argument(argv
[optind
- 1]);
3714 unrecognized_option(argv
[optind
- 1]);
3725 case OPTION_OBJECT
: {
3727 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3733 case OPTION_IMAGE_OPTS
:
3736 case OPTION_PREALLOCATION
:
3737 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3738 PREALLOC_MODE__MAX
, NULL
);
3739 if (prealloc
== PREALLOC_MODE__MAX
) {
3740 error_report("Invalid preallocation mode '%s'", optarg
);
3749 if (optind
!= argc
- 1) {
3750 error_exit("Expecting image file name and size");
3752 filename
= argv
[optind
++];
3754 if (qemu_opts_foreach(&qemu_object_opts
,
3755 user_creatable_add_opts_foreach
,
3756 qemu_img_object_print_help
, &error_fatal
)) {
3760 /* Choose grow, shrink, or absolute resize mode */
3776 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3777 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3779 error_report_err(err
);
3781 qemu_opts_del(param
);
3784 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3785 qemu_opts_del(param
);
3787 blk
= img_open(image_opts
, filename
, fmt
,
3788 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3795 current_size
= blk_getlength(blk
);
3796 if (current_size
< 0) {
3797 error_report("Failed to inquire current image length: %s",
3798 strerror(-current_size
));
3804 total_size
= current_size
+ n
* relative
;
3808 if (total_size
<= 0) {
3809 error_report("New image size must be positive");
3814 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3815 error_report("Preallocation can only be used for growing images");
3820 if (total_size
< current_size
&& !shrink
) {
3821 warn_report("Shrinking an image will delete all data beyond the "
3822 "shrunken image's end. Before performing such an "
3823 "operation, make sure there is no important data there.");
3825 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3827 "Use the --shrink option to perform a shrink operation.");
3831 warn_report("Using the --shrink option will suppress this message. "
3832 "Note that future versions of qemu-img may refuse to "
3833 "shrink images without this option.");
3838 * The user expects the image to have the desired size after
3839 * resizing, so pass @exact=true. It is of no use to report
3840 * success when the image has not actually been resized.
3842 ret
= blk_truncate(blk
, total_size
, true, prealloc
, &err
);
3844 qprintf(quiet
, "Image resized.\n");
3846 error_report_err(err
);
3856 static void amend_status_cb(BlockDriverState
*bs
,
3857 int64_t offset
, int64_t total_work_size
,
3860 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3863 static int print_amend_option_help(const char *format
)
3867 /* Find driver and parse its options */
3868 drv
= bdrv_find_format(format
);
3870 error_report("Unknown file format '%s'", format
);
3874 if (!drv
->bdrv_amend_options
) {
3875 error_report("Format driver '%s' does not support option amendment",
3880 /* Every driver supporting amendment must have create_opts */
3881 assert(drv
->create_opts
);
3883 printf("Creation options for '%s':\n", format
);
3884 qemu_opts_print_help(drv
->create_opts
, false);
3885 printf("\nNote that not all of these options may be amendable.\n");
3889 static int img_amend(int argc
, char **argv
)
3893 char *options
= NULL
;
3894 QemuOptsList
*create_opts
= NULL
;
3895 QemuOpts
*opts
= NULL
;
3896 const char *fmt
= NULL
, *filename
, *cache
;
3899 bool quiet
= false, progress
= false;
3900 BlockBackend
*blk
= NULL
;
3901 BlockDriverState
*bs
= NULL
;
3902 bool image_opts
= false;
3904 cache
= BDRV_DEFAULT_CACHE
;
3906 static const struct option long_options
[] = {
3907 {"help", no_argument
, 0, 'h'},
3908 {"object", required_argument
, 0, OPTION_OBJECT
},
3909 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3912 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3913 long_options
, NULL
);
3920 missing_argument(argv
[optind
- 1]);
3923 unrecognized_option(argv
[optind
- 1]);
3929 if (!is_valid_option_list(optarg
)) {
3930 error_report("Invalid option list: %s", optarg
);
3932 goto out_no_progress
;
3935 options
= g_strdup(optarg
);
3937 char *old_options
= options
;
3938 options
= g_strdup_printf("%s,%s", options
, optarg
);
3939 g_free(old_options
);
3955 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3959 goto out_no_progress
;
3962 case OPTION_IMAGE_OPTS
:
3969 error_exit("Must specify options (-o)");
3972 if (qemu_opts_foreach(&qemu_object_opts
,
3973 user_creatable_add_opts_foreach
,
3974 qemu_img_object_print_help
, &error_fatal
)) {
3976 goto out_no_progress
;
3982 qemu_progress_init(progress
, 1.0);
3984 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3985 if (fmt
&& has_help_option(options
)) {
3986 /* If a format is explicitly specified (and possibly no filename is
3987 * given), print option help here */
3988 ret
= print_amend_option_help(fmt
);
3992 if (optind
!= argc
- 1) {
3993 error_report("Expecting one image file name");
3998 flags
= BDRV_O_RDWR
;
3999 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4001 error_report("Invalid cache option: %s", cache
);
4005 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4013 fmt
= bs
->drv
->format_name
;
4015 if (has_help_option(options
)) {
4016 /* If the format was auto-detected, print option help here */
4017 ret
= print_amend_option_help(fmt
);
4021 if (!bs
->drv
->bdrv_amend_options
) {
4022 error_report("Format driver '%s' does not support option amendment",
4028 /* Every driver supporting amendment must have create_opts */
4029 assert(bs
->drv
->create_opts
);
4031 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
4032 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4033 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
4035 error_report_err(err
);
4040 /* In case the driver does not call amend_status_cb() */
4041 qemu_progress_print(0.f
, 0);
4042 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
4043 qemu_progress_print(100.f
, 0);
4045 error_report_err(err
);
4050 qemu_progress_end();
4054 qemu_opts_del(opts
);
4055 qemu_opts_free(create_opts
);
4064 typedef struct BenchData
{
4066 uint64_t image_size
;
4073 bool drain_on_flush
;
4082 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4085 error_report("Failed flush request: %s", strerror(-ret
));
4090 static void bench_cb(void *opaque
, int ret
)
4092 BenchData
*b
= opaque
;
4096 error_report("Failed request: %s", strerror(-ret
));
4101 /* Just finished a flush with drained queue: Start next requests */
4102 assert(b
->in_flight
== 0);
4103 b
->in_flush
= false;
4104 } else if (b
->in_flight
> 0) {
4105 int remaining
= b
->n
- b
->in_flight
;
4110 /* Time for flush? Drain queue if requested, then flush */
4111 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4112 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4113 BlockCompletionFunc
*cb
;
4115 if (b
->drain_on_flush
) {
4119 cb
= bench_undrained_flush_cb
;
4122 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4124 error_report("Failed to issue flush request");
4128 if (b
->drain_on_flush
) {
4134 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4135 int64_t offset
= b
->offset
;
4136 /* blk_aio_* might look for completed I/Os and kick bench_cb
4137 * again, so make sure this operation is counted by in_flight
4138 * and b->offset is ready for the next submission.
4141 b
->offset
+= b
->step
;
4142 b
->offset
%= b
->image_size
;
4144 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4146 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4149 error_report("Failed to issue request");
4155 static int img_bench(int argc
, char **argv
)
4158 const char *fmt
= NULL
, *filename
;
4160 bool image_opts
= false;
4161 bool is_write
= false;
4165 size_t bufsize
= 4096;
4168 int flush_interval
= 0;
4169 bool drain_on_flush
= true;
4171 BlockBackend
*blk
= NULL
;
4172 BenchData data
= {};
4174 bool writethrough
= false;
4175 struct timeval t1
, t2
;
4177 bool force_share
= false;
4181 static const struct option long_options
[] = {
4182 {"help", no_argument
, 0, 'h'},
4183 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4184 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4185 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4186 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4187 {"force-share", no_argument
, 0, 'U'},
4190 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4198 missing_argument(argv
[optind
- 1]);
4201 unrecognized_option(argv
[optind
- 1]);
4210 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4211 error_report("Invalid request count specified");
4221 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4222 error_report("Invalid queue depth specified");
4232 flags
|= BDRV_O_NATIVE_AIO
;
4235 ret
= bdrv_parse_aio(optarg
, &flags
);
4237 error_report("Invalid aio option: %s", optarg
);
4244 offset
= cvtnum(optarg
);
4246 error_report("Invalid offset specified");
4259 sval
= cvtnum(optarg
);
4260 if (sval
< 0 || sval
> INT_MAX
) {
4261 error_report("Invalid buffer size specified");
4272 sval
= cvtnum(optarg
);
4273 if (sval
< 0 || sval
> INT_MAX
) {
4274 error_report("Invalid step size specified");
4282 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4284 error_report("Invalid cache mode");
4290 flags
|= BDRV_O_RDWR
;
4296 case OPTION_PATTERN
:
4300 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4301 error_report("Invalid pattern byte specified");
4307 case OPTION_FLUSH_INTERVAL
:
4311 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4312 error_report("Invalid flush interval specified");
4315 flush_interval
= res
;
4318 case OPTION_NO_DRAIN
:
4319 drain_on_flush
= false;
4321 case OPTION_IMAGE_OPTS
:
4327 if (optind
!= argc
- 1) {
4328 error_exit("Expecting one image file name");
4330 filename
= argv
[argc
- 1];
4332 if (!is_write
&& flush_interval
) {
4333 error_report("--flush-interval is only available in write tests");
4337 if (flush_interval
&& flush_interval
< depth
) {
4338 error_report("Flush interval can't be smaller than depth");
4343 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4350 image_size
= blk_getlength(blk
);
4351 if (image_size
< 0) {
4356 data
= (BenchData
) {
4358 .image_size
= image_size
,
4360 .step
= step
?: bufsize
,
4365 .flush_interval
= flush_interval
,
4366 .drain_on_flush
= drain_on_flush
,
4368 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4369 "(starting at offset %" PRId64
", step size %d)\n",
4370 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4371 data
.offset
, data
.step
);
4372 if (flush_interval
) {
4373 printf("Sending flush every %d requests\n", flush_interval
);
4376 buf_size
= data
.nrreq
* data
.bufsize
;
4377 data
.buf
= blk_blockalign(blk
, buf_size
);
4378 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4380 blk_register_buf(blk
, data
.buf
, buf_size
);
4382 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4383 for (i
= 0; i
< data
.nrreq
; i
++) {
4384 qemu_iovec_init(&data
.qiov
[i
], 1);
4385 qemu_iovec_add(&data
.qiov
[i
],
4386 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4389 gettimeofday(&t1
, NULL
);
4392 while (data
.n
> 0) {
4393 main_loop_wait(false);
4395 gettimeofday(&t2
, NULL
);
4397 printf("Run completed in %3.3f seconds.\n",
4398 (t2
.tv_sec
- t1
.tv_sec
)
4399 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4403 blk_unregister_buf(blk
, data
.buf
);
4405 qemu_vfree(data
.buf
);
4426 int bsz
; /* Block size */
4434 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4438 static int img_dd_bs(const char *arg
,
4439 struct DdIo
*in
, struct DdIo
*out
,
4446 if (res
<= 0 || res
> INT_MAX
) {
4447 error_report("invalid number: '%s'", arg
);
4450 in
->bsz
= out
->bsz
= res
;
4455 static int img_dd_count(const char *arg
,
4456 struct DdIo
*in
, struct DdIo
*out
,
4459 dd
->count
= cvtnum(arg
);
4461 if (dd
->count
< 0) {
4462 error_report("invalid number: '%s'", arg
);
4469 static int img_dd_if(const char *arg
,
4470 struct DdIo
*in
, struct DdIo
*out
,
4473 in
->filename
= g_strdup(arg
);
4478 static int img_dd_of(const char *arg
,
4479 struct DdIo
*in
, struct DdIo
*out
,
4482 out
->filename
= g_strdup(arg
);
4487 static int img_dd_skip(const char *arg
,
4488 struct DdIo
*in
, struct DdIo
*out
,
4491 in
->offset
= cvtnum(arg
);
4493 if (in
->offset
< 0) {
4494 error_report("invalid number: '%s'", arg
);
4501 static int img_dd(int argc
, char **argv
)
4506 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4507 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4508 QemuOpts
*opts
= NULL
;
4509 QemuOptsList
*create_opts
= NULL
;
4510 Error
*local_err
= NULL
;
4511 bool image_opts
= false;
4513 const char *out_fmt
= "raw";
4514 const char *fmt
= NULL
;
4516 int64_t block_count
= 0, out_pos
, in_pos
;
4517 bool force_share
= false;
4518 struct DdInfo dd
= {
4523 .bsz
= 512, /* Block size is by default 512 bytes */
4535 const struct DdOpts options
[] = {
4536 { "bs", img_dd_bs
, C_BS
},
4537 { "count", img_dd_count
, C_COUNT
},
4538 { "if", img_dd_if
, C_IF
},
4539 { "of", img_dd_of
, C_OF
},
4540 { "skip", img_dd_skip
, C_SKIP
},
4543 const struct option long_options
[] = {
4544 { "help", no_argument
, 0, 'h'},
4545 { "object", required_argument
, 0, OPTION_OBJECT
},
4546 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4547 { "force-share", no_argument
, 0, 'U'},
4551 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4563 missing_argument(argv
[optind
- 1]);
4566 unrecognized_option(argv
[optind
- 1]);
4575 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4580 case OPTION_IMAGE_OPTS
:
4586 for (i
= optind
; i
< argc
; i
++) {
4588 arg
= g_strdup(argv
[i
]);
4590 tmp
= strchr(arg
, '=');
4592 error_report("unrecognized operand %s", arg
);
4599 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4600 if (!strcmp(arg
, options
[j
].name
)) {
4604 if (options
[j
].name
== NULL
) {
4605 error_report("unrecognized operand %s", arg
);
4610 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4614 dd
.flags
|= options
[j
].flag
;
4619 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4620 error_report("Must specify both input and output files");
4625 if (qemu_opts_foreach(&qemu_object_opts
,
4626 user_creatable_add_opts_foreach
,
4627 qemu_img_object_print_help
, &error_fatal
)) {
4632 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4640 drv
= bdrv_find_format(out_fmt
);
4642 error_report("Unknown file format");
4646 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4649 error_report_err(local_err
);
4653 if (!drv
->create_opts
) {
4654 error_report("Format driver '%s' does not support image creation",
4659 if (!proto_drv
->create_opts
) {
4660 error_report("Protocol driver '%s' does not support image creation",
4661 proto_drv
->format_name
);
4665 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4666 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4668 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4670 size
= blk_getlength(blk1
);
4672 error_report("Failed to get size for '%s'", in
.filename
);
4677 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4678 dd
.count
* in
.bsz
< size
) {
4679 size
= dd
.count
* in
.bsz
;
4682 /* Overflow means the specified offset is beyond input image's size */
4683 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4684 size
< in
.bsz
* in
.offset
)) {
4685 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4687 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4688 size
- in
.bsz
* in
.offset
, &error_abort
);
4691 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4693 error_reportf_err(local_err
,
4694 "%s: error while creating output image: ",
4700 /* TODO, we can't honour --image-opts for the target,
4701 * since it needs to be given in a format compatible
4702 * with the bdrv_create() call above which does not
4703 * support image-opts style.
4705 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4706 false, false, false);
4713 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4714 size
< in
.offset
* in
.bsz
)) {
4715 /* We give a warning if the skip option is bigger than the input
4716 * size and create an empty output disk image (i.e. like dd(1)).
4718 error_report("%s: cannot skip to specified offset", in
.filename
);
4721 in_pos
= in
.offset
* in
.bsz
;
4724 in
.buf
= g_new(uint8_t, in
.bsz
);
4726 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4727 int in_ret
, out_ret
;
4729 if (in_pos
+ in
.bsz
> size
) {
4730 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4732 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4735 error_report("error while reading from input image file: %s",
4742 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4745 error_report("error while writing to output image file: %s",
4746 strerror(-out_ret
));
4755 qemu_opts_del(opts
);
4756 qemu_opts_free(create_opts
);
4759 g_free(in
.filename
);
4760 g_free(out
.filename
);
4770 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4774 Visitor
*v
= qobject_output_visitor_new(&obj
);
4776 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4777 visit_complete(v
, &obj
);
4778 str
= qobject_to_json_pretty(obj
);
4779 assert(str
!= NULL
);
4780 printf("%s\n", qstring_get_str(str
));
4786 static int img_measure(int argc
, char **argv
)
4788 static const struct option long_options
[] = {
4789 {"help", no_argument
, 0, 'h'},
4790 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4791 {"object", required_argument
, 0, OPTION_OBJECT
},
4792 {"output", required_argument
, 0, OPTION_OUTPUT
},
4793 {"size", required_argument
, 0, OPTION_SIZE
},
4794 {"force-share", no_argument
, 0, 'U'},
4797 OutputFormat output_format
= OFORMAT_HUMAN
;
4798 BlockBackend
*in_blk
= NULL
;
4800 const char *filename
= NULL
;
4801 const char *fmt
= NULL
;
4802 const char *out_fmt
= "raw";
4803 char *options
= NULL
;
4804 char *snapshot_name
= NULL
;
4805 bool force_share
= false;
4806 QemuOpts
*opts
= NULL
;
4807 QemuOpts
*object_opts
= NULL
;
4808 QemuOpts
*sn_opts
= NULL
;
4809 QemuOptsList
*create_opts
= NULL
;
4810 bool image_opts
= false;
4811 uint64_t img_size
= UINT64_MAX
;
4812 BlockMeasureInfo
*info
= NULL
;
4813 Error
*local_err
= NULL
;
4817 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4818 long_options
, NULL
)) != -1) {
4831 if (!is_valid_option_list(optarg
)) {
4832 error_report("Invalid option list: %s", optarg
);
4836 options
= g_strdup(optarg
);
4838 char *old_options
= options
;
4839 options
= g_strdup_printf("%s,%s", options
, optarg
);
4840 g_free(old_options
);
4844 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4845 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4848 error_report("Failed in parsing snapshot param '%s'",
4853 snapshot_name
= optarg
;
4860 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4866 case OPTION_IMAGE_OPTS
:
4870 if (!strcmp(optarg
, "json")) {
4871 output_format
= OFORMAT_JSON
;
4872 } else if (!strcmp(optarg
, "human")) {
4873 output_format
= OFORMAT_HUMAN
;
4875 error_report("--output must be used with human or json "
4884 sval
= cvtnum(optarg
);
4886 if (sval
== -ERANGE
) {
4887 error_report("Image size must be less than 8 EiB!");
4889 error_report("Invalid image size specified! You may use "
4890 "k, M, G, T, P or E suffixes for ");
4891 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4892 "petabytes and exabytes.");
4896 img_size
= (uint64_t)sval
;
4902 if (qemu_opts_foreach(&qemu_object_opts
,
4903 user_creatable_add_opts_foreach
,
4904 qemu_img_object_print_help
, &error_fatal
)) {
4908 if (argc
- optind
> 1) {
4909 error_report("At most one filename argument is allowed.");
4911 } else if (argc
- optind
== 1) {
4912 filename
= argv
[optind
];
4916 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4917 error_report("--object, --image-opts, -f, and -l "
4918 "require a filename argument.");
4921 if (filename
&& img_size
!= UINT64_MAX
) {
4922 error_report("--size N cannot be used together with a filename.");
4925 if (!filename
&& img_size
== UINT64_MAX
) {
4926 error_report("Either --size N or one filename must be specified.");
4931 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4932 false, false, force_share
);
4938 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4939 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4940 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4942 } else if (snapshot_name
!= NULL
) {
4943 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4944 snapshot_name
, &local_err
);
4947 error_reportf_err(local_err
, "Failed to load snapshot: ");
4952 drv
= bdrv_find_format(out_fmt
);
4954 error_report("Unknown file format '%s'", out_fmt
);
4957 if (!drv
->create_opts
) {
4958 error_report("Format driver '%s' does not support image creation",
4963 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4964 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4965 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4967 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4969 error_report_err(local_err
);
4970 error_report("Invalid options for file format '%s'", out_fmt
);
4974 if (img_size
!= UINT64_MAX
) {
4975 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4978 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4980 error_report_err(local_err
);
4984 if (output_format
== OFORMAT_HUMAN
) {
4985 printf("required size: %" PRIu64
"\n", info
->required
);
4986 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4988 dump_json_block_measure_info(info
);
4994 qapi_free_BlockMeasureInfo(info
);
4995 qemu_opts_del(object_opts
);
4996 qemu_opts_del(opts
);
4997 qemu_opts_del(sn_opts
);
4998 qemu_opts_free(create_opts
);
5004 static const img_cmd_t img_cmds
[] = {
5005 #define DEF(option, callback, arg_string) \
5006 { option, callback },
5007 #include "qemu-img-cmds.h"
5012 int main(int argc
, char **argv
)
5014 const img_cmd_t
*cmd
;
5015 const char *cmdname
;
5016 Error
*local_error
= NULL
;
5017 char *trace_file
= NULL
;
5019 static const struct option long_options
[] = {
5020 {"help", no_argument
, 0, 'h'},
5021 {"version", no_argument
, 0, 'V'},
5022 {"trace", required_argument
, NULL
, 'T'},
5027 signal(SIGPIPE
, SIG_IGN
);
5030 error_init(argv
[0]);
5031 module_call_init(MODULE_INIT_TRACE
);
5032 qemu_init_exec_dir(argv
[0]);
5034 if (qemu_init_main_loop(&local_error
)) {
5035 error_report_err(local_error
);
5039 qcrypto_init(&error_fatal
);
5041 module_call_init(MODULE_INIT_QOM
);
5044 error_exit("Not enough arguments");
5047 qemu_add_opts(&qemu_object_opts
);
5048 qemu_add_opts(&qemu_source_opts
);
5049 qemu_add_opts(&qemu_trace_opts
);
5051 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5054 missing_argument(argv
[optind
- 1]);
5057 unrecognized_option(argv
[optind
- 1]);
5063 printf(QEMU_IMG_VERSION
);
5067 trace_file
= trace_opt_parse(optarg
);
5072 cmdname
= argv
[optind
];
5074 /* reset getopt_long scanning */
5080 qemu_reset_optind();
5082 if (!trace_init_backends()) {
5085 trace_init_file(trace_file
);
5086 qemu_set_log(LOG_TRACE
);
5088 /* find the command */
5089 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5090 if (!strcmp(cmdname
, cmd
->name
)) {
5091 return cmd
->handler(argc
, argv
);
5096 error_exit("Command not found: %s", cmdname
);