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-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
40 #include "qemu/units.h"
41 #include "qom/object_interfaces.h"
42 #include "sysemu/sysemu.h"
43 #include "sysemu/block-backend.h"
44 #include "block/block_int.h"
45 #include "block/blockjob.h"
46 #include "block/qapi.h"
47 #include "crypto/init.h"
48 #include "trace/control.h"
50 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
51 "\n" QEMU_COPYRIGHT "\n"
53 typedef struct img_cmd_t
{
55 int (*handler
)(int argc
, char **argv
);
60 OPTION_BACKING_CHAIN
= 257,
62 OPTION_IMAGE_OPTS
= 259,
64 OPTION_FLUSH_INTERVAL
= 261,
65 OPTION_NO_DRAIN
= 262,
66 OPTION_TARGET_IMAGE_OPTS
= 263,
68 OPTION_PREALLOCATION
= 265,
72 typedef enum OutputFormat
{
77 /* Default to cache=writeback as data integrity is not important for qemu-img */
78 #define BDRV_DEFAULT_CACHE "writeback"
80 static void format_print(void *opaque
, const char *name
)
85 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
90 error_vreport(fmt
, ap
);
93 error_printf("Try 'qemu-img --help' for more information\n");
97 static void QEMU_NORETURN
missing_argument(const char *option
)
99 error_exit("missing argument for option '%s'", option
);
102 static void QEMU_NORETURN
unrecognized_option(const char *option
)
104 error_exit("unrecognized option '%s'", option
);
107 /* Please keep in synch with qemu-img.texi */
108 static void QEMU_NORETURN
help(void)
110 const char *help_msg
=
112 "usage: qemu-img [standard options] command [command options]\n"
113 "QEMU disk image utility\n"
115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
121 #define DEF(option, callback, arg_string) \
123 #include "qemu-img-cmds.h"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
138 " 'size' is the disk image size in bytes. Optional suffixes\n"
139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '-c' indicates that target image must be compressed (qcow format only)\n"
151 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
152 " new backing file match exactly. The image doesn't need a working\n"
153 " backing file before rebasing in this case (useful for renaming the\n"
154 " backing file). For image creation, allow creating without attempting\n"
155 " to open the backing file.\n"
156 " '-h' with or without a command shows this help and lists the supported formats\n"
157 " '-p' show progress of command (only certain commands)\n"
158 " '-q' use Quiet mode - do not print any output (except errors)\n"
159 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
160 " contain only zeros for qemu-img to create a sparse image during\n"
161 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
162 " unallocated or zero sectors, and the destination image will always be\n"
164 " '--output' takes the format in which the output must be done (human or json)\n"
165 " '-n' skips the target volume creation (useful if the volume is created\n"
166 " prior to running qemu-img)\n"
168 "Parameters to check subcommand:\n"
169 " '-r' tries to repair any inconsistencies that are found during the check.\n"
170 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
171 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
172 " hiding corruption that has already occurred.\n"
174 "Parameters to convert subcommand:\n"
175 " '-m' specifies how many coroutines work in parallel during the convert\n"
176 " process (defaults to 8)\n"
177 " '-W' allow to write to the target out of order rather than sequential\n"
179 "Parameters to snapshot subcommand:\n"
180 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
181 " '-a' applies a snapshot (revert disk to saved state)\n"
182 " '-c' creates a snapshot\n"
183 " '-d' deletes a snapshot\n"
184 " '-l' lists all snapshots in the given image\n"
186 "Parameters to compare subcommand:\n"
187 " '-f' first image format\n"
188 " '-F' second image format\n"
189 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "Parameters to dd subcommand:\n"
192 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 " 'count=N' copy only N input blocks\n"
195 " 'if=FILE' read from FILE\n"
196 " 'of=FILE' write to FILE\n"
197 " 'skip=N' skip N bs-sized blocks at the start of input\n";
199 printf("%s\nSupported formats:", help_msg
);
200 bdrv_iterate_format(format_print
, NULL
, false);
201 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
205 static QemuOptsList qemu_object_opts
= {
207 .implied_opt_name
= "qom-type",
208 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
214 static QemuOptsList qemu_source_opts
= {
216 .implied_opt_name
= "file",
217 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
223 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
229 ret
= vprintf(fmt
, args
);
236 static int print_block_option_help(const char *filename
, const char *fmt
)
238 BlockDriver
*drv
, *proto_drv
;
239 QemuOptsList
*create_opts
= NULL
;
240 Error
*local_err
= NULL
;
242 /* Find driver and parse its options */
243 drv
= bdrv_find_format(fmt
);
245 error_report("Unknown file format '%s'", fmt
);
249 if (!drv
->create_opts
) {
250 error_report("Format driver '%s' does not support image creation", fmt
);
254 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
256 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
258 error_report_err(local_err
);
259 qemu_opts_free(create_opts
);
262 if (!proto_drv
->create_opts
) {
263 error_report("Protocol driver '%s' does not support image creation",
264 proto_drv
->format_name
);
265 qemu_opts_free(create_opts
);
268 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
272 printf("Supported options:\n");
274 printf("Supported %s options:\n", fmt
);
276 qemu_opts_print_help(create_opts
, false);
277 qemu_opts_free(create_opts
);
281 "The protocol level may support further options.\n"
282 "Specify the target filename to include those options.\n");
289 static BlockBackend
*img_open_opts(const char *optstr
,
290 QemuOpts
*opts
, int flags
, bool writethrough
,
291 bool quiet
, bool force_share
)
294 Error
*local_err
= NULL
;
296 options
= qemu_opts_to_qdict(opts
, NULL
);
298 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
299 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
300 error_report("--force-share/-U conflicts with image options");
301 qobject_unref(options
);
304 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
306 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
308 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
311 blk_set_enable_write_cache(blk
, !writethrough
);
316 static BlockBackend
*img_open_file(const char *filename
,
318 const char *fmt
, int flags
,
319 bool writethrough
, bool quiet
,
323 Error
*local_err
= NULL
;
326 options
= qdict_new();
329 qdict_put_str(options
, "driver", fmt
);
333 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
335 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
337 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
340 blk_set_enable_write_cache(blk
, !writethrough
);
346 static int img_add_key_secrets(void *opaque
,
347 const char *name
, const char *value
,
350 QDict
*options
= opaque
;
352 if (g_str_has_suffix(name
, "key-secret")) {
353 qdict_put_str(options
, name
, value
);
360 static BlockBackend
*img_open(bool image_opts
,
361 const char *filename
,
362 const char *fmt
, int flags
, bool writethrough
,
363 bool quiet
, bool force_share
)
369 error_report("--image-opts and --format are mutually exclusive");
372 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
377 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
380 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
387 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
388 const char *base_filename
,
389 const char *base_fmt
)
394 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
396 error_report("Backing file not supported for file format '%s'",
403 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
405 error_report("Backing file format not supported for file "
414 static int64_t cvtnum(const char *s
)
419 err
= qemu_strtosz(s
, NULL
, &value
);
423 if (value
> INT64_MAX
) {
429 static int img_create(int argc
, char **argv
)
432 uint64_t img_size
= -1;
433 const char *fmt
= "raw";
434 const char *base_fmt
= NULL
;
435 const char *filename
;
436 const char *base_filename
= NULL
;
437 char *options
= NULL
;
438 Error
*local_err
= NULL
;
443 static const struct option long_options
[] = {
444 {"help", no_argument
, 0, 'h'},
445 {"object", required_argument
, 0, OPTION_OBJECT
},
448 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
455 missing_argument(argv
[optind
- 1]);
458 unrecognized_option(argv
[optind
- 1]);
467 base_filename
= optarg
;
473 if (!is_valid_option_list(optarg
)) {
474 error_report("Invalid option list: %s", optarg
);
478 options
= g_strdup(optarg
);
480 char *old_options
= options
;
481 options
= g_strdup_printf("%s,%s", options
, optarg
);
489 flags
|= BDRV_O_NO_BACKING
;
491 case OPTION_OBJECT
: {
493 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
502 /* Get the filename */
503 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
504 if (options
&& has_help_option(options
)) {
506 return print_block_option_help(filename
, fmt
);
509 if (optind
>= argc
) {
510 error_exit("Expecting image file name");
514 if (qemu_opts_foreach(&qemu_object_opts
,
515 user_creatable_add_opts_foreach
,
516 NULL
, &error_fatal
)) {
520 /* Get image size, if specified */
524 sval
= cvtnum(argv
[optind
++]);
526 if (sval
== -ERANGE
) {
527 error_report("Image size must be less than 8 EiB!");
529 error_report("Invalid image size specified! You may use k, M, "
530 "G, T, P or E suffixes for ");
531 error_report("kilobytes, megabytes, gigabytes, terabytes, "
532 "petabytes and exabytes.");
536 img_size
= (uint64_t)sval
;
538 if (optind
!= argc
) {
539 error_exit("Unexpected argument: %s", argv
[optind
]);
542 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
543 options
, img_size
, flags
, quiet
, &local_err
);
545 error_reportf_err(local_err
, "%s: ", filename
);
557 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
561 Visitor
*v
= qobject_output_visitor_new(&obj
);
563 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
564 visit_complete(v
, &obj
);
565 str
= qobject_to_json_pretty(obj
);
567 qprintf(quiet
, "%s\n", qstring_get_str(str
));
573 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
575 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
576 qprintf(quiet
, "No errors were found on the image.\n");
578 if (check
->corruptions
) {
579 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
580 "Data may be corrupted, or further writes to the image "
587 "\n%" PRId64
" leaked clusters were found on the image.\n"
588 "This means waste of disk space, but no harm to data.\n",
592 if (check
->check_errors
) {
595 " internal errors have occurred during the check.\n",
596 check
->check_errors
);
600 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
601 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
602 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
603 check
->allocated_clusters
, check
->total_clusters
,
604 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
605 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
606 check
->compressed_clusters
* 100.0 /
607 check
->allocated_clusters
);
610 if (check
->image_end_offset
) {
612 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
616 static int collect_image_check(BlockDriverState
*bs
,
618 const char *filename
,
623 BdrvCheckResult result
;
625 ret
= bdrv_check(bs
, &result
, fix
);
630 check
->filename
= g_strdup(filename
);
631 check
->format
= g_strdup(bdrv_get_format_name(bs
));
632 check
->check_errors
= result
.check_errors
;
633 check
->corruptions
= result
.corruptions
;
634 check
->has_corruptions
= result
.corruptions
!= 0;
635 check
->leaks
= result
.leaks
;
636 check
->has_leaks
= result
.leaks
!= 0;
637 check
->corruptions_fixed
= result
.corruptions_fixed
;
638 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
639 check
->leaks_fixed
= result
.leaks_fixed
;
640 check
->has_leaks_fixed
= result
.leaks
!= 0;
641 check
->image_end_offset
= result
.image_end_offset
;
642 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
643 check
->total_clusters
= result
.bfi
.total_clusters
;
644 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
645 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
646 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
647 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
648 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
649 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
650 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
656 * Checks an image for consistency. Exit codes:
658 * 0 - Check completed, image is good
659 * 1 - Check not completed because of internal errors
660 * 2 - Check completed, image is corrupted
661 * 3 - Check completed, image has leaked clusters, but is good otherwise
662 * 63 - Checks are not supported by the image format
664 static int img_check(int argc
, char **argv
)
667 OutputFormat output_format
= OFORMAT_HUMAN
;
668 const char *filename
, *fmt
, *output
, *cache
;
670 BlockDriverState
*bs
;
672 int flags
= BDRV_O_CHECK
;
676 bool image_opts
= false;
677 bool force_share
= false;
681 cache
= BDRV_DEFAULT_CACHE
;
684 int option_index
= 0;
685 static const struct option long_options
[] = {
686 {"help", no_argument
, 0, 'h'},
687 {"format", required_argument
, 0, 'f'},
688 {"repair", required_argument
, 0, 'r'},
689 {"output", required_argument
, 0, OPTION_OUTPUT
},
690 {"object", required_argument
, 0, OPTION_OBJECT
},
691 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
692 {"force-share", no_argument
, 0, 'U'},
695 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
696 long_options
, &option_index
);
702 missing_argument(argv
[optind
- 1]);
705 unrecognized_option(argv
[optind
- 1]);
714 flags
|= BDRV_O_RDWR
;
716 if (!strcmp(optarg
, "leaks")) {
717 fix
= BDRV_FIX_LEAKS
;
718 } else if (!strcmp(optarg
, "all")) {
719 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
721 error_exit("Unknown option value for -r "
722 "(expecting 'leaks' or 'all'): %s", optarg
);
737 case OPTION_OBJECT
: {
739 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
745 case OPTION_IMAGE_OPTS
:
750 if (optind
!= argc
- 1) {
751 error_exit("Expecting one image file name");
753 filename
= argv
[optind
++];
755 if (output
&& !strcmp(output
, "json")) {
756 output_format
= OFORMAT_JSON
;
757 } else if (output
&& !strcmp(output
, "human")) {
758 output_format
= OFORMAT_HUMAN
;
760 error_report("--output must be used with human or json as argument.");
764 if (qemu_opts_foreach(&qemu_object_opts
,
765 user_creatable_add_opts_foreach
,
766 NULL
, &error_fatal
)) {
770 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
772 error_report("Invalid source cache option: %s", cache
);
776 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
783 check
= g_new0(ImageCheck
, 1);
784 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
786 if (ret
== -ENOTSUP
) {
787 error_report("This image format does not support checks");
792 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
793 int corruptions_fixed
, leaks_fixed
;
795 leaks_fixed
= check
->leaks_fixed
;
796 corruptions_fixed
= check
->corruptions_fixed
;
798 if (output_format
== OFORMAT_HUMAN
) {
800 "The following inconsistencies were found and repaired:\n\n"
801 " %" PRId64
" leaked clusters\n"
802 " %" PRId64
" corruptions\n\n"
803 "Double checking the fixed image now...\n",
805 check
->corruptions_fixed
);
808 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
810 check
->leaks_fixed
= leaks_fixed
;
811 check
->corruptions_fixed
= corruptions_fixed
;
815 switch (output_format
) {
817 dump_human_image_check(check
, quiet
);
820 dump_json_image_check(check
, quiet
);
825 if (ret
|| check
->check_errors
) {
827 error_report("Check failed: %s", strerror(-ret
));
829 error_report("Check failed");
835 if (check
->corruptions
) {
837 } else if (check
->leaks
) {
844 qapi_free_ImageCheck(check
);
849 typedef struct CommonBlockJobCBInfo
{
850 BlockDriverState
*bs
;
852 } CommonBlockJobCBInfo
;
854 static void common_block_job_cb(void *opaque
, int ret
)
856 CommonBlockJobCBInfo
*cbi
= opaque
;
859 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
863 static void run_block_job(BlockJob
*job
, Error
**errp
)
865 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
868 aio_context_acquire(aio_context
);
871 float progress
= 0.0f
;
872 aio_poll(aio_context
, true);
873 if (job
->job
.progress_total
) {
874 progress
= (float)job
->job
.progress_current
/
875 job
->job
.progress_total
* 100.f
;
877 qemu_progress_print(progress
, 0);
878 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
880 if (!job_is_completed(&job
->job
)) {
881 ret
= job_complete_sync(&job
->job
, errp
);
885 job_unref(&job
->job
);
886 aio_context_release(aio_context
);
888 /* publish completion progress only when success */
890 qemu_progress_print(100.f
, 0);
894 static int img_commit(int argc
, char **argv
)
897 const char *filename
, *fmt
, *cache
, *base
;
899 BlockDriverState
*bs
, *base_bs
;
901 bool progress
= false, quiet
= false, drop
= false;
903 Error
*local_err
= NULL
;
904 CommonBlockJobCBInfo cbi
;
905 bool image_opts
= false;
906 AioContext
*aio_context
;
909 cache
= BDRV_DEFAULT_CACHE
;
912 static const struct option long_options
[] = {
913 {"help", no_argument
, 0, 'h'},
914 {"object", required_argument
, 0, OPTION_OBJECT
},
915 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
918 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
925 missing_argument(argv
[optind
- 1]);
928 unrecognized_option(argv
[optind
- 1]);
953 case OPTION_OBJECT
: {
955 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
961 case OPTION_IMAGE_OPTS
:
967 /* Progress is not shown in Quiet mode */
972 if (optind
!= argc
- 1) {
973 error_exit("Expecting one image file name");
975 filename
= argv
[optind
++];
977 if (qemu_opts_foreach(&qemu_object_opts
,
978 user_creatable_add_opts_foreach
,
979 NULL
, &error_fatal
)) {
983 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
984 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
986 error_report("Invalid cache option: %s", cache
);
990 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
997 qemu_progress_init(progress
, 1.f
);
998 qemu_progress_print(0.f
, 100);
1001 base_bs
= bdrv_find_backing_image(bs
, base
);
1003 error_setg(&local_err
,
1004 "Did not find '%s' in the backing chain of '%s'",
1009 /* This is different from QMP, which by default uses the deepest file in
1010 * the backing chain (i.e., the very base); however, the traditional
1011 * behavior of qemu-img commit is using the immediate backing file. */
1012 base_bs
= backing_bs(bs
);
1014 error_setg(&local_err
, "Image does not have a backing file");
1019 cbi
= (CommonBlockJobCBInfo
){
1024 aio_context
= bdrv_get_aio_context(bs
);
1025 aio_context_acquire(aio_context
);
1026 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1027 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1028 &cbi
, false, &local_err
);
1029 aio_context_release(aio_context
);
1034 /* When the block job completes, the BlockBackend reference will point to
1035 * the old backing file. In order to avoid that the top image is already
1036 * deleted, so we can still empty it afterwards, increment the reference
1037 * counter here preemptively. */
1042 job
= block_job_get("commit");
1044 run_block_job(job
, &local_err
);
1049 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1050 ret
= bs
->drv
->bdrv_make_empty(bs
);
1052 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1064 qemu_progress_end();
1069 error_report_err(local_err
);
1073 qprintf(quiet
, "Image committed.\n");
1078 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1079 * of the first sector boundary within buf where the sector contains a
1080 * non-zero byte. This function is robust to a buffer that is not
1083 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1086 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1088 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1089 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1093 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1100 * Returns true iff the first sector pointed to by 'buf' contains at least
1103 * 'pnum' is set to the number of sectors (including and immediately following
1104 * the first one) that are known to be in the same allocated/unallocated state.
1105 * The function will try to align the end offset to alignment boundaries so
1106 * that the request will at least end aligned and consequtive requests will
1107 * also start at an aligned offset.
1109 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1110 int64_t sector_num
, int alignment
)
1119 is_zero
= buffer_is_zero(buf
, 512);
1120 for(i
= 1; i
< n
; i
++) {
1122 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1127 tail
= (sector_num
+ i
) & (alignment
- 1);
1129 if (is_zero
&& i
<= tail
) {
1130 /* treat unallocated areas which only consist
1131 * of a small tail as allocated. */
1135 /* align up end offset of allocated areas. */
1136 i
+= alignment
- tail
;
1139 /* align down end offset of zero areas. */
1148 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1149 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1150 * breaking up write requests for only small sparse areas.
1152 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1153 int min
, int64_t sector_num
, int alignment
)
1156 int num_checked
, num_used
;
1162 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1168 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1170 sector_num
+= *pnum
;
1171 num_checked
= num_used
;
1174 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1176 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1178 sector_num
+= *pnum
;
1179 num_checked
+= *pnum
;
1181 num_used
= num_checked
;
1182 } else if (*pnum
>= min
) {
1192 * Compares two buffers sector by sector. Returns 0 if the first
1193 * sector of each buffer matches, non-zero otherwise.
1195 * pnum is set to the sector-aligned size of the buffer prefix that
1196 * has the same matching status as the first sector.
1198 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1199 int64_t bytes
, int64_t *pnum
)
1202 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1206 res
= !!memcmp(buf1
, buf2
, i
);
1208 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1210 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1220 #define IO_BUF_SIZE (2 * MiB)
1223 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1225 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1226 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1227 * failure), and 4 on error (the exit status for read errors), after emitting
1230 * @param blk: BlockBackend for the image
1231 * @param offset: Starting offset to check
1232 * @param bytes: Number of bytes to check
1233 * @param filename: Name of disk file we are checking (logging purpose)
1234 * @param buffer: Allocated buffer for storing read data
1235 * @param quiet: Flag for quiet mode
1237 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1238 int64_t bytes
, const char *filename
,
1239 uint8_t *buffer
, bool quiet
)
1244 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1246 error_report("Error while reading offset %" PRId64
" of %s: %s",
1247 offset
, filename
, strerror(-ret
));
1250 idx
= find_nonzero(buffer
, bytes
);
1252 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1261 * Compares two images. Exit codes:
1263 * 0 - Images are identical
1265 * >1 - Error occurred
1267 static int img_compare(int argc
, char **argv
)
1269 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1270 BlockBackend
*blk1
, *blk2
;
1271 BlockDriverState
*bs1
, *bs2
;
1272 int64_t total_size1
, total_size2
;
1273 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1274 int64_t pnum1
, pnum2
;
1275 int allocated1
, allocated2
;
1276 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1277 bool progress
= false, quiet
= false, strict
= false;
1284 uint64_t progress_base
;
1285 bool image_opts
= false;
1286 bool force_share
= false;
1288 cache
= BDRV_DEFAULT_CACHE
;
1290 static const struct option long_options
[] = {
1291 {"help", no_argument
, 0, 'h'},
1292 {"object", required_argument
, 0, OPTION_OBJECT
},
1293 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1294 {"force-share", no_argument
, 0, 'U'},
1297 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1298 long_options
, NULL
);
1304 missing_argument(argv
[optind
- 1]);
1307 unrecognized_option(argv
[optind
- 1]);
1333 case OPTION_OBJECT
: {
1335 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1342 case OPTION_IMAGE_OPTS
:
1348 /* Progress is not shown in Quiet mode */
1354 if (optind
!= argc
- 2) {
1355 error_exit("Expecting two image file names");
1357 filename1
= argv
[optind
++];
1358 filename2
= argv
[optind
++];
1360 if (qemu_opts_foreach(&qemu_object_opts
,
1361 user_creatable_add_opts_foreach
,
1362 NULL
, &error_fatal
)) {
1367 /* Initialize before goto out */
1368 qemu_progress_init(progress
, 2.0);
1371 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1373 error_report("Invalid source cache option: %s", cache
);
1378 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1385 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1394 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1395 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1396 total_size1
= blk_getlength(blk1
);
1397 if (total_size1
< 0) {
1398 error_report("Can't get size of %s: %s",
1399 filename1
, strerror(-total_size1
));
1403 total_size2
= blk_getlength(blk2
);
1404 if (total_size2
< 0) {
1405 error_report("Can't get size of %s: %s",
1406 filename2
, strerror(-total_size2
));
1410 total_size
= MIN(total_size1
, total_size2
);
1411 progress_base
= MAX(total_size1
, total_size2
);
1413 qemu_progress_print(0, 100);
1415 if (strict
&& total_size1
!= total_size2
) {
1417 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1421 while (offset
< total_size
) {
1422 int status1
, status2
;
1424 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1425 total_size1
- offset
, &pnum1
, NULL
,
1429 error_report("Sector allocation test failed for %s", filename1
);
1432 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1434 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1435 total_size2
- offset
, &pnum2
, NULL
,
1439 error_report("Sector allocation test failed for %s", filename2
);
1442 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1444 assert(pnum1
&& pnum2
);
1445 chunk
= MIN(pnum1
, pnum2
);
1448 if (status1
!= status2
) {
1450 qprintf(quiet
, "Strict mode: Offset %" PRId64
1451 " block status mismatch!\n", offset
);
1455 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1457 } else if (allocated1
== allocated2
) {
1461 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1462 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1464 error_report("Error while reading offset %" PRId64
1466 offset
, filename1
, strerror(-ret
));
1470 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1472 error_report("Error while reading offset %" PRId64
1474 offset
, filename2
, strerror(-ret
));
1478 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1479 if (ret
|| pnum
!= chunk
) {
1480 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1481 offset
+ (ret
? 0 : pnum
));
1487 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1489 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1490 filename1
, buf1
, quiet
);
1492 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1493 filename2
, buf1
, quiet
);
1500 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1503 if (total_size1
!= total_size2
) {
1504 BlockBackend
*blk_over
;
1505 const char *filename_over
;
1507 qprintf(quiet
, "Warning: Image size mismatch!\n");
1508 if (total_size1
> total_size2
) {
1510 filename_over
= filename1
;
1513 filename_over
= filename2
;
1516 while (offset
< progress_base
) {
1517 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1518 progress_base
- offset
, &chunk
,
1522 error_report("Sector allocation test failed for %s",
1527 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1528 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1529 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1530 filename_over
, buf1
, quiet
);
1536 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1540 qprintf(quiet
, "Images are identical.\n");
1550 qemu_progress_end();
1555 enum ImgConvertBlockStatus
{
1561 #define MAX_COROUTINES 16
1563 typedef struct ImgConvertState
{
1565 int64_t *src_sectors
;
1567 int64_t total_sectors
;
1568 int64_t allocated_sectors
;
1569 int64_t allocated_done
;
1572 enum ImgConvertBlockStatus status
;
1573 int64_t sector_next_status
;
1574 BlockBackend
*target
;
1577 bool unallocated_blocks_are_zero
;
1578 bool target_has_backing
;
1579 int64_t target_backing_sectors
; /* negative if unknown */
1584 size_t cluster_sectors
;
1586 long num_coroutines
;
1587 int running_coroutines
;
1588 Coroutine
*co
[MAX_COROUTINES
];
1589 int64_t wait_sector_num
[MAX_COROUTINES
];
1594 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1595 int *src_cur
, int64_t *src_cur_offset
)
1598 *src_cur_offset
= 0;
1599 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1600 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1602 assert(*src_cur
< s
->src_num
);
1606 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1608 int64_t src_cur_offset
;
1609 int ret
, n
, src_cur
;
1610 bool post_backing_zero
= false;
1612 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1614 assert(s
->total_sectors
> sector_num
);
1615 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1617 if (s
->target_backing_sectors
>= 0) {
1618 if (sector_num
>= s
->target_backing_sectors
) {
1619 post_backing_zero
= s
->unallocated_blocks_are_zero
;
1620 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1621 /* Split requests around target_backing_sectors (because
1622 * starting from there, zeros are handled differently) */
1623 n
= s
->target_backing_sectors
- sector_num
;
1627 if (s
->sector_next_status
<= sector_num
) {
1628 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1630 if (s
->target_has_backing
) {
1632 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1633 (sector_num
- src_cur_offset
) *
1635 count
, &count
, NULL
, NULL
);
1637 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1638 (sector_num
- src_cur_offset
) *
1640 count
, &count
, NULL
, NULL
);
1643 error_report("error while reading block status of sector %" PRId64
1644 ": %s", sector_num
, strerror(-ret
));
1647 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1649 if (ret
& BDRV_BLOCK_ZERO
) {
1650 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1651 } else if (ret
& BDRV_BLOCK_DATA
) {
1652 s
->status
= BLK_DATA
;
1654 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1657 s
->sector_next_status
= sector_num
+ n
;
1660 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1661 if (s
->status
== BLK_DATA
) {
1662 n
= MIN(n
, s
->buf_sectors
);
1665 /* We need to write complete clusters for compressed images, so if an
1666 * unallocated area is shorter than that, we must consider the whole
1667 * cluster allocated. */
1668 if (s
->compressed
) {
1669 if (n
< s
->cluster_sectors
) {
1670 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1671 s
->status
= BLK_DATA
;
1673 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1680 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1681 int nb_sectors
, uint8_t *buf
)
1685 assert(nb_sectors
<= s
->buf_sectors
);
1686 while (nb_sectors
> 0) {
1689 int64_t bs_sectors
, src_cur_offset
;
1691 /* In the case of compression with multiple source files, we can get a
1692 * nb_sectors that spreads into the next part. So we must be able to
1693 * read across multiple BDSes for one convert_read() call. */
1694 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1695 blk
= s
->src
[src_cur
];
1696 bs_sectors
= s
->src_sectors
[src_cur
];
1698 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1701 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1702 n
<< BDRV_SECTOR_BITS
, buf
, 0);
1709 buf
+= n
* BDRV_SECTOR_SIZE
;
1716 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1717 int nb_sectors
, uint8_t *buf
,
1718 enum ImgConvertBlockStatus status
)
1722 while (nb_sectors
> 0) {
1724 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1727 case BLK_BACKING_FILE
:
1728 /* If we have a backing file, leave clusters unallocated that are
1729 * unallocated in the source image, so that the backing file is
1730 * visible at the respective offset. */
1731 assert(s
->target_has_backing
);
1735 /* If we're told to keep the target fully allocated (-S 0) or there
1736 * is real non-zero data, we must write it. Otherwise we can treat
1737 * it as zero sectors.
1738 * Compressed clusters need to be written as a whole, so in that
1739 * case we can only save the write if the buffer is completely
1741 if (!s
->min_sparse
||
1743 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1744 sector_num
, s
->alignment
)) ||
1746 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1748 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1749 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1758 if (s
->has_zero_init
) {
1759 assert(!s
->target_has_backing
);
1762 ret
= blk_co_pwrite_zeroes(s
->target
,
1763 sector_num
<< BDRV_SECTOR_BITS
,
1764 n
<< BDRV_SECTOR_BITS
,
1765 BDRV_REQ_MAY_UNMAP
);
1774 buf
+= n
* BDRV_SECTOR_SIZE
;
1780 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1785 while (nb_sectors
> 0) {
1788 int64_t bs_sectors
, src_cur_offset
;
1791 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1792 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1793 blk
= s
->src
[src_cur
];
1794 bs_sectors
= s
->src_sectors
[src_cur
];
1796 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1798 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1799 sector_num
<< BDRV_SECTOR_BITS
,
1800 n
<< BDRV_SECTOR_BITS
, 0, 0);
1811 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1813 ImgConvertState
*s
= opaque
;
1814 uint8_t *buf
= NULL
;
1818 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1819 if (s
->co
[i
] == qemu_coroutine_self()) {
1826 s
->running_coroutines
++;
1827 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1832 enum ImgConvertBlockStatus status
;
1835 qemu_co_mutex_lock(&s
->lock
);
1836 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1837 qemu_co_mutex_unlock(&s
->lock
);
1840 n
= convert_iteration_sectors(s
, s
->sector_num
);
1842 qemu_co_mutex_unlock(&s
->lock
);
1846 /* save current sector and allocation status to local variables */
1847 sector_num
= s
->sector_num
;
1849 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1850 n
= MIN(n
, s
->buf_sectors
);
1852 /* increment global sector counter so that other coroutines can
1853 * already continue reading beyond this request */
1855 qemu_co_mutex_unlock(&s
->lock
);
1857 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1858 s
->allocated_done
+= n
;
1859 qemu_progress_print(100.0 * s
->allocated_done
/
1860 s
->allocated_sectors
, 0);
1864 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1865 if (status
== BLK_DATA
&& !copy_range
) {
1866 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1868 error_report("error while reading sector %" PRId64
1869 ": %s", sector_num
, strerror(-ret
));
1872 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1874 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1877 if (s
->wr_in_order
) {
1878 /* keep writes in order */
1879 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1880 s
->wait_sector_num
[index
] = sector_num
;
1881 qemu_coroutine_yield();
1883 s
->wait_sector_num
[index
] = -1;
1886 if (s
->ret
== -EINPROGRESS
) {
1888 ret
= convert_co_copy_range(s
, sector_num
, n
);
1890 s
->copy_range
= false;
1894 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1897 error_report("error while writing sector %" PRId64
1898 ": %s", sector_num
, strerror(-ret
));
1903 if (s
->wr_in_order
) {
1904 /* reenter the coroutine that might have waited
1905 * for this write to complete */
1906 s
->wr_offs
= sector_num
+ n
;
1907 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1908 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1910 * A -> B -> A cannot occur because A has
1911 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1912 * B will never enter A during this time window.
1914 qemu_coroutine_enter(s
->co
[i
]);
1922 s
->co
[index
] = NULL
;
1923 s
->running_coroutines
--;
1924 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1925 /* the convert job finished successfully */
1930 static int convert_do_copy(ImgConvertState
*s
)
1933 int64_t sector_num
= 0;
1935 /* Check whether we have zero initialisation or can get it efficiently */
1936 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1937 ? bdrv_has_zero_init(blk_bs(s
->target
))
1940 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1941 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1943 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
);
1945 s
->has_zero_init
= true;
1949 /* Allocate buffer for copied data. For compressed images, only one cluster
1950 * can be copied at a time. */
1951 if (s
->compressed
) {
1952 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1953 error_report("invalid cluster size");
1956 s
->buf_sectors
= s
->cluster_sectors
;
1959 while (sector_num
< s
->total_sectors
) {
1960 n
= convert_iteration_sectors(s
, sector_num
);
1964 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1966 s
->allocated_sectors
+= n
;
1972 s
->sector_next_status
= 0;
1973 s
->ret
= -EINPROGRESS
;
1975 qemu_co_mutex_init(&s
->lock
);
1976 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1977 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1978 s
->wait_sector_num
[i
] = -1;
1979 qemu_coroutine_enter(s
->co
[i
]);
1982 while (s
->running_coroutines
) {
1983 main_loop_wait(false);
1986 if (s
->compressed
&& !s
->ret
) {
1987 /* signal EOF to align */
1988 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1997 #define MAX_BUF_SECTORS 32768
1999 static int img_convert(int argc
, char **argv
)
2001 int c
, bs_i
, flags
, src_flags
= 0;
2002 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2003 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2004 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
2005 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2006 BlockDriverInfo bdi
;
2007 BlockDriverState
*out_bs
;
2008 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2009 QemuOptsList
*create_opts
= NULL
;
2010 QDict
*open_opts
= NULL
;
2011 char *options
= NULL
;
2012 Error
*local_err
= NULL
;
2013 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
2014 skip_create
= false, progress
= false, tgt_image_opts
= false;
2015 int64_t ret
= -EINVAL
;
2016 bool force_share
= false;
2017 bool explict_min_sparse
= false;
2019 ImgConvertState s
= (ImgConvertState
) {
2020 /* Need at least 4k of zeros for sparse detection */
2022 .copy_range
= false,
2023 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2024 .wr_in_order
= true,
2025 .num_coroutines
= 8,
2029 static const struct option long_options
[] = {
2030 {"help", no_argument
, 0, 'h'},
2031 {"object", required_argument
, 0, OPTION_OBJECT
},
2032 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2033 {"force-share", no_argument
, 0, 'U'},
2034 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2037 c
= getopt_long(argc
, argv
, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2038 long_options
, NULL
);
2044 missing_argument(argv
[optind
- 1]);
2047 unrecognized_option(argv
[optind
- 1]);
2059 out_baseimg
= optarg
;
2062 s
.copy_range
= true;
2065 s
.compressed
= true;
2068 if (!is_valid_option_list(optarg
)) {
2069 error_report("Invalid option list: %s", optarg
);
2073 options
= g_strdup(optarg
);
2075 char *old_options
= options
;
2076 options
= g_strdup_printf("%s,%s", options
, optarg
);
2077 g_free(old_options
);
2081 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2082 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2085 error_report("Failed in parsing snapshot param '%s'",
2090 snapshot_name
= optarg
;
2097 sval
= cvtnum(optarg
);
2098 if (sval
< 0 || sval
& (BDRV_SECTOR_SIZE
- 1) ||
2099 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2100 error_report("Invalid buffer size for sparse output specified. "
2101 "Valid sizes are multiples of %llu up to %llu. Select "
2102 "0 to disable sparse detection (fully allocates output).",
2103 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2107 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2108 explict_min_sparse
= true;
2127 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2128 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2129 error_report("Invalid number of coroutines. Allowed number of"
2130 " coroutines is between 1 and %d", MAX_COROUTINES
);
2135 s
.wr_in_order
= false;
2140 case OPTION_OBJECT
: {
2141 QemuOpts
*object_opts
;
2142 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2149 case OPTION_IMAGE_OPTS
:
2152 case OPTION_TARGET_IMAGE_OPTS
:
2153 tgt_image_opts
= true;
2158 if (!out_fmt
&& !tgt_image_opts
) {
2162 if (qemu_opts_foreach(&qemu_object_opts
,
2163 user_creatable_add_opts_foreach
,
2164 NULL
, &error_fatal
)) {
2168 if (s
.compressed
&& s
.copy_range
) {
2169 error_report("Cannot enable copy offloading when -c is used");
2173 if (explict_min_sparse
&& s
.copy_range
) {
2174 error_report("Cannot enable copy offloading when -S is used");
2178 if (tgt_image_opts
&& !skip_create
) {
2179 error_report("--target-image-opts requires use of -n flag");
2183 s
.src_num
= argc
- optind
- 1;
2184 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2186 if (options
&& has_help_option(options
)) {
2188 ret
= print_block_option_help(out_filename
, out_fmt
);
2191 error_report("Option help requires a format be specified");
2196 if (s
.src_num
< 1) {
2197 error_report("Must specify image file name");
2202 /* ret is still -EINVAL until here */
2203 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2205 error_report("Invalid source cache option: %s", src_cache
);
2209 /* Initialize before goto out */
2213 qemu_progress_init(progress
, 1.0);
2214 qemu_progress_print(0, 100);
2216 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2217 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2219 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2220 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2221 fmt
, src_flags
, src_writethrough
, quiet
,
2227 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2228 if (s
.src_sectors
[bs_i
] < 0) {
2229 error_report("Could not get size of %s: %s",
2230 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2234 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2238 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2239 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2240 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2242 } else if (snapshot_name
!= NULL
) {
2243 if (s
.src_num
> 1) {
2244 error_report("No support for concatenating multiple snapshot");
2249 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2253 error_reportf_err(local_err
, "Failed to load snapshot: ");
2259 /* Find driver and parse its options */
2260 drv
= bdrv_find_format(out_fmt
);
2262 error_report("Unknown file format '%s'", out_fmt
);
2267 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2269 error_report_err(local_err
);
2274 if (!drv
->create_opts
) {
2275 error_report("Format driver '%s' does not support image creation",
2281 if (!proto_drv
->create_opts
) {
2282 error_report("Protocol driver '%s' does not support image creation",
2283 proto_drv
->format_name
);
2288 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2289 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2291 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2293 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2295 error_report_err(local_err
);
2301 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2303 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2309 /* Get backing file name if -o backing_file was used */
2310 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2311 if (out_baseimg_param
) {
2312 out_baseimg
= out_baseimg_param
;
2314 s
.target_has_backing
= (bool) out_baseimg
;
2316 if (s
.src_num
> 1 && out_baseimg
) {
2317 error_report("Having a backing file for the target makes no sense when "
2318 "concatenating multiple input images");
2323 /* Check if compression is supported */
2326 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2327 const char *encryptfmt
=
2328 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2329 const char *preallocation
=
2330 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2332 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2333 error_report("Compression not supported for this file format");
2338 if (encryption
|| encryptfmt
) {
2339 error_report("Compression and encryption not supported at "
2346 && strcmp(preallocation
, "off"))
2348 error_report("Compression and preallocation not supported at "
2356 * The later open call will need any decryption secrets, and
2357 * bdrv_create() will purge "opts", so extract them now before
2361 open_opts
= qdict_new();
2362 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2366 /* Create the new image */
2367 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2369 error_reportf_err(local_err
, "%s: error while converting %s: ",
2370 out_filename
, out_fmt
);
2375 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2376 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2378 error_report("Invalid cache option: %s", cache
);
2383 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2384 flags
, writethrough
, quiet
, false);
2386 /* TODO ultimately we should allow --target-image-opts
2387 * to be used even when -n is not given.
2388 * That has to wait for bdrv_create to be improved
2389 * to allow filenames in option syntax
2391 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2392 flags
, writethrough
, quiet
, false);
2393 open_opts
= NULL
; /* blk_new_open will have freed it */
2399 out_bs
= blk_bs(s
.target
);
2401 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2402 error_report("Compression not supported for this file format");
2407 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2408 * or discard_alignment of the out_bs is greater. Limit to
2409 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2410 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2412 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2413 out_bs
->bl
.pdiscard_alignment
>>
2414 BDRV_SECTOR_BITS
)));
2416 /* try to align the write requests to the destination to avoid unnecessary
2418 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2419 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2421 assert(is_power_of_2(s
.alignment
));
2424 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2425 if (output_sectors
< 0) {
2426 error_report("unable to get output image length: %s",
2427 strerror(-output_sectors
));
2430 } else if (output_sectors
< s
.total_sectors
) {
2431 error_report("output file is smaller than input file");
2437 if (s
.target_has_backing
) {
2438 /* Errors are treated as "backing length unknown" (which means
2439 * s.target_backing_sectors has to be negative, which it will
2440 * be automatically). The backing file length is used only
2441 * for optimizations, so such a case is not fatal. */
2442 s
.target_backing_sectors
= bdrv_nb_sectors(out_bs
->backing
->bs
);
2444 s
.target_backing_sectors
= -1;
2447 ret
= bdrv_get_info(out_bs
, &bdi
);
2450 error_report("could not get block driver info");
2454 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2455 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2456 s
.unallocated_blocks_are_zero
= bdi
.unallocated_blocks_are_zero
;
2459 ret
= convert_do_copy(&s
);
2462 qemu_progress_print(100, 0);
2464 qemu_progress_end();
2465 qemu_opts_del(opts
);
2466 qemu_opts_free(create_opts
);
2467 qemu_opts_del(sn_opts
);
2468 qobject_unref(open_opts
);
2469 blk_unref(s
.target
);
2471 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2472 blk_unref(s
.src
[bs_i
]);
2476 g_free(s
.src_sectors
);
2484 static void dump_snapshots(BlockDriverState
*bs
)
2486 QEMUSnapshotInfo
*sn_tab
, *sn
;
2489 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2492 printf("Snapshot list:\n");
2493 bdrv_snapshot_dump(NULL
);
2495 for(i
= 0; i
< nb_sns
; i
++) {
2497 bdrv_snapshot_dump(sn
);
2503 static void dump_json_image_info_list(ImageInfoList
*list
)
2507 Visitor
*v
= qobject_output_visitor_new(&obj
);
2509 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2510 visit_complete(v
, &obj
);
2511 str
= qobject_to_json_pretty(obj
);
2512 assert(str
!= NULL
);
2513 printf("%s\n", qstring_get_str(str
));
2519 static void dump_json_image_info(ImageInfo
*info
)
2523 Visitor
*v
= qobject_output_visitor_new(&obj
);
2525 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2526 visit_complete(v
, &obj
);
2527 str
= qobject_to_json_pretty(obj
);
2528 assert(str
!= NULL
);
2529 printf("%s\n", qstring_get_str(str
));
2535 static void dump_human_image_info_list(ImageInfoList
*list
)
2537 ImageInfoList
*elem
;
2540 for (elem
= list
; elem
; elem
= elem
->next
) {
2546 bdrv_image_info_dump(elem
->value
);
2550 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2552 return strcmp(a
, b
) == 0;
2556 * Open an image file chain and return an ImageInfoList
2558 * @filename: topmost image filename
2559 * @fmt: topmost image format (may be NULL to autodetect)
2560 * @chain: true - enumerate entire backing file chain
2561 * false - only topmost image file
2563 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2564 * image file. If there was an error a message will have been printed to
2567 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2568 const char *filename
,
2570 bool chain
, bool force_share
)
2572 ImageInfoList
*head
= NULL
;
2573 ImageInfoList
**last
= &head
;
2574 GHashTable
*filenames
;
2577 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2581 BlockDriverState
*bs
;
2583 ImageInfoList
*elem
;
2585 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2586 error_report("Backing file '%s' creates an infinite loop.",
2590 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2592 blk
= img_open(image_opts
, filename
, fmt
,
2593 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2600 bdrv_query_image_info(bs
, &info
, &err
);
2602 error_report_err(err
);
2607 elem
= g_new0(ImageInfoList
, 1);
2614 filename
= fmt
= NULL
;
2616 if (info
->has_full_backing_filename
) {
2617 filename
= info
->full_backing_filename
;
2618 } else if (info
->has_backing_filename
) {
2619 error_report("Could not determine absolute backing filename,"
2620 " but backing filename '%s' present",
2621 info
->backing_filename
);
2624 if (info
->has_backing_filename_format
) {
2625 fmt
= info
->backing_filename_format
;
2629 g_hash_table_destroy(filenames
);
2633 qapi_free_ImageInfoList(head
);
2634 g_hash_table_destroy(filenames
);
2638 static int img_info(int argc
, char **argv
)
2641 OutputFormat output_format
= OFORMAT_HUMAN
;
2643 const char *filename
, *fmt
, *output
;
2644 ImageInfoList
*list
;
2645 bool image_opts
= false;
2646 bool force_share
= false;
2651 int option_index
= 0;
2652 static const struct option long_options
[] = {
2653 {"help", no_argument
, 0, 'h'},
2654 {"format", required_argument
, 0, 'f'},
2655 {"output", required_argument
, 0, OPTION_OUTPUT
},
2656 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2657 {"object", required_argument
, 0, OPTION_OBJECT
},
2658 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2659 {"force-share", no_argument
, 0, 'U'},
2662 c
= getopt_long(argc
, argv
, ":f:hU",
2663 long_options
, &option_index
);
2669 missing_argument(argv
[optind
- 1]);
2672 unrecognized_option(argv
[optind
- 1]);
2686 case OPTION_BACKING_CHAIN
:
2689 case OPTION_OBJECT
: {
2691 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2697 case OPTION_IMAGE_OPTS
:
2702 if (optind
!= argc
- 1) {
2703 error_exit("Expecting one image file name");
2705 filename
= argv
[optind
++];
2707 if (output
&& !strcmp(output
, "json")) {
2708 output_format
= OFORMAT_JSON
;
2709 } else if (output
&& !strcmp(output
, "human")) {
2710 output_format
= OFORMAT_HUMAN
;
2711 } else if (output
) {
2712 error_report("--output must be used with human or json as argument.");
2716 if (qemu_opts_foreach(&qemu_object_opts
,
2717 user_creatable_add_opts_foreach
,
2718 NULL
, &error_fatal
)) {
2722 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2728 switch (output_format
) {
2730 dump_human_image_info_list(list
);
2734 dump_json_image_info_list(list
);
2736 dump_json_image_info(list
->value
);
2741 qapi_free_ImageInfoList(list
);
2745 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2748 switch (output_format
) {
2750 if (e
->data
&& !e
->has_offset
) {
2751 error_report("File contains external, encrypted or compressed clusters.");
2754 if (e
->data
&& !e
->zero
) {
2755 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2756 e
->start
, e
->length
,
2757 e
->has_offset
? e
->offset
: 0,
2758 e
->has_filename
? e
->filename
: "");
2760 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2761 * Modify the flags here to allow more coalescing.
2763 if (next
&& (!next
->data
|| next
->zero
)) {
2769 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2770 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2771 (e
->start
== 0 ? "[" : ",\n"),
2772 e
->start
, e
->length
, e
->depth
,
2773 e
->zero
? "true" : "false",
2774 e
->data
? "true" : "false");
2775 if (e
->has_offset
) {
2776 printf(", \"offset\": %"PRId64
"", e
->offset
);
2788 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2789 int64_t bytes
, MapEntry
*e
)
2793 BlockDriverState
*file
;
2796 char *filename
= NULL
;
2798 /* As an optimization, we could cache the current range of unallocated
2799 * clusters in each file of the chain, and avoid querying the same
2805 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2810 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2813 bs
= backing_bs(bs
);
2822 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2824 if (file
&& has_offset
) {
2825 bdrv_refresh_filename(file
);
2826 filename
= file
->filename
;
2832 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2833 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2835 .has_offset
= has_offset
,
2837 .has_filename
= filename
,
2838 .filename
= filename
,
2844 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2846 if (curr
->length
== 0) {
2849 if (curr
->zero
!= next
->zero
||
2850 curr
->data
!= next
->data
||
2851 curr
->depth
!= next
->depth
||
2852 curr
->has_filename
!= next
->has_filename
||
2853 curr
->has_offset
!= next
->has_offset
) {
2856 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2859 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2865 static int img_map(int argc
, char **argv
)
2868 OutputFormat output_format
= OFORMAT_HUMAN
;
2870 BlockDriverState
*bs
;
2871 const char *filename
, *fmt
, *output
;
2873 MapEntry curr
= { .length
= 0 }, next
;
2875 bool image_opts
= false;
2876 bool force_share
= false;
2881 int option_index
= 0;
2882 static const struct option long_options
[] = {
2883 {"help", no_argument
, 0, 'h'},
2884 {"format", required_argument
, 0, 'f'},
2885 {"output", required_argument
, 0, OPTION_OUTPUT
},
2886 {"object", required_argument
, 0, OPTION_OBJECT
},
2887 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2888 {"force-share", no_argument
, 0, 'U'},
2891 c
= getopt_long(argc
, argv
, ":f:hU",
2892 long_options
, &option_index
);
2898 missing_argument(argv
[optind
- 1]);
2901 unrecognized_option(argv
[optind
- 1]);
2915 case OPTION_OBJECT
: {
2917 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2923 case OPTION_IMAGE_OPTS
:
2928 if (optind
!= argc
- 1) {
2929 error_exit("Expecting one image file name");
2931 filename
= argv
[optind
];
2933 if (output
&& !strcmp(output
, "json")) {
2934 output_format
= OFORMAT_JSON
;
2935 } else if (output
&& !strcmp(output
, "human")) {
2936 output_format
= OFORMAT_HUMAN
;
2937 } else if (output
) {
2938 error_report("--output must be used with human or json as argument.");
2942 if (qemu_opts_foreach(&qemu_object_opts
,
2943 user_creatable_add_opts_foreach
,
2944 NULL
, &error_fatal
)) {
2948 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2954 if (output_format
== OFORMAT_HUMAN
) {
2955 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2958 length
= blk_getlength(blk
);
2959 while (curr
.start
+ curr
.length
< length
) {
2960 int64_t offset
= curr
.start
+ curr
.length
;
2963 /* Probe up to 1 GiB at a time. */
2964 n
= MIN(1 * GiB
, length
- offset
);
2965 ret
= get_block_status(bs
, offset
, n
, &next
);
2968 error_report("Could not read file metadata: %s", strerror(-ret
));
2972 if (entry_mergeable(&curr
, &next
)) {
2973 curr
.length
+= next
.length
;
2977 if (curr
.length
> 0) {
2978 ret
= dump_map_entry(output_format
, &curr
, &next
);
2986 ret
= dump_map_entry(output_format
, &curr
, NULL
);
2993 #define SNAPSHOT_LIST 1
2994 #define SNAPSHOT_CREATE 2
2995 #define SNAPSHOT_APPLY 3
2996 #define SNAPSHOT_DELETE 4
2998 static int img_snapshot(int argc
, char **argv
)
3001 BlockDriverState
*bs
;
3002 QEMUSnapshotInfo sn
;
3003 char *filename
, *snapshot_name
= NULL
;
3004 int c
, ret
= 0, bdrv_oflags
;
3009 bool image_opts
= false;
3010 bool force_share
= false;
3012 bdrv_oflags
= BDRV_O_RDWR
;
3013 /* Parse commandline parameters */
3015 static const struct option long_options
[] = {
3016 {"help", no_argument
, 0, 'h'},
3017 {"object", required_argument
, 0, OPTION_OBJECT
},
3018 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3019 {"force-share", no_argument
, 0, 'U'},
3022 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3023 long_options
, NULL
);
3029 missing_argument(argv
[optind
- 1]);
3032 unrecognized_option(argv
[optind
- 1]);
3039 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3042 action
= SNAPSHOT_LIST
;
3043 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3047 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3050 action
= SNAPSHOT_APPLY
;
3051 snapshot_name
= optarg
;
3055 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3058 action
= SNAPSHOT_CREATE
;
3059 snapshot_name
= optarg
;
3063 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3066 action
= SNAPSHOT_DELETE
;
3067 snapshot_name
= optarg
;
3075 case OPTION_OBJECT
: {
3077 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3083 case OPTION_IMAGE_OPTS
:
3089 if (optind
!= argc
- 1) {
3090 error_exit("Expecting one image file name");
3092 filename
= argv
[optind
++];
3094 if (qemu_opts_foreach(&qemu_object_opts
,
3095 user_creatable_add_opts_foreach
,
3096 NULL
, &error_fatal
)) {
3100 /* Open the image */
3101 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3108 /* Perform the requested action */
3114 case SNAPSHOT_CREATE
:
3115 memset(&sn
, 0, sizeof(sn
));
3116 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3118 qemu_gettimeofday(&tv
);
3119 sn
.date_sec
= tv
.tv_sec
;
3120 sn
.date_nsec
= tv
.tv_usec
* 1000;
3122 ret
= bdrv_snapshot_create(bs
, &sn
);
3124 error_report("Could not create snapshot '%s': %d (%s)",
3125 snapshot_name
, ret
, strerror(-ret
));
3129 case SNAPSHOT_APPLY
:
3130 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3132 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3137 case SNAPSHOT_DELETE
:
3138 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3140 error_report("Could not delete snapshot '%s': snapshot not "
3141 "found", snapshot_name
);
3144 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3146 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3162 static int img_rebase(int argc
, char **argv
)
3164 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3165 uint8_t *buf_old
= NULL
;
3166 uint8_t *buf_new
= NULL
;
3167 BlockDriverState
*bs
= NULL
;
3169 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3170 int c
, flags
, src_flags
, ret
;
3171 bool writethrough
, src_writethrough
;
3173 bool force_share
= false;
3176 Error
*local_err
= NULL
;
3177 bool image_opts
= false;
3179 /* Parse commandline parameters */
3181 cache
= BDRV_DEFAULT_CACHE
;
3182 src_cache
= BDRV_DEFAULT_CACHE
;
3186 static const struct option long_options
[] = {
3187 {"help", no_argument
, 0, 'h'},
3188 {"object", required_argument
, 0, OPTION_OBJECT
},
3189 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3190 {"force-share", no_argument
, 0, 'U'},
3193 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3194 long_options
, NULL
);
3200 missing_argument(argv
[optind
- 1]);
3203 unrecognized_option(argv
[optind
- 1]);
3212 out_basefmt
= optarg
;
3215 out_baseimg
= optarg
;
3232 case OPTION_OBJECT
: {
3234 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3240 case OPTION_IMAGE_OPTS
:
3253 if (optind
!= argc
- 1) {
3254 error_exit("Expecting one image file name");
3256 if (!unsafe
&& !out_baseimg
) {
3257 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3259 filename
= argv
[optind
++];
3261 if (qemu_opts_foreach(&qemu_object_opts
,
3262 user_creatable_add_opts_foreach
,
3263 NULL
, &error_fatal
)) {
3267 qemu_progress_init(progress
, 2.0);
3268 qemu_progress_print(0, 100);
3270 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3271 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3273 error_report("Invalid cache option: %s", cache
);
3278 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3280 error_report("Invalid source cache option: %s", src_cache
);
3284 /* The source files are opened read-only, don't care about WCE */
3285 assert((src_flags
& BDRV_O_RDWR
) == 0);
3286 (void) src_writethrough
;
3291 * Ignore the old backing file for unsafe rebase in case we want to correct
3292 * the reference to a renamed or moved backing file.
3294 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3302 if (out_basefmt
!= NULL
) {
3303 if (bdrv_find_format(out_basefmt
) == NULL
) {
3304 error_report("Invalid format name: '%s'", out_basefmt
);
3310 /* For safe rebasing we need to compare old and new backing file */
3312 char backing_name
[PATH_MAX
];
3313 QDict
*options
= NULL
;
3316 if (bs
->backing_format
[0] != '\0') {
3317 options
= qdict_new();
3318 qdict_put_str(options
, "driver", bs
->backing_format
);
3323 options
= qdict_new();
3325 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3327 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3328 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3329 options
, src_flags
, &local_err
);
3330 if (!blk_old_backing
) {
3331 error_reportf_err(local_err
,
3332 "Could not open old backing file '%s': ",
3338 blk_old_backing
= NULL
;
3341 if (out_baseimg
[0]) {
3342 const char *overlay_filename
;
3343 char *out_real_path
;
3345 options
= qdict_new();
3347 qdict_put_str(options
, "driver", out_basefmt
);
3350 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3353 bdrv_refresh_filename(bs
);
3354 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3357 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3361 error_reportf_err(local_err
,
3362 "Could not resolve backing filename: ");
3367 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3368 options
, src_flags
, &local_err
);
3369 g_free(out_real_path
);
3370 if (!blk_new_backing
) {
3371 error_reportf_err(local_err
,
3372 "Could not open new backing file '%s': ",
3381 * Check each unallocated cluster in the COW file. If it is unallocated,
3382 * accesses go to the backing file. We must therefore compare this cluster
3383 * in the old and new backing file, and if they differ we need to copy it
3384 * from the old backing file into the COW file.
3386 * If qemu-img crashes during this step, no harm is done. The content of
3387 * the image is the same as the original one at any time.
3391 int64_t old_backing_size
= 0;
3392 int64_t new_backing_size
= 0;
3395 float local_progress
= 0;
3397 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3398 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3400 size
= blk_getlength(blk
);
3402 error_report("Could not get size of '%s': %s",
3403 filename
, strerror(-size
));
3407 if (blk_old_backing
) {
3408 old_backing_size
= blk_getlength(blk_old_backing
);
3409 if (old_backing_size
< 0) {
3410 char backing_name
[PATH_MAX
];
3412 bdrv_get_backing_filename(bs
, backing_name
,
3413 sizeof(backing_name
));
3414 error_report("Could not get size of '%s': %s",
3415 backing_name
, strerror(-old_backing_size
));
3420 if (blk_new_backing
) {
3421 new_backing_size
= blk_getlength(blk_new_backing
);
3422 if (new_backing_size
< 0) {
3423 error_report("Could not get size of '%s': %s",
3424 out_baseimg
, strerror(-new_backing_size
));
3431 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3434 for (offset
= 0; offset
< size
; offset
+= n
) {
3435 bool buf_old_is_zero
= false;
3437 /* How many bytes can we handle with the next read? */
3438 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3440 /* If the cluster is allocated, we don't need to take action */
3441 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3443 error_report("error while reading image metadata: %s",
3452 * Read old and new backing file and take into consideration that
3453 * backing files may be smaller than the COW image.
3455 if (offset
>= old_backing_size
) {
3456 memset(buf_old
, 0, n
);
3457 buf_old_is_zero
= true;
3459 if (offset
+ n
> old_backing_size
) {
3460 n
= old_backing_size
- offset
;
3463 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3465 error_report("error while reading from old backing file");
3470 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3471 memset(buf_new
, 0, n
);
3473 if (offset
+ n
> new_backing_size
) {
3474 n
= new_backing_size
- offset
;
3477 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3479 error_report("error while reading from new backing file");
3484 /* If they differ, we need to write to the COW file */
3485 uint64_t written
= 0;
3487 while (written
< n
) {
3490 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3491 n
- written
, &pnum
))
3493 if (buf_old_is_zero
) {
3494 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3496 ret
= blk_pwrite(blk
, offset
+ written
,
3497 buf_old
+ written
, pnum
, 0);
3500 error_report("Error while writing to COW image: %s",
3508 qemu_progress_print(local_progress
, 100);
3513 * Change the backing file. All clusters that are different from the old
3514 * backing file are overwritten in the COW file now, so the visible content
3515 * doesn't change when we switch the backing file.
3517 if (out_baseimg
&& *out_baseimg
) {
3518 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3520 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3523 if (ret
== -ENOSPC
) {
3524 error_report("Could not change the backing file to '%s': No "
3525 "space left in the file header", out_baseimg
);
3526 } else if (ret
< 0) {
3527 error_report("Could not change the backing file to '%s': %s",
3528 out_baseimg
, strerror(-ret
));
3531 qemu_progress_print(100, 0);
3533 * TODO At this point it is possible to check if any clusters that are
3534 * allocated in the COW file are the same in the backing file. If so, they
3535 * could be dropped from the COW file. Don't do this before switching the
3536 * backing file, in case of a crash this would lead to corruption.
3539 qemu_progress_end();
3542 blk_unref(blk_old_backing
);
3543 blk_unref(blk_new_backing
);
3545 qemu_vfree(buf_old
);
3546 qemu_vfree(buf_new
);
3555 static int img_resize(int argc
, char **argv
)
3558 int c
, ret
, relative
;
3559 const char *filename
, *fmt
, *size
;
3560 int64_t n
, total_size
, current_size
, new_size
;
3562 BlockBackend
*blk
= NULL
;
3563 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3566 static QemuOptsList resize_options
= {
3567 .name
= "resize_options",
3568 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3571 .name
= BLOCK_OPT_SIZE
,
3572 .type
= QEMU_OPT_SIZE
,
3573 .help
= "Virtual disk size"
3579 bool image_opts
= false;
3580 bool shrink
= false;
3582 /* Remove size from argv manually so that negative numbers are not treated
3583 * as options by getopt. */
3585 error_exit("Not enough arguments");
3589 size
= argv
[--argc
];
3591 /* Parse getopt arguments */
3594 static const struct option long_options
[] = {
3595 {"help", no_argument
, 0, 'h'},
3596 {"object", required_argument
, 0, OPTION_OBJECT
},
3597 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3598 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3599 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3602 c
= getopt_long(argc
, argv
, ":f:hq",
3603 long_options
, NULL
);
3609 missing_argument(argv
[optind
- 1]);
3612 unrecognized_option(argv
[optind
- 1]);
3623 case OPTION_OBJECT
: {
3625 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3631 case OPTION_IMAGE_OPTS
:
3634 case OPTION_PREALLOCATION
:
3635 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3636 PREALLOC_MODE__MAX
, NULL
);
3637 if (prealloc
== PREALLOC_MODE__MAX
) {
3638 error_report("Invalid preallocation mode '%s'", optarg
);
3647 if (optind
!= argc
- 1) {
3648 error_exit("Expecting image file name and size");
3650 filename
= argv
[optind
++];
3652 if (qemu_opts_foreach(&qemu_object_opts
,
3653 user_creatable_add_opts_foreach
,
3654 NULL
, &error_fatal
)) {
3658 /* Choose grow, shrink, or absolute resize mode */
3674 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3675 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3677 error_report_err(err
);
3679 qemu_opts_del(param
);
3682 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3683 qemu_opts_del(param
);
3685 blk
= img_open(image_opts
, filename
, fmt
,
3686 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3693 current_size
= blk_getlength(blk
);
3694 if (current_size
< 0) {
3695 error_report("Failed to inquire current image length: %s",
3696 strerror(-current_size
));
3702 total_size
= current_size
+ n
* relative
;
3706 if (total_size
<= 0) {
3707 error_report("New image size must be positive");
3712 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3713 error_report("Preallocation can only be used for growing images");
3718 if (total_size
< current_size
&& !shrink
) {
3719 warn_report("Shrinking an image will delete all data beyond the "
3720 "shrunken image's end. Before performing such an "
3721 "operation, make sure there is no important data there.");
3723 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3725 "Use the --shrink option to perform a shrink operation.");
3729 warn_report("Using the --shrink option will suppress this message. "
3730 "Note that future versions of qemu-img may refuse to "
3731 "shrink images without this option.");
3735 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3737 error_report_err(err
);
3741 new_size
= blk_getlength(blk
);
3743 error_report("Failed to verify truncated image length: %s",
3744 strerror(-new_size
));
3749 /* Some block drivers implement a truncation method, but only so
3750 * the user can cause qemu to refresh the image's size from disk.
3751 * The idea is that the user resizes the image outside of qemu and
3752 * then invokes block_resize to inform qemu about it.
3753 * (This includes iscsi and file-posix for device files.)
3754 * Of course, that is not the behavior someone invoking
3755 * qemu-img resize would find useful, so we catch that behavior
3756 * here and tell the user. */
3757 if (new_size
!= total_size
&& new_size
== current_size
) {
3758 error_report("Image was not resized; resizing may not be supported "
3764 if (new_size
!= total_size
) {
3765 warn_report("Image should have been resized to %" PRIi64
3766 " bytes, but was resized to %" PRIi64
" bytes",
3767 total_size
, new_size
);
3770 qprintf(quiet
, "Image resized.\n");
3780 static void amend_status_cb(BlockDriverState
*bs
,
3781 int64_t offset
, int64_t total_work_size
,
3784 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3787 static int print_amend_option_help(const char *format
)
3791 /* Find driver and parse its options */
3792 drv
= bdrv_find_format(format
);
3794 error_report("Unknown file format '%s'", format
);
3798 if (!drv
->bdrv_amend_options
) {
3799 error_report("Format driver '%s' does not support option amendment",
3804 /* Every driver supporting amendment must have create_opts */
3805 assert(drv
->create_opts
);
3807 printf("Creation options for '%s':\n", format
);
3808 qemu_opts_print_help(drv
->create_opts
, false);
3809 printf("\nNote that not all of these options may be amendable.\n");
3813 static int img_amend(int argc
, char **argv
)
3817 char *options
= NULL
;
3818 QemuOptsList
*create_opts
= NULL
;
3819 QemuOpts
*opts
= NULL
;
3820 const char *fmt
= NULL
, *filename
, *cache
;
3823 bool quiet
= false, progress
= false;
3824 BlockBackend
*blk
= NULL
;
3825 BlockDriverState
*bs
= NULL
;
3826 bool image_opts
= false;
3828 cache
= BDRV_DEFAULT_CACHE
;
3830 static const struct option long_options
[] = {
3831 {"help", no_argument
, 0, 'h'},
3832 {"object", required_argument
, 0, OPTION_OBJECT
},
3833 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3836 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3837 long_options
, NULL
);
3844 missing_argument(argv
[optind
- 1]);
3847 unrecognized_option(argv
[optind
- 1]);
3853 if (!is_valid_option_list(optarg
)) {
3854 error_report("Invalid option list: %s", optarg
);
3856 goto out_no_progress
;
3859 options
= g_strdup(optarg
);
3861 char *old_options
= options
;
3862 options
= g_strdup_printf("%s,%s", options
, optarg
);
3863 g_free(old_options
);
3879 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3883 goto out_no_progress
;
3886 case OPTION_IMAGE_OPTS
:
3893 error_exit("Must specify options (-o)");
3896 if (qemu_opts_foreach(&qemu_object_opts
,
3897 user_creatable_add_opts_foreach
,
3898 NULL
, &error_fatal
)) {
3900 goto out_no_progress
;
3906 qemu_progress_init(progress
, 1.0);
3908 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3909 if (fmt
&& has_help_option(options
)) {
3910 /* If a format is explicitly specified (and possibly no filename is
3911 * given), print option help here */
3912 ret
= print_amend_option_help(fmt
);
3916 if (optind
!= argc
- 1) {
3917 error_report("Expecting one image file name");
3922 flags
= BDRV_O_RDWR
;
3923 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3925 error_report("Invalid cache option: %s", cache
);
3929 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3937 fmt
= bs
->drv
->format_name
;
3939 if (has_help_option(options
)) {
3940 /* If the format was auto-detected, print option help here */
3941 ret
= print_amend_option_help(fmt
);
3945 if (!bs
->drv
->bdrv_amend_options
) {
3946 error_report("Format driver '%s' does not support option amendment",
3952 /* Every driver supporting amendment must have create_opts */
3953 assert(bs
->drv
->create_opts
);
3955 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3956 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3957 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3959 error_report_err(err
);
3964 /* In case the driver does not call amend_status_cb() */
3965 qemu_progress_print(0.f
, 0);
3966 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, &err
);
3967 qemu_progress_print(100.f
, 0);
3969 error_report_err(err
);
3974 qemu_progress_end();
3978 qemu_opts_del(opts
);
3979 qemu_opts_free(create_opts
);
3988 typedef struct BenchData
{
3990 uint64_t image_size
;
3997 bool drain_on_flush
;
4006 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4009 error_report("Failed flush request: %s", strerror(-ret
));
4014 static void bench_cb(void *opaque
, int ret
)
4016 BenchData
*b
= opaque
;
4020 error_report("Failed request: %s", strerror(-ret
));
4025 /* Just finished a flush with drained queue: Start next requests */
4026 assert(b
->in_flight
== 0);
4027 b
->in_flush
= false;
4028 } else if (b
->in_flight
> 0) {
4029 int remaining
= b
->n
- b
->in_flight
;
4034 /* Time for flush? Drain queue if requested, then flush */
4035 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4036 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4037 BlockCompletionFunc
*cb
;
4039 if (b
->drain_on_flush
) {
4043 cb
= bench_undrained_flush_cb
;
4046 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4048 error_report("Failed to issue flush request");
4052 if (b
->drain_on_flush
) {
4058 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4059 int64_t offset
= b
->offset
;
4060 /* blk_aio_* might look for completed I/Os and kick bench_cb
4061 * again, so make sure this operation is counted by in_flight
4062 * and b->offset is ready for the next submission.
4065 b
->offset
+= b
->step
;
4066 b
->offset
%= b
->image_size
;
4068 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4070 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4073 error_report("Failed to issue request");
4079 static int img_bench(int argc
, char **argv
)
4082 const char *fmt
= NULL
, *filename
;
4084 bool image_opts
= false;
4085 bool is_write
= false;
4089 size_t bufsize
= 4096;
4092 int flush_interval
= 0;
4093 bool drain_on_flush
= true;
4095 BlockBackend
*blk
= NULL
;
4096 BenchData data
= {};
4098 bool writethrough
= false;
4099 struct timeval t1
, t2
;
4101 bool force_share
= false;
4105 static const struct option long_options
[] = {
4106 {"help", no_argument
, 0, 'h'},
4107 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4108 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4109 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4110 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4111 {"force-share", no_argument
, 0, 'U'},
4114 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
4121 missing_argument(argv
[optind
- 1]);
4124 unrecognized_option(argv
[optind
- 1]);
4133 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4134 error_report("Invalid request count specified");
4144 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4145 error_report("Invalid queue depth specified");
4155 flags
|= BDRV_O_NATIVE_AIO
;
4159 offset
= cvtnum(optarg
);
4161 error_report("Invalid offset specified");
4174 sval
= cvtnum(optarg
);
4175 if (sval
< 0 || sval
> INT_MAX
) {
4176 error_report("Invalid buffer size specified");
4187 sval
= cvtnum(optarg
);
4188 if (sval
< 0 || sval
> INT_MAX
) {
4189 error_report("Invalid step size specified");
4197 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4199 error_report("Invalid cache mode");
4205 flags
|= BDRV_O_RDWR
;
4211 case OPTION_PATTERN
:
4215 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4216 error_report("Invalid pattern byte specified");
4222 case OPTION_FLUSH_INTERVAL
:
4226 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4227 error_report("Invalid flush interval specified");
4230 flush_interval
= res
;
4233 case OPTION_NO_DRAIN
:
4234 drain_on_flush
= false;
4236 case OPTION_IMAGE_OPTS
:
4242 if (optind
!= argc
- 1) {
4243 error_exit("Expecting one image file name");
4245 filename
= argv
[argc
- 1];
4247 if (!is_write
&& flush_interval
) {
4248 error_report("--flush-interval is only available in write tests");
4252 if (flush_interval
&& flush_interval
< depth
) {
4253 error_report("Flush interval can't be smaller than depth");
4258 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4265 image_size
= blk_getlength(blk
);
4266 if (image_size
< 0) {
4271 data
= (BenchData
) {
4273 .image_size
= image_size
,
4275 .step
= step
?: bufsize
,
4280 .flush_interval
= flush_interval
,
4281 .drain_on_flush
= drain_on_flush
,
4283 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4284 "(starting at offset %" PRId64
", step size %d)\n",
4285 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4286 data
.offset
, data
.step
);
4287 if (flush_interval
) {
4288 printf("Sending flush every %d requests\n", flush_interval
);
4291 buf_size
= data
.nrreq
* data
.bufsize
;
4292 data
.buf
= blk_blockalign(blk
, buf_size
);
4293 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4295 blk_register_buf(blk
, data
.buf
, buf_size
);
4297 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4298 for (i
= 0; i
< data
.nrreq
; i
++) {
4299 qemu_iovec_init(&data
.qiov
[i
], 1);
4300 qemu_iovec_add(&data
.qiov
[i
],
4301 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4304 gettimeofday(&t1
, NULL
);
4307 while (data
.n
> 0) {
4308 main_loop_wait(false);
4310 gettimeofday(&t2
, NULL
);
4312 printf("Run completed in %3.3f seconds.\n",
4313 (t2
.tv_sec
- t1
.tv_sec
)
4314 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4318 blk_unregister_buf(blk
, data
.buf
);
4320 qemu_vfree(data
.buf
);
4341 int bsz
; /* Block size */
4349 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4353 static int img_dd_bs(const char *arg
,
4354 struct DdIo
*in
, struct DdIo
*out
,
4361 if (res
<= 0 || res
> INT_MAX
) {
4362 error_report("invalid number: '%s'", arg
);
4365 in
->bsz
= out
->bsz
= res
;
4370 static int img_dd_count(const char *arg
,
4371 struct DdIo
*in
, struct DdIo
*out
,
4374 dd
->count
= cvtnum(arg
);
4376 if (dd
->count
< 0) {
4377 error_report("invalid number: '%s'", arg
);
4384 static int img_dd_if(const char *arg
,
4385 struct DdIo
*in
, struct DdIo
*out
,
4388 in
->filename
= g_strdup(arg
);
4393 static int img_dd_of(const char *arg
,
4394 struct DdIo
*in
, struct DdIo
*out
,
4397 out
->filename
= g_strdup(arg
);
4402 static int img_dd_skip(const char *arg
,
4403 struct DdIo
*in
, struct DdIo
*out
,
4406 in
->offset
= cvtnum(arg
);
4408 if (in
->offset
< 0) {
4409 error_report("invalid number: '%s'", arg
);
4416 static int img_dd(int argc
, char **argv
)
4421 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4422 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4423 QemuOpts
*opts
= NULL
;
4424 QemuOptsList
*create_opts
= NULL
;
4425 Error
*local_err
= NULL
;
4426 bool image_opts
= false;
4428 const char *out_fmt
= "raw";
4429 const char *fmt
= NULL
;
4431 int64_t block_count
= 0, out_pos
, in_pos
;
4432 bool force_share
= false;
4433 struct DdInfo dd
= {
4438 .bsz
= 512, /* Block size is by default 512 bytes */
4450 const struct DdOpts options
[] = {
4451 { "bs", img_dd_bs
, C_BS
},
4452 { "count", img_dd_count
, C_COUNT
},
4453 { "if", img_dd_if
, C_IF
},
4454 { "of", img_dd_of
, C_OF
},
4455 { "skip", img_dd_skip
, C_SKIP
},
4458 const struct option long_options
[] = {
4459 { "help", no_argument
, 0, 'h'},
4460 { "object", required_argument
, 0, OPTION_OBJECT
},
4461 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4462 { "force-share", no_argument
, 0, 'U'},
4466 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4478 missing_argument(argv
[optind
- 1]);
4481 unrecognized_option(argv
[optind
- 1]);
4490 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4495 case OPTION_IMAGE_OPTS
:
4501 for (i
= optind
; i
< argc
; i
++) {
4503 arg
= g_strdup(argv
[i
]);
4505 tmp
= strchr(arg
, '=');
4507 error_report("unrecognized operand %s", arg
);
4514 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4515 if (!strcmp(arg
, options
[j
].name
)) {
4519 if (options
[j
].name
== NULL
) {
4520 error_report("unrecognized operand %s", arg
);
4525 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4529 dd
.flags
|= options
[j
].flag
;
4534 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4535 error_report("Must specify both input and output files");
4540 if (qemu_opts_foreach(&qemu_object_opts
,
4541 user_creatable_add_opts_foreach
,
4542 NULL
, &error_fatal
)) {
4547 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4555 drv
= bdrv_find_format(out_fmt
);
4557 error_report("Unknown file format");
4561 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4564 error_report_err(local_err
);
4568 if (!drv
->create_opts
) {
4569 error_report("Format driver '%s' does not support image creation",
4574 if (!proto_drv
->create_opts
) {
4575 error_report("Protocol driver '%s' does not support image creation",
4576 proto_drv
->format_name
);
4580 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4581 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4583 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4585 size
= blk_getlength(blk1
);
4587 error_report("Failed to get size for '%s'", in
.filename
);
4592 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4593 dd
.count
* in
.bsz
< size
) {
4594 size
= dd
.count
* in
.bsz
;
4597 /* Overflow means the specified offset is beyond input image's size */
4598 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4599 size
< in
.bsz
* in
.offset
)) {
4600 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4602 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4603 size
- in
.bsz
* in
.offset
, &error_abort
);
4606 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4608 error_reportf_err(local_err
,
4609 "%s: error while creating output image: ",
4615 /* TODO, we can't honour --image-opts for the target,
4616 * since it needs to be given in a format compatible
4617 * with the bdrv_create() call above which does not
4618 * support image-opts style.
4620 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4621 false, false, false);
4628 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4629 size
< in
.offset
* in
.bsz
)) {
4630 /* We give a warning if the skip option is bigger than the input
4631 * size and create an empty output disk image (i.e. like dd(1)).
4633 error_report("%s: cannot skip to specified offset", in
.filename
);
4636 in_pos
= in
.offset
* in
.bsz
;
4639 in
.buf
= g_new(uint8_t, in
.bsz
);
4641 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4642 int in_ret
, out_ret
;
4644 if (in_pos
+ in
.bsz
> size
) {
4645 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4647 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4650 error_report("error while reading from input image file: %s",
4657 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4660 error_report("error while writing to output image file: %s",
4661 strerror(-out_ret
));
4670 qemu_opts_del(opts
);
4671 qemu_opts_free(create_opts
);
4674 g_free(in
.filename
);
4675 g_free(out
.filename
);
4685 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4689 Visitor
*v
= qobject_output_visitor_new(&obj
);
4691 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4692 visit_complete(v
, &obj
);
4693 str
= qobject_to_json_pretty(obj
);
4694 assert(str
!= NULL
);
4695 printf("%s\n", qstring_get_str(str
));
4701 static int img_measure(int argc
, char **argv
)
4703 static const struct option long_options
[] = {
4704 {"help", no_argument
, 0, 'h'},
4705 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4706 {"object", required_argument
, 0, OPTION_OBJECT
},
4707 {"output", required_argument
, 0, OPTION_OUTPUT
},
4708 {"size", required_argument
, 0, OPTION_SIZE
},
4709 {"force-share", no_argument
, 0, 'U'},
4712 OutputFormat output_format
= OFORMAT_HUMAN
;
4713 BlockBackend
*in_blk
= NULL
;
4715 const char *filename
= NULL
;
4716 const char *fmt
= NULL
;
4717 const char *out_fmt
= "raw";
4718 char *options
= NULL
;
4719 char *snapshot_name
= NULL
;
4720 bool force_share
= false;
4721 QemuOpts
*opts
= NULL
;
4722 QemuOpts
*object_opts
= NULL
;
4723 QemuOpts
*sn_opts
= NULL
;
4724 QemuOptsList
*create_opts
= NULL
;
4725 bool image_opts
= false;
4726 uint64_t img_size
= UINT64_MAX
;
4727 BlockMeasureInfo
*info
= NULL
;
4728 Error
*local_err
= NULL
;
4732 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4733 long_options
, NULL
)) != -1) {
4746 if (!is_valid_option_list(optarg
)) {
4747 error_report("Invalid option list: %s", optarg
);
4751 options
= g_strdup(optarg
);
4753 char *old_options
= options
;
4754 options
= g_strdup_printf("%s,%s", options
, optarg
);
4755 g_free(old_options
);
4759 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4760 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4763 error_report("Failed in parsing snapshot param '%s'",
4768 snapshot_name
= optarg
;
4775 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4781 case OPTION_IMAGE_OPTS
:
4785 if (!strcmp(optarg
, "json")) {
4786 output_format
= OFORMAT_JSON
;
4787 } else if (!strcmp(optarg
, "human")) {
4788 output_format
= OFORMAT_HUMAN
;
4790 error_report("--output must be used with human or json "
4799 sval
= cvtnum(optarg
);
4801 if (sval
== -ERANGE
) {
4802 error_report("Image size must be less than 8 EiB!");
4804 error_report("Invalid image size specified! You may use "
4805 "k, M, G, T, P or E suffixes for ");
4806 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4807 "petabytes and exabytes.");
4811 img_size
= (uint64_t)sval
;
4817 if (qemu_opts_foreach(&qemu_object_opts
,
4818 user_creatable_add_opts_foreach
,
4819 NULL
, &error_fatal
)) {
4823 if (argc
- optind
> 1) {
4824 error_report("At most one filename argument is allowed.");
4826 } else if (argc
- optind
== 1) {
4827 filename
= argv
[optind
];
4831 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4832 error_report("--object, --image-opts, -f, and -l "
4833 "require a filename argument.");
4836 if (filename
&& img_size
!= UINT64_MAX
) {
4837 error_report("--size N cannot be used together with a filename.");
4840 if (!filename
&& img_size
== UINT64_MAX
) {
4841 error_report("Either --size N or one filename must be specified.");
4846 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4847 false, false, force_share
);
4853 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4854 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4855 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4857 } else if (snapshot_name
!= NULL
) {
4858 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4859 snapshot_name
, &local_err
);
4862 error_reportf_err(local_err
, "Failed to load snapshot: ");
4867 drv
= bdrv_find_format(out_fmt
);
4869 error_report("Unknown file format '%s'", out_fmt
);
4872 if (!drv
->create_opts
) {
4873 error_report("Format driver '%s' does not support image creation",
4878 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4879 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4880 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4882 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4884 error_report_err(local_err
);
4885 error_report("Invalid options for file format '%s'", out_fmt
);
4889 if (img_size
!= UINT64_MAX
) {
4890 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4893 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4895 error_report_err(local_err
);
4899 if (output_format
== OFORMAT_HUMAN
) {
4900 printf("required size: %" PRIu64
"\n", info
->required
);
4901 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4903 dump_json_block_measure_info(info
);
4909 qapi_free_BlockMeasureInfo(info
);
4910 qemu_opts_del(object_opts
);
4911 qemu_opts_del(opts
);
4912 qemu_opts_del(sn_opts
);
4913 qemu_opts_free(create_opts
);
4919 static const img_cmd_t img_cmds
[] = {
4920 #define DEF(option, callback, arg_string) \
4921 { option, callback },
4922 #include "qemu-img-cmds.h"
4927 int main(int argc
, char **argv
)
4929 const img_cmd_t
*cmd
;
4930 const char *cmdname
;
4931 Error
*local_error
= NULL
;
4932 char *trace_file
= NULL
;
4934 static const struct option long_options
[] = {
4935 {"help", no_argument
, 0, 'h'},
4936 {"version", no_argument
, 0, 'V'},
4937 {"trace", required_argument
, NULL
, 'T'},
4942 signal(SIGPIPE
, SIG_IGN
);
4945 error_init(argv
[0]);
4946 module_call_init(MODULE_INIT_TRACE
);
4947 qemu_init_exec_dir(argv
[0]);
4949 if (qemu_init_main_loop(&local_error
)) {
4950 error_report_err(local_error
);
4954 qcrypto_init(&error_fatal
);
4956 module_call_init(MODULE_INIT_QOM
);
4959 error_exit("Not enough arguments");
4962 qemu_add_opts(&qemu_object_opts
);
4963 qemu_add_opts(&qemu_source_opts
);
4964 qemu_add_opts(&qemu_trace_opts
);
4966 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4969 missing_argument(argv
[optind
- 1]);
4972 unrecognized_option(argv
[optind
- 1]);
4978 printf(QEMU_IMG_VERSION
);
4982 trace_file
= trace_opt_parse(optarg
);
4987 cmdname
= argv
[optind
];
4989 /* reset getopt_long scanning */
4995 qemu_reset_optind();
4997 if (!trace_init_backends()) {
5000 trace_init_file(trace_file
);
5001 qemu_set_log(LOG_TRACE
);
5003 /* find the command */
5004 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5005 if (!strcmp(cmdname
, cmd
->name
)) {
5006 return cmd
->handler(argc
, argv
);
5011 error_exit("Command not found: %s", cmdname
);