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,
73 OPTION_TARGET_IS_ZERO
= 268,
76 typedef enum OutputFormat
{
81 /* Default to cache=writeback as data integrity is not important for qemu-img */
82 #define BDRV_DEFAULT_CACHE "writeback"
84 static void format_print(void *opaque
, const char *name
)
89 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
94 error_vreport(fmt
, ap
);
97 error_printf("Try 'qemu-img --help' for more information\n");
101 static void QEMU_NORETURN
missing_argument(const char *option
)
103 error_exit("missing argument for option '%s'", option
);
106 static void QEMU_NORETURN
unrecognized_option(const char *option
)
108 error_exit("unrecognized option '%s'", option
);
111 /* Please keep in synch with qemu-img.texi */
112 static void QEMU_NORETURN
help(void)
114 const char *help_msg
=
116 "usage: qemu-img [standard options] command [command options]\n"
117 "QEMU disk image utility\n"
119 " '-h', '--help' display this help and exit\n"
120 " '-V', '--version' output version information and exit\n"
121 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122 " specify tracing options\n"
125 #define DEF(option, callback, arg_string) \
127 #include "qemu-img-cmds.h"
130 "Command parameters:\n"
131 " 'filename' is a disk image filename\n"
132 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
133 " manual page for a description of the object properties. The most common\n"
134 " object type is a 'secret', which is used to supply passwords and/or\n"
135 " encryption keys.\n"
136 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
137 " 'cache' is the cache mode used to write the output disk image, the valid\n"
138 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
139 " 'directsync' and 'unsafe' (default for convert)\n"
140 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
141 " options are the same as for the 'cache' option\n"
142 " 'size' is the disk image size in bytes. Optional suffixes\n"
143 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
144 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
145 " supported. 'b' is ignored.\n"
146 " 'output_filename' is the destination disk image filename\n"
147 " 'output_fmt' is the destination format\n"
148 " 'options' is a comma separated list of format specific options in a\n"
149 " name=value format. Use -o ? for an overview of the options supported by the\n"
151 " 'snapshot_param' is param used for internal snapshot, format\n"
152 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
154 " '-c' indicates that target image must be compressed (qcow format only)\n"
155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
160 " '-h' with or without a command shows this help and lists the supported formats\n"
161 " '-p' show progress of command (only certain commands)\n"
162 " '-q' use Quiet mode - do not print any output (except errors)\n"
163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
168 " '--output' takes the format in which the output must be done (human or json)\n"
169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
176 " hiding corruption that has already occurred.\n"
178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
188 " '-l' lists all snapshots in the given image\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
203 printf("%s\nSupported formats:", help_msg
);
204 bdrv_iterate_format(format_print
, NULL
, false);
205 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
209 static QemuOptsList qemu_object_opts
= {
211 .implied_opt_name
= "qom-type",
212 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
218 static bool qemu_img_object_print_help(const char *type
, QemuOpts
*opts
)
220 if (user_creatable_print_help(type
, opts
)) {
226 static QemuOptsList qemu_source_opts
= {
228 .implied_opt_name
= "file",
229 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
235 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
241 ret
= vprintf(fmt
, args
);
248 static int print_block_option_help(const char *filename
, const char *fmt
)
250 BlockDriver
*drv
, *proto_drv
;
251 QemuOptsList
*create_opts
= NULL
;
252 Error
*local_err
= NULL
;
254 /* Find driver and parse its options */
255 drv
= bdrv_find_format(fmt
);
257 error_report("Unknown file format '%s'", fmt
);
261 if (!drv
->create_opts
) {
262 error_report("Format driver '%s' does not support image creation", fmt
);
266 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
268 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
270 error_report_err(local_err
);
271 qemu_opts_free(create_opts
);
274 if (!proto_drv
->create_opts
) {
275 error_report("Protocol driver '%s' does not support image creation",
276 proto_drv
->format_name
);
277 qemu_opts_free(create_opts
);
280 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
284 printf("Supported options:\n");
286 printf("Supported %s options:\n", fmt
);
288 qemu_opts_print_help(create_opts
, false);
289 qemu_opts_free(create_opts
);
293 "The protocol level may support further options.\n"
294 "Specify the target filename to include those options.\n");
301 static BlockBackend
*img_open_opts(const char *optstr
,
302 QemuOpts
*opts
, int flags
, bool writethrough
,
303 bool quiet
, bool force_share
)
306 Error
*local_err
= NULL
;
308 options
= qemu_opts_to_qdict(opts
, NULL
);
310 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
311 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
312 error_report("--force-share/-U conflicts with image options");
313 qobject_unref(options
);
316 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
318 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
320 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
323 blk_set_enable_write_cache(blk
, !writethrough
);
328 static BlockBackend
*img_open_file(const char *filename
,
330 const char *fmt
, int flags
,
331 bool writethrough
, bool quiet
,
335 Error
*local_err
= NULL
;
338 options
= qdict_new();
341 qdict_put_str(options
, "driver", fmt
);
345 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
347 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
349 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
352 blk_set_enable_write_cache(blk
, !writethrough
);
358 static int img_add_key_secrets(void *opaque
,
359 const char *name
, const char *value
,
362 QDict
*options
= opaque
;
364 if (g_str_has_suffix(name
, "key-secret")) {
365 qdict_put_str(options
, name
, value
);
372 static BlockBackend
*img_open(bool image_opts
,
373 const char *filename
,
374 const char *fmt
, int flags
, bool writethrough
,
375 bool quiet
, bool force_share
)
381 error_report("--image-opts and --format are mutually exclusive");
384 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
389 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
392 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
399 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
400 const char *base_filename
,
401 const char *base_fmt
)
406 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
408 error_report("Backing file not supported for file format '%s'",
415 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
417 error_report("Backing file format not supported for file "
426 static int64_t cvtnum(const char *s
)
431 err
= qemu_strtosz(s
, NULL
, &value
);
435 if (value
> INT64_MAX
) {
441 static int img_create(int argc
, char **argv
)
444 uint64_t img_size
= -1;
445 const char *fmt
= "raw";
446 const char *base_fmt
= NULL
;
447 const char *filename
;
448 const char *base_filename
= NULL
;
449 char *options
= NULL
;
450 Error
*local_err
= NULL
;
455 static const struct option long_options
[] = {
456 {"help", no_argument
, 0, 'h'},
457 {"object", required_argument
, 0, OPTION_OBJECT
},
460 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
467 missing_argument(argv
[optind
- 1]);
470 unrecognized_option(argv
[optind
- 1]);
479 base_filename
= optarg
;
485 if (!is_valid_option_list(optarg
)) {
486 error_report("Invalid option list: %s", optarg
);
490 options
= g_strdup(optarg
);
492 char *old_options
= options
;
493 options
= g_strdup_printf("%s,%s", options
, optarg
);
501 flags
|= BDRV_O_NO_BACKING
;
503 case OPTION_OBJECT
: {
505 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
514 /* Get the filename */
515 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
516 if (options
&& has_help_option(options
)) {
518 return print_block_option_help(filename
, fmt
);
521 if (optind
>= argc
) {
522 error_exit("Expecting image file name");
526 if (qemu_opts_foreach(&qemu_object_opts
,
527 user_creatable_add_opts_foreach
,
528 qemu_img_object_print_help
, &error_fatal
)) {
532 /* Get image size, if specified */
536 sval
= cvtnum(argv
[optind
++]);
538 if (sval
== -ERANGE
) {
539 error_report("Image size must be less than 8 EiB!");
541 error_report("Invalid image size specified! You may use k, M, "
542 "G, T, P or E suffixes for ");
543 error_report("kilobytes, megabytes, gigabytes, terabytes, "
544 "petabytes and exabytes.");
548 img_size
= (uint64_t)sval
;
550 if (optind
!= argc
) {
551 error_exit("Unexpected argument: %s", argv
[optind
]);
554 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
555 options
, img_size
, flags
, quiet
, &local_err
);
557 error_reportf_err(local_err
, "%s: ", filename
);
569 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
573 Visitor
*v
= qobject_output_visitor_new(&obj
);
575 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
576 visit_complete(v
, &obj
);
577 str
= qobject_to_json_pretty(obj
);
579 qprintf(quiet
, "%s\n", qstring_get_str(str
));
585 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
587 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
588 qprintf(quiet
, "No errors were found on the image.\n");
590 if (check
->corruptions
) {
591 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
592 "Data may be corrupted, or further writes to the image "
599 "\n%" PRId64
" leaked clusters were found on the image.\n"
600 "This means waste of disk space, but no harm to data.\n",
604 if (check
->check_errors
) {
607 " internal errors have occurred during the check.\n",
608 check
->check_errors
);
612 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
613 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
614 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
615 check
->allocated_clusters
, check
->total_clusters
,
616 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
617 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
618 check
->compressed_clusters
* 100.0 /
619 check
->allocated_clusters
);
622 if (check
->image_end_offset
) {
624 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
628 static int collect_image_check(BlockDriverState
*bs
,
630 const char *filename
,
635 BdrvCheckResult result
;
637 ret
= bdrv_check(bs
, &result
, fix
);
642 check
->filename
= g_strdup(filename
);
643 check
->format
= g_strdup(bdrv_get_format_name(bs
));
644 check
->check_errors
= result
.check_errors
;
645 check
->corruptions
= result
.corruptions
;
646 check
->has_corruptions
= result
.corruptions
!= 0;
647 check
->leaks
= result
.leaks
;
648 check
->has_leaks
= result
.leaks
!= 0;
649 check
->corruptions_fixed
= result
.corruptions_fixed
;
650 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
651 check
->leaks_fixed
= result
.leaks_fixed
;
652 check
->has_leaks_fixed
= result
.leaks
!= 0;
653 check
->image_end_offset
= result
.image_end_offset
;
654 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
655 check
->total_clusters
= result
.bfi
.total_clusters
;
656 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
657 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
658 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
659 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
660 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
661 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
662 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
668 * Checks an image for consistency. Exit codes:
670 * 0 - Check completed, image is good
671 * 1 - Check not completed because of internal errors
672 * 2 - Check completed, image is corrupted
673 * 3 - Check completed, image has leaked clusters, but is good otherwise
674 * 63 - Checks are not supported by the image format
676 static int img_check(int argc
, char **argv
)
679 OutputFormat output_format
= OFORMAT_HUMAN
;
680 const char *filename
, *fmt
, *output
, *cache
;
682 BlockDriverState
*bs
;
684 int flags
= BDRV_O_CHECK
;
688 bool image_opts
= false;
689 bool force_share
= false;
693 cache
= BDRV_DEFAULT_CACHE
;
696 int option_index
= 0;
697 static const struct option long_options
[] = {
698 {"help", no_argument
, 0, 'h'},
699 {"format", required_argument
, 0, 'f'},
700 {"repair", required_argument
, 0, 'r'},
701 {"output", required_argument
, 0, OPTION_OUTPUT
},
702 {"object", required_argument
, 0, OPTION_OBJECT
},
703 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
704 {"force-share", no_argument
, 0, 'U'},
707 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
708 long_options
, &option_index
);
714 missing_argument(argv
[optind
- 1]);
717 unrecognized_option(argv
[optind
- 1]);
726 flags
|= BDRV_O_RDWR
;
728 if (!strcmp(optarg
, "leaks")) {
729 fix
= BDRV_FIX_LEAKS
;
730 } else if (!strcmp(optarg
, "all")) {
731 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
733 error_exit("Unknown option value for -r "
734 "(expecting 'leaks' or 'all'): %s", optarg
);
749 case OPTION_OBJECT
: {
751 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
757 case OPTION_IMAGE_OPTS
:
762 if (optind
!= argc
- 1) {
763 error_exit("Expecting one image file name");
765 filename
= argv
[optind
++];
767 if (output
&& !strcmp(output
, "json")) {
768 output_format
= OFORMAT_JSON
;
769 } else if (output
&& !strcmp(output
, "human")) {
770 output_format
= OFORMAT_HUMAN
;
772 error_report("--output must be used with human or json as argument.");
776 if (qemu_opts_foreach(&qemu_object_opts
,
777 user_creatable_add_opts_foreach
,
778 qemu_img_object_print_help
, &error_fatal
)) {
782 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
784 error_report("Invalid source cache option: %s", cache
);
788 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
795 check
= g_new0(ImageCheck
, 1);
796 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
798 if (ret
== -ENOTSUP
) {
799 error_report("This image format does not support checks");
804 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
805 int corruptions_fixed
, leaks_fixed
;
807 leaks_fixed
= check
->leaks_fixed
;
808 corruptions_fixed
= check
->corruptions_fixed
;
810 if (output_format
== OFORMAT_HUMAN
) {
812 "The following inconsistencies were found and repaired:\n\n"
813 " %" PRId64
" leaked clusters\n"
814 " %" PRId64
" corruptions\n\n"
815 "Double checking the fixed image now...\n",
817 check
->corruptions_fixed
);
820 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
822 check
->leaks_fixed
= leaks_fixed
;
823 check
->corruptions_fixed
= corruptions_fixed
;
827 switch (output_format
) {
829 dump_human_image_check(check
, quiet
);
832 dump_json_image_check(check
, quiet
);
837 if (ret
|| check
->check_errors
) {
839 error_report("Check failed: %s", strerror(-ret
));
841 error_report("Check failed");
847 if (check
->corruptions
) {
849 } else if (check
->leaks
) {
856 qapi_free_ImageCheck(check
);
861 typedef struct CommonBlockJobCBInfo
{
862 BlockDriverState
*bs
;
864 } CommonBlockJobCBInfo
;
866 static void common_block_job_cb(void *opaque
, int ret
)
868 CommonBlockJobCBInfo
*cbi
= opaque
;
871 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
875 static void run_block_job(BlockJob
*job
, Error
**errp
)
877 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
880 aio_context_acquire(aio_context
);
883 float progress
= 0.0f
;
884 aio_poll(aio_context
, true);
885 if (job
->job
.progress_total
) {
886 progress
= (float)job
->job
.progress_current
/
887 job
->job
.progress_total
* 100.f
;
889 qemu_progress_print(progress
, 0);
890 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
892 if (!job_is_completed(&job
->job
)) {
893 ret
= job_complete_sync(&job
->job
, errp
);
897 job_unref(&job
->job
);
898 aio_context_release(aio_context
);
900 /* publish completion progress only when success */
902 qemu_progress_print(100.f
, 0);
906 static int img_commit(int argc
, char **argv
)
909 const char *filename
, *fmt
, *cache
, *base
;
911 BlockDriverState
*bs
, *base_bs
;
913 bool progress
= false, quiet
= false, drop
= false;
915 Error
*local_err
= NULL
;
916 CommonBlockJobCBInfo cbi
;
917 bool image_opts
= false;
918 AioContext
*aio_context
;
921 cache
= BDRV_DEFAULT_CACHE
;
924 static const struct option long_options
[] = {
925 {"help", no_argument
, 0, 'h'},
926 {"object", required_argument
, 0, OPTION_OBJECT
},
927 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
930 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
937 missing_argument(argv
[optind
- 1]);
940 unrecognized_option(argv
[optind
- 1]);
965 case OPTION_OBJECT
: {
967 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
973 case OPTION_IMAGE_OPTS
:
979 /* Progress is not shown in Quiet mode */
984 if (optind
!= argc
- 1) {
985 error_exit("Expecting one image file name");
987 filename
= argv
[optind
++];
989 if (qemu_opts_foreach(&qemu_object_opts
,
990 user_creatable_add_opts_foreach
,
991 qemu_img_object_print_help
, &error_fatal
)) {
995 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
996 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
998 error_report("Invalid cache option: %s", cache
);
1002 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1009 qemu_progress_init(progress
, 1.f
);
1010 qemu_progress_print(0.f
, 100);
1013 base_bs
= bdrv_find_backing_image(bs
, base
);
1015 error_setg(&local_err
,
1016 "Did not find '%s' in the backing chain of '%s'",
1021 /* This is different from QMP, which by default uses the deepest file in
1022 * the backing chain (i.e., the very base); however, the traditional
1023 * behavior of qemu-img commit is using the immediate backing file. */
1024 base_bs
= backing_bs(bs
);
1026 error_setg(&local_err
, "Image does not have a backing file");
1031 cbi
= (CommonBlockJobCBInfo
){
1036 aio_context
= bdrv_get_aio_context(bs
);
1037 aio_context_acquire(aio_context
);
1038 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1039 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1040 &cbi
, false, &local_err
);
1041 aio_context_release(aio_context
);
1046 /* When the block job completes, the BlockBackend reference will point to
1047 * the old backing file. In order to avoid that the top image is already
1048 * deleted, so we can still empty it afterwards, increment the reference
1049 * counter here preemptively. */
1054 job
= block_job_get("commit");
1056 run_block_job(job
, &local_err
);
1061 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1062 ret
= bs
->drv
->bdrv_make_empty(bs
);
1064 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1076 qemu_progress_end();
1081 error_report_err(local_err
);
1085 qprintf(quiet
, "Image committed.\n");
1090 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1091 * of the first sector boundary within buf where the sector contains a
1092 * non-zero byte. This function is robust to a buffer that is not
1095 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1098 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1100 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1101 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1105 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1112 * Returns true iff the first sector pointed to by 'buf' contains at least
1115 * 'pnum' is set to the number of sectors (including and immediately following
1116 * the first one) that are known to be in the same allocated/unallocated state.
1117 * The function will try to align the end offset to alignment boundaries so
1118 * that the request will at least end aligned and consequtive requests will
1119 * also start at an aligned offset.
1121 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1122 int64_t sector_num
, int alignment
)
1131 is_zero
= buffer_is_zero(buf
, 512);
1132 for(i
= 1; i
< n
; i
++) {
1134 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1139 tail
= (sector_num
+ i
) & (alignment
- 1);
1141 if (is_zero
&& i
<= tail
) {
1142 /* treat unallocated areas which only consist
1143 * of a small tail as allocated. */
1147 /* align up end offset of allocated areas. */
1148 i
+= alignment
- tail
;
1151 /* align down end offset of zero areas. */
1160 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1161 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1162 * breaking up write requests for only small sparse areas.
1164 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1165 int min
, int64_t sector_num
, int alignment
)
1168 int num_checked
, num_used
;
1174 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1180 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1182 sector_num
+= *pnum
;
1183 num_checked
= num_used
;
1186 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1188 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1190 sector_num
+= *pnum
;
1191 num_checked
+= *pnum
;
1193 num_used
= num_checked
;
1194 } else if (*pnum
>= min
) {
1204 * Compares two buffers sector by sector. Returns 0 if the first
1205 * sector of each buffer matches, non-zero otherwise.
1207 * pnum is set to the sector-aligned size of the buffer prefix that
1208 * has the same matching status as the first sector.
1210 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1211 int64_t bytes
, int64_t *pnum
)
1214 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1218 res
= !!memcmp(buf1
, buf2
, i
);
1220 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1222 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1232 #define IO_BUF_SIZE (2 * MiB)
1235 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1237 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1238 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1239 * failure), and 4 on error (the exit status for read errors), after emitting
1242 * @param blk: BlockBackend for the image
1243 * @param offset: Starting offset to check
1244 * @param bytes: Number of bytes to check
1245 * @param filename: Name of disk file we are checking (logging purpose)
1246 * @param buffer: Allocated buffer for storing read data
1247 * @param quiet: Flag for quiet mode
1249 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1250 int64_t bytes
, const char *filename
,
1251 uint8_t *buffer
, bool quiet
)
1256 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1258 error_report("Error while reading offset %" PRId64
" of %s: %s",
1259 offset
, filename
, strerror(-ret
));
1262 idx
= find_nonzero(buffer
, bytes
);
1264 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1273 * Compares two images. Exit codes:
1275 * 0 - Images are identical
1277 * >1 - Error occurred
1279 static int img_compare(int argc
, char **argv
)
1281 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1282 BlockBackend
*blk1
, *blk2
;
1283 BlockDriverState
*bs1
, *bs2
;
1284 int64_t total_size1
, total_size2
;
1285 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1286 int64_t pnum1
, pnum2
;
1287 int allocated1
, allocated2
;
1288 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1289 bool progress
= false, quiet
= false, strict
= false;
1296 uint64_t progress_base
;
1297 bool image_opts
= false;
1298 bool force_share
= false;
1300 cache
= BDRV_DEFAULT_CACHE
;
1302 static const struct option long_options
[] = {
1303 {"help", no_argument
, 0, 'h'},
1304 {"object", required_argument
, 0, OPTION_OBJECT
},
1305 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1306 {"force-share", no_argument
, 0, 'U'},
1309 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1310 long_options
, NULL
);
1316 missing_argument(argv
[optind
- 1]);
1319 unrecognized_option(argv
[optind
- 1]);
1345 case OPTION_OBJECT
: {
1347 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1354 case OPTION_IMAGE_OPTS
:
1360 /* Progress is not shown in Quiet mode */
1366 if (optind
!= argc
- 2) {
1367 error_exit("Expecting two image file names");
1369 filename1
= argv
[optind
++];
1370 filename2
= argv
[optind
++];
1372 if (qemu_opts_foreach(&qemu_object_opts
,
1373 user_creatable_add_opts_foreach
,
1374 qemu_img_object_print_help
, &error_fatal
)) {
1379 /* Initialize before goto out */
1380 qemu_progress_init(progress
, 2.0);
1383 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1385 error_report("Invalid source cache option: %s", cache
);
1390 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1397 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1406 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1407 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1408 total_size1
= blk_getlength(blk1
);
1409 if (total_size1
< 0) {
1410 error_report("Can't get size of %s: %s",
1411 filename1
, strerror(-total_size1
));
1415 total_size2
= blk_getlength(blk2
);
1416 if (total_size2
< 0) {
1417 error_report("Can't get size of %s: %s",
1418 filename2
, strerror(-total_size2
));
1422 total_size
= MIN(total_size1
, total_size2
);
1423 progress_base
= MAX(total_size1
, total_size2
);
1425 qemu_progress_print(0, 100);
1427 if (strict
&& total_size1
!= total_size2
) {
1429 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1433 while (offset
< total_size
) {
1434 int status1
, status2
;
1436 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1437 total_size1
- offset
, &pnum1
, NULL
,
1441 error_report("Sector allocation test failed for %s", filename1
);
1444 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1446 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1447 total_size2
- offset
, &pnum2
, NULL
,
1451 error_report("Sector allocation test failed for %s", filename2
);
1454 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1456 assert(pnum1
&& pnum2
);
1457 chunk
= MIN(pnum1
, pnum2
);
1460 if (status1
!= status2
) {
1462 qprintf(quiet
, "Strict mode: Offset %" PRId64
1463 " block status mismatch!\n", offset
);
1467 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1469 } else if (allocated1
== allocated2
) {
1473 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1474 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1476 error_report("Error while reading offset %" PRId64
1478 offset
, filename1
, strerror(-ret
));
1482 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1484 error_report("Error while reading offset %" PRId64
1486 offset
, filename2
, strerror(-ret
));
1490 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1491 if (ret
|| pnum
!= chunk
) {
1492 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1493 offset
+ (ret ?
0 : pnum
));
1499 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1501 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1502 filename1
, buf1
, quiet
);
1504 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1505 filename2
, buf1
, quiet
);
1512 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1515 if (total_size1
!= total_size2
) {
1516 BlockBackend
*blk_over
;
1517 const char *filename_over
;
1519 qprintf(quiet
, "Warning: Image size mismatch!\n");
1520 if (total_size1
> total_size2
) {
1522 filename_over
= filename1
;
1525 filename_over
= filename2
;
1528 while (offset
< progress_base
) {
1529 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1530 progress_base
- offset
, &chunk
,
1534 error_report("Sector allocation test failed for %s",
1539 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1540 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1541 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1542 filename_over
, buf1
, quiet
);
1548 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1552 qprintf(quiet
, "Images are identical.\n");
1562 qemu_progress_end();
1567 enum ImgConvertBlockStatus
{
1573 #define MAX_COROUTINES 16
1575 typedef struct ImgConvertState
{
1577 int64_t *src_sectors
;
1579 int64_t total_sectors
;
1580 int64_t allocated_sectors
;
1581 int64_t allocated_done
;
1584 enum ImgConvertBlockStatus status
;
1585 int64_t sector_next_status
;
1586 BlockBackend
*target
;
1589 bool unallocated_blocks_are_zero
;
1591 bool target_has_backing
;
1592 int64_t target_backing_sectors
; /* negative if unknown */
1599 size_t cluster_sectors
;
1601 long num_coroutines
;
1602 int running_coroutines
;
1603 Coroutine
*co
[MAX_COROUTINES
];
1604 int64_t wait_sector_num
[MAX_COROUTINES
];
1609 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1610 int *src_cur
, int64_t *src_cur_offset
)
1613 *src_cur_offset
= 0;
1614 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1615 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1617 assert(*src_cur
< s
->src_num
);
1621 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1623 int64_t src_cur_offset
;
1624 int ret
, n
, src_cur
;
1625 bool post_backing_zero
= false;
1627 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1629 assert(s
->total_sectors
> sector_num
);
1630 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1632 if (s
->target_backing_sectors
>= 0) {
1633 if (sector_num
>= s
->target_backing_sectors
) {
1634 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1635 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1636 /* Split requests around target_backing_sectors (because
1637 * starting from there, zeros are handled differently) */
1638 n
= s
->target_backing_sectors
- sector_num
;
1642 if (s
->sector_next_status
<= sector_num
) {
1643 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1647 count
= n
* BDRV_SECTOR_SIZE
;
1649 if (s
->target_has_backing
) {
1650 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]), offset
,
1651 count
, &count
, NULL
, NULL
);
1653 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1654 offset
, count
, &count
, NULL
,
1662 warn_report("error while reading block status at "
1663 "offset %" PRIu64
": %s", offset
,
1666 /* Just try to read the data, then */
1667 ret
= BDRV_BLOCK_DATA
;
1668 count
= BDRV_SECTOR_SIZE
;
1670 /* Retry on a shorter range */
1671 n
= DIV_ROUND_UP(n
, 4);
1674 error_report("error while reading block status at offset "
1675 "%" PRIu64
": %s", offset
, strerror(-ret
));
1681 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1683 if (ret
& BDRV_BLOCK_ZERO
) {
1684 s
->status
= post_backing_zero ? BLK_BACKING_FILE
: BLK_ZERO
;
1685 } else if (ret
& BDRV_BLOCK_DATA
) {
1686 s
->status
= BLK_DATA
;
1688 s
->status
= s
->target_has_backing ? BLK_BACKING_FILE
: BLK_DATA
;
1691 s
->sector_next_status
= sector_num
+ n
;
1694 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1695 if (s
->status
== BLK_DATA
) {
1696 n
= MIN(n
, s
->buf_sectors
);
1699 /* We need to write complete clusters for compressed images, so if an
1700 * unallocated area is shorter than that, we must consider the whole
1701 * cluster allocated. */
1702 if (s
->compressed
) {
1703 if (n
< s
->cluster_sectors
) {
1704 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1705 s
->status
= BLK_DATA
;
1707 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1714 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1715 int nb_sectors
, uint8_t *buf
)
1717 uint64_t single_read_until
= 0;
1720 assert(nb_sectors
<= s
->buf_sectors
);
1721 while (nb_sectors
> 0) {
1724 int64_t bs_sectors
, src_cur_offset
;
1727 /* In the case of compression with multiple source files, we can get a
1728 * nb_sectors that spreads into the next part. So we must be able to
1729 * read across multiple BDSes for one convert_read() call. */
1730 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1731 blk
= s
->src
[src_cur
];
1732 bs_sectors
= s
->src_sectors
[src_cur
];
1734 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1736 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1737 if (single_read_until
> offset
) {
1741 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1745 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1749 warn_report("error while reading offset %" PRIu64
1750 ": %s", offset
, strerror(-ret
));
1752 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1761 buf
+= n
* BDRV_SECTOR_SIZE
;
1768 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1769 int nb_sectors
, uint8_t *buf
,
1770 enum ImgConvertBlockStatus status
)
1774 while (nb_sectors
> 0) {
1776 BdrvRequestFlags flags
= s
->compressed ? BDRV_REQ_WRITE_COMPRESSED
: 0;
1779 case BLK_BACKING_FILE
:
1780 /* If we have a backing file, leave clusters unallocated that are
1781 * unallocated in the source image, so that the backing file is
1782 * visible at the respective offset. */
1783 assert(s
->target_has_backing
);
1787 /* If we're told to keep the target fully allocated (-S 0) or there
1788 * is real non-zero data, we must write it. Otherwise we can treat
1789 * it as zero sectors.
1790 * Compressed clusters need to be written as a whole, so in that
1791 * case we can only save the write if the buffer is completely
1793 if (!s
->min_sparse
||
1795 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1796 sector_num
, s
->alignment
)) ||
1798 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1800 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1801 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1810 if (s
->has_zero_init
) {
1811 assert(!s
->target_has_backing
);
1814 ret
= blk_co_pwrite_zeroes(s
->target
,
1815 sector_num
<< BDRV_SECTOR_BITS
,
1816 n
<< BDRV_SECTOR_BITS
,
1817 BDRV_REQ_MAY_UNMAP
);
1826 buf
+= n
* BDRV_SECTOR_SIZE
;
1832 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1837 while (nb_sectors
> 0) {
1840 int64_t bs_sectors
, src_cur_offset
;
1843 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1844 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1845 blk
= s
->src
[src_cur
];
1846 bs_sectors
= s
->src_sectors
[src_cur
];
1848 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1850 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1851 sector_num
<< BDRV_SECTOR_BITS
,
1852 n
<< BDRV_SECTOR_BITS
, 0, 0);
1863 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1865 ImgConvertState
*s
= opaque
;
1866 uint8_t *buf
= NULL
;
1870 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1871 if (s
->co
[i
] == qemu_coroutine_self()) {
1878 s
->running_coroutines
++;
1879 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1884 enum ImgConvertBlockStatus status
;
1887 qemu_co_mutex_lock(&s
->lock
);
1888 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1889 qemu_co_mutex_unlock(&s
->lock
);
1892 n
= convert_iteration_sectors(s
, s
->sector_num
);
1894 qemu_co_mutex_unlock(&s
->lock
);
1898 /* save current sector and allocation status to local variables */
1899 sector_num
= s
->sector_num
;
1901 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1902 n
= MIN(n
, s
->buf_sectors
);
1904 /* increment global sector counter so that other coroutines can
1905 * already continue reading beyond this request */
1907 qemu_co_mutex_unlock(&s
->lock
);
1909 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1910 s
->allocated_done
+= n
;
1911 qemu_progress_print(100.0 * s
->allocated_done
/
1912 s
->allocated_sectors
, 0);
1916 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1917 if (status
== BLK_DATA
&& !copy_range
) {
1918 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1920 error_report("error while reading sector %" PRId64
1921 ": %s", sector_num
, strerror(-ret
));
1924 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1926 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1929 if (s
->wr_in_order
) {
1930 /* keep writes in order */
1931 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1932 s
->wait_sector_num
[index
] = sector_num
;
1933 qemu_coroutine_yield();
1935 s
->wait_sector_num
[index
] = -1;
1938 if (s
->ret
== -EINPROGRESS
) {
1940 ret
= convert_co_copy_range(s
, sector_num
, n
);
1942 s
->copy_range
= false;
1946 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1949 error_report("error while writing sector %" PRId64
1950 ": %s", sector_num
, strerror(-ret
));
1955 if (s
->wr_in_order
) {
1956 /* reenter the coroutine that might have waited
1957 * for this write to complete */
1958 s
->wr_offs
= sector_num
+ n
;
1959 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1960 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1962 * A -> B -> A cannot occur because A has
1963 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1964 * B will never enter A during this time window.
1966 qemu_coroutine_enter(s
->co
[i
]);
1974 s
->co
[index
] = NULL
;
1975 s
->running_coroutines
--;
1976 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1977 /* the convert job finished successfully */
1982 static int convert_do_copy(ImgConvertState
*s
)
1985 int64_t sector_num
= 0;
1987 /* Check whether we have zero initialisation or can get it efficiently */
1988 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
1989 !s
->target_has_backing
) {
1990 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
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
},
2089 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2092 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2093 long_options
, NULL
);
2099 missing_argument(argv
[optind
- 1]);
2102 unrecognized_option(argv
[optind
- 1]);
2114 out_baseimg
= optarg
;
2117 s
.copy_range
= true;
2120 s
.compressed
= true;
2123 if (!is_valid_option_list(optarg
)) {
2124 error_report("Invalid option list: %s", optarg
);
2128 options
= g_strdup(optarg
);
2130 char *old_options
= options
;
2131 options
= g_strdup_printf("%s,%s", options
, optarg
);
2132 g_free(old_options
);
2136 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2137 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2140 error_report("Failed in parsing snapshot param '%s'",
2145 snapshot_name
= optarg
;
2152 sval
= cvtnum(optarg
);
2153 if (sval
< 0 || !QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2154 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2155 error_report("Invalid buffer size for sparse output specified. "
2156 "Valid sizes are multiples of %llu up to %llu. Select "
2157 "0 to disable sparse detection (fully allocates output).",
2158 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2162 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2163 explict_min_sparse
= true;
2182 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2183 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2184 error_report("Invalid number of coroutines. Allowed number of"
2185 " coroutines is between 1 and %d", MAX_COROUTINES
);
2190 s
.wr_in_order
= false;
2195 case OPTION_OBJECT
: {
2196 QemuOpts
*object_opts
;
2197 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2204 case OPTION_IMAGE_OPTS
:
2207 case OPTION_SALVAGE
:
2210 case OPTION_TARGET_IMAGE_OPTS
:
2211 tgt_image_opts
= true;
2213 case OPTION_TARGET_IS_ZERO
:
2215 * The user asserting that the target is blank has the
2216 * same effect as the target driver supporting zero
2219 s
.has_zero_init
= true;
2224 if (!out_fmt
&& !tgt_image_opts
) {
2228 if (qemu_opts_foreach(&qemu_object_opts
,
2229 user_creatable_add_opts_foreach
,
2230 qemu_img_object_print_help
, &error_fatal
)) {
2234 if (s
.compressed
&& s
.copy_range
) {
2235 error_report("Cannot enable copy offloading when -c is used");
2239 if (explict_min_sparse
&& s
.copy_range
) {
2240 error_report("Cannot enable copy offloading when -S is used");
2244 if (s
.copy_range
&& s
.salvage
) {
2245 error_report("Cannot use copy offloading in salvaging mode");
2249 if (tgt_image_opts
&& !skip_create
) {
2250 error_report("--target-image-opts requires use of -n flag");
2254 if (skip_create
&& options
) {
2255 warn_report("-o has no effect when skipping image creation");
2256 warn_report("This will become an error in future QEMU versions.");
2259 if (s
.has_zero_init
&& !skip_create
) {
2260 error_report("--target-is-zero requires use of -n flag");
2264 s
.src_num
= argc
- optind
- 1;
2265 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2267 if (options
&& has_help_option(options
)) {
2269 ret
= print_block_option_help(out_filename
, out_fmt
);
2272 error_report("Option help requires a format be specified");
2277 if (s
.src_num
< 1) {
2278 error_report("Must specify image file name");
2283 /* ret is still -EINVAL until here */
2284 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2286 error_report("Invalid source cache option: %s", src_cache
);
2290 /* Initialize before goto out */
2294 qemu_progress_init(progress
, 1.0);
2295 qemu_progress_print(0, 100);
2297 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2298 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2300 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2301 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2302 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2308 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2309 if (s
.src_sectors
[bs_i
] < 0) {
2310 error_report("Could not get size of %s: %s",
2311 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2315 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2319 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2320 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2321 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2323 } else if (snapshot_name
!= NULL
) {
2324 if (s
.src_num
> 1) {
2325 error_report("No support for concatenating multiple snapshot");
2330 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2334 error_reportf_err(local_err
, "Failed to load snapshot: ");
2340 /* Find driver and parse its options */
2341 drv
= bdrv_find_format(out_fmt
);
2343 error_report("Unknown file format '%s'", out_fmt
);
2348 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2350 error_report_err(local_err
);
2355 if (!drv
->create_opts
) {
2356 error_report("Format driver '%s' does not support image creation",
2362 if (!proto_drv
->create_opts
) {
2363 error_report("Protocol driver '%s' does not support image creation",
2364 proto_drv
->format_name
);
2369 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2370 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2372 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2374 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2376 error_report_err(local_err
);
2382 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2384 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2390 /* Get backing file name if -o backing_file was used */
2391 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2392 if (out_baseimg_param
) {
2393 out_baseimg
= out_baseimg_param
;
2395 s
.target_has_backing
= (bool) out_baseimg
;
2397 if (s
.has_zero_init
&& s
.target_has_backing
) {
2398 error_report("Cannot use --target-is-zero when the destination "
2399 "image has a backing file");
2403 if (s
.src_num
> 1 && out_baseimg
) {
2404 error_report("Having a backing file for the target makes no sense when "
2405 "concatenating multiple input images");
2410 /* Check if compression is supported */
2413 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2414 const char *encryptfmt
=
2415 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2416 const char *preallocation
=
2417 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2419 if (drv
&& !block_driver_can_compress(drv
)) {
2420 error_report("Compression not supported for this file format");
2425 if (encryption
|| encryptfmt
) {
2426 error_report("Compression and encryption not supported at "
2433 && strcmp(preallocation
, "off"))
2435 error_report("Compression and preallocation not supported at "
2443 * The later open call will need any decryption secrets, and
2444 * bdrv_create() will purge "opts", so extract them now before
2448 open_opts
= qdict_new();
2449 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2453 /* Create the new image */
2454 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2456 error_reportf_err(local_err
, "%s: error while converting %s: ",
2457 out_filename
, out_fmt
);
2462 s
.target_is_new
= !skip_create
;
2464 flags
= s
.min_sparse ?
(BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2465 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2467 error_report("Invalid cache option: %s", cache
);
2472 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2473 flags
, writethrough
, s
.quiet
, false);
2475 /* TODO ultimately we should allow --target-image-opts
2476 * to be used even when -n is not given.
2477 * That has to wait for bdrv_create to be improved
2478 * to allow filenames in option syntax
2480 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2481 flags
, writethrough
, s
.quiet
, false);
2482 open_opts
= NULL
; /* blk_new_open will have freed it */
2488 out_bs
= blk_bs(s
.target
);
2490 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2491 error_report("Compression not supported for this file format");
2496 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2497 * or discard_alignment of the out_bs is greater. Limit to
2498 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2499 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2501 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2502 out_bs
->bl
.pdiscard_alignment
>>
2503 BDRV_SECTOR_BITS
)));
2505 /* try to align the write requests to the destination to avoid unnecessary
2507 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2508 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2510 assert(is_power_of_2(s
.alignment
));
2513 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2514 if (output_sectors
< 0) {
2515 error_report("unable to get output image length: %s",
2516 strerror(-output_sectors
));
2519 } else if (output_sectors
< s
.total_sectors
) {
2520 error_report("output file is smaller than input file");
2526 if (s
.target_has_backing
&& s
.target_is_new
) {
2527 /* Errors are treated as "backing length unknown" (which means
2528 * s.target_backing_sectors has to be negative, which it will
2529 * be automatically). The backing file length is used only
2530 * for optimizations, so such a case is not fatal. */
2531 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2533 s
.target_backing_sectors
= -1;
2536 ret
= bdrv_get_info(out_bs
, &bdi
);
2539 error_report("could not get block driver info");
2543 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2544 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2545 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2548 ret
= convert_do_copy(&s
);
2551 qemu_progress_print(100, 0);
2553 qemu_progress_end();
2554 qemu_opts_del(opts
);
2555 qemu_opts_free(create_opts
);
2556 qemu_opts_del(sn_opts
);
2557 qobject_unref(open_opts
);
2558 blk_unref(s
.target
);
2560 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2561 blk_unref(s
.src
[bs_i
]);
2565 g_free(s
.src_sectors
);
2573 static void dump_snapshots(BlockDriverState
*bs
)
2575 QEMUSnapshotInfo
*sn_tab
, *sn
;
2578 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2581 printf("Snapshot list:\n");
2582 bdrv_snapshot_dump(NULL
);
2584 for(i
= 0; i
< nb_sns
; i
++) {
2586 bdrv_snapshot_dump(sn
);
2592 static void dump_json_image_info_list(ImageInfoList
*list
)
2596 Visitor
*v
= qobject_output_visitor_new(&obj
);
2598 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2599 visit_complete(v
, &obj
);
2600 str
= qobject_to_json_pretty(obj
);
2601 assert(str
!= NULL
);
2602 printf("%s\n", qstring_get_str(str
));
2608 static void dump_json_image_info(ImageInfo
*info
)
2612 Visitor
*v
= qobject_output_visitor_new(&obj
);
2614 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2615 visit_complete(v
, &obj
);
2616 str
= qobject_to_json_pretty(obj
);
2617 assert(str
!= NULL
);
2618 printf("%s\n", qstring_get_str(str
));
2624 static void dump_human_image_info_list(ImageInfoList
*list
)
2626 ImageInfoList
*elem
;
2629 for (elem
= list
; elem
; elem
= elem
->next
) {
2635 bdrv_image_info_dump(elem
->value
);
2639 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2641 return strcmp(a
, b
) == 0;
2645 * Open an image file chain and return an ImageInfoList
2647 * @filename: topmost image filename
2648 * @fmt: topmost image format (may be NULL to autodetect)
2649 * @chain: true - enumerate entire backing file chain
2650 * false - only topmost image file
2652 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2653 * image file. If there was an error a message will have been printed to
2656 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2657 const char *filename
,
2659 bool chain
, bool force_share
)
2661 ImageInfoList
*head
= NULL
;
2662 ImageInfoList
**last
= &head
;
2663 GHashTable
*filenames
;
2666 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2670 BlockDriverState
*bs
;
2672 ImageInfoList
*elem
;
2674 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2675 error_report("Backing file '%s' creates an infinite loop.",
2679 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2681 blk
= img_open(image_opts
, filename
, fmt
,
2682 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2689 bdrv_query_image_info(bs
, &info
, &err
);
2691 error_report_err(err
);
2696 elem
= g_new0(ImageInfoList
, 1);
2703 /* Clear parameters that only apply to the topmost image */
2704 filename
= fmt
= NULL
;
2708 if (info
->has_full_backing_filename
) {
2709 filename
= info
->full_backing_filename
;
2710 } else if (info
->has_backing_filename
) {
2711 error_report("Could not determine absolute backing filename,"
2712 " but backing filename '%s' present",
2713 info
->backing_filename
);
2716 if (info
->has_backing_filename_format
) {
2717 fmt
= info
->backing_filename_format
;
2721 g_hash_table_destroy(filenames
);
2725 qapi_free_ImageInfoList(head
);
2726 g_hash_table_destroy(filenames
);
2730 static int img_info(int argc
, char **argv
)
2733 OutputFormat output_format
= OFORMAT_HUMAN
;
2735 const char *filename
, *fmt
, *output
;
2736 ImageInfoList
*list
;
2737 bool image_opts
= false;
2738 bool force_share
= false;
2743 int option_index
= 0;
2744 static const struct option long_options
[] = {
2745 {"help", no_argument
, 0, 'h'},
2746 {"format", required_argument
, 0, 'f'},
2747 {"output", required_argument
, 0, OPTION_OUTPUT
},
2748 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2749 {"object", required_argument
, 0, OPTION_OBJECT
},
2750 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2751 {"force-share", no_argument
, 0, 'U'},
2754 c
= getopt_long(argc
, argv
, ":f:hU",
2755 long_options
, &option_index
);
2761 missing_argument(argv
[optind
- 1]);
2764 unrecognized_option(argv
[optind
- 1]);
2778 case OPTION_BACKING_CHAIN
:
2781 case OPTION_OBJECT
: {
2783 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2789 case OPTION_IMAGE_OPTS
:
2794 if (optind
!= argc
- 1) {
2795 error_exit("Expecting one image file name");
2797 filename
= argv
[optind
++];
2799 if (output
&& !strcmp(output
, "json")) {
2800 output_format
= OFORMAT_JSON
;
2801 } else if (output
&& !strcmp(output
, "human")) {
2802 output_format
= OFORMAT_HUMAN
;
2803 } else if (output
) {
2804 error_report("--output must be used with human or json as argument.");
2808 if (qemu_opts_foreach(&qemu_object_opts
,
2809 user_creatable_add_opts_foreach
,
2810 qemu_img_object_print_help
, &error_fatal
)) {
2814 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2820 switch (output_format
) {
2822 dump_human_image_info_list(list
);
2826 dump_json_image_info_list(list
);
2828 dump_json_image_info(list
->value
);
2833 qapi_free_ImageInfoList(list
);
2837 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2840 switch (output_format
) {
2842 if (e
->data
&& !e
->has_offset
) {
2843 error_report("File contains external, encrypted or compressed clusters.");
2846 if (e
->data
&& !e
->zero
) {
2847 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2848 e
->start
, e
->length
,
2849 e
->has_offset ? e
->offset
: 0,
2850 e
->has_filename ? e
->filename
: "");
2852 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2853 * Modify the flags here to allow more coalescing.
2855 if (next
&& (!next
->data
|| next
->zero
)) {
2861 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2862 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2863 (e
->start
== 0 ?
"[" : ",\n"),
2864 e
->start
, e
->length
, e
->depth
,
2865 e
->zero ?
"true" : "false",
2866 e
->data ?
"true" : "false");
2867 if (e
->has_offset
) {
2868 printf(", \"offset\": %"PRId64
"", e
->offset
);
2880 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2881 int64_t bytes
, MapEntry
*e
)
2885 BlockDriverState
*file
;
2888 char *filename
= NULL
;
2890 /* As an optimization, we could cache the current range of unallocated
2891 * clusters in each file of the chain, and avoid querying the same
2897 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2902 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2905 bs
= backing_bs(bs
);
2914 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2916 if (file
&& has_offset
) {
2917 bdrv_refresh_filename(file
);
2918 filename
= file
->filename
;
2924 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2925 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2927 .has_offset
= has_offset
,
2929 .has_filename
= filename
,
2930 .filename
= filename
,
2936 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2938 if (curr
->length
== 0) {
2941 if (curr
->zero
!= next
->zero
||
2942 curr
->data
!= next
->data
||
2943 curr
->depth
!= next
->depth
||
2944 curr
->has_filename
!= next
->has_filename
||
2945 curr
->has_offset
!= next
->has_offset
) {
2948 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2951 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2957 static int img_map(int argc
, char **argv
)
2960 OutputFormat output_format
= OFORMAT_HUMAN
;
2962 BlockDriverState
*bs
;
2963 const char *filename
, *fmt
, *output
;
2965 MapEntry curr
= { .length
= 0 }, next
;
2967 bool image_opts
= false;
2968 bool force_share
= false;
2973 int option_index
= 0;
2974 static const struct option long_options
[] = {
2975 {"help", no_argument
, 0, 'h'},
2976 {"format", required_argument
, 0, 'f'},
2977 {"output", required_argument
, 0, OPTION_OUTPUT
},
2978 {"object", required_argument
, 0, OPTION_OBJECT
},
2979 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2980 {"force-share", no_argument
, 0, 'U'},
2983 c
= getopt_long(argc
, argv
, ":f:hU",
2984 long_options
, &option_index
);
2990 missing_argument(argv
[optind
- 1]);
2993 unrecognized_option(argv
[optind
- 1]);
3007 case OPTION_OBJECT
: {
3009 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3015 case OPTION_IMAGE_OPTS
:
3020 if (optind
!= argc
- 1) {
3021 error_exit("Expecting one image file name");
3023 filename
= argv
[optind
];
3025 if (output
&& !strcmp(output
, "json")) {
3026 output_format
= OFORMAT_JSON
;
3027 } else if (output
&& !strcmp(output
, "human")) {
3028 output_format
= OFORMAT_HUMAN
;
3029 } else if (output
) {
3030 error_report("--output must be used with human or json as argument.");
3034 if (qemu_opts_foreach(&qemu_object_opts
,
3035 user_creatable_add_opts_foreach
,
3036 qemu_img_object_print_help
, &error_fatal
)) {
3040 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3046 if (output_format
== OFORMAT_HUMAN
) {
3047 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3050 length
= blk_getlength(blk
);
3051 while (curr
.start
+ curr
.length
< length
) {
3052 int64_t offset
= curr
.start
+ curr
.length
;
3055 /* Probe up to 1 GiB at a time. */
3056 n
= MIN(1 * GiB
, length
- offset
);
3057 ret
= get_block_status(bs
, offset
, n
, &next
);
3060 error_report("Could not read file metadata: %s", strerror(-ret
));
3064 if (entry_mergeable(&curr
, &next
)) {
3065 curr
.length
+= next
.length
;
3069 if (curr
.length
> 0) {
3070 ret
= dump_map_entry(output_format
, &curr
, &next
);
3078 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3085 #define SNAPSHOT_LIST 1
3086 #define SNAPSHOT_CREATE 2
3087 #define SNAPSHOT_APPLY 3
3088 #define SNAPSHOT_DELETE 4
3090 static int img_snapshot(int argc
, char **argv
)
3093 BlockDriverState
*bs
;
3094 QEMUSnapshotInfo sn
;
3095 char *filename
, *snapshot_name
= NULL
;
3096 int c
, ret
= 0, bdrv_oflags
;
3101 bool image_opts
= false;
3102 bool force_share
= false;
3104 bdrv_oflags
= BDRV_O_RDWR
;
3105 /* Parse commandline parameters */
3107 static const struct option long_options
[] = {
3108 {"help", no_argument
, 0, 'h'},
3109 {"object", required_argument
, 0, OPTION_OBJECT
},
3110 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3111 {"force-share", no_argument
, 0, 'U'},
3114 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3115 long_options
, NULL
);
3121 missing_argument(argv
[optind
- 1]);
3124 unrecognized_option(argv
[optind
- 1]);
3131 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3134 action
= SNAPSHOT_LIST
;
3135 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3139 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3142 action
= SNAPSHOT_APPLY
;
3143 snapshot_name
= optarg
;
3147 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3150 action
= SNAPSHOT_CREATE
;
3151 snapshot_name
= optarg
;
3155 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3158 action
= SNAPSHOT_DELETE
;
3159 snapshot_name
= optarg
;
3167 case OPTION_OBJECT
: {
3169 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3175 case OPTION_IMAGE_OPTS
:
3181 if (optind
!= argc
- 1) {
3182 error_exit("Expecting one image file name");
3184 filename
= argv
[optind
++];
3186 if (qemu_opts_foreach(&qemu_object_opts
,
3187 user_creatable_add_opts_foreach
,
3188 qemu_img_object_print_help
, &error_fatal
)) {
3192 /* Open the image */
3193 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3200 /* Perform the requested action */
3206 case SNAPSHOT_CREATE
:
3207 memset(&sn
, 0, sizeof(sn
));
3208 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3210 qemu_gettimeofday(&tv
);
3211 sn
.date_sec
= tv
.tv_sec
;
3212 sn
.date_nsec
= tv
.tv_usec
* 1000;
3214 ret
= bdrv_snapshot_create(bs
, &sn
);
3216 error_report("Could not create snapshot '%s': %d (%s)",
3217 snapshot_name
, ret
, strerror(-ret
));
3221 case SNAPSHOT_APPLY
:
3222 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3224 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3229 case SNAPSHOT_DELETE
:
3230 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3232 error_report("Could not delete snapshot '%s': snapshot not "
3233 "found", snapshot_name
);
3236 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3238 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3254 static int img_rebase(int argc
, char **argv
)
3256 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3257 uint8_t *buf_old
= NULL
;
3258 uint8_t *buf_new
= NULL
;
3259 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3261 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3262 int c
, flags
, src_flags
, ret
;
3263 bool writethrough
, src_writethrough
;
3265 bool force_share
= false;
3268 Error
*local_err
= NULL
;
3269 bool image_opts
= false;
3271 /* Parse commandline parameters */
3273 cache
= BDRV_DEFAULT_CACHE
;
3274 src_cache
= BDRV_DEFAULT_CACHE
;
3278 static const struct option long_options
[] = {
3279 {"help", no_argument
, 0, 'h'},
3280 {"object", required_argument
, 0, OPTION_OBJECT
},
3281 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3282 {"force-share", no_argument
, 0, 'U'},
3285 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3286 long_options
, NULL
);
3292 missing_argument(argv
[optind
- 1]);
3295 unrecognized_option(argv
[optind
- 1]);
3304 out_basefmt
= optarg
;
3307 out_baseimg
= optarg
;
3324 case OPTION_OBJECT
: {
3326 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3332 case OPTION_IMAGE_OPTS
:
3345 if (optind
!= argc
- 1) {
3346 error_exit("Expecting one image file name");
3348 if (!unsafe
&& !out_baseimg
) {
3349 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3351 filename
= argv
[optind
++];
3353 if (qemu_opts_foreach(&qemu_object_opts
,
3354 user_creatable_add_opts_foreach
,
3355 qemu_img_object_print_help
, &error_fatal
)) {
3359 qemu_progress_init(progress
, 2.0);
3360 qemu_progress_print(0, 100);
3362 flags
= BDRV_O_RDWR
| (unsafe ? BDRV_O_NO_BACKING
: 0);
3363 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3365 error_report("Invalid cache option: %s", cache
);
3370 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3372 error_report("Invalid source cache option: %s", src_cache
);
3376 /* The source files are opened read-only, don't care about WCE */
3377 assert((src_flags
& BDRV_O_RDWR
) == 0);
3378 (void) src_writethrough
;
3383 * Ignore the old backing file for unsafe rebase in case we want to correct
3384 * the reference to a renamed or moved backing file.
3386 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3394 if (out_basefmt
!= NULL
) {
3395 if (bdrv_find_format(out_basefmt
) == NULL
) {
3396 error_report("Invalid format name: '%s'", out_basefmt
);
3402 /* For safe rebasing we need to compare old and new backing file */
3404 QDict
*options
= NULL
;
3405 BlockDriverState
*base_bs
= backing_bs(bs
);
3408 blk_old_backing
= blk_new(qemu_get_aio_context(),
3409 BLK_PERM_CONSISTENT_READ
,
3411 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3414 error_reportf_err(local_err
,
3415 "Could not reuse old backing file '%s': ",