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/module.h"
42 #include "qemu/units.h"
43 #include "qom/object_interfaces.h"
44 #include "sysemu/sysemu.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,
74 typedef enum OutputFormat
{
79 /* Default to cache=writeback as data integrity is not important for qemu-img */
80 #define BDRV_DEFAULT_CACHE "writeback"
82 static void format_print(void *opaque
, const char *name
)
87 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
92 error_vreport(fmt
, ap
);
95 error_printf("Try 'qemu-img --help' for more information\n");
99 static void QEMU_NORETURN
missing_argument(const char *option
)
101 error_exit("missing argument for option '%s'", option
);
104 static void QEMU_NORETURN
unrecognized_option(const char *option
)
106 error_exit("unrecognized option '%s'", option
);
109 /* Please keep in synch with qemu-img.texi */
110 static void QEMU_NORETURN
help(void)
112 const char *help_msg
=
114 "usage: qemu-img [standard options] command [command options]\n"
115 "QEMU disk image utility\n"
117 " '-h', '--help' display this help and exit\n"
118 " '-V', '--version' output version information and exit\n"
119 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
120 " specify tracing options\n"
123 #define DEF(option, callback, arg_string) \
125 #include "qemu-img-cmds.h"
128 "Command parameters:\n"
129 " 'filename' is a disk image filename\n"
130 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
131 " manual page for a description of the object properties. The most common\n"
132 " object type is a 'secret', which is used to supply passwords and/or\n"
133 " encryption keys.\n"
134 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
135 " 'cache' is the cache mode used to write the output disk image, the valid\n"
136 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
137 " 'directsync' and 'unsafe' (default for convert)\n"
138 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
139 " options are the same as for the 'cache' option\n"
140 " 'size' is the disk image size in bytes. Optional suffixes\n"
141 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
142 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
143 " supported. 'b' is ignored.\n"
144 " 'output_filename' is the destination disk image filename\n"
145 " 'output_fmt' is the destination format\n"
146 " 'options' is a comma separated list of format specific options in a\n"
147 " name=value format. Use -o ? for an overview of the options supported by the\n"
149 " 'snapshot_param' is param used for internal snapshot, format\n"
150 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
152 " '-c' indicates that target image must be compressed (qcow format only)\n"
153 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
154 " new backing file match exactly. The image doesn't need a working\n"
155 " backing file before rebasing in this case (useful for renaming the\n"
156 " backing file). For image creation, allow creating without attempting\n"
157 " to open the backing file.\n"
158 " '-h' with or without a command shows this help and lists the supported formats\n"
159 " '-p' show progress of command (only certain commands)\n"
160 " '-q' use Quiet mode - do not print any output (except errors)\n"
161 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
162 " contain only zeros for qemu-img to create a sparse image during\n"
163 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
164 " unallocated or zero sectors, and the destination image will always be\n"
166 " '--output' takes the format in which the output must be done (human or json)\n"
167 " '-n' skips the target volume creation (useful if the volume is created\n"
168 " prior to running qemu-img)\n"
170 "Parameters to check subcommand:\n"
171 " '-r' tries to repair any inconsistencies that are found during the check.\n"
172 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
173 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
174 " hiding corruption that has already occurred.\n"
176 "Parameters to convert subcommand:\n"
177 " '-m' specifies how many coroutines work in parallel during the convert\n"
178 " process (defaults to 8)\n"
179 " '-W' allow to write to the target out of order rather than sequential\n"
181 "Parameters to snapshot subcommand:\n"
182 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
183 " '-a' applies a snapshot (revert disk to saved state)\n"
184 " '-c' creates a snapshot\n"
185 " '-d' deletes a snapshot\n"
186 " '-l' lists all snapshots in the given image\n"
188 "Parameters to compare subcommand:\n"
189 " '-f' first image format\n"
190 " '-F' second image format\n"
191 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "Parameters to dd subcommand:\n"
194 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 " 'count=N' copy only N input blocks\n"
197 " 'if=FILE' read from FILE\n"
198 " 'of=FILE' write to FILE\n"
199 " 'skip=N' skip N bs-sized blocks at the start of input\n";
201 printf("%s\nSupported formats:", help_msg
);
202 bdrv_iterate_format(format_print
, NULL
, false);
203 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
207 static QemuOptsList qemu_object_opts
= {
209 .implied_opt_name
= "qom-type",
210 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
216 static QemuOptsList qemu_source_opts
= {
218 .implied_opt_name
= "file",
219 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
225 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
231 ret
= vprintf(fmt
, args
);
238 static int print_block_option_help(const char *filename
, const char *fmt
)
240 BlockDriver
*drv
, *proto_drv
;
241 QemuOptsList
*create_opts
= NULL
;
242 Error
*local_err
= NULL
;
244 /* Find driver and parse its options */
245 drv
= bdrv_find_format(fmt
);
247 error_report("Unknown file format '%s'", fmt
);
251 if (!drv
->create_opts
) {
252 error_report("Format driver '%s' does not support image creation", fmt
);
256 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
258 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
260 error_report_err(local_err
);
261 qemu_opts_free(create_opts
);
264 if (!proto_drv
->create_opts
) {
265 error_report("Protocol driver '%s' does not support image creation",
266 proto_drv
->format_name
);
267 qemu_opts_free(create_opts
);
270 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
274 printf("Supported options:\n");
276 printf("Supported %s options:\n", fmt
);
278 qemu_opts_print_help(create_opts
, false);
279 qemu_opts_free(create_opts
);
283 "The protocol level may support further options.\n"
284 "Specify the target filename to include those options.\n");
291 static BlockBackend
*img_open_opts(const char *optstr
,
292 QemuOpts
*opts
, int flags
, bool writethrough
,
293 bool quiet
, bool force_share
)
296 Error
*local_err
= NULL
;
298 options
= qemu_opts_to_qdict(opts
, NULL
);
300 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
301 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
302 error_report("--force-share/-U conflicts with image options");
303 qobject_unref(options
);
306 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
308 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
310 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
313 blk_set_enable_write_cache(blk
, !writethrough
);
318 static BlockBackend
*img_open_file(const char *filename
,
320 const char *fmt
, int flags
,
321 bool writethrough
, bool quiet
,
325 Error
*local_err
= NULL
;
328 options
= qdict_new();
331 qdict_put_str(options
, "driver", fmt
);
335 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
337 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
339 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
342 blk_set_enable_write_cache(blk
, !writethrough
);
348 static int img_add_key_secrets(void *opaque
,
349 const char *name
, const char *value
,
352 QDict
*options
= opaque
;
354 if (g_str_has_suffix(name
, "key-secret")) {
355 qdict_put_str(options
, name
, value
);
362 static BlockBackend
*img_open(bool image_opts
,
363 const char *filename
,
364 const char *fmt
, int flags
, bool writethrough
,
365 bool quiet
, bool force_share
)
371 error_report("--image-opts and --format are mutually exclusive");
374 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
379 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
382 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
389 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
390 const char *base_filename
,
391 const char *base_fmt
)
396 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
398 error_report("Backing file not supported for file format '%s'",
405 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
407 error_report("Backing file format not supported for file "
416 static int64_t cvtnum(const char *s
)
421 err
= qemu_strtosz(s
, NULL
, &value
);
425 if (value
> INT64_MAX
) {
431 static int img_create(int argc
, char **argv
)
434 uint64_t img_size
= -1;
435 const char *fmt
= "raw";
436 const char *base_fmt
= NULL
;
437 const char *filename
;
438 const char *base_filename
= NULL
;
439 char *options
= NULL
;
440 Error
*local_err
= NULL
;
445 static const struct option long_options
[] = {
446 {"help", no_argument
, 0, 'h'},
447 {"object", required_argument
, 0, OPTION_OBJECT
},
450 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
457 missing_argument(argv
[optind
- 1]);
460 unrecognized_option(argv
[optind
- 1]);
469 base_filename
= optarg
;
475 if (!is_valid_option_list(optarg
)) {
476 error_report("Invalid option list: %s", optarg
);
480 options
= g_strdup(optarg
);
482 char *old_options
= options
;
483 options
= g_strdup_printf("%s,%s", options
, optarg
);
491 flags
|= BDRV_O_NO_BACKING
;
493 case OPTION_OBJECT
: {
495 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
504 /* Get the filename */
505 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
506 if (options
&& has_help_option(options
)) {
508 return print_block_option_help(filename
, fmt
);
511 if (optind
>= argc
) {
512 error_exit("Expecting image file name");
516 if (qemu_opts_foreach(&qemu_object_opts
,
517 user_creatable_add_opts_foreach
,
518 NULL
, &error_fatal
)) {
522 /* Get image size, if specified */
526 sval
= cvtnum(argv
[optind
++]);
528 if (sval
== -ERANGE
) {
529 error_report("Image size must be less than 8 EiB!");
531 error_report("Invalid image size specified! You may use k, M, "
532 "G, T, P or E suffixes for ");
533 error_report("kilobytes, megabytes, gigabytes, terabytes, "
534 "petabytes and exabytes.");
538 img_size
= (uint64_t)sval
;
540 if (optind
!= argc
) {
541 error_exit("Unexpected argument: %s", argv
[optind
]);
544 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
545 options
, img_size
, flags
, quiet
, &local_err
);
547 error_reportf_err(local_err
, "%s: ", filename
);
559 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
563 Visitor
*v
= qobject_output_visitor_new(&obj
);
565 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
566 visit_complete(v
, &obj
);
567 str
= qobject_to_json_pretty(obj
);
569 qprintf(quiet
, "%s\n", qstring_get_str(str
));
575 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
577 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
578 qprintf(quiet
, "No errors were found on the image.\n");
580 if (check
->corruptions
) {
581 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
582 "Data may be corrupted, or further writes to the image "
589 "\n%" PRId64
" leaked clusters were found on the image.\n"
590 "This means waste of disk space, but no harm to data.\n",
594 if (check
->check_errors
) {
597 " internal errors have occurred during the check.\n",
598 check
->check_errors
);
602 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
603 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
604 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
605 check
->allocated_clusters
, check
->total_clusters
,
606 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
607 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
608 check
->compressed_clusters
* 100.0 /
609 check
->allocated_clusters
);
612 if (check
->image_end_offset
) {
614 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
618 static int collect_image_check(BlockDriverState
*bs
,
620 const char *filename
,
625 BdrvCheckResult result
;
627 ret
= bdrv_check(bs
, &result
, fix
);
632 check
->filename
= g_strdup(filename
);
633 check
->format
= g_strdup(bdrv_get_format_name(bs
));
634 check
->check_errors
= result
.check_errors
;
635 check
->corruptions
= result
.corruptions
;
636 check
->has_corruptions
= result
.corruptions
!= 0;
637 check
->leaks
= result
.leaks
;
638 check
->has_leaks
= result
.leaks
!= 0;
639 check
->corruptions_fixed
= result
.corruptions_fixed
;
640 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
641 check
->leaks_fixed
= result
.leaks_fixed
;
642 check
->has_leaks_fixed
= result
.leaks
!= 0;
643 check
->image_end_offset
= result
.image_end_offset
;
644 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
645 check
->total_clusters
= result
.bfi
.total_clusters
;
646 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
647 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
648 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
649 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
650 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
651 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
652 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
658 * Checks an image for consistency. Exit codes:
660 * 0 - Check completed, image is good
661 * 1 - Check not completed because of internal errors
662 * 2 - Check completed, image is corrupted
663 * 3 - Check completed, image has leaked clusters, but is good otherwise
664 * 63 - Checks are not supported by the image format
666 static int img_check(int argc
, char **argv
)
669 OutputFormat output_format
= OFORMAT_HUMAN
;
670 const char *filename
, *fmt
, *output
, *cache
;
672 BlockDriverState
*bs
;
674 int flags
= BDRV_O_CHECK
;
678 bool image_opts
= false;
679 bool force_share
= false;
683 cache
= BDRV_DEFAULT_CACHE
;
686 int option_index
= 0;
687 static const struct option long_options
[] = {
688 {"help", no_argument
, 0, 'h'},
689 {"format", required_argument
, 0, 'f'},
690 {"repair", required_argument
, 0, 'r'},
691 {"output", required_argument
, 0, OPTION_OUTPUT
},
692 {"object", required_argument
, 0, OPTION_OBJECT
},
693 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
694 {"force-share", no_argument
, 0, 'U'},
697 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
698 long_options
, &option_index
);
704 missing_argument(argv
[optind
- 1]);
707 unrecognized_option(argv
[optind
- 1]);
716 flags
|= BDRV_O_RDWR
;
718 if (!strcmp(optarg
, "leaks")) {
719 fix
= BDRV_FIX_LEAKS
;
720 } else if (!strcmp(optarg
, "all")) {
721 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
723 error_exit("Unknown option value for -r "
724 "(expecting 'leaks' or 'all'): %s", optarg
);
739 case OPTION_OBJECT
: {
741 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
747 case OPTION_IMAGE_OPTS
:
752 if (optind
!= argc
- 1) {
753 error_exit("Expecting one image file name");
755 filename
= argv
[optind
++];
757 if (output
&& !strcmp(output
, "json")) {
758 output_format
= OFORMAT_JSON
;
759 } else if (output
&& !strcmp(output
, "human")) {
760 output_format
= OFORMAT_HUMAN
;
762 error_report("--output must be used with human or json as argument.");
766 if (qemu_opts_foreach(&qemu_object_opts
,
767 user_creatable_add_opts_foreach
,
768 NULL
, &error_fatal
)) {
772 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
774 error_report("Invalid source cache option: %s", cache
);
778 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
785 check
= g_new0(ImageCheck
, 1);
786 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
788 if (ret
== -ENOTSUP
) {
789 error_report("This image format does not support checks");
794 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
795 int corruptions_fixed
, leaks_fixed
;
797 leaks_fixed
= check
->leaks_fixed
;
798 corruptions_fixed
= check
->corruptions_fixed
;
800 if (output_format
== OFORMAT_HUMAN
) {
802 "The following inconsistencies were found and repaired:\n\n"
803 " %" PRId64
" leaked clusters\n"
804 " %" PRId64
" corruptions\n\n"
805 "Double checking the fixed image now...\n",
807 check
->corruptions_fixed
);
810 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
812 check
->leaks_fixed
= leaks_fixed
;
813 check
->corruptions_fixed
= corruptions_fixed
;
817 switch (output_format
) {
819 dump_human_image_check(check
, quiet
);
822 dump_json_image_check(check
, quiet
);
827 if (ret
|| check
->check_errors
) {
829 error_report("Check failed: %s", strerror(-ret
));
831 error_report("Check failed");
837 if (check
->corruptions
) {
839 } else if (check
->leaks
) {
846 qapi_free_ImageCheck(check
);
851 typedef struct CommonBlockJobCBInfo
{
852 BlockDriverState
*bs
;
854 } CommonBlockJobCBInfo
;
856 static void common_block_job_cb(void *opaque
, int ret
)
858 CommonBlockJobCBInfo
*cbi
= opaque
;
861 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
865 static void run_block_job(BlockJob
*job
, Error
**errp
)
867 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
870 aio_context_acquire(aio_context
);
873 float progress
= 0.0f
;
874 aio_poll(aio_context
, true);
875 if (job
->job
.progress_total
) {
876 progress
= (float)job
->job
.progress_current
/
877 job
->job
.progress_total
* 100.f
;
879 qemu_progress_print(progress
, 0);
880 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
882 if (!job_is_completed(&job
->job
)) {
883 ret
= job_complete_sync(&job
->job
, errp
);
887 job_unref(&job
->job
);
888 aio_context_release(aio_context
);
890 /* publish completion progress only when success */
892 qemu_progress_print(100.f
, 0);
896 static int img_commit(int argc
, char **argv
)
899 const char *filename
, *fmt
, *cache
, *base
;
901 BlockDriverState
*bs
, *base_bs
;
903 bool progress
= false, quiet
= false, drop
= false;
905 Error
*local_err
= NULL
;
906 CommonBlockJobCBInfo cbi
;
907 bool image_opts
= false;
908 AioContext
*aio_context
;
911 cache
= BDRV_DEFAULT_CACHE
;
914 static const struct option long_options
[] = {
915 {"help", no_argument
, 0, 'h'},
916 {"object", required_argument
, 0, OPTION_OBJECT
},
917 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
920 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
927 missing_argument(argv
[optind
- 1]);
930 unrecognized_option(argv
[optind
- 1]);
955 case OPTION_OBJECT
: {
957 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
963 case OPTION_IMAGE_OPTS
:
969 /* Progress is not shown in Quiet mode */
974 if (optind
!= argc
- 1) {
975 error_exit("Expecting one image file name");
977 filename
= argv
[optind
++];
979 if (qemu_opts_foreach(&qemu_object_opts
,
980 user_creatable_add_opts_foreach
,
981 NULL
, &error_fatal
)) {
985 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
986 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
988 error_report("Invalid cache option: %s", cache
);
992 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
999 qemu_progress_init(progress
, 1.f
);
1000 qemu_progress_print(0.f
, 100);
1003 base_bs
= bdrv_find_backing_image(bs
, base
);
1005 error_setg(&local_err
,
1006 "Did not find '%s' in the backing chain of '%s'",
1011 /* This is different from QMP, which by default uses the deepest file in
1012 * the backing chain (i.e., the very base); however, the traditional
1013 * behavior of qemu-img commit is using the immediate backing file. */
1014 base_bs
= backing_bs(bs
);
1016 error_setg(&local_err
, "Image does not have a backing file");
1021 cbi
= (CommonBlockJobCBInfo
){
1026 aio_context
= bdrv_get_aio_context(bs
);
1027 aio_context_acquire(aio_context
);
1028 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1029 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1030 &cbi
, false, &local_err
);
1031 aio_context_release(aio_context
);
1036 /* When the block job completes, the BlockBackend reference will point to
1037 * the old backing file. In order to avoid that the top image is already
1038 * deleted, so we can still empty it afterwards, increment the reference
1039 * counter here preemptively. */
1044 job
= block_job_get("commit");
1046 run_block_job(job
, &local_err
);
1051 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1052 ret
= bs
->drv
->bdrv_make_empty(bs
);
1054 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1066 qemu_progress_end();
1071 error_report_err(local_err
);
1075 qprintf(quiet
, "Image committed.\n");
1080 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1081 * of the first sector boundary within buf where the sector contains a
1082 * non-zero byte. This function is robust to a buffer that is not
1085 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1088 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1090 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1091 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1095 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1102 * Returns true iff the first sector pointed to by 'buf' contains at least
1105 * 'pnum' is set to the number of sectors (including and immediately following
1106 * the first one) that are known to be in the same allocated/unallocated state.
1107 * The function will try to align the end offset to alignment boundaries so
1108 * that the request will at least end aligned and consequtive requests will
1109 * also start at an aligned offset.
1111 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1112 int64_t sector_num
, int alignment
)
1121 is_zero
= buffer_is_zero(buf
, 512);
1122 for(i
= 1; i
< n
; i
++) {
1124 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1129 tail
= (sector_num
+ i
) & (alignment
- 1);
1131 if (is_zero
&& i
<= tail
) {
1132 /* treat unallocated areas which only consist
1133 * of a small tail as allocated. */
1137 /* align up end offset of allocated areas. */
1138 i
+= alignment
- tail
;
1141 /* align down end offset of zero areas. */
1150 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1151 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1152 * breaking up write requests for only small sparse areas.
1154 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1155 int min
, int64_t sector_num
, int alignment
)
1158 int num_checked
, num_used
;
1164 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1170 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1172 sector_num
+= *pnum
;
1173 num_checked
= num_used
;
1176 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1178 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1180 sector_num
+= *pnum
;
1181 num_checked
+= *pnum
;
1183 num_used
= num_checked
;
1184 } else if (*pnum
>= min
) {
1194 * Compares two buffers sector by sector. Returns 0 if the first
1195 * sector of each buffer matches, non-zero otherwise.
1197 * pnum is set to the sector-aligned size of the buffer prefix that
1198 * has the same matching status as the first sector.
1200 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1201 int64_t bytes
, int64_t *pnum
)
1204 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1208 res
= !!memcmp(buf1
, buf2
, i
);
1210 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1212 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1222 #define IO_BUF_SIZE (2 * MiB)
1225 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1227 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1228 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1229 * failure), and 4 on error (the exit status for read errors), after emitting
1232 * @param blk: BlockBackend for the image
1233 * @param offset: Starting offset to check
1234 * @param bytes: Number of bytes to check
1235 * @param filename: Name of disk file we are checking (logging purpose)
1236 * @param buffer: Allocated buffer for storing read data
1237 * @param quiet: Flag for quiet mode
1239 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1240 int64_t bytes
, const char *filename
,
1241 uint8_t *buffer
, bool quiet
)
1246 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1248 error_report("Error while reading offset %" PRId64
" of %s: %s",
1249 offset
, filename
, strerror(-ret
));
1252 idx
= find_nonzero(buffer
, bytes
);
1254 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1263 * Compares two images. Exit codes:
1265 * 0 - Images are identical
1267 * >1 - Error occurred
1269 static int img_compare(int argc
, char **argv
)
1271 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1272 BlockBackend
*blk1
, *blk2
;
1273 BlockDriverState
*bs1
, *bs2
;
1274 int64_t total_size1
, total_size2
;
1275 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1276 int64_t pnum1
, pnum2
;
1277 int allocated1
, allocated2
;
1278 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1279 bool progress
= false, quiet
= false, strict
= false;
1286 uint64_t progress_base
;
1287 bool image_opts
= false;
1288 bool force_share
= false;
1290 cache
= BDRV_DEFAULT_CACHE
;
1292 static const struct option long_options
[] = {
1293 {"help", no_argument
, 0, 'h'},
1294 {"object", required_argument
, 0, OPTION_OBJECT
},
1295 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1296 {"force-share", no_argument
, 0, 'U'},
1299 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1300 long_options
, NULL
);
1306 missing_argument(argv
[optind
- 1]);
1309 unrecognized_option(argv
[optind
- 1]);
1335 case OPTION_OBJECT
: {
1337 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1344 case OPTION_IMAGE_OPTS
:
1350 /* Progress is not shown in Quiet mode */
1356 if (optind
!= argc
- 2) {
1357 error_exit("Expecting two image file names");
1359 filename1
= argv
[optind
++];
1360 filename2
= argv
[optind
++];
1362 if (qemu_opts_foreach(&qemu_object_opts
,
1363 user_creatable_add_opts_foreach
,
1364 NULL
, &error_fatal
)) {
1369 /* Initialize before goto out */
1370 qemu_progress_init(progress
, 2.0);
1373 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1375 error_report("Invalid source cache option: %s", cache
);
1380 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1387 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1396 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1397 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1398 total_size1
= blk_getlength(blk1
);
1399 if (total_size1
< 0) {
1400 error_report("Can't get size of %s: %s",
1401 filename1
, strerror(-total_size1
));
1405 total_size2
= blk_getlength(blk2
);
1406 if (total_size2
< 0) {
1407 error_report("Can't get size of %s: %s",
1408 filename2
, strerror(-total_size2
));
1412 total_size
= MIN(total_size1
, total_size2
);
1413 progress_base
= MAX(total_size1
, total_size2
);
1415 qemu_progress_print(0, 100);
1417 if (strict
&& total_size1
!= total_size2
) {
1419 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1423 while (offset
< total_size
) {
1424 int status1
, status2
;
1426 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1427 total_size1
- offset
, &pnum1
, NULL
,
1431 error_report("Sector allocation test failed for %s", filename1
);
1434 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1436 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1437 total_size2
- offset
, &pnum2
, NULL
,
1441 error_report("Sector allocation test failed for %s", filename2
);
1444 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1446 assert(pnum1
&& pnum2
);
1447 chunk
= MIN(pnum1
, pnum2
);
1450 if (status1
!= status2
) {
1452 qprintf(quiet
, "Strict mode: Offset %" PRId64
1453 " block status mismatch!\n", offset
);
1457 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1459 } else if (allocated1
== allocated2
) {
1463 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1464 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1466 error_report("Error while reading offset %" PRId64
1468 offset
, filename1
, strerror(-ret
));
1472 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1474 error_report("Error while reading offset %" PRId64
1476 offset
, filename2
, strerror(-ret
));
1480 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1481 if (ret
|| pnum
!= chunk
) {
1482 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1483 offset
+ (ret
? 0 : pnum
));
1489 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1491 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1492 filename1
, buf1
, quiet
);
1494 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1495 filename2
, buf1
, quiet
);
1502 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1505 if (total_size1
!= total_size2
) {
1506 BlockBackend
*blk_over
;
1507 const char *filename_over
;
1509 qprintf(quiet
, "Warning: Image size mismatch!\n");
1510 if (total_size1
> total_size2
) {
1512 filename_over
= filename1
;
1515 filename_over
= filename2
;
1518 while (offset
< progress_base
) {
1519 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1520 progress_base
- offset
, &chunk
,
1524 error_report("Sector allocation test failed for %s",
1529 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1530 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1531 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1532 filename_over
, buf1
, quiet
);
1538 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1542 qprintf(quiet
, "Images are identical.\n");
1552 qemu_progress_end();
1557 enum ImgConvertBlockStatus
{
1563 #define MAX_COROUTINES 16
1565 typedef struct ImgConvertState
{
1567 int64_t *src_sectors
;
1569 int64_t total_sectors
;
1570 int64_t allocated_sectors
;
1571 int64_t allocated_done
;
1574 enum ImgConvertBlockStatus status
;
1575 int64_t sector_next_status
;
1576 BlockBackend
*target
;
1579 bool unallocated_blocks_are_zero
;
1580 bool target_has_backing
;
1581 int64_t target_backing_sectors
; /* negative if unknown */
1586 size_t cluster_sectors
;
1588 long num_coroutines
;
1589 int running_coroutines
;
1590 Coroutine
*co
[MAX_COROUTINES
];
1591 int64_t wait_sector_num
[MAX_COROUTINES
];
1596 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1597 int *src_cur
, int64_t *src_cur_offset
)
1600 *src_cur_offset
= 0;
1601 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1602 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1604 assert(*src_cur
< s
->src_num
);
1608 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1610 int64_t src_cur_offset
;
1611 int ret
, n
, src_cur
;
1612 bool post_backing_zero
= false;
1614 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1616 assert(s
->total_sectors
> sector_num
);
1617 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1619 if (s
->target_backing_sectors
>= 0) {
1620 if (sector_num
>= s
->target_backing_sectors
) {
1621 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1622 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1623 /* Split requests around target_backing_sectors (because
1624 * starting from there, zeros are handled differently) */
1625 n
= s
->target_backing_sectors
- sector_num
;
1629 if (s
->sector_next_status
<= sector_num
) {
1630 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1632 if (s
->target_has_backing
) {
1634 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1635 (sector_num
- src_cur_offset
) *
1637 count
, &count
, NULL
, NULL
);
1639 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1640 (sector_num
- src_cur_offset
) *
1642 count
, &count
, NULL
, NULL
);
1645 error_report("error while reading block status of sector %" PRId64
1646 ": %s", sector_num
, strerror(-ret
));
1649 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1651 if (ret
& BDRV_BLOCK_ZERO
) {
1652 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1653 } else if (ret
& BDRV_BLOCK_DATA
) {
1654 s
->status
= BLK_DATA
;
1656 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1659 s
->sector_next_status
= sector_num
+ n
;
1662 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1663 if (s
->status
== BLK_DATA
) {
1664 n
= MIN(n
, s
->buf_sectors
);
1667 /* We need to write complete clusters for compressed images, so if an
1668 * unallocated area is shorter than that, we must consider the whole
1669 * cluster allocated. */
1670 if (s
->compressed
) {
1671 if (n
< s
->cluster_sectors
) {
1672 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1673 s
->status
= BLK_DATA
;
1675 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1682 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1683 int nb_sectors
, uint8_t *buf
)
1687 assert(nb_sectors
<= s
->buf_sectors
);
1688 while (nb_sectors
> 0) {
1691 int64_t bs_sectors
, src_cur_offset
;
1693 /* In the case of compression with multiple source files, we can get a
1694 * nb_sectors that spreads into the next part. So we must be able to
1695 * read across multiple BDSes for one convert_read() call. */
1696 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1697 blk
= s
->src
[src_cur
];
1698 bs_sectors
= s
->src_sectors
[src_cur
];
1700 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1703 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1704 n
<< BDRV_SECTOR_BITS
, buf
, 0);
1711 buf
+= n
* BDRV_SECTOR_SIZE
;
1718 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1719 int nb_sectors
, uint8_t *buf
,
1720 enum ImgConvertBlockStatus status
)
1724 while (nb_sectors
> 0) {
1726 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1729 case BLK_BACKING_FILE
:
1730 /* If we have a backing file, leave clusters unallocated that are
1731 * unallocated in the source image, so that the backing file is
1732 * visible at the respective offset. */
1733 assert(s
->target_has_backing
);
1737 /* If we're told to keep the target fully allocated (-S 0) or there
1738 * is real non-zero data, we must write it. Otherwise we can treat
1739 * it as zero sectors.
1740 * Compressed clusters need to be written as a whole, so in that
1741 * case we can only save the write if the buffer is completely
1743 if (!s
->min_sparse
||
1745 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1746 sector_num
, s
->alignment
)) ||
1748 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1750 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1751 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1760 if (s
->has_zero_init
) {
1761 assert(!s
->target_has_backing
);
1764 ret
= blk_co_pwrite_zeroes(s
->target
,
1765 sector_num
<< BDRV_SECTOR_BITS
,
1766 n
<< BDRV_SECTOR_BITS
,
1767 BDRV_REQ_MAY_UNMAP
);
1776 buf
+= n
* BDRV_SECTOR_SIZE
;
1782 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1787 while (nb_sectors
> 0) {
1790 int64_t bs_sectors
, src_cur_offset
;
1793 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1794 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1795 blk
= s
->src
[src_cur
];
1796 bs_sectors
= s
->src_sectors
[src_cur
];
1798 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1800 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1801 sector_num
<< BDRV_SECTOR_BITS
,
1802 n
<< BDRV_SECTOR_BITS
, 0, 0);
1813 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1815 ImgConvertState
*s
= opaque
;
1816 uint8_t *buf
= NULL
;
1820 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1821 if (s
->co
[i
] == qemu_coroutine_self()) {
1828 s
->running_coroutines
++;
1829 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1834 enum ImgConvertBlockStatus status
;
1837 qemu_co_mutex_lock(&s
->lock
);
1838 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1839 qemu_co_mutex_unlock(&s
->lock
);
1842 n
= convert_iteration_sectors(s
, s
->sector_num
);
1844 qemu_co_mutex_unlock(&s
->lock
);
1848 /* save current sector and allocation status to local variables */
1849 sector_num
= s
->sector_num
;
1851 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1852 n
= MIN(n
, s
->buf_sectors
);
1854 /* increment global sector counter so that other coroutines can
1855 * already continue reading beyond this request */
1857 qemu_co_mutex_unlock(&s
->lock
);
1859 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1860 s
->allocated_done
+= n
;
1861 qemu_progress_print(100.0 * s
->allocated_done
/
1862 s
->allocated_sectors
, 0);
1866 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1867 if (status
== BLK_DATA
&& !copy_range
) {
1868 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1870 error_report("error while reading sector %" PRId64
1871 ": %s", sector_num
, strerror(-ret
));
1874 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1876 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1879 if (s
->wr_in_order
) {
1880 /* keep writes in order */
1881 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1882 s
->wait_sector_num
[index
] = sector_num
;
1883 qemu_coroutine_yield();
1885 s
->wait_sector_num
[index
] = -1;
1888 if (s
->ret
== -EINPROGRESS
) {
1890 ret
= convert_co_copy_range(s
, sector_num
, n
);
1892 s
->copy_range
= false;
1896 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1899 error_report("error while writing sector %" PRId64
1900 ": %s", sector_num
, strerror(-ret
));
1905 if (s
->wr_in_order
) {
1906 /* reenter the coroutine that might have waited
1907 * for this write to complete */
1908 s
->wr_offs
= sector_num
+ n
;
1909 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1910 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1912 * A -> B -> A cannot occur because A has
1913 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1914 * B will never enter A during this time window.
1916 qemu_coroutine_enter(s
->co
[i
]);
1924 s
->co
[index
] = NULL
;
1925 s
->running_coroutines
--;
1926 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1927 /* the convert job finished successfully */
1932 static int convert_do_copy(ImgConvertState
*s
)
1935 int64_t sector_num
= 0;
1937 /* Check whether we have zero initialisation or can get it efficiently */
1938 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1939 ? bdrv_has_zero_init(blk_bs(s
->target
))
1942 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1943 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1945 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
1947 s
->has_zero_init
= true;
1951 /* Allocate buffer for copied data. For compressed images, only one cluster
1952 * can be copied at a time. */
1953 if (s
->compressed
) {
1954 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1955 error_report("invalid cluster size");
1958 s
->buf_sectors
= s
->cluster_sectors
;
1961 while (sector_num
< s
->total_sectors
) {
1962 n
= convert_iteration_sectors(s
, sector_num
);
1966 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1968 s
->allocated_sectors
+= n
;
1974 s
->sector_next_status
= 0;
1975 s
->ret
= -EINPROGRESS
;
1977 qemu_co_mutex_init(&s
->lock
);
1978 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1979 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1980 s
->wait_sector_num
[i
] = -1;
1981 qemu_coroutine_enter(s
->co
[i
]);
1984 while (s
->running_coroutines
) {
1985 main_loop_wait(false);
1988 if (s
->compressed
&& !s
->ret
) {
1989 /* signal EOF to align */
1990 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1999 #define MAX_BUF_SECTORS 32768
2001 static int img_convert(int argc
, char **argv
)
2003 int c
, bs_i
, flags
, src_flags
= 0;
2004 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2005 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2006 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2007 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2008 BlockDriverInfo bdi
;
2009 BlockDriverState
*out_bs
;
2010 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2011 QemuOptsList
*create_opts
= NULL
;
2012 QDict
*open_opts
= NULL
;
2013 char *options
= NULL
;
2014 Error
*local_err
= NULL
;
2015 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
2016 skip_create
= false, progress
= false, tgt_image_opts
= false;
2017 int64_t ret
= -EINVAL
;
2018 bool force_share
= false;
2019 bool explict_min_sparse
= false;
2021 ImgConvertState s
= (ImgConvertState
) {
2022 /* Need at least 4k of zeros for sparse detection */
2024 .copy_range
= false,
2025 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2026 .wr_in_order
= true,
2027 .num_coroutines
= 8,
2031 static const struct option long_options
[] = {
2032 {"help", no_argument
, 0, 'h'},
2033 {"object", required_argument
, 0, OPTION_OBJECT
},
2034 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2035 {"force-share", no_argument
, 0, 'U'},
2036 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2039 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2040 long_options
, NULL
);
2046 missing_argument(argv
[optind
- 1]);
2049 unrecognized_option(argv
[optind
- 1]);
2061 out_baseimg
= optarg
;
2064 s
.copy_range
= true;
2067 s
.compressed
= true;
2070 if (!is_valid_option_list(optarg
)) {
2071 error_report("Invalid option list: %s", optarg
);
2075 options
= g_strdup(optarg
);
2077 char *old_options
= options
;
2078 options
= g_strdup_printf("%s,%s", options
, optarg
);
2079 g_free(old_options
);
2083 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2084 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2087 error_report("Failed in parsing snapshot param '%s'",
2092 snapshot_name
= optarg
;
2099 sval
= cvtnum(optarg
);
2100 if (sval
< 0 || sval
& (BDRV_SECTOR_SIZE
- 1) ||
2101 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2102 error_report("Invalid buffer size for sparse output specified. "
2103 "Valid sizes are multiples of %llu up to %llu. Select "
2104 "0 to disable sparse detection (fully allocates output).",
2105 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2109 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2110 explict_min_sparse
= true;
2129 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2130 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2131 error_report("Invalid number of coroutines. Allowed number of"
2132 " coroutines is between 1 and %d", MAX_COROUTINES
);
2137 s
.wr_in_order
= false;
2142 case OPTION_OBJECT
: {
2143 QemuOpts
*object_opts
;
2144 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2151 case OPTION_IMAGE_OPTS
:
2154 case OPTION_TARGET_IMAGE_OPTS
:
2155 tgt_image_opts
= true;
2160 if (!out_fmt
&& !tgt_image_opts
) {
2164 if (qemu_opts_foreach(&qemu_object_opts
,
2165 user_creatable_add_opts_foreach
,
2166 NULL
, &error_fatal
)) {
2170 if (s
.compressed
&& s
.copy_range
) {
2171 error_report("Cannot enable copy offloading when -c is used");
2175 if (explict_min_sparse
&& s
.copy_range
) {
2176 error_report("Cannot enable copy offloading when -S is used");
2180 if (tgt_image_opts
&& !skip_create
) {
2181 error_report("--target-image-opts requires use of -n flag");
2185 s
.src_num
= argc
- optind
- 1;
2186 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2188 if (options
&& has_help_option(options
)) {
2190 ret
= print_block_option_help(out_filename
, out_fmt
);
2193 error_report("Option help requires a format be specified");
2198 if (s
.src_num
< 1) {
2199 error_report("Must specify image file name");
2204 /* ret is still -EINVAL until here */
2205 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2207 error_report("Invalid source cache option: %s", src_cache
);
2211 /* Initialize before goto out */
2215 qemu_progress_init(progress
, 1.0);
2216 qemu_progress_print(0, 100);
2218 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2219 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2221 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2222 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2223 fmt
, src_flags
, src_writethrough
, quiet
,
2229 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2230 if (s
.src_sectors
[bs_i
] < 0) {
2231 error_report("Could not get size of %s: %s",
2232 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2236 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2240 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2241 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2242 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2244 } else if (snapshot_name
!= NULL
) {
2245 if (s
.src_num
> 1) {
2246 error_report("No support for concatenating multiple snapshot");
2251 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2255 error_reportf_err(local_err
, "Failed to load snapshot: ");
2261 /* Find driver and parse its options */
2262 drv
= bdrv_find_format(out_fmt
);
2264 error_report("Unknown file format '%s'", out_fmt
);
2269 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2271 error_report_err(local_err
);
2276 if (!drv
->create_opts
) {
2277 error_report("Format driver '%s' does not support image creation",
2283 if (!proto_drv
->create_opts
) {
2284 error_report("Protocol driver '%s' does not support image creation",
2285 proto_drv
->format_name
);
2290 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2291 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2293 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2295 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2297 error_report_err(local_err
);
2303 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2305 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2311 /* Get backing file name if -o backing_file was used */
2312 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2313 if (out_baseimg_param
) {
2314 out_baseimg
= out_baseimg_param
;
2316 s
.target_has_backing
= (bool) out_baseimg
;
2318 if (s
.src_num
> 1 && out_baseimg
) {
2319 error_report("Having a backing file for the target makes no sense when "
2320 "concatenating multiple input images");
2325 /* Check if compression is supported */
2328 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2329 const char *encryptfmt
=
2330 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2331 const char *preallocation
=
2332 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2334 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2335 error_report("Compression not supported for this file format");
2340 if (encryption
|| encryptfmt
) {
2341 error_report("Compression and encryption not supported at "
2348 && strcmp(preallocation
, "off"))
2350 error_report("Compression and preallocation not supported at "
2358 * The later open call will need any decryption secrets, and
2359 * bdrv_create() will purge "opts", so extract them now before
2363 open_opts
= qdict_new();
2364 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2368 /* Create the new image */
2369 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2371 error_reportf_err(local_err
, "%s: error while converting %s: ",
2372 out_filename
, out_fmt
);
2377 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2378 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2380 error_report("Invalid cache option: %s", cache
);
2385 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2386 flags
, writethrough
, quiet
, false);
2388 /* TODO ultimately we should allow --target-image-opts
2389 * to be used even when -n is not given.
2390 * That has to wait for bdrv_create to be improved
2391 * to allow filenames in option syntax
2393 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2394 flags
, writethrough
, quiet
, false);
2395 open_opts
= NULL
; /* blk_new_open will have freed it */
2401 out_bs
= blk_bs(s
.target
);
2403 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2404 error_report("Compression not supported for this file format");
2409 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2410 * or discard_alignment of the out_bs is greater. Limit to
2411 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2412 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2414 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2415 out_bs
->bl
.pdiscard_alignment
>>
2416 BDRV_SECTOR_BITS
)));
2418 /* try to align the write requests to the destination to avoid unnecessary
2420 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2421 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2423 assert(is_power_of_2(s
.alignment
));
2426 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2427 if (output_sectors
< 0) {
2428 error_report("unable to get output image length: %s",
2429 strerror(-output_sectors
));
2432 } else if (output_sectors
< s
.total_sectors
) {
2433 error_report("output file is smaller than input file");
2439 if (s
.target_has_backing
) {
2440 /* Errors are treated as "backing length unknown" (which means
2441 * s.target_backing_sectors has to be negative, which it will
2442 * be automatically). The backing file length is used only
2443 * for optimizations, so such a case is not fatal. */
2444 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2446 s
.target_backing_sectors
= -1;
2449 ret
= bdrv_get_info(out_bs
, &bdi
);
2452 error_report("could not get block driver info");
2456 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2457 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2458 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2461 ret
= convert_do_copy(&s
);
2464 qemu_progress_print(100, 0);
2466 qemu_progress_end();
2467 qemu_opts_del(opts
);
2468 qemu_opts_free(create_opts
);
2469 qemu_opts_del(sn_opts
);
2470 qobject_unref(open_opts
);
2471 blk_unref(s
.target
);
2473 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2474 blk_unref(s
.src
[bs_i
]);
2478 g_free(s
.src_sectors
);
2486 static void dump_snapshots(BlockDriverState
*bs
)
2488 QEMUSnapshotInfo
*sn_tab
, *sn
;
2491 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2494 printf("Snapshot list:\n");
2495 bdrv_snapshot_dump(NULL
);
2497 for(i
= 0; i
< nb_sns
; i
++) {
2499 bdrv_snapshot_dump(sn
);
2505 static void dump_json_image_info_list(ImageInfoList
*list
)
2509 Visitor
*v
= qobject_output_visitor_new(&obj
);
2511 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2512 visit_complete(v
, &obj
);
2513 str
= qobject_to_json_pretty(obj
);
2514 assert(str
!= NULL
);
2515 printf("%s\n", qstring_get_str(str
));
2521 static void dump_json_image_info(ImageInfo
*info
)
2525 Visitor
*v
= qobject_output_visitor_new(&obj
);
2527 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2528 visit_complete(v
, &obj
);
2529 str
= qobject_to_json_pretty(obj
);
2530 assert(str
!= NULL
);
2531 printf("%s\n", qstring_get_str(str
));
2537 static void dump_human_image_info_list(ImageInfoList
*list
)
2539 ImageInfoList
*elem
;
2542 for (elem
= list
; elem
; elem
= elem
->next
) {
2548 bdrv_image_info_dump(elem
->value
);
2552 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2554 return strcmp(a
, b
) == 0;
2558 * Open an image file chain and return an ImageInfoList
2560 * @filename: topmost image filename
2561 * @fmt: topmost image format (may be NULL to autodetect)
2562 * @chain: true - enumerate entire backing file chain
2563 * false - only topmost image file
2565 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2566 * image file. If there was an error a message will have been printed to
2569 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2570 const char *filename
,
2572 bool chain
, bool force_share
)
2574 ImageInfoList
*head
= NULL
;
2575 ImageInfoList
**last
= &head
;
2576 GHashTable
*filenames
;
2579 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2583 BlockDriverState
*bs
;
2585 ImageInfoList
*elem
;
2587 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2588 error_report("Backing file '%s' creates an infinite loop.",
2592 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2594 blk
= img_open(image_opts
, filename
, fmt
,
2595 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2602 bdrv_query_image_info(bs
, &info
, &err
);
2604 error_report_err(err
);
2609 elem
= g_new0(ImageInfoList
, 1);
2616 filename
= fmt
= NULL
;
2618 if (info
->has_full_backing_filename
) {
2619 filename
= info
->full_backing_filename
;
2620 } else if (info
->has_backing_filename
) {
2621 error_report("Could not determine absolute backing filename,"
2622 " but backing filename '%s' present",
2623 info
->backing_filename
);
2626 if (info
->has_backing_filename_format
) {
2627 fmt
= info
->backing_filename_format
;
2631 g_hash_table_destroy(filenames
);
2635 qapi_free_ImageInfoList(head
);
2636 g_hash_table_destroy(filenames
);
2640 static int img_info(int argc
, char **argv
)
2643 OutputFormat output_format
= OFORMAT_HUMAN
;
2645 const char *filename
, *fmt
, *output
;
2646 ImageInfoList
*list
;
2647 bool image_opts
= false;
2648 bool force_share
= false;
2653 int option_index
= 0;
2654 static const struct option long_options
[] = {
2655 {"help", no_argument
, 0, 'h'},
2656 {"format", required_argument
, 0, 'f'},
2657 {"output", required_argument
, 0, OPTION_OUTPUT
},
2658 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2659 {"object", required_argument
, 0, OPTION_OBJECT
},
2660 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2661 {"force-share", no_argument
, 0, 'U'},
2664 c
= getopt_long(argc
, argv
, ":f:hU",
2665 long_options
, &option_index
);
2671 missing_argument(argv
[optind
- 1]);
2674 unrecognized_option(argv
[optind
- 1]);
2688 case OPTION_BACKING_CHAIN
:
2691 case OPTION_OBJECT
: {
2693 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2699 case OPTION_IMAGE_OPTS
:
2704 if (optind
!= argc
- 1) {
2705 error_exit("Expecting one image file name");
2707 filename
= argv
[optind
++];
2709 if (output
&& !strcmp(output
, "json")) {
2710 output_format
= OFORMAT_JSON
;
2711 } else if (output
&& !strcmp(output
, "human")) {
2712 output_format
= OFORMAT_HUMAN
;
2713 } else if (output
) {
2714 error_report("--output must be used with human or json as argument.");
2718 if (qemu_opts_foreach(&qemu_object_opts
,
2719 user_creatable_add_opts_foreach
,
2720 NULL
, &error_fatal
)) {
2724 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2730 switch (output_format
) {
2732 dump_human_image_info_list(list
);
2736 dump_json_image_info_list(list
);
2738 dump_json_image_info(list
->value
);
2743 qapi_free_ImageInfoList(list
);
2747 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2750 switch (output_format
) {
2752 if (e
->data
&& !e
->has_offset
) {
2753 error_report("File contains external, encrypted or compressed clusters.");
2756 if (e
->data
&& !e
->zero
) {
2757 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2758 e
->start
, e
->length
,
2759 e
->has_offset
? e
->offset
: 0,
2760 e
->has_filename
? e
->filename
: "");
2762 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2763 * Modify the flags here to allow more coalescing.
2765 if (next
&& (!next
->data
|| next
->zero
)) {
2771 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2772 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2773 (e
->start
== 0 ? "[" : ",\n"),
2774 e
->start
, e
->length
, e
->depth
,
2775 e
->zero
? "true" : "false",
2776 e
->data
? "true" : "false");
2777 if (e
->has_offset
) {
2778 printf(", \"offset\": %"PRId64
"", e
->offset
);
2790 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2791 int64_t bytes
, MapEntry
*e
)
2795 BlockDriverState
*file
;
2798 char *filename
= NULL
;
2800 /* As an optimization, we could cache the current range of unallocated
2801 * clusters in each file of the chain, and avoid querying the same
2807 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2812 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2815 bs
= backing_bs(bs
);
2824 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2826 if (file
&& has_offset
) {
2827 bdrv_refresh_filename(file
);
2828 filename
= file
->filename
;
2834 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2835 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2837 .has_offset
= has_offset
,
2839 .has_filename
= filename
,
2840 .filename
= filename
,
2846 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2848 if (curr
->length
== 0) {
2851 if (curr
->zero
!= next
->zero
||
2852 curr
->data
!= next
->data
||
2853 curr
->depth
!= next
->depth
||
2854 curr
->has_filename
!= next
->has_filename
||
2855 curr
->has_offset
!= next
->has_offset
) {
2858 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2861 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2867 static int img_map(int argc
, char **argv
)
2870 OutputFormat output_format
= OFORMAT_HUMAN
;
2872 BlockDriverState
*bs
;
2873 const char *filename
, *fmt
, *output
;
2875 MapEntry curr
= { .length
= 0 }, next
;
2877 bool image_opts
= false;
2878 bool force_share
= false;
2883 int option_index
= 0;
2884 static const struct option long_options
[] = {
2885 {"help", no_argument
, 0, 'h'},
2886 {"format", required_argument
, 0, 'f'},
2887 {"output", required_argument
, 0, OPTION_OUTPUT
},
2888 {"object", required_argument
, 0, OPTION_OBJECT
},
2889 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2890 {"force-share", no_argument
, 0, 'U'},
2893 c
= getopt_long(argc
, argv
, ":f:hU",
2894 long_options
, &option_index
);
2900 missing_argument(argv
[optind
- 1]);
2903 unrecognized_option(argv
[optind
- 1]);
2917 case OPTION_OBJECT
: {
2919 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2925 case OPTION_IMAGE_OPTS
:
2930 if (optind
!= argc
- 1) {
2931 error_exit("Expecting one image file name");
2933 filename
= argv
[optind
];
2935 if (output
&& !strcmp(output
, "json")) {
2936 output_format
= OFORMAT_JSON
;
2937 } else if (output
&& !strcmp(output
, "human")) {
2938 output_format
= OFORMAT_HUMAN
;
2939 } else if (output
) {
2940 error_report("--output must be used with human or json as argument.");
2944 if (qemu_opts_foreach(&qemu_object_opts
,
2945 user_creatable_add_opts_foreach
,
2946 NULL
, &error_fatal
)) {
2950 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2956 if (output_format
== OFORMAT_HUMAN
) {
2957 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2960 length
= blk_getlength(blk
);
2961 while (curr
.start
+ curr
.length
< length
) {
2962 int64_t offset
= curr
.start
+ curr
.length
;
2965 /* Probe up to 1 GiB at a time. */
2966 n
= MIN(1 * GiB
, length
- offset
);
2967 ret
= get_block_status(bs
, offset
, n
, &next
);
2970 error_report("Could not read file metadata: %s", strerror(-ret
));
2974 if (entry_mergeable(&curr
, &next
)) {
2975 curr
.length
+= next
.length
;
2979 if (curr
.length
> 0) {
2980 ret
= dump_map_entry(output_format
, &curr
, &next
);
2988 ret
= dump_map_entry(output_format
, &curr
, NULL
);
2995 #define SNAPSHOT_LIST 1
2996 #define SNAPSHOT_CREATE 2
2997 #define SNAPSHOT_APPLY 3
2998 #define SNAPSHOT_DELETE 4
3000 static int img_snapshot(int argc
, char **argv
)
3003 BlockDriverState
*bs
;
3004 QEMUSnapshotInfo sn
;
3005 char *filename
, *snapshot_name
= NULL
;
3006 int c
, ret
= 0, bdrv_oflags
;
3011 bool image_opts
= false;
3012 bool force_share
= false;
3014 bdrv_oflags
= BDRV_O_RDWR
;
3015 /* Parse commandline parameters */
3017 static const struct option long_options
[] = {
3018 {"help", no_argument
, 0, 'h'},
3019 {"object", required_argument
, 0, OPTION_OBJECT
},
3020 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3021 {"force-share", no_argument
, 0, 'U'},
3024 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3025 long_options
, NULL
);
3031 missing_argument(argv
[optind
- 1]);
3034 unrecognized_option(argv
[optind
- 1]);
3041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3044 action
= SNAPSHOT_LIST
;
3045 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3052 action
= SNAPSHOT_APPLY
;
3053 snapshot_name
= optarg
;
3057 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3060 action
= SNAPSHOT_CREATE
;
3061 snapshot_name
= optarg
;
3065 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3068 action
= SNAPSHOT_DELETE
;
3069 snapshot_name
= optarg
;
3077 case OPTION_OBJECT
: {
3079 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3085 case OPTION_IMAGE_OPTS
:
3091 if (optind
!= argc
- 1) {
3092 error_exit("Expecting one image file name");
3094 filename
= argv
[optind
++];
3096 if (qemu_opts_foreach(&qemu_object_opts
,
3097 user_creatable_add_opts_foreach
,
3098 NULL
, &error_fatal
)) {
3102 /* Open the image */
3103 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3110 /* Perform the requested action */
3116 case SNAPSHOT_CREATE
:
3117 memset(&sn
, 0, sizeof(sn
));
3118 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3120 qemu_gettimeofday(&tv
);
3121 sn
.date_sec
= tv
.tv_sec
;
3122 sn
.date_nsec
= tv
.tv_usec
* 1000;
3124 ret
= bdrv_snapshot_create(bs
, &sn
);
3126 error_report("Could not create snapshot '%s': %d (%s)",
3127 snapshot_name
, ret
, strerror(-ret
));
3131 case SNAPSHOT_APPLY
:
3132 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3134 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3139 case SNAPSHOT_DELETE
:
3140 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3142 error_report("Could not delete snapshot '%s': snapshot not "
3143 "found", snapshot_name
);
3146 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3148 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3164 static int img_rebase(int argc
, char **argv
)
3166 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3167 uint8_t *buf_old
= NULL
;
3168 uint8_t *buf_new
= NULL
;
3169 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3171 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3172 int c
, flags
, src_flags
, ret
;
3173 bool writethrough
, src_writethrough
;
3175 bool force_share
= false;
3178 Error
*local_err
= NULL
;
3179 bool image_opts
= false;
3181 /* Parse commandline parameters */
3183 cache
= BDRV_DEFAULT_CACHE
;
3184 src_cache
= BDRV_DEFAULT_CACHE
;
3188 static const struct option long_options
[] = {
3189 {"help", no_argument
, 0, 'h'},
3190 {"object", required_argument
, 0, OPTION_OBJECT
},
3191 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3192 {"force-share", no_argument
, 0, 'U'},
3195 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3196 long_options
, NULL
);
3202 missing_argument(argv
[optind
- 1]);
3205 unrecognized_option(argv
[optind
- 1]);
3214 out_basefmt
= optarg
;
3217 out_baseimg
= optarg
;
3234 case OPTION_OBJECT
: {
3236 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3242 case OPTION_IMAGE_OPTS
:
3255 if (optind
!= argc
- 1) {
3256 error_exit("Expecting one image file name");
3258 if (!unsafe
&& !out_baseimg
) {
3259 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3261 filename
= argv
[optind
++];
3263 if (qemu_opts_foreach(&qemu_object_opts
,
3264 user_creatable_add_opts_foreach
,
3265 NULL
, &error_fatal
)) {
3269 qemu_progress_init(progress
, 2.0);
3270 qemu_progress_print(0, 100);
3272 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3273 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3275 error_report("Invalid cache option: %s", cache
);
3280 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3282 error_report("Invalid source cache option: %s", src_cache
);
3286 /* The source files are opened read-only, don't care about WCE */
3287 assert((src_flags
& BDRV_O_RDWR
) == 0);
3288 (void) src_writethrough
;
3293 * Ignore the old backing file for unsafe rebase in case we want to correct
3294 * the reference to a renamed or moved backing file.
3296 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3304 if (out_basefmt
!= NULL
) {
3305 if (bdrv_find_format(out_basefmt
) == NULL
) {
3306 error_report("Invalid format name: '%s'", out_basefmt
);
3312 /* For safe rebasing we need to compare old and new backing file */
3314 QDict
*options
= NULL
;
3315 BlockDriverState
*base_bs
= backing_bs(bs
);
3318 blk_old_backing
= blk_new(qemu_get_aio_context(),
3319 BLK_PERM_CONSISTENT_READ
,
3321 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3324 error_reportf_err(local_err
,
3325 "Could not reuse old backing file '%s': ",
3330 blk_old_backing
= NULL
;
3333 if (out_baseimg
[0]) {
3334 const char *overlay_filename
;
3335 char *out_real_path
;
3337 options
= qdict_new();
3339 qdict_put_str(options
, "driver", out_basefmt
);
3342 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3345 bdrv_refresh_filename(bs
);
3346 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3349 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3353 error_reportf_err(local_err
,
3354 "Could not resolve backing filename: ");
3360 * Find out whether we rebase an image on top of a previous image
3363 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3364 if (prefix_chain_bs
) {
3365 g_free(out_real_path
);
3366 blk_new_backing
= blk_new(qemu_get_aio_context(),
3367 BLK_PERM_CONSISTENT_READ
,
3369 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3372 error_reportf_err(local_err
,
3373 "Could not reuse backing file '%s': ",
3378 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3379 options
, src_flags
, &local_err
);
3380 g_free(out_real_path
);
3381 if (!blk_new_backing
) {
3382 error_reportf_err(local_err
,
3383 "Could not open new backing file '%s': ",
3393 * Check each unallocated cluster in the COW file. If it is unallocated,
3394 * accesses go to the backing file. We must therefore compare this cluster
3395 * in the old and new backing file, and if they differ we need to copy it
3396 * from the old backing file into the COW file.
3398 * If qemu-img crashes during this step, no harm is done. The content of
3399 * the image is the same as the original one at any time.
3403 int64_t old_backing_size
= 0;
3404 int64_t new_backing_size
= 0;
3407 float local_progress
= 0;
3409 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3410 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3412 size
= blk_getlength(blk
);
3414 error_report("Could not get size of '%s': %s",
3415 filename
, strerror(-size
));
3419 if (blk_old_backing
) {
3420 old_backing_size
= blk_getlength(blk_old_backing
);
3421 if (old_backing_size
< 0) {
3422 char backing_name
[PATH_MAX
];
3424 bdrv_get_backing_filename(bs
, backing_name
,
3425 sizeof(backing_name
));
3426 error_report("Could not get size of '%s': %s",
3427 backing_name
, strerror(-old_backing_size
));
3432 if (blk_new_backing
) {
3433 new_backing_size
= blk_getlength(blk_new_backing
);
3434 if (new_backing_size
< 0) {
3435 error_report("Could not get size of '%s': %s",
3436 out_baseimg
, strerror(-new_backing_size
));
3443 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3446 for (offset
= 0; offset
< size
; offset
+= n
) {
3447 bool buf_old_is_zero
= false;
3449 /* How many bytes can we handle with the next read? */
3450 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3452 /* If the cluster is allocated, we don't need to take action */
3453 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3455 error_report("error while reading image metadata: %s",
3463 if (prefix_chain_bs
) {
3465 * If cluster wasn't changed since prefix_chain, we don't need
3468 ret
= bdrv_is_allocated_above(backing_bs(bs
), prefix_chain_bs
,
3471 error_report("error while reading image metadata: %s",
3481 * Read old and new backing file and take into consideration that
3482 * backing files may be smaller than the COW image.
3484 if (offset
>= old_backing_size
) {
3485 memset(buf_old
, 0, n
);
3486 buf_old_is_zero
= true;
3488 if (offset
+ n
> old_backing_size
) {
3489 n
= old_backing_size
- offset
;
3492 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3494 error_report("error while reading from old backing file");
3499 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3500 memset(buf_new
, 0, n
);
3502 if (offset
+ n
> new_backing_size
) {
3503 n
= new_backing_size
- offset
;
3506 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3508 error_report("error while reading from new backing file");
3513 /* If they differ, we need to write to the COW file */
3514 uint64_t written
= 0;
3516 while (written
< n
) {
3519 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3520 n
- written
, &pnum
))
3522 if (buf_old_is_zero
) {
3523 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3525 ret
= blk_pwrite(blk
, offset
+ written
,
3526 buf_old
+ written
, pnum
, 0);
3529 error_report("Error while writing to COW image: %s",
3537 qemu_progress_print(local_progress
, 100);
3542 * Change the backing file. All clusters that are different from the old
3543 * backing file are overwritten in the COW file now, so the visible content
3544 * doesn't change when we switch the backing file.
3546 if (out_baseimg
&& *out_baseimg
) {
3547 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3549 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3552 if (ret
== -ENOSPC
) {
3553 error_report("Could not change the backing file to '%s': No "
3554 "space left in the file header", out_baseimg
);
3555 } else if (ret
< 0) {
3556 error_report("Could not change the backing file to '%s': %s",
3557 out_baseimg
, strerror(-ret
));
3560 qemu_progress_print(100, 0);
3562 * TODO At this point it is possible to check if any clusters that are
3563 * allocated in the COW file are the same in the backing file. If so, they
3564 * could be dropped from the COW file. Don't do this before switching the
3565 * backing file, in case of a crash this would lead to corruption.
3568 qemu_progress_end();
3571 blk_unref(blk_old_backing
);
3572 blk_unref(blk_new_backing
);
3574 qemu_vfree(buf_old
);
3575 qemu_vfree(buf_new
);
3584 static int img_resize(int argc
, char **argv
)
3587 int c
, ret
, relative
;
3588 const char *filename
, *fmt
, *size
;
3589 int64_t n
, total_size
, current_size
, new_size
;
3591 BlockBackend
*blk
= NULL
;
3592 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3595 static QemuOptsList resize_options
= {
3596 .name
= "resize_options",
3597 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3600 .name
= BLOCK_OPT_SIZE
,
3601 .type
= QEMU_OPT_SIZE
,
3602 .help
= "Virtual disk size"
3608 bool image_opts
= false;
3609 bool shrink
= false;
3611 /* Remove size from argv manually so that negative numbers are not treated
3612 * as options by getopt. */
3614 error_exit("Not enough arguments");
3618 size
= argv
[--argc
];
3620 /* Parse getopt arguments */
3623 static const struct option long_options
[] = {
3624 {"help", no_argument
, 0, 'h'},
3625 {"object", required_argument
, 0, OPTION_OBJECT
},
3626 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3627 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3628 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3631 c
= getopt_long(argc
, argv
, ":f:hq",
3632 long_options
, NULL
);
3638 missing_argument(argv
[optind
- 1]);
3641 unrecognized_option(argv
[optind
- 1]);
3652 case OPTION_OBJECT
: {
3654 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3660 case OPTION_IMAGE_OPTS
:
3663 case OPTION_PREALLOCATION
:
3664 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3665 PREALLOC_MODE__MAX
, NULL
);
3666 if (prealloc
== PREALLOC_MODE__MAX
) {
3667 error_report("Invalid preallocation mode '%s'", optarg
);
3676 if (optind
!= argc
- 1) {
3677 error_exit("Expecting image file name and size");
3679 filename
= argv
[optind
++];
3681 if (qemu_opts_foreach(&qemu_object_opts
,
3682 user_creatable_add_opts_foreach
,
3683 NULL
, &error_fatal
)) {
3687 /* Choose grow, shrink, or absolute resize mode */
3703 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3704 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3706 error_report_err(err
);
3708 qemu_opts_del(param
);
3711 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3712 qemu_opts_del(param
);
3714 blk
= img_open(image_opts
, filename
, fmt
,
3715 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3722 current_size
= blk_getlength(blk
);
3723 if (current_size
< 0) {
3724 error_report("Failed to inquire current image length: %s",
3725 strerror(-current_size
));
3731 total_size
= current_size
+ n
* relative
;
3735 if (total_size
<= 0) {
3736 error_report("New image size must be positive");
3741 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3742 error_report("Preallocation can only be used for growing images");
3747 if (total_size
< current_size
&& !shrink
) {
3748 warn_report("Shrinking an image will delete all data beyond the "
3749 "shrunken image's end. Before performing such an "
3750 "operation, make sure there is no important data there.");
3752 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3754 "Use the --shrink option to perform a shrink operation.");
3758 warn_report("Using the --shrink option will suppress this message. "
3759 "Note that future versions of qemu-img may refuse to "
3760 "shrink images without this option.");
3764 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3766 error_report_err(err
);
3770 new_size
= blk_getlength(blk
);
3772 error_report("Failed to verify truncated image length: %s",
3773 strerror(-new_size
));
3778 /* Some block drivers implement a truncation method, but only so
3779 * the user can cause qemu to refresh the image's size from disk.
3780 * The idea is that the user resizes the image outside of qemu and
3781 * then invokes block_resize to inform qemu about it.
3782 * (This includes iscsi and file-posix for device files.)
3783 * Of course, that is not the behavior someone invoking
3784 * qemu-img resize would find useful, so we catch that behavior
3785 * here and tell the user. */
3786 if (new_size
!= total_size
&& new_size
== current_size
) {
3787 error_report("Image was not resized; resizing may not be supported "
3793 if (new_size
!= total_size
) {
3794 warn_report("Image should have been resized to %" PRIi64
3795 " bytes, but was resized to %" PRIi64
" bytes",
3796 total_size
, new_size
);
3799 qprintf(quiet
, "Image resized.\n");
3809 static void amend_status_cb(BlockDriverState
*bs
,
3810 int64_t offset
, int64_t total_work_size
,
3813 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3816 static int print_amend_option_help(const char *format
)
3820 /* Find driver and parse its options */
3821 drv
= bdrv_find_format(format
);
3823 error_report("Unknown file format '%s'", format
);
3827 if (!drv
->bdrv_amend_options
) {
3828 error_report("Format driver '%s' does not support option amendment",
3833 /* Every driver supporting amendment must have create_opts */
3834 assert(drv
->create_opts
);
3836 printf("Creation options for '%s':\n", format
);
3837 qemu_opts_print_help(drv
->create_opts
, false);
3838 printf("\nNote that not all of these options may be amendable.\n");
3842 static int img_amend(int argc
, char **argv
)
3846 char *options
= NULL
;
3847 QemuOptsList
*create_opts
= NULL
;
3848 QemuOpts
*opts
= NULL
;
3849 const char *fmt
= NULL
, *filename
, *cache
;
3852 bool quiet
= false, progress
= false;
3853 BlockBackend
*blk
= NULL
;
3854 BlockDriverState
*bs
= NULL
;
3855 bool image_opts
= false;
3857 cache
= BDRV_DEFAULT_CACHE
;
3859 static const struct option long_options
[] = {
3860 {"help", no_argument
, 0, 'h'},
3861 {"object", required_argument
, 0, OPTION_OBJECT
},
3862 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3865 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3866 long_options
, NULL
);
3873 missing_argument(argv
[optind
- 1]);
3876 unrecognized_option(argv
[optind
- 1]);
3882 if (!is_valid_option_list(optarg
)) {
3883 error_report("Invalid option list: %s", optarg
);
3885 goto out_no_progress
;
3888 options
= g_strdup(optarg
);
3890 char *old_options
= options
;
3891 options
= g_strdup_printf("%s,%s", options
, optarg
);
3892 g_free(old_options
);
3908 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3912 goto out_no_progress
;
3915 case OPTION_IMAGE_OPTS
:
3922 error_exit("Must specify options (-o)");
3925 if (qemu_opts_foreach(&qemu_object_opts
,
3926 user_creatable_add_opts_foreach
,
3927 NULL
, &error_fatal
)) {
3929 goto out_no_progress
;
3935 qemu_progress_init(progress
, 1.0);
3937 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3938 if (fmt
&& has_help_option(options
)) {
3939 /* If a format is explicitly specified (and possibly no filename is
3940 * given), print option help here */
3941 ret
= print_amend_option_help(fmt
);
3945 if (optind
!= argc
- 1) {
3946 error_report("Expecting one image file name");
3951 flags
= BDRV_O_RDWR
;
3952 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3954 error_report("Invalid cache option: %s", cache
);
3958 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3966 fmt
= bs
->drv
->format_name
;
3968 if (has_help_option(options
)) {
3969 /* If the format was auto-detected, print option help here */
3970 ret
= print_amend_option_help(fmt
);
3974 if (!bs
->drv
->bdrv_amend_options
) {
3975 error_report("Format driver '%s' does not support option amendment",
3981 /* Every driver supporting amendment must have create_opts */
3982 assert(bs
->drv
->create_opts
);
3984 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3985 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3986 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3988 error_report_err(err
);
3993 /* In case the driver does not call amend_status_cb() */
3994 qemu_progress_print(0.f
, 0);
3995 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
3996 qemu_progress_print(100.f
, 0);
3998 error_report_err(err
);
4003 qemu_progress_end();
4007 qemu_opts_del(opts
);
4008 qemu_opts_free(create_opts
);
4017 typedef struct BenchData
{
4019 uint64_t image_size
;
4026 bool drain_on_flush
;
4035 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4038 error_report("Failed flush request: %s", strerror(-ret
));
4043 static void bench_cb(void *opaque
, int ret
)
4045 BenchData
*b
= opaque
;
4049 error_report("Failed request: %s", strerror(-ret
));
4054 /* Just finished a flush with drained queue: Start next requests */
4055 assert(b
->in_flight
== 0);
4056 b
->in_flush
= false;
4057 } else if (b
->in_flight
> 0) {
4058 int remaining
= b
->n
- b
->in_flight
;
4063 /* Time for flush? Drain queue if requested, then flush */
4064 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4065 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4066 BlockCompletionFunc
*cb
;
4068 if (b
->drain_on_flush
) {
4072 cb
= bench_undrained_flush_cb
;
4075 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4077 error_report("Failed to issue flush request");
4081 if (b
->drain_on_flush
) {
4087 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4088 int64_t offset
= b
->offset
;
4089 /* blk_aio_* might look for completed I/Os and kick bench_cb
4090 * again, so make sure this operation is counted by in_flight
4091 * and b->offset is ready for the next submission.
4094 b
->offset
+= b
->step
;
4095 b
->offset
%= b
->image_size
;
4097 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4099 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4102 error_report("Failed to issue request");
4108 static int img_bench(int argc
, char **argv
)
4111 const char *fmt
= NULL
, *filename
;
4113 bool image_opts
= false;
4114 bool is_write
= false;
4118 size_t bufsize
= 4096;
4121 int flush_interval
= 0;
4122 bool drain_on_flush
= true;
4124 BlockBackend
*blk
= NULL
;
4125 BenchData data
= {};
4127 bool writethrough
= false;
4128 struct timeval t1
, t2
;
4130 bool force_share
= false;
4134 static const struct option long_options
[] = {
4135 {"help", no_argument
, 0, 'h'},
4136 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4137 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4138 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4139 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4140 {"force-share", no_argument
, 0, 'U'},
4143 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
4150 missing_argument(argv
[optind
- 1]);
4153 unrecognized_option(argv
[optind
- 1]);
4162 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4163 error_report("Invalid request count specified");
4173 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4174 error_report("Invalid queue depth specified");
4184 flags
|= BDRV_O_NATIVE_AIO
;
4188 offset
= cvtnum(optarg
);
4190 error_report("Invalid offset specified");
4203 sval
= cvtnum(optarg
);
4204 if (sval
< 0 || sval
> INT_MAX
) {
4205 error_report("Invalid buffer size specified");
4216 sval
= cvtnum(optarg
);
4217 if (sval
< 0 || sval
> INT_MAX
) {
4218 error_report("Invalid step size specified");
4226 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4228 error_report("Invalid cache mode");
4234 flags
|= BDRV_O_RDWR
;
4240 case OPTION_PATTERN
:
4244 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4245 error_report("Invalid pattern byte specified");
4251 case OPTION_FLUSH_INTERVAL
:
4255 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4256 error_report("Invalid flush interval specified");
4259 flush_interval
= res
;
4262 case OPTION_NO_DRAIN
:
4263 drain_on_flush
= false;
4265 case OPTION_IMAGE_OPTS
:
4271 if (optind
!= argc
- 1) {
4272 error_exit("Expecting one image file name");
4274 filename
= argv
[argc
- 1];
4276 if (!is_write
&& flush_interval
) {
4277 error_report("--flush-interval is only available in write tests");
4281 if (flush_interval
&& flush_interval
< depth
) {
4282 error_report("Flush interval can't be smaller than depth");
4287 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4294 image_size
= blk_getlength(blk
);
4295 if (image_size
< 0) {
4300 data
= (BenchData
) {
4302 .image_size
= image_size
,
4304 .step
= step
?: bufsize
,
4309 .flush_interval
= flush_interval
,
4310 .drain_on_flush
= drain_on_flush
,
4312 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4313 "(starting at offset %" PRId64
", step size %d)\n",
4314 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4315 data
.offset
, data
.step
);
4316 if (flush_interval
) {
4317 printf("Sending flush every %d requests\n", flush_interval
);
4320 buf_size
= data
.nrreq
* data
.bufsize
;
4321 data
.buf
= blk_blockalign(blk
, buf_size
);
4322 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4324 blk_register_buf(blk
, data
.buf
, buf_size
);
4326 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4327 for (i
= 0; i
< data
.nrreq
; i
++) {
4328 qemu_iovec_init(&data
.qiov
[i
], 1);
4329 qemu_iovec_add(&data
.qiov
[i
],
4330 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4333 gettimeofday(&t1
, NULL
);
4336 while (data
.n
> 0) {
4337 main_loop_wait(false);
4339 gettimeofday(&t2
, NULL
);
4341 printf("Run completed in %3.3f seconds.\n",
4342 (t2
.tv_sec
- t1
.tv_sec
)
4343 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4347 blk_unregister_buf(blk
, data
.buf
);
4349 qemu_vfree(data
.buf
);
4370 int bsz
; /* Block size */
4378 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4382 static int img_dd_bs(const char *arg
,
4383 struct DdIo
*in
, struct DdIo
*out
,
4390 if (res
<= 0 || res
> INT_MAX
) {
4391 error_report("invalid number: '%s'", arg
);
4394 in
->bsz
= out
->bsz
= res
;
4399 static int img_dd_count(const char *arg
,
4400 struct DdIo
*in
, struct DdIo
*out
,
4403 dd
->count
= cvtnum(arg
);
4405 if (dd
->count
< 0) {
4406 error_report("invalid number: '%s'", arg
);
4413 static int img_dd_if(const char *arg
,
4414 struct DdIo
*in
, struct DdIo
*out
,
4417 in
->filename
= g_strdup(arg
);
4422 static int img_dd_of(const char *arg
,
4423 struct DdIo
*in
, struct DdIo
*out
,
4426 out
->filename
= g_strdup(arg
);
4431 static int img_dd_skip(const char *arg
,
4432 struct DdIo
*in
, struct DdIo
*out
,
4435 in
->offset
= cvtnum(arg
);
4437 if (in
->offset
< 0) {
4438 error_report("invalid number: '%s'", arg
);
4445 static int img_dd(int argc
, char **argv
)
4450 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4451 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4452 QemuOpts
*opts
= NULL
;
4453 QemuOptsList
*create_opts
= NULL
;
4454 Error
*local_err
= NULL
;
4455 bool image_opts
= false;
4457 const char *out_fmt
= "raw";
4458 const char *fmt
= NULL
;
4460 int64_t block_count
= 0, out_pos
, in_pos
;
4461 bool force_share
= false;
4462 struct DdInfo dd
= {
4467 .bsz
= 512, /* Block size is by default 512 bytes */
4479 const struct DdOpts options
[] = {
4480 { "bs", img_dd_bs
, C_BS
},
4481 { "count", img_dd_count
, C_COUNT
},
4482 { "if", img_dd_if
, C_IF
},
4483 { "of", img_dd_of
, C_OF
},
4484 { "skip", img_dd_skip
, C_SKIP
},
4487 const struct option long_options
[] = {
4488 { "help", no_argument
, 0, 'h'},
4489 { "object", required_argument
, 0, OPTION_OBJECT
},
4490 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4491 { "force-share", no_argument
, 0, 'U'},
4495 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4507 missing_argument(argv
[optind
- 1]);
4510 unrecognized_option(argv
[optind
- 1]);
4519 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4524 case OPTION_IMAGE_OPTS
:
4530 for (i
= optind
; i
< argc
; i
++) {
4532 arg
= g_strdup(argv
[i
]);
4534 tmp
= strchr(arg
, '=');
4536 error_report("unrecognized operand %s", arg
);
4543 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4544 if (!strcmp(arg
, options
[j
].name
)) {
4548 if (options
[j
].name
== NULL
) {
4549 error_report("unrecognized operand %s", arg
);
4554 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4558 dd
.flags
|= options
[j
].flag
;
4563 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4564 error_report("Must specify both input and output files");
4569 if (qemu_opts_foreach(&qemu_object_opts
,
4570 user_creatable_add_opts_foreach
,
4571 NULL
, &error_fatal
)) {
4576 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4584 drv
= bdrv_find_format(out_fmt
);
4586 error_report("Unknown file format");
4590 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4593 error_report_err(local_err
);
4597 if (!drv
->create_opts
) {
4598 error_report("Format driver '%s' does not support image creation",
4603 if (!proto_drv
->create_opts
) {
4604 error_report("Protocol driver '%s' does not support image creation",
4605 proto_drv
->format_name
);
4609 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4610 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4612 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4614 size
= blk_getlength(blk1
);
4616 error_report("Failed to get size for '%s'", in
.filename
);
4621 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4622 dd
.count
* in
.bsz
< size
) {
4623 size
= dd
.count
* in
.bsz
;
4626 /* Overflow means the specified offset is beyond input image's size */
4627 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4628 size
< in
.bsz
* in
.offset
)) {
4629 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4631 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4632 size
- in
.bsz
* in
.offset
, &error_abort
);
4635 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4637 error_reportf_err(local_err
,
4638 "%s: error while creating output image: ",
4644 /* TODO, we can't honour --image-opts for the target,
4645 * since it needs to be given in a format compatible
4646 * with the bdrv_create() call above which does not
4647 * support image-opts style.
4649 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4650 false, false, false);
4657 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4658 size
< in
.offset
* in
.bsz
)) {
4659 /* We give a warning if the skip option is bigger than the input
4660 * size and create an empty output disk image (i.e. like dd(1)).
4662 error_report("%s: cannot skip to specified offset", in
.filename
);
4665 in_pos
= in
.offset
* in
.bsz
;
4668 in
.buf
= g_new(uint8_t, in
.bsz
);
4670 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4671 int in_ret
, out_ret
;
4673 if (in_pos
+ in
.bsz
> size
) {
4674 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4676 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4679 error_report("error while reading from input image file: %s",
4686 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4689 error_report("error while writing to output image file: %s",
4690 strerror(-out_ret
));
4699 qemu_opts_del(opts
);
4700 qemu_opts_free(create_opts
);
4703 g_free(in
.filename
);
4704 g_free(out
.filename
);
4714 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4718 Visitor
*v
= qobject_output_visitor_new(&obj
);
4720 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4721 visit_complete(v
, &obj
);
4722 str
= qobject_to_json_pretty(obj
);
4723 assert(str
!= NULL
);
4724 printf("%s\n", qstring_get_str(str
));
4730 static int img_measure(int argc
, char **argv
)
4732 static const struct option long_options
[] = {
4733 {"help", no_argument
, 0, 'h'},
4734 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4735 {"object", required_argument
, 0, OPTION_OBJECT
},
4736 {"output", required_argument
, 0, OPTION_OUTPUT
},
4737 {"size", required_argument
, 0, OPTION_SIZE
},
4738 {"force-share", no_argument
, 0, 'U'},
4741 OutputFormat output_format
= OFORMAT_HUMAN
;
4742 BlockBackend
*in_blk
= NULL
;
4744 const char *filename
= NULL
;
4745 const char *fmt
= NULL
;
4746 const char *out_fmt
= "raw";
4747 char *options
= NULL
;
4748 char *snapshot_name
= NULL
;
4749 bool force_share
= false;
4750 QemuOpts
*opts
= NULL
;
4751 QemuOpts
*object_opts
= NULL
;
4752 QemuOpts
*sn_opts
= NULL
;
4753 QemuOptsList
*create_opts
= NULL
;
4754 bool image_opts
= false;
4755 uint64_t img_size
= UINT64_MAX
;
4756 BlockMeasureInfo
*info
= NULL
;
4757 Error
*local_err
= NULL
;
4761 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4762 long_options
, NULL
)) != -1) {
4775 if (!is_valid_option_list(optarg
)) {
4776 error_report("Invalid option list: %s", optarg
);
4780 options
= g_strdup(optarg
);
4782 char *old_options
= options
;
4783 options
= g_strdup_printf("%s,%s", options
, optarg
);
4784 g_free(old_options
);
4788 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4789 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4792 error_report("Failed in parsing snapshot param '%s'",
4797 snapshot_name
= optarg
;
4804 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4810 case OPTION_IMAGE_OPTS
:
4814 if (!strcmp(optarg
, "json")) {
4815 output_format
= OFORMAT_JSON
;
4816 } else if (!strcmp(optarg
, "human")) {
4817 output_format
= OFORMAT_HUMAN
;
4819 error_report("--output must be used with human or json "
4828 sval
= cvtnum(optarg
);
4830 if (sval
== -ERANGE
) {
4831 error_report("Image size must be less than 8 EiB!");
4833 error_report("Invalid image size specified! You may use "
4834 "k, M, G, T, P or E suffixes for ");
4835 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4836 "petabytes and exabytes.");
4840 img_size
= (uint64_t)sval
;
4846 if (qemu_opts_foreach(&qemu_object_opts
,
4847 user_creatable_add_opts_foreach
,
4848 NULL
, &error_fatal
)) {
4852 if (argc
- optind
> 1) {
4853 error_report("At most one filename argument is allowed.");
4855 } else if (argc
- optind
== 1) {
4856 filename
= argv
[optind
];
4860 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4861 error_report("--object, --image-opts, -f, and -l "
4862 "require a filename argument.");
4865 if (filename
&& img_size
!= UINT64_MAX
) {
4866 error_report("--size N cannot be used together with a filename.");
4869 if (!filename
&& img_size
== UINT64_MAX
) {
4870 error_report("Either --size N or one filename must be specified.");
4875 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4876 false, false, force_share
);
4882 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4883 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4884 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4886 } else if (snapshot_name
!= NULL
) {
4887 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4888 snapshot_name
, &local_err
);
4891 error_reportf_err(local_err
, "Failed to load snapshot: ");
4896 drv
= bdrv_find_format(out_fmt
);
4898 error_report("Unknown file format '%s'", out_fmt
);
4901 if (!drv
->create_opts
) {
4902 error_report("Format driver '%s' does not support image creation",
4907 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4908 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4909 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4911 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4913 error_report_err(local_err
);
4914 error_report("Invalid options for file format '%s'", out_fmt
);
4918 if (img_size
!= UINT64_MAX
) {
4919 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4922 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4924 error_report_err(local_err
);
4928 if (output_format
== OFORMAT_HUMAN
) {
4929 printf("required size: %" PRIu64
"\n", info
->required
);
4930 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4932 dump_json_block_measure_info(info
);
4938 qapi_free_BlockMeasureInfo(info
);
4939 qemu_opts_del(object_opts
);
4940 qemu_opts_del(opts
);
4941 qemu_opts_del(sn_opts
);
4942 qemu_opts_free(create_opts
);
4948 static const img_cmd_t img_cmds
[] = {
4949 #define DEF(option, callback, arg_string) \
4950 { option, callback },
4951 #include "qemu-img-cmds.h"
4956 int main(int argc
, char **argv
)
4958 const img_cmd_t
*cmd
;
4959 const char *cmdname
;
4960 Error
*local_error
= NULL
;
4961 char *trace_file
= NULL
;
4963 static const struct option long_options
[] = {
4964 {"help", no_argument
, 0, 'h'},
4965 {"version", no_argument
, 0, 'V'},
4966 {"trace", required_argument
, NULL
, 'T'},
4971 signal(SIGPIPE
, SIG_IGN
);
4974 error_init(argv
[0]);
4975 module_call_init(MODULE_INIT_TRACE
);
4976 qemu_init_exec_dir(argv
[0]);
4978 if (qemu_init_main_loop(&local_error
)) {
4979 error_report_err(local_error
);
4983 qcrypto_init(&error_fatal
);
4985 module_call_init(MODULE_INIT_QOM
);
4988 error_exit("Not enough arguments");
4991 qemu_add_opts(&qemu_object_opts
);
4992 qemu_add_opts(&qemu_source_opts
);
4993 qemu_add_opts(&qemu_trace_opts
);
4995 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4998 missing_argument(argv
[optind
- 1]);
5001 unrecognized_option(argv
[optind
- 1]);
5007 printf(QEMU_IMG_VERSION
);
5011 trace_file
= trace_opt_parse(optarg
);
5016 cmdname
= argv
[optind
];
5018 /* reset getopt_long scanning */
5024 qemu_reset_optind();
5026 if (!trace_init_backends()) {
5029 trace_init_file(trace_file
);
5030 qemu_set_log(LOG_TRACE
);
5032 /* find the command */
5033 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5034 if (!strcmp(cmdname
, cmd
->name
)) {
5035 return cmd
->handler(argc
, argv
);
5040 error_exit("Command not found: %s", cmdname
);