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 "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t
{
54 int (*handler
)(int argc
, char **argv
);
59 OPTION_BACKING_CHAIN
= 257,
61 OPTION_IMAGE_OPTS
= 259,
63 OPTION_FLUSH_INTERVAL
= 261,
64 OPTION_NO_DRAIN
= 262,
65 OPTION_TARGET_IMAGE_OPTS
= 263,
67 OPTION_PREALLOCATION
= 265,
71 typedef enum OutputFormat
{
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque
, const char *name
)
84 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
88 error_printf("qemu-img: ");
91 error_vprintf(fmt
, ap
);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
98 static void QEMU_NORETURN
missing_argument(const char *option
)
100 error_exit("missing argument for option '%s'", option
);
103 static void QEMU_NORETURN
unrecognized_option(const char *option
)
105 error_exit("unrecognized option '%s'", option
);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN
help(void)
111 const char *help_msg
=
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
122 #define DEF(option, callback, arg_string) \
124 #include "qemu-img-cmds.h"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
153 " '-c' indicates that target image must be compressed (qcow format only)\n"
154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
159 " '-h' with or without a command shows this help and lists the supported formats\n"
160 " '-p' show progress of command (only certain commands)\n"
161 " '-q' use Quiet mode - do not print any output (except errors)\n"
162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
167 " '--output' takes the format in which the output must be done (human or json)\n"
168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
175 " hiding corruption that has already occurred.\n"
177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
187 " '-l' lists all snapshots in the given image\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
202 printf("%s\nSupported formats:", help_msg
);
203 bdrv_iterate_format(format_print
, NULL
);
204 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
208 static QemuOptsList qemu_object_opts
= {
210 .implied_opt_name
= "qom-type",
211 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
217 static QemuOptsList qemu_source_opts
= {
219 .implied_opt_name
= "file",
220 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
226 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
232 ret
= vprintf(fmt
, args
);
239 static int print_block_option_help(const char *filename
, const char *fmt
)
241 BlockDriver
*drv
, *proto_drv
;
242 QemuOptsList
*create_opts
= NULL
;
243 Error
*local_err
= NULL
;
245 /* Find driver and parse its options */
246 drv
= bdrv_find_format(fmt
);
248 error_report("Unknown file format '%s'", fmt
);
252 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
254 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
256 error_report_err(local_err
);
257 qemu_opts_free(create_opts
);
260 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
263 qemu_opts_print_help(create_opts
);
264 qemu_opts_free(create_opts
);
269 static BlockBackend
*img_open_opts(const char *optstr
,
270 QemuOpts
*opts
, int flags
, bool writethrough
,
271 bool quiet
, bool force_share
)
274 Error
*local_err
= NULL
;
276 options
= qemu_opts_to_qdict(opts
, NULL
);
278 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
279 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
280 error_report("--force-share/-U conflicts with image options");
281 qobject_unref(options
);
284 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
286 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
288 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
291 blk_set_enable_write_cache(blk
, !writethrough
);
296 static BlockBackend
*img_open_file(const char *filename
,
298 const char *fmt
, int flags
,
299 bool writethrough
, bool quiet
,
303 Error
*local_err
= NULL
;
306 options
= qdict_new();
309 qdict_put_str(options
, "driver", fmt
);
313 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
315 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
317 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
320 blk_set_enable_write_cache(blk
, !writethrough
);
326 static int img_add_key_secrets(void *opaque
,
327 const char *name
, const char *value
,
330 QDict
*options
= opaque
;
332 if (g_str_has_suffix(name
, "key-secret")) {
333 qdict_put_str(options
, name
, value
);
339 static BlockBackend
*img_open_new_file(const char *filename
,
340 QemuOpts
*create_opts
,
341 const char *fmt
, int flags
,
342 bool writethrough
, bool quiet
,
345 QDict
*options
= NULL
;
347 options
= qdict_new();
348 qemu_opt_foreach(create_opts
, img_add_key_secrets
, options
, &error_abort
);
350 return img_open_file(filename
, options
, fmt
, flags
, writethrough
, quiet
,
355 static BlockBackend
*img_open(bool image_opts
,
356 const char *filename
,
357 const char *fmt
, int flags
, bool writethrough
,
358 bool quiet
, bool force_share
)
364 error_report("--image-opts and --format are mutually exclusive");
367 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
372 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
375 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
382 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
383 const char *base_filename
,
384 const char *base_fmt
)
389 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
391 error_report("Backing file not supported for file format '%s'",
398 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
400 error_report("Backing file format not supported for file "
409 static int64_t cvtnum(const char *s
)
414 err
= qemu_strtosz(s
, NULL
, &value
);
418 if (value
> INT64_MAX
) {
424 static int img_create(int argc
, char **argv
)
427 uint64_t img_size
= -1;
428 const char *fmt
= "raw";
429 const char *base_fmt
= NULL
;
430 const char *filename
;
431 const char *base_filename
= NULL
;
432 char *options
= NULL
;
433 Error
*local_err
= NULL
;
438 static const struct option long_options
[] = {
439 {"help", no_argument
, 0, 'h'},
440 {"object", required_argument
, 0, OPTION_OBJECT
},
443 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
450 missing_argument(argv
[optind
- 1]);
453 unrecognized_option(argv
[optind
- 1]);
462 base_filename
= optarg
;
468 if (!is_valid_option_list(optarg
)) {
469 error_report("Invalid option list: %s", optarg
);
473 options
= g_strdup(optarg
);
475 char *old_options
= options
;
476 options
= g_strdup_printf("%s,%s", options
, optarg
);
484 flags
|= BDRV_O_NO_BACKING
;
486 case OPTION_OBJECT
: {
488 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
497 /* Get the filename */
498 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
499 if (options
&& has_help_option(options
)) {
501 return print_block_option_help(filename
, fmt
);
504 if (optind
>= argc
) {
505 error_exit("Expecting image file name");
509 if (qemu_opts_foreach(&qemu_object_opts
,
510 user_creatable_add_opts_foreach
,
515 /* Get image size, if specified */
519 sval
= cvtnum(argv
[optind
++]);
521 if (sval
== -ERANGE
) {
522 error_report("Image size must be less than 8 EiB!");
524 error_report("Invalid image size specified! You may use k, M, "
525 "G, T, P or E suffixes for ");
526 error_report("kilobytes, megabytes, gigabytes, terabytes, "
527 "petabytes and exabytes.");
531 img_size
= (uint64_t)sval
;
533 if (optind
!= argc
) {
534 error_exit("Unexpected argument: %s", argv
[optind
]);
537 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
538 options
, img_size
, flags
, quiet
, &local_err
);
540 error_reportf_err(local_err
, "%s: ", filename
);
552 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
556 Visitor
*v
= qobject_output_visitor_new(&obj
);
558 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
559 visit_complete(v
, &obj
);
560 str
= qobject_to_json_pretty(obj
);
562 qprintf(quiet
, "%s\n", qstring_get_str(str
));
568 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
570 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
571 qprintf(quiet
, "No errors were found on the image.\n");
573 if (check
->corruptions
) {
574 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
575 "Data may be corrupted, or further writes to the image "
582 "\n%" PRId64
" leaked clusters were found on the image.\n"
583 "This means waste of disk space, but no harm to data.\n",
587 if (check
->check_errors
) {
590 " internal errors have occurred during the check.\n",
591 check
->check_errors
);
595 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
596 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
597 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
598 check
->allocated_clusters
, check
->total_clusters
,
599 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
600 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
601 check
->compressed_clusters
* 100.0 /
602 check
->allocated_clusters
);
605 if (check
->image_end_offset
) {
607 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
611 static int collect_image_check(BlockDriverState
*bs
,
613 const char *filename
,
618 BdrvCheckResult result
;
620 ret
= bdrv_check(bs
, &result
, fix
);
625 check
->filename
= g_strdup(filename
);
626 check
->format
= g_strdup(bdrv_get_format_name(bs
));
627 check
->check_errors
= result
.check_errors
;
628 check
->corruptions
= result
.corruptions
;
629 check
->has_corruptions
= result
.corruptions
!= 0;
630 check
->leaks
= result
.leaks
;
631 check
->has_leaks
= result
.leaks
!= 0;
632 check
->corruptions_fixed
= result
.corruptions_fixed
;
633 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
634 check
->leaks_fixed
= result
.leaks_fixed
;
635 check
->has_leaks_fixed
= result
.leaks
!= 0;
636 check
->image_end_offset
= result
.image_end_offset
;
637 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
638 check
->total_clusters
= result
.bfi
.total_clusters
;
639 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
640 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
641 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
642 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
643 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
644 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
645 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
651 * Checks an image for consistency. Exit codes:
653 * 0 - Check completed, image is good
654 * 1 - Check not completed because of internal errors
655 * 2 - Check completed, image is corrupted
656 * 3 - Check completed, image has leaked clusters, but is good otherwise
657 * 63 - Checks are not supported by the image format
659 static int img_check(int argc
, char **argv
)
662 OutputFormat output_format
= OFORMAT_HUMAN
;
663 const char *filename
, *fmt
, *output
, *cache
;
665 BlockDriverState
*bs
;
667 int flags
= BDRV_O_CHECK
;
671 bool image_opts
= false;
672 bool force_share
= false;
676 cache
= BDRV_DEFAULT_CACHE
;
679 int option_index
= 0;
680 static const struct option long_options
[] = {
681 {"help", no_argument
, 0, 'h'},
682 {"format", required_argument
, 0, 'f'},
683 {"repair", required_argument
, 0, 'r'},
684 {"output", required_argument
, 0, OPTION_OUTPUT
},
685 {"object", required_argument
, 0, OPTION_OBJECT
},
686 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
687 {"force-share", no_argument
, 0, 'U'},
690 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
691 long_options
, &option_index
);
697 missing_argument(argv
[optind
- 1]);
700 unrecognized_option(argv
[optind
- 1]);
709 flags
|= BDRV_O_RDWR
;
711 if (!strcmp(optarg
, "leaks")) {
712 fix
= BDRV_FIX_LEAKS
;
713 } else if (!strcmp(optarg
, "all")) {
714 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
716 error_exit("Unknown option value for -r "
717 "(expecting 'leaks' or 'all'): %s", optarg
);
732 case OPTION_OBJECT
: {
734 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
740 case OPTION_IMAGE_OPTS
:
745 if (optind
!= argc
- 1) {
746 error_exit("Expecting one image file name");
748 filename
= argv
[optind
++];
750 if (output
&& !strcmp(output
, "json")) {
751 output_format
= OFORMAT_JSON
;
752 } else if (output
&& !strcmp(output
, "human")) {
753 output_format
= OFORMAT_HUMAN
;
755 error_report("--output must be used with human or json as argument.");
759 if (qemu_opts_foreach(&qemu_object_opts
,
760 user_creatable_add_opts_foreach
,
765 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
767 error_report("Invalid source cache option: %s", cache
);
771 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
778 check
= g_new0(ImageCheck
, 1);
779 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
781 if (ret
== -ENOTSUP
) {
782 error_report("This image format does not support checks");
787 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
788 int corruptions_fixed
, leaks_fixed
;
790 leaks_fixed
= check
->leaks_fixed
;
791 corruptions_fixed
= check
->corruptions_fixed
;
793 if (output_format
== OFORMAT_HUMAN
) {
795 "The following inconsistencies were found and repaired:\n\n"
796 " %" PRId64
" leaked clusters\n"
797 " %" PRId64
" corruptions\n\n"
798 "Double checking the fixed image now...\n",
800 check
->corruptions_fixed
);
803 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
805 check
->leaks_fixed
= leaks_fixed
;
806 check
->corruptions_fixed
= corruptions_fixed
;
810 switch (output_format
) {
812 dump_human_image_check(check
, quiet
);
815 dump_json_image_check(check
, quiet
);
820 if (ret
|| check
->check_errors
) {
822 error_report("Check failed: %s", strerror(-ret
));
824 error_report("Check failed");
830 if (check
->corruptions
) {
832 } else if (check
->leaks
) {
839 qapi_free_ImageCheck(check
);
844 typedef struct CommonBlockJobCBInfo
{
845 BlockDriverState
*bs
;
847 } CommonBlockJobCBInfo
;
849 static void common_block_job_cb(void *opaque
, int ret
)
851 CommonBlockJobCBInfo
*cbi
= opaque
;
854 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
858 static void run_block_job(BlockJob
*job
, Error
**errp
)
860 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
863 aio_context_acquire(aio_context
);
866 float progress
= 0.0f
;
867 aio_poll(aio_context
, true);
868 if (job
->job
.progress_total
) {
869 progress
= (float)job
->job
.progress_current
/
870 job
->job
.progress_total
* 100.f
;
872 qemu_progress_print(progress
, 0);
873 } while (!job_is_ready(&job
->job
) && !job_is_completed(&job
->job
));
875 if (!job_is_completed(&job
->job
)) {
876 ret
= job_complete_sync(&job
->job
, errp
);
880 job_unref(&job
->job
);
881 aio_context_release(aio_context
);
883 /* publish completion progress only when success */
885 qemu_progress_print(100.f
, 0);
889 static int img_commit(int argc
, char **argv
)
892 const char *filename
, *fmt
, *cache
, *base
;
894 BlockDriverState
*bs
, *base_bs
;
896 bool progress
= false, quiet
= false, drop
= false;
898 Error
*local_err
= NULL
;
899 CommonBlockJobCBInfo cbi
;
900 bool image_opts
= false;
901 AioContext
*aio_context
;
904 cache
= BDRV_DEFAULT_CACHE
;
907 static const struct option long_options
[] = {
908 {"help", no_argument
, 0, 'h'},
909 {"object", required_argument
, 0, OPTION_OBJECT
},
910 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
913 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
920 missing_argument(argv
[optind
- 1]);
923 unrecognized_option(argv
[optind
- 1]);
948 case OPTION_OBJECT
: {
950 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
956 case OPTION_IMAGE_OPTS
:
962 /* Progress is not shown in Quiet mode */
967 if (optind
!= argc
- 1) {
968 error_exit("Expecting one image file name");
970 filename
= argv
[optind
++];
972 if (qemu_opts_foreach(&qemu_object_opts
,
973 user_creatable_add_opts_foreach
,
978 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
979 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
981 error_report("Invalid cache option: %s", cache
);
985 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
992 qemu_progress_init(progress
, 1.f
);
993 qemu_progress_print(0.f
, 100);
996 base_bs
= bdrv_find_backing_image(bs
, base
);
998 error_setg(&local_err
,
999 "Did not find '%s' in the backing chain of '%s'",
1004 /* This is different from QMP, which by default uses the deepest file in
1005 * the backing chain (i.e., the very base); however, the traditional
1006 * behavior of qemu-img commit is using the immediate backing file. */
1007 base_bs
= backing_bs(bs
);
1009 error_setg(&local_err
, "Image does not have a backing file");
1014 cbi
= (CommonBlockJobCBInfo
){
1019 aio_context
= bdrv_get_aio_context(bs
);
1020 aio_context_acquire(aio_context
);
1021 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, 0,
1022 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1023 &cbi
, false, &local_err
);
1024 aio_context_release(aio_context
);
1029 /* When the block job completes, the BlockBackend reference will point to
1030 * the old backing file. In order to avoid that the top image is already
1031 * deleted, so we can still empty it afterwards, increment the reference
1032 * counter here preemptively. */
1037 job
= block_job_get("commit");
1038 run_block_job(job
, &local_err
);
1043 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1044 ret
= bs
->drv
->bdrv_make_empty(bs
);
1046 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1058 qemu_progress_end();
1063 error_report_err(local_err
);
1067 qprintf(quiet
, "Image committed.\n");
1072 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1073 * of the first sector boundary within buf where the sector contains a
1074 * non-zero byte. This function is robust to a buffer that is not
1077 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1080 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1082 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1083 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1087 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1094 * Returns true iff the first sector pointed to by 'buf' contains at least
1097 * 'pnum' is set to the number of sectors (including and immediately following
1098 * the first one) that are known to be in the same allocated/unallocated state.
1100 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1109 is_zero
= buffer_is_zero(buf
, 512);
1110 for(i
= 1; i
< n
; i
++) {
1112 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1121 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1122 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1123 * breaking up write requests for only small sparse areas.
1125 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1129 int num_checked
, num_used
;
1135 ret
= is_allocated_sectors(buf
, n
, pnum
);
1141 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1143 num_checked
= num_used
;
1146 ret
= is_allocated_sectors(buf
, n
, pnum
);
1148 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1150 num_checked
+= *pnum
;
1152 num_used
= num_checked
;
1153 } else if (*pnum
>= min
) {
1163 * Compares two buffers sector by sector. Returns 0 if the first
1164 * sector of each buffer matches, non-zero otherwise.
1166 * pnum is set to the sector-aligned size of the buffer prefix that
1167 * has the same matching status as the first sector.
1169 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1170 int64_t bytes
, int64_t *pnum
)
1173 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1177 res
= !!memcmp(buf1
, buf2
, i
);
1179 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1181 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1191 #define IO_BUF_SIZE (2 * 1024 * 1024)
1194 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1196 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1197 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1198 * failure), and 4 on error (the exit status for read errors), after emitting
1201 * @param blk: BlockBackend for the image
1202 * @param offset: Starting offset to check
1203 * @param bytes: Number of bytes to check
1204 * @param filename: Name of disk file we are checking (logging purpose)
1205 * @param buffer: Allocated buffer for storing read data
1206 * @param quiet: Flag for quiet mode
1208 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1209 int64_t bytes
, const char *filename
,
1210 uint8_t *buffer
, bool quiet
)
1215 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1217 error_report("Error while reading offset %" PRId64
" of %s: %s",
1218 offset
, filename
, strerror(-ret
));
1221 idx
= find_nonzero(buffer
, bytes
);
1223 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1232 * Compares two images. Exit codes:
1234 * 0 - Images are identical
1236 * >1 - Error occurred
1238 static int img_compare(int argc
, char **argv
)
1240 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1241 BlockBackend
*blk1
, *blk2
;
1242 BlockDriverState
*bs1
, *bs2
;
1243 int64_t total_size1
, total_size2
;
1244 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1245 int64_t pnum1
, pnum2
;
1246 int allocated1
, allocated2
;
1247 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1248 bool progress
= false, quiet
= false, strict
= false;
1255 uint64_t progress_base
;
1256 bool image_opts
= false;
1257 bool force_share
= false;
1259 cache
= BDRV_DEFAULT_CACHE
;
1261 static const struct option long_options
[] = {
1262 {"help", no_argument
, 0, 'h'},
1263 {"object", required_argument
, 0, OPTION_OBJECT
},
1264 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1265 {"force-share", no_argument
, 0, 'U'},
1268 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1269 long_options
, NULL
);
1275 missing_argument(argv
[optind
- 1]);
1278 unrecognized_option(argv
[optind
- 1]);
1304 case OPTION_OBJECT
: {
1306 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1313 case OPTION_IMAGE_OPTS
:
1319 /* Progress is not shown in Quiet mode */
1325 if (optind
!= argc
- 2) {
1326 error_exit("Expecting two image file names");
1328 filename1
= argv
[optind
++];
1329 filename2
= argv
[optind
++];
1331 if (qemu_opts_foreach(&qemu_object_opts
,
1332 user_creatable_add_opts_foreach
,
1338 /* Initialize before goto out */
1339 qemu_progress_init(progress
, 2.0);
1342 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1344 error_report("Invalid source cache option: %s", cache
);
1349 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1356 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1365 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1366 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1367 total_size1
= blk_getlength(blk1
);
1368 if (total_size1
< 0) {
1369 error_report("Can't get size of %s: %s",
1370 filename1
, strerror(-total_size1
));
1374 total_size2
= blk_getlength(blk2
);
1375 if (total_size2
< 0) {
1376 error_report("Can't get size of %s: %s",
1377 filename2
, strerror(-total_size2
));
1381 total_size
= MIN(total_size1
, total_size2
);
1382 progress_base
= MAX(total_size1
, total_size2
);
1384 qemu_progress_print(0, 100);
1386 if (strict
&& total_size1
!= total_size2
) {
1388 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1392 while (offset
< total_size
) {
1393 int status1
, status2
;
1395 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1396 total_size1
- offset
, &pnum1
, NULL
,
1400 error_report("Sector allocation test failed for %s", filename1
);
1403 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1405 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1406 total_size2
- offset
, &pnum2
, NULL
,
1410 error_report("Sector allocation test failed for %s", filename2
);
1413 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1415 assert(pnum1
&& pnum2
);
1416 chunk
= MIN(pnum1
, pnum2
);
1419 if (status1
!= status2
) {
1421 qprintf(quiet
, "Strict mode: Offset %" PRId64
1422 " block status mismatch!\n", offset
);
1426 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1428 } else if (allocated1
== allocated2
) {
1432 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1433 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1435 error_report("Error while reading offset %" PRId64
1437 offset
, filename1
, strerror(-ret
));
1441 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1443 error_report("Error while reading offset %" PRId64
1445 offset
, filename2
, strerror(-ret
));
1449 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1450 if (ret
|| pnum
!= chunk
) {
1451 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1452 offset
+ (ret
? 0 : pnum
));
1458 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1460 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1461 filename1
, buf1
, quiet
);
1463 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1464 filename2
, buf1
, quiet
);
1471 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1474 if (total_size1
!= total_size2
) {
1475 BlockBackend
*blk_over
;
1476 const char *filename_over
;
1478 qprintf(quiet
, "Warning: Image size mismatch!\n");
1479 if (total_size1
> total_size2
) {
1481 filename_over
= filename1
;
1484 filename_over
= filename2
;
1487 while (offset
< progress_base
) {
1488 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1489 progress_base
- offset
, &chunk
,
1493 error_report("Sector allocation test failed for %s",
1498 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1499 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1500 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1501 filename_over
, buf1
, quiet
);
1507 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1511 qprintf(quiet
, "Images are identical.\n");
1521 qemu_progress_end();
1526 enum ImgConvertBlockStatus
{
1532 #define MAX_COROUTINES 16
1534 typedef struct ImgConvertState
{
1536 int64_t *src_sectors
;
1538 int64_t total_sectors
;
1539 int64_t allocated_sectors
;
1540 int64_t allocated_done
;
1543 enum ImgConvertBlockStatus status
;
1544 int64_t sector_next_status
;
1545 BlockBackend
*target
;
1548 bool target_has_backing
;
1552 size_t cluster_sectors
;
1554 long num_coroutines
;
1555 int running_coroutines
;
1556 Coroutine
*co
[MAX_COROUTINES
];
1557 int64_t wait_sector_num
[MAX_COROUTINES
];
1562 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1563 int *src_cur
, int64_t *src_cur_offset
)
1566 *src_cur_offset
= 0;
1567 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1568 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1570 assert(*src_cur
< s
->src_num
);
1574 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1576 int64_t src_cur_offset
;
1577 int ret
, n
, src_cur
;
1579 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1581 assert(s
->total_sectors
> sector_num
);
1582 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1584 if (s
->sector_next_status
<= sector_num
) {
1585 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1587 if (s
->target_has_backing
) {
1589 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1590 (sector_num
- src_cur_offset
) *
1592 count
, &count
, NULL
, NULL
);
1594 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1595 (sector_num
- src_cur_offset
) *
1597 count
, &count
, NULL
, NULL
);
1602 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1604 if (ret
& BDRV_BLOCK_ZERO
) {
1605 s
->status
= BLK_ZERO
;
1606 } else if (ret
& BDRV_BLOCK_DATA
) {
1607 s
->status
= BLK_DATA
;
1609 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1612 s
->sector_next_status
= sector_num
+ n
;
1615 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1616 if (s
->status
== BLK_DATA
) {
1617 n
= MIN(n
, s
->buf_sectors
);
1620 /* We need to write complete clusters for compressed images, so if an
1621 * unallocated area is shorter than that, we must consider the whole
1622 * cluster allocated. */
1623 if (s
->compressed
) {
1624 if (n
< s
->cluster_sectors
) {
1625 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1626 s
->status
= BLK_DATA
;
1628 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1635 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1636 int nb_sectors
, uint8_t *buf
)
1642 assert(nb_sectors
<= s
->buf_sectors
);
1643 while (nb_sectors
> 0) {
1646 int64_t bs_sectors
, src_cur_offset
;
1648 /* In the case of compression with multiple source files, we can get a
1649 * nb_sectors that spreads into the next part. So we must be able to
1650 * read across multiple BDSes for one convert_read() call. */
1651 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1652 blk
= s
->src
[src_cur
];
1653 bs_sectors
= s
->src_sectors
[src_cur
];
1655 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1657 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1658 qemu_iovec_init_external(&qiov
, &iov
, 1);
1660 ret
= blk_co_preadv(
1661 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1662 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1669 buf
+= n
* BDRV_SECTOR_SIZE
;
1676 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1677 int nb_sectors
, uint8_t *buf
,
1678 enum ImgConvertBlockStatus status
)
1684 while (nb_sectors
> 0) {
1686 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1689 case BLK_BACKING_FILE
:
1690 /* If we have a backing file, leave clusters unallocated that are
1691 * unallocated in the source image, so that the backing file is
1692 * visible at the respective offset. */
1693 assert(s
->target_has_backing
);
1697 /* If we're told to keep the target fully allocated (-S 0) or there
1698 * is real non-zero data, we must write it. Otherwise we can treat
1699 * it as zero sectors.
1700 * Compressed clusters need to be written as a whole, so in that
1701 * case we can only save the write if the buffer is completely
1703 if (!s
->min_sparse
||
1705 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1707 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1710 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1711 qemu_iovec_init_external(&qiov
, &iov
, 1);
1713 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1714 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1723 if (s
->has_zero_init
) {
1724 assert(!s
->target_has_backing
);
1727 ret
= blk_co_pwrite_zeroes(s
->target
,
1728 sector_num
<< BDRV_SECTOR_BITS
,
1729 n
<< BDRV_SECTOR_BITS
, 0);
1738 buf
+= n
* BDRV_SECTOR_SIZE
;
1744 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1749 while (nb_sectors
> 0) {
1752 int64_t bs_sectors
, src_cur_offset
;
1755 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1756 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1757 blk
= s
->src
[src_cur
];
1758 bs_sectors
= s
->src_sectors
[src_cur
];
1760 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1762 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1763 sector_num
<< BDRV_SECTOR_BITS
,
1764 n
<< BDRV_SECTOR_BITS
, 0);
1775 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1777 ImgConvertState
*s
= opaque
;
1778 uint8_t *buf
= NULL
;
1782 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1783 if (s
->co
[i
] == qemu_coroutine_self()) {
1790 s
->running_coroutines
++;
1791 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1796 enum ImgConvertBlockStatus status
;
1799 qemu_co_mutex_lock(&s
->lock
);
1800 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1801 qemu_co_mutex_unlock(&s
->lock
);
1804 n
= convert_iteration_sectors(s
, s
->sector_num
);
1806 qemu_co_mutex_unlock(&s
->lock
);
1810 /* save current sector and allocation status to local variables */
1811 sector_num
= s
->sector_num
;
1813 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1814 n
= MIN(n
, s
->buf_sectors
);
1816 /* increment global sector counter so that other coroutines can
1817 * already continue reading beyond this request */
1819 qemu_co_mutex_unlock(&s
->lock
);
1821 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1822 s
->allocated_done
+= n
;
1823 qemu_progress_print(100.0 * s
->allocated_done
/
1824 s
->allocated_sectors
, 0);
1828 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
1829 if (status
== BLK_DATA
&& !copy_range
) {
1830 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1832 error_report("error while reading sector %" PRId64
1833 ": %s", sector_num
, strerror(-ret
));
1836 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1838 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1841 if (s
->wr_in_order
) {
1842 /* keep writes in order */
1843 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1844 s
->wait_sector_num
[index
] = sector_num
;
1845 qemu_coroutine_yield();
1847 s
->wait_sector_num
[index
] = -1;
1850 if (s
->ret
== -EINPROGRESS
) {
1852 ret
= convert_co_copy_range(s
, sector_num
, n
);
1854 s
->copy_range
= false;
1858 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1861 error_report("error while writing sector %" PRId64
1862 ": %s", sector_num
, strerror(-ret
));
1867 if (s
->wr_in_order
) {
1868 /* reenter the coroutine that might have waited
1869 * for this write to complete */
1870 s
->wr_offs
= sector_num
+ n
;
1871 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1872 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1874 * A -> B -> A cannot occur because A has
1875 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1876 * B will never enter A during this time window.
1878 qemu_coroutine_enter(s
->co
[i
]);
1886 s
->co
[index
] = NULL
;
1887 s
->running_coroutines
--;
1888 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1889 /* the convert job finished successfully */
1894 static int convert_do_copy(ImgConvertState
*s
)
1897 int64_t sector_num
= 0;
1899 /* Check whether we have zero initialisation or can get it efficiently */
1900 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1901 ? bdrv_has_zero_init(blk_bs(s
->target
))
1904 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1905 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1907 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1909 s
->has_zero_init
= true;
1913 /* Allocate buffer for copied data. For compressed images, only one cluster
1914 * can be copied at a time. */
1915 if (s
->compressed
) {
1916 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1917 error_report("invalid cluster size");
1920 s
->buf_sectors
= s
->cluster_sectors
;
1923 while (sector_num
< s
->total_sectors
) {
1924 n
= convert_iteration_sectors(s
, sector_num
);
1928 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1930 s
->allocated_sectors
+= n
;
1936 s
->sector_next_status
= 0;
1937 s
->ret
= -EINPROGRESS
;
1939 qemu_co_mutex_init(&s
->lock
);
1940 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1941 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1942 s
->wait_sector_num
[i
] = -1;
1943 qemu_coroutine_enter(s
->co
[i
]);
1946 while (s
->running_coroutines
) {
1947 main_loop_wait(false);
1950 if (s
->compressed
&& !s
->ret
) {
1951 /* signal EOF to align */
1952 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1961 static int img_convert(int argc
, char **argv
)
1963 int c
, bs_i
, flags
, src_flags
= 0;
1964 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1965 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1966 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1967 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1968 BlockDriverInfo bdi
;
1969 BlockDriverState
*out_bs
;
1970 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1971 QemuOptsList
*create_opts
= NULL
;
1972 char *options
= NULL
;
1973 Error
*local_err
= NULL
;
1974 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1975 skip_create
= false, progress
= false, tgt_image_opts
= false;
1976 int64_t ret
= -EINVAL
;
1977 bool force_share
= false;
1979 ImgConvertState s
= (ImgConvertState
) {
1980 /* Need at least 4k of zeros for sparse detection */
1983 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1984 .wr_in_order
= true,
1985 .num_coroutines
= 8,
1989 static const struct option long_options
[] = {
1990 {"help", no_argument
, 0, 'h'},
1991 {"object", required_argument
, 0, OPTION_OBJECT
},
1992 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1993 {"force-share", no_argument
, 0, 'U'},
1994 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1997 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1998 long_options
, NULL
);
2004 missing_argument(argv
[optind
- 1]);
2007 unrecognized_option(argv
[optind
- 1]);
2019 out_baseimg
= optarg
;
2022 s
.compressed
= true;
2023 s
.copy_range
= false;
2026 if (!is_valid_option_list(optarg
)) {
2027 error_report("Invalid option list: %s", optarg
);
2031 options
= g_strdup(optarg
);
2033 char *old_options
= options
;
2034 options
= g_strdup_printf("%s,%s", options
, optarg
);
2035 g_free(old_options
);
2039 snapshot_name
= optarg
;
2042 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2043 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2046 error_report("Failed in parsing snapshot param '%s'",
2051 snapshot_name
= optarg
;
2058 sval
= cvtnum(optarg
);
2060 error_report("Invalid minimum zero buffer size for sparse output specified");
2064 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2065 s
.copy_range
= false;
2084 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2085 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2086 error_report("Invalid number of coroutines. Allowed number of"
2087 " coroutines is between 1 and %d", MAX_COROUTINES
);
2092 s
.wr_in_order
= false;
2097 case OPTION_OBJECT
: {
2098 QemuOpts
*object_opts
;
2099 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2106 case OPTION_IMAGE_OPTS
:
2109 case OPTION_TARGET_IMAGE_OPTS
:
2110 tgt_image_opts
= true;
2115 if (!out_fmt
&& !tgt_image_opts
) {
2119 if (qemu_opts_foreach(&qemu_object_opts
,
2120 user_creatable_add_opts_foreach
,
2125 if (!s
.wr_in_order
&& s
.compressed
) {
2126 error_report("Out of order write and compress are mutually exclusive");
2130 if (tgt_image_opts
&& !skip_create
) {
2131 error_report("--target-image-opts requires use of -n flag");
2135 s
.src_num
= argc
- optind
- 1;
2136 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2138 if (options
&& has_help_option(options
)) {
2140 ret
= print_block_option_help(out_filename
, out_fmt
);
2143 error_report("Option help requires a format be specified");
2148 if (s
.src_num
< 1) {
2149 error_report("Must specify image file name");
2154 /* ret is still -EINVAL until here */
2155 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2157 error_report("Invalid source cache option: %s", src_cache
);
2161 /* Initialize before goto out */
2165 qemu_progress_init(progress
, 1.0);
2166 qemu_progress_print(0, 100);
2168 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2169 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2171 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2172 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2173 fmt
, src_flags
, src_writethrough
, quiet
,
2179 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2180 if (s
.src_sectors
[bs_i
] < 0) {
2181 error_report("Could not get size of %s: %s",
2182 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2186 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2190 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2191 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2192 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2194 } else if (snapshot_name
!= NULL
) {
2195 if (s
.src_num
> 1) {
2196 error_report("No support for concatenating multiple snapshot");
2201 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2205 error_reportf_err(local_err
, "Failed to load snapshot: ");
2211 /* Find driver and parse its options */
2212 drv
= bdrv_find_format(out_fmt
);
2214 error_report("Unknown file format '%s'", out_fmt
);
2219 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2221 error_report_err(local_err
);
2226 if (!drv
->create_opts
) {
2227 error_report("Format driver '%s' does not support image creation",
2233 if (!proto_drv
->create_opts
) {
2234 error_report("Protocol driver '%s' does not support image creation",
2235 proto_drv
->format_name
);
2240 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2241 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2243 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2245 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2247 error_report_err(local_err
);
2253 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2255 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2261 /* Get backing file name if -o backing_file was used */
2262 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2263 if (out_baseimg_param
) {
2264 out_baseimg
= out_baseimg_param
;
2266 s
.target_has_backing
= (bool) out_baseimg
;
2268 if (s
.src_num
> 1 && out_baseimg
) {
2269 error_report("Having a backing file for the target makes no sense when "
2270 "concatenating multiple input images");
2275 /* Check if compression is supported */
2278 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2279 const char *encryptfmt
=
2280 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2281 const char *preallocation
=
2282 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2284 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2285 error_report("Compression not supported for this file format");
2290 if (encryption
|| encryptfmt
) {
2291 error_report("Compression and encryption not supported at "
2298 && strcmp(preallocation
, "off"))
2300 error_report("Compression and preallocation not supported at "
2308 /* Create the new image */
2309 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2311 error_reportf_err(local_err
, "%s: error while converting %s: ",
2312 out_filename
, out_fmt
);
2317 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2318 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2320 error_report("Invalid cache option: %s", cache
);
2325 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2326 flags
, writethrough
, quiet
, false);
2328 /* TODO ultimately we should allow --target-image-opts
2329 * to be used even when -n is not given.
2330 * That has to wait for bdrv_create to be improved
2331 * to allow filenames in option syntax
2333 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2334 flags
, writethrough
, quiet
, false);
2340 out_bs
= blk_bs(s
.target
);
2342 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2343 error_report("Compression not supported for this file format");
2348 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2349 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2351 s
.buf_sectors
= MIN(32768,
2353 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2354 out_bs
->bl
.pdiscard_alignment
>>
2355 BDRV_SECTOR_BITS
)));
2358 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2359 if (output_sectors
< 0) {
2360 error_report("unable to get output image length: %s",
2361 strerror(-output_sectors
));
2364 } else if (output_sectors
< s
.total_sectors
) {
2365 error_report("output file is smaller than input file");
2371 ret
= bdrv_get_info(out_bs
, &bdi
);
2374 error_report("could not get block driver info");
2378 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2379 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2382 ret
= convert_do_copy(&s
);
2385 qemu_progress_print(100, 0);
2387 qemu_progress_end();
2388 qemu_opts_del(opts
);
2389 qemu_opts_free(create_opts
);
2390 qemu_opts_del(sn_opts
);
2391 blk_unref(s
.target
);
2393 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2394 blk_unref(s
.src
[bs_i
]);
2398 g_free(s
.src_sectors
);
2406 static void dump_snapshots(BlockDriverState
*bs
)
2408 QEMUSnapshotInfo
*sn_tab
, *sn
;
2411 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2414 printf("Snapshot list:\n");
2415 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2417 for(i
= 0; i
< nb_sns
; i
++) {
2419 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2425 static void dump_json_image_info_list(ImageInfoList
*list
)
2429 Visitor
*v
= qobject_output_visitor_new(&obj
);
2431 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2432 visit_complete(v
, &obj
);
2433 str
= qobject_to_json_pretty(obj
);
2434 assert(str
!= NULL
);
2435 printf("%s\n", qstring_get_str(str
));
2441 static void dump_json_image_info(ImageInfo
*info
)
2445 Visitor
*v
= qobject_output_visitor_new(&obj
);
2447 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2448 visit_complete(v
, &obj
);
2449 str
= qobject_to_json_pretty(obj
);
2450 assert(str
!= NULL
);
2451 printf("%s\n", qstring_get_str(str
));
2457 static void dump_human_image_info_list(ImageInfoList
*list
)
2459 ImageInfoList
*elem
;
2462 for (elem
= list
; elem
; elem
= elem
->next
) {
2468 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2472 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2474 return strcmp(a
, b
) == 0;
2478 * Open an image file chain and return an ImageInfoList
2480 * @filename: topmost image filename
2481 * @fmt: topmost image format (may be NULL to autodetect)
2482 * @chain: true - enumerate entire backing file chain
2483 * false - only topmost image file
2485 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2486 * image file. If there was an error a message will have been printed to
2489 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2490 const char *filename
,
2492 bool chain
, bool force_share
)
2494 ImageInfoList
*head
= NULL
;
2495 ImageInfoList
**last
= &head
;
2496 GHashTable
*filenames
;
2499 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2503 BlockDriverState
*bs
;
2505 ImageInfoList
*elem
;
2507 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2508 error_report("Backing file '%s' creates an infinite loop.",
2512 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2514 blk
= img_open(image_opts
, filename
, fmt
,
2515 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2522 bdrv_query_image_info(bs
, &info
, &err
);
2524 error_report_err(err
);
2529 elem
= g_new0(ImageInfoList
, 1);
2536 filename
= fmt
= NULL
;
2538 if (info
->has_full_backing_filename
) {
2539 filename
= info
->full_backing_filename
;
2540 } else if (info
->has_backing_filename
) {
2541 error_report("Could not determine absolute backing filename,"
2542 " but backing filename '%s' present",
2543 info
->backing_filename
);
2546 if (info
->has_backing_filename_format
) {
2547 fmt
= info
->backing_filename_format
;
2551 g_hash_table_destroy(filenames
);
2555 qapi_free_ImageInfoList(head
);
2556 g_hash_table_destroy(filenames
);
2560 static int img_info(int argc
, char **argv
)
2563 OutputFormat output_format
= OFORMAT_HUMAN
;
2565 const char *filename
, *fmt
, *output
;
2566 ImageInfoList
*list
;
2567 bool image_opts
= false;
2568 bool force_share
= false;
2573 int option_index
= 0;
2574 static const struct option long_options
[] = {
2575 {"help", no_argument
, 0, 'h'},
2576 {"format", required_argument
, 0, 'f'},
2577 {"output", required_argument
, 0, OPTION_OUTPUT
},
2578 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2579 {"object", required_argument
, 0, OPTION_OBJECT
},
2580 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2581 {"force-share", no_argument
, 0, 'U'},
2584 c
= getopt_long(argc
, argv
, ":f:hU",
2585 long_options
, &option_index
);
2591 missing_argument(argv
[optind
- 1]);
2594 unrecognized_option(argv
[optind
- 1]);
2608 case OPTION_BACKING_CHAIN
:
2611 case OPTION_OBJECT
: {
2613 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2619 case OPTION_IMAGE_OPTS
:
2624 if (optind
!= argc
- 1) {
2625 error_exit("Expecting one image file name");
2627 filename
= argv
[optind
++];
2629 if (output
&& !strcmp(output
, "json")) {
2630 output_format
= OFORMAT_JSON
;
2631 } else if (output
&& !strcmp(output
, "human")) {
2632 output_format
= OFORMAT_HUMAN
;
2633 } else if (output
) {
2634 error_report("--output must be used with human or json as argument.");
2638 if (qemu_opts_foreach(&qemu_object_opts
,
2639 user_creatable_add_opts_foreach
,
2644 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2650 switch (output_format
) {
2652 dump_human_image_info_list(list
);
2656 dump_json_image_info_list(list
);
2658 dump_json_image_info(list
->value
);
2663 qapi_free_ImageInfoList(list
);
2667 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2670 switch (output_format
) {
2672 if (e
->data
&& !e
->has_offset
) {
2673 error_report("File contains external, encrypted or compressed clusters.");
2676 if (e
->data
&& !e
->zero
) {
2677 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2678 e
->start
, e
->length
,
2679 e
->has_offset
? e
->offset
: 0,
2680 e
->has_filename
? e
->filename
: "");
2682 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2683 * Modify the flags here to allow more coalescing.
2685 if (next
&& (!next
->data
|| next
->zero
)) {
2691 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2692 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2693 (e
->start
== 0 ? "[" : ",\n"),
2694 e
->start
, e
->length
, e
->depth
,
2695 e
->zero
? "true" : "false",
2696 e
->data
? "true" : "false");
2697 if (e
->has_offset
) {
2698 printf(", \"offset\": %"PRId64
"", e
->offset
);
2709 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2710 int64_t bytes
, MapEntry
*e
)
2714 BlockDriverState
*file
;
2718 /* As an optimization, we could cache the current range of unallocated
2719 * clusters in each file of the chain, and avoid querying the same
2725 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2730 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2733 bs
= backing_bs(bs
);
2742 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2747 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2748 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2750 .has_offset
= has_offset
,
2752 .has_filename
= file
&& has_offset
,
2753 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2759 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2761 if (curr
->length
== 0) {
2764 if (curr
->zero
!= next
->zero
||
2765 curr
->data
!= next
->data
||
2766 curr
->depth
!= next
->depth
||
2767 curr
->has_filename
!= next
->has_filename
||
2768 curr
->has_offset
!= next
->has_offset
) {
2771 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2774 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2780 static int img_map(int argc
, char **argv
)
2783 OutputFormat output_format
= OFORMAT_HUMAN
;
2785 BlockDriverState
*bs
;
2786 const char *filename
, *fmt
, *output
;
2788 MapEntry curr
= { .length
= 0 }, next
;
2790 bool image_opts
= false;
2791 bool force_share
= false;
2796 int option_index
= 0;
2797 static const struct option long_options
[] = {
2798 {"help", no_argument
, 0, 'h'},
2799 {"format", required_argument
, 0, 'f'},
2800 {"output", required_argument
, 0, OPTION_OUTPUT
},
2801 {"object", required_argument
, 0, OPTION_OBJECT
},
2802 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2803 {"force-share", no_argument
, 0, 'U'},
2806 c
= getopt_long(argc
, argv
, ":f:hU",
2807 long_options
, &option_index
);
2813 missing_argument(argv
[optind
- 1]);
2816 unrecognized_option(argv
[optind
- 1]);
2830 case OPTION_OBJECT
: {
2832 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2838 case OPTION_IMAGE_OPTS
:
2843 if (optind
!= argc
- 1) {
2844 error_exit("Expecting one image file name");
2846 filename
= argv
[optind
];
2848 if (output
&& !strcmp(output
, "json")) {
2849 output_format
= OFORMAT_JSON
;
2850 } else if (output
&& !strcmp(output
, "human")) {
2851 output_format
= OFORMAT_HUMAN
;
2852 } else if (output
) {
2853 error_report("--output must be used with human or json as argument.");
2857 if (qemu_opts_foreach(&qemu_object_opts
,
2858 user_creatable_add_opts_foreach
,
2863 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2869 if (output_format
== OFORMAT_HUMAN
) {
2870 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2873 length
= blk_getlength(blk
);
2874 while (curr
.start
+ curr
.length
< length
) {
2875 int64_t offset
= curr
.start
+ curr
.length
;
2878 /* Probe up to 1 GiB at a time. */
2879 n
= QEMU_ALIGN_DOWN(MIN(1 << 30, length
- offset
), BDRV_SECTOR_SIZE
);
2880 ret
= get_block_status(bs
, offset
, n
, &next
);
2883 error_report("Could not read file metadata: %s", strerror(-ret
));
2887 if (entry_mergeable(&curr
, &next
)) {
2888 curr
.length
+= next
.length
;
2892 if (curr
.length
> 0) {
2893 dump_map_entry(output_format
, &curr
, &next
);
2898 dump_map_entry(output_format
, &curr
, NULL
);
2905 #define SNAPSHOT_LIST 1
2906 #define SNAPSHOT_CREATE 2
2907 #define SNAPSHOT_APPLY 3
2908 #define SNAPSHOT_DELETE 4
2910 static int img_snapshot(int argc
, char **argv
)
2913 BlockDriverState
*bs
;
2914 QEMUSnapshotInfo sn
;
2915 char *filename
, *snapshot_name
= NULL
;
2916 int c
, ret
= 0, bdrv_oflags
;
2921 bool image_opts
= false;
2922 bool force_share
= false;
2924 bdrv_oflags
= BDRV_O_RDWR
;
2925 /* Parse commandline parameters */
2927 static const struct option long_options
[] = {
2928 {"help", no_argument
, 0, 'h'},
2929 {"object", required_argument
, 0, OPTION_OBJECT
},
2930 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2931 {"force-share", no_argument
, 0, 'U'},
2934 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2935 long_options
, NULL
);
2941 missing_argument(argv
[optind
- 1]);
2944 unrecognized_option(argv
[optind
- 1]);
2951 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2954 action
= SNAPSHOT_LIST
;
2955 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2959 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2962 action
= SNAPSHOT_APPLY
;
2963 snapshot_name
= optarg
;
2967 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2970 action
= SNAPSHOT_CREATE
;
2971 snapshot_name
= optarg
;
2975 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2978 action
= SNAPSHOT_DELETE
;
2979 snapshot_name
= optarg
;
2987 case OPTION_OBJECT
: {
2989 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2995 case OPTION_IMAGE_OPTS
:
3001 if (optind
!= argc
- 1) {
3002 error_exit("Expecting one image file name");
3004 filename
= argv
[optind
++];
3006 if (qemu_opts_foreach(&qemu_object_opts
,
3007 user_creatable_add_opts_foreach
,
3012 /* Open the image */
3013 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3020 /* Perform the requested action */
3026 case SNAPSHOT_CREATE
:
3027 memset(&sn
, 0, sizeof(sn
));
3028 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3030 qemu_gettimeofday(&tv
);
3031 sn
.date_sec
= tv
.tv_sec
;
3032 sn
.date_nsec
= tv
.tv_usec
* 1000;
3034 ret
= bdrv_snapshot_create(bs
, &sn
);
3036 error_report("Could not create snapshot '%s': %d (%s)",
3037 snapshot_name
, ret
, strerror(-ret
));
3041 case SNAPSHOT_APPLY
:
3042 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3044 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3049 case SNAPSHOT_DELETE
:
3050 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3052 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3067 static int img_rebase(int argc
, char **argv
)
3069 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3070 uint8_t *buf_old
= NULL
;
3071 uint8_t *buf_new
= NULL
;
3072 BlockDriverState
*bs
= NULL
;
3074 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3075 int c
, flags
, src_flags
, ret
;
3076 bool writethrough
, src_writethrough
;
3078 bool force_share
= false;
3081 Error
*local_err
= NULL
;
3082 bool image_opts
= false;
3084 /* Parse commandline parameters */
3086 cache
= BDRV_DEFAULT_CACHE
;
3087 src_cache
= BDRV_DEFAULT_CACHE
;
3091 static const struct option long_options
[] = {
3092 {"help", no_argument
, 0, 'h'},
3093 {"object", required_argument
, 0, OPTION_OBJECT
},
3094 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3095 {"force-share", no_argument
, 0, 'U'},
3098 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3099 long_options
, NULL
);
3105 missing_argument(argv
[optind
- 1]);
3108 unrecognized_option(argv
[optind
- 1]);
3117 out_basefmt
= optarg
;
3120 out_baseimg
= optarg
;
3137 case OPTION_OBJECT
: {
3139 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3145 case OPTION_IMAGE_OPTS
:
3158 if (optind
!= argc
- 1) {
3159 error_exit("Expecting one image file name");
3161 if (!unsafe
&& !out_baseimg
) {
3162 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3164 filename
= argv
[optind
++];
3166 if (qemu_opts_foreach(&qemu_object_opts
,
3167 user_creatable_add_opts_foreach
,
3172 qemu_progress_init(progress
, 2.0);
3173 qemu_progress_print(0, 100);
3175 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3176 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3178 error_report("Invalid cache option: %s", cache
);
3183 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3185 error_report("Invalid source cache option: %s", src_cache
);
3189 /* The source files are opened read-only, don't care about WCE */
3190 assert((src_flags
& BDRV_O_RDWR
) == 0);
3191 (void) src_writethrough
;
3196 * Ignore the old backing file for unsafe rebase in case we want to correct
3197 * the reference to a renamed or moved backing file.
3199 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3207 if (out_basefmt
!= NULL
) {
3208 if (bdrv_find_format(out_basefmt
) == NULL
) {
3209 error_report("Invalid format name: '%s'", out_basefmt
);
3215 /* For safe rebasing we need to compare old and new backing file */
3217 char backing_name
[PATH_MAX
];
3218 QDict
*options
= NULL
;
3220 if (bs
->backing_format
[0] != '\0') {
3221 options
= qdict_new();
3222 qdict_put_str(options
, "driver", bs
->backing_format
);
3227 options
= qdict_new();
3229 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3231 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3232 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3233 options
, src_flags
, &local_err
);
3234 if (!blk_old_backing
) {
3235 error_reportf_err(local_err
,
3236 "Could not open old backing file '%s': ",
3242 if (out_baseimg
[0]) {
3243 options
= qdict_new();
3245 qdict_put_str(options
, "driver", out_basefmt
);
3248 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3251 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3252 options
, src_flags
, &local_err
);
3253 if (!blk_new_backing
) {
3254 error_reportf_err(local_err
,
3255 "Could not open new backing file '%s': ",
3264 * Check each unallocated cluster in the COW file. If it is unallocated,
3265 * accesses go to the backing file. We must therefore compare this cluster
3266 * in the old and new backing file, and if they differ we need to copy it
3267 * from the old backing file into the COW file.
3269 * If qemu-img crashes during this step, no harm is done. The content of
3270 * the image is the same as the original one at any time.
3274 int64_t old_backing_size
;
3275 int64_t new_backing_size
= 0;
3278 float local_progress
= 0;
3280 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3281 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3283 size
= blk_getlength(blk
);
3285 error_report("Could not get size of '%s': %s",
3286 filename
, strerror(-size
));
3290 old_backing_size
= blk_getlength(blk_old_backing
);
3291 if (old_backing_size
< 0) {
3292 char backing_name
[PATH_MAX
];
3294 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3295 error_report("Could not get size of '%s': %s",
3296 backing_name
, strerror(-old_backing_size
));
3300 if (blk_new_backing
) {
3301 new_backing_size
= blk_getlength(blk_new_backing
);
3302 if (new_backing_size
< 0) {
3303 error_report("Could not get size of '%s': %s",
3304 out_baseimg
, strerror(-new_backing_size
));
3311 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3314 for (offset
= 0; offset
< size
; offset
+= n
) {
3315 /* How many bytes can we handle with the next read? */
3316 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3318 /* If the cluster is allocated, we don't need to take action */
3319 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3321 error_report("error while reading image metadata: %s",
3330 * Read old and new backing file and take into consideration that
3331 * backing files may be smaller than the COW image.
3333 if (offset
>= old_backing_size
) {
3334 memset(buf_old
, 0, n
);
3336 if (offset
+ n
> old_backing_size
) {
3337 n
= old_backing_size
- offset
;
3340 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3342 error_report("error while reading from old backing file");
3347 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3348 memset(buf_new
, 0, n
);
3350 if (offset
+ n
> new_backing_size
) {
3351 n
= new_backing_size
- offset
;
3354 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3356 error_report("error while reading from new backing file");
3361 /* If they differ, we need to write to the COW file */
3362 uint64_t written
= 0;
3364 while (written
< n
) {
3367 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3368 n
- written
, &pnum
))
3370 ret
= blk_pwrite(blk
, offset
+ written
,
3371 buf_old
+ written
, pnum
, 0);
3373 error_report("Error while writing to COW image: %s",
3381 qemu_progress_print(local_progress
, 100);
3386 * Change the backing file. All clusters that are different from the old
3387 * backing file are overwritten in the COW file now, so the visible content
3388 * doesn't change when we switch the backing file.
3390 if (out_baseimg
&& *out_baseimg
) {
3391 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3393 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3396 if (ret
== -ENOSPC
) {
3397 error_report("Could not change the backing file to '%s': No "
3398 "space left in the file header", out_baseimg
);
3399 } else if (ret
< 0) {
3400 error_report("Could not change the backing file to '%s': %s",
3401 out_baseimg
, strerror(-ret
));
3404 qemu_progress_print(100, 0);
3406 * TODO At this point it is possible to check if any clusters that are
3407 * allocated in the COW file are the same in the backing file. If so, they
3408 * could be dropped from the COW file. Don't do this before switching the
3409 * backing file, in case of a crash this would lead to corruption.
3412 qemu_progress_end();
3415 blk_unref(blk_old_backing
);
3416 blk_unref(blk_new_backing
);
3418 qemu_vfree(buf_old
);
3419 qemu_vfree(buf_new
);
3428 static int img_resize(int argc
, char **argv
)
3431 int c
, ret
, relative
;
3432 const char *filename
, *fmt
, *size
;
3433 int64_t n
, total_size
, current_size
, new_size
;
3435 BlockBackend
*blk
= NULL
;
3436 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3439 static QemuOptsList resize_options
= {
3440 .name
= "resize_options",
3441 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3444 .name
= BLOCK_OPT_SIZE
,
3445 .type
= QEMU_OPT_SIZE
,
3446 .help
= "Virtual disk size"
3452 bool image_opts
= false;
3453 bool shrink
= false;
3455 /* Remove size from argv manually so that negative numbers are not treated
3456 * as options by getopt. */
3458 error_exit("Not enough arguments");
3462 size
= argv
[--argc
];
3464 /* Parse getopt arguments */
3467 static const struct option long_options
[] = {
3468 {"help", no_argument
, 0, 'h'},
3469 {"object", required_argument
, 0, OPTION_OBJECT
},
3470 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3471 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3472 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3475 c
= getopt_long(argc
, argv
, ":f:hq",
3476 long_options
, NULL
);
3482 missing_argument(argv
[optind
- 1]);
3485 unrecognized_option(argv
[optind
- 1]);
3496 case OPTION_OBJECT
: {
3498 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3504 case OPTION_IMAGE_OPTS
:
3507 case OPTION_PREALLOCATION
:
3508 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3509 PREALLOC_MODE__MAX
, NULL
);
3510 if (prealloc
== PREALLOC_MODE__MAX
) {
3511 error_report("Invalid preallocation mode '%s'", optarg
);
3520 if (optind
!= argc
- 1) {
3521 error_exit("Expecting image file name and size");
3523 filename
= argv
[optind
++];
3525 if (qemu_opts_foreach(&qemu_object_opts
,
3526 user_creatable_add_opts_foreach
,
3531 /* Choose grow, shrink, or absolute resize mode */
3547 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3548 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3550 error_report_err(err
);
3552 qemu_opts_del(param
);
3555 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3556 qemu_opts_del(param
);
3558 blk
= img_open(image_opts
, filename
, fmt
,
3559 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3566 current_size
= blk_getlength(blk
);
3567 if (current_size
< 0) {
3568 error_report("Failed to inquire current image length: %s",
3569 strerror(-current_size
));
3575 total_size
= current_size
+ n
* relative
;
3579 if (total_size
<= 0) {
3580 error_report("New image size must be positive");
3585 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3586 error_report("Preallocation can only be used for growing images");
3591 if (total_size
< current_size
&& !shrink
) {
3592 warn_report("Shrinking an image will delete all data beyond the "
3593 "shrunken image's end. Before performing such an "
3594 "operation, make sure there is no important data there.");
3596 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3598 "Use the --shrink option to perform a shrink operation.");
3602 warn_report("Using the --shrink option will suppress this message. "
3603 "Note that future versions of qemu-img may refuse to "
3604 "shrink images without this option.");
3608 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3610 error_report_err(err
);
3614 new_size
= blk_getlength(blk
);
3616 error_report("Failed to verify truncated image length: %s",
3617 strerror(-new_size
));
3622 /* Some block drivers implement a truncation method, but only so
3623 * the user can cause qemu to refresh the image's size from disk.
3624 * The idea is that the user resizes the image outside of qemu and
3625 * then invokes block_resize to inform qemu about it.
3626 * (This includes iscsi and file-posix for device files.)
3627 * Of course, that is not the behavior someone invoking
3628 * qemu-img resize would find useful, so we catch that behavior
3629 * here and tell the user. */
3630 if (new_size
!= total_size
&& new_size
== current_size
) {
3631 error_report("Image was not resized; resizing may not be supported "
3637 if (new_size
!= total_size
) {
3638 warn_report("Image should have been resized to %" PRIi64
3639 " bytes, but was resized to %" PRIi64
" bytes",
3640 total_size
, new_size
);
3643 qprintf(quiet
, "Image resized.\n");
3653 static void amend_status_cb(BlockDriverState
*bs
,
3654 int64_t offset
, int64_t total_work_size
,
3657 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3660 static int img_amend(int argc
, char **argv
)
3664 char *options
= NULL
;
3665 QemuOptsList
*create_opts
= NULL
;
3666 QemuOpts
*opts
= NULL
;
3667 const char *fmt
= NULL
, *filename
, *cache
;
3670 bool quiet
= false, progress
= false;
3671 BlockBackend
*blk
= NULL
;
3672 BlockDriverState
*bs
= NULL
;
3673 bool image_opts
= false;
3675 cache
= BDRV_DEFAULT_CACHE
;
3677 static const struct option long_options
[] = {
3678 {"help", no_argument
, 0, 'h'},
3679 {"object", required_argument
, 0, OPTION_OBJECT
},
3680 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3683 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3684 long_options
, NULL
);
3691 missing_argument(argv
[optind
- 1]);
3694 unrecognized_option(argv
[optind
- 1]);
3700 if (!is_valid_option_list(optarg
)) {
3701 error_report("Invalid option list: %s", optarg
);
3703 goto out_no_progress
;
3706 options
= g_strdup(optarg
);
3708 char *old_options
= options
;
3709 options
= g_strdup_printf("%s,%s", options
, optarg
);
3710 g_free(old_options
);
3726 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3730 goto out_no_progress
;
3733 case OPTION_IMAGE_OPTS
:
3740 error_exit("Must specify options (-o)");
3743 if (qemu_opts_foreach(&qemu_object_opts
,
3744 user_creatable_add_opts_foreach
,
3747 goto out_no_progress
;
3753 qemu_progress_init(progress
, 1.0);
3755 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3756 if (fmt
&& has_help_option(options
)) {
3757 /* If a format is explicitly specified (and possibly no filename is
3758 * given), print option help here */
3759 ret
= print_block_option_help(filename
, fmt
);
3763 if (optind
!= argc
- 1) {
3764 error_report("Expecting one image file name");
3769 flags
= BDRV_O_RDWR
;
3770 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3772 error_report("Invalid cache option: %s", cache
);
3776 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3784 fmt
= bs
->drv
->format_name
;
3786 if (has_help_option(options
)) {
3787 /* If the format was auto-detected, print option help here */
3788 ret
= print_block_option_help(filename
, fmt
);
3792 if (!bs
->drv
->create_opts
) {
3793 error_report("Format driver '%s' does not support any options to amend",
3799 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3800 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3801 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3803 error_report_err(err
);
3808 /* In case the driver does not call amend_status_cb() */
3809 qemu_progress_print(0.f
, 0);
3810 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3811 qemu_progress_print(100.f
, 0);
3813 error_report("Error while amending options: %s", strerror(-ret
));
3818 qemu_progress_end();
3822 qemu_opts_del(opts
);
3823 qemu_opts_free(create_opts
);
3832 typedef struct BenchData
{
3834 uint64_t image_size
;
3841 bool drain_on_flush
;
3850 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3853 error_report("Failed flush request: %s", strerror(-ret
));
3858 static void bench_cb(void *opaque
, int ret
)
3860 BenchData
*b
= opaque
;
3864 error_report("Failed request: %s", strerror(-ret
));
3869 /* Just finished a flush with drained queue: Start next requests */
3870 assert(b
->in_flight
== 0);
3871 b
->in_flush
= false;
3872 } else if (b
->in_flight
> 0) {
3873 int remaining
= b
->n
- b
->in_flight
;
3878 /* Time for flush? Drain queue if requested, then flush */
3879 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3880 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3881 BlockCompletionFunc
*cb
;
3883 if (b
->drain_on_flush
) {
3887 cb
= bench_undrained_flush_cb
;
3890 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3892 error_report("Failed to issue flush request");
3896 if (b
->drain_on_flush
) {
3902 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3903 int64_t offset
= b
->offset
;
3904 /* blk_aio_* might look for completed I/Os and kick bench_cb
3905 * again, so make sure this operation is counted by in_flight
3906 * and b->offset is ready for the next submission.
3909 b
->offset
+= b
->step
;
3910 b
->offset
%= b
->image_size
;
3912 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3914 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3917 error_report("Failed to issue request");
3923 static int img_bench(int argc
, char **argv
)
3926 const char *fmt
= NULL
, *filename
;
3928 bool image_opts
= false;
3929 bool is_write
= false;
3933 size_t bufsize
= 4096;
3936 int flush_interval
= 0;
3937 bool drain_on_flush
= true;
3939 BlockBackend
*blk
= NULL
;
3940 BenchData data
= {};
3942 bool writethrough
= false;
3943 struct timeval t1
, t2
;
3945 bool force_share
= false;
3949 static const struct option long_options
[] = {
3950 {"help", no_argument
, 0, 'h'},
3951 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3952 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3953 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3954 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3955 {"force-share", no_argument
, 0, 'U'},
3958 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3965 missing_argument(argv
[optind
- 1]);
3968 unrecognized_option(argv
[optind
- 1]);
3977 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3978 error_report("Invalid request count specified");
3988 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3989 error_report("Invalid queue depth specified");
3999 flags
|= BDRV_O_NATIVE_AIO
;
4003 offset
= cvtnum(optarg
);
4005 error_report("Invalid offset specified");
4018 sval
= cvtnum(optarg
);
4019 if (sval
< 0 || sval
> INT_MAX
) {
4020 error_report("Invalid buffer size specified");
4031 sval
= cvtnum(optarg
);
4032 if (sval
< 0 || sval
> INT_MAX
) {
4033 error_report("Invalid step size specified");
4041 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4043 error_report("Invalid cache mode");
4049 flags
|= BDRV_O_RDWR
;
4055 case OPTION_PATTERN
:
4059 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4060 error_report("Invalid pattern byte specified");
4066 case OPTION_FLUSH_INTERVAL
:
4070 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4071 error_report("Invalid flush interval specified");
4074 flush_interval
= res
;
4077 case OPTION_NO_DRAIN
:
4078 drain_on_flush
= false;
4080 case OPTION_IMAGE_OPTS
:
4086 if (optind
!= argc
- 1) {
4087 error_exit("Expecting one image file name");
4089 filename
= argv
[argc
- 1];
4091 if (!is_write
&& flush_interval
) {
4092 error_report("--flush-interval is only available in write tests");
4096 if (flush_interval
&& flush_interval
< depth
) {
4097 error_report("Flush interval can't be smaller than depth");
4102 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4109 image_size
= blk_getlength(blk
);
4110 if (image_size
< 0) {
4115 data
= (BenchData
) {
4117 .image_size
= image_size
,
4119 .step
= step
?: bufsize
,
4124 .flush_interval
= flush_interval
,
4125 .drain_on_flush
= drain_on_flush
,
4127 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4128 "(starting at offset %" PRId64
", step size %d)\n",
4129 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4130 data
.offset
, data
.step
);
4131 if (flush_interval
) {
4132 printf("Sending flush every %d requests\n", flush_interval
);
4135 buf_size
= data
.nrreq
* data
.bufsize
;
4136 data
.buf
= blk_blockalign(blk
, buf_size
);
4137 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4139 blk_register_buf(blk
, data
.buf
, buf_size
);
4141 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4142 for (i
= 0; i
< data
.nrreq
; i
++) {
4143 qemu_iovec_init(&data
.qiov
[i
], 1);
4144 qemu_iovec_add(&data
.qiov
[i
],
4145 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4148 gettimeofday(&t1
, NULL
);
4151 while (data
.n
> 0) {
4152 main_loop_wait(false);
4154 gettimeofday(&t2
, NULL
);
4156 printf("Run completed in %3.3f seconds.\n",
4157 (t2
.tv_sec
- t1
.tv_sec
)
4158 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4162 blk_unregister_buf(blk
, data
.buf
);
4164 qemu_vfree(data
.buf
);
4185 int bsz
; /* Block size */
4193 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4197 static int img_dd_bs(const char *arg
,
4198 struct DdIo
*in
, struct DdIo
*out
,
4205 if (res
<= 0 || res
> INT_MAX
) {
4206 error_report("invalid number: '%s'", arg
);
4209 in
->bsz
= out
->bsz
= res
;
4214 static int img_dd_count(const char *arg
,
4215 struct DdIo
*in
, struct DdIo
*out
,
4218 dd
->count
= cvtnum(arg
);
4220 if (dd
->count
< 0) {
4221 error_report("invalid number: '%s'", arg
);
4228 static int img_dd_if(const char *arg
,
4229 struct DdIo
*in
, struct DdIo
*out
,
4232 in
->filename
= g_strdup(arg
);
4237 static int img_dd_of(const char *arg
,
4238 struct DdIo
*in
, struct DdIo
*out
,
4241 out
->filename
= g_strdup(arg
);
4246 static int img_dd_skip(const char *arg
,
4247 struct DdIo
*in
, struct DdIo
*out
,
4250 in
->offset
= cvtnum(arg
);
4252 if (in
->offset
< 0) {
4253 error_report("invalid number: '%s'", arg
);
4260 static int img_dd(int argc
, char **argv
)
4265 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4266 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4267 QemuOpts
*opts
= NULL
;
4268 QemuOptsList
*create_opts
= NULL
;
4269 Error
*local_err
= NULL
;
4270 bool image_opts
= false;
4272 const char *out_fmt
= "raw";
4273 const char *fmt
= NULL
;
4275 int64_t block_count
= 0, out_pos
, in_pos
;
4276 bool force_share
= false;
4277 struct DdInfo dd
= {
4282 .bsz
= 512, /* Block size is by default 512 bytes */
4294 const struct DdOpts options
[] = {
4295 { "bs", img_dd_bs
, C_BS
},
4296 { "count", img_dd_count
, C_COUNT
},
4297 { "if", img_dd_if
, C_IF
},
4298 { "of", img_dd_of
, C_OF
},
4299 { "skip", img_dd_skip
, C_SKIP
},
4302 const struct option long_options
[] = {
4303 { "help", no_argument
, 0, 'h'},
4304 { "object", required_argument
, 0, OPTION_OBJECT
},
4305 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4306 { "force-share", no_argument
, 0, 'U'},
4310 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4322 missing_argument(argv
[optind
- 1]);
4325 unrecognized_option(argv
[optind
- 1]);
4334 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4339 case OPTION_IMAGE_OPTS
:
4345 for (i
= optind
; i
< argc
; i
++) {
4347 arg
= g_strdup(argv
[i
]);
4349 tmp
= strchr(arg
, '=');
4351 error_report("unrecognized operand %s", arg
);
4358 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4359 if (!strcmp(arg
, options
[j
].name
)) {
4363 if (options
[j
].name
== NULL
) {
4364 error_report("unrecognized operand %s", arg
);
4369 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4373 dd
.flags
|= options
[j
].flag
;
4378 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4379 error_report("Must specify both input and output files");
4384 if (qemu_opts_foreach(&qemu_object_opts
,
4385 user_creatable_add_opts_foreach
,
4391 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4399 drv
= bdrv_find_format(out_fmt
);
4401 error_report("Unknown file format");
4405 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4408 error_report_err(local_err
);
4412 if (!drv
->create_opts
) {
4413 error_report("Format driver '%s' does not support image creation",
4418 if (!proto_drv
->create_opts
) {
4419 error_report("Protocol driver '%s' does not support image creation",
4420 proto_drv
->format_name
);
4424 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4425 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4427 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4429 size
= blk_getlength(blk1
);
4431 error_report("Failed to get size for '%s'", in
.filename
);
4436 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4437 dd
.count
* in
.bsz
< size
) {
4438 size
= dd
.count
* in
.bsz
;
4441 /* Overflow means the specified offset is beyond input image's size */
4442 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4443 size
< in
.bsz
* in
.offset
)) {
4444 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4446 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4447 size
- in
.bsz
* in
.offset
, &error_abort
);
4450 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4452 error_reportf_err(local_err
,
4453 "%s: error while creating output image: ",
4459 /* TODO, we can't honour --image-opts for the target,
4460 * since it needs to be given in a format compatible
4461 * with the bdrv_create() call above which does not
4462 * support image-opts style.
4464 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4465 false, false, false);
4472 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4473 size
< in
.offset
* in
.bsz
)) {
4474 /* We give a warning if the skip option is bigger than the input
4475 * size and create an empty output disk image (i.e. like dd(1)).
4477 error_report("%s: cannot skip to specified offset", in
.filename
);
4480 in_pos
= in
.offset
* in
.bsz
;
4483 in
.buf
= g_new(uint8_t, in
.bsz
);
4485 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4486 int in_ret
, out_ret
;
4488 if (in_pos
+ in
.bsz
> size
) {
4489 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4491 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4494 error_report("error while reading from input image file: %s",
4501 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4504 error_report("error while writing to output image file: %s",
4505 strerror(-out_ret
));
4514 qemu_opts_del(opts
);
4515 qemu_opts_free(create_opts
);
4518 g_free(in
.filename
);
4519 g_free(out
.filename
);
4529 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4533 Visitor
*v
= qobject_output_visitor_new(&obj
);
4535 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4536 visit_complete(v
, &obj
);
4537 str
= qobject_to_json_pretty(obj
);
4538 assert(str
!= NULL
);
4539 printf("%s\n", qstring_get_str(str
));
4545 static int img_measure(int argc
, char **argv
)
4547 static const struct option long_options
[] = {
4548 {"help", no_argument
, 0, 'h'},
4549 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4550 {"object", required_argument
, 0, OPTION_OBJECT
},
4551 {"output", required_argument
, 0, OPTION_OUTPUT
},
4552 {"size", required_argument
, 0, OPTION_SIZE
},
4553 {"force-share", no_argument
, 0, 'U'},
4556 OutputFormat output_format
= OFORMAT_HUMAN
;
4557 BlockBackend
*in_blk
= NULL
;
4559 const char *filename
= NULL
;
4560 const char *fmt
= NULL
;
4561 const char *out_fmt
= "raw";
4562 char *options
= NULL
;
4563 char *snapshot_name
= NULL
;
4564 bool force_share
= false;
4565 QemuOpts
*opts
= NULL
;
4566 QemuOpts
*object_opts
= NULL
;
4567 QemuOpts
*sn_opts
= NULL
;
4568 QemuOptsList
*create_opts
= NULL
;
4569 bool image_opts
= false;
4570 uint64_t img_size
= UINT64_MAX
;
4571 BlockMeasureInfo
*info
= NULL
;
4572 Error
*local_err
= NULL
;
4576 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4577 long_options
, NULL
)) != -1) {
4590 if (!is_valid_option_list(optarg
)) {
4591 error_report("Invalid option list: %s", optarg
);
4595 options
= g_strdup(optarg
);
4597 char *old_options
= options
;
4598 options
= g_strdup_printf("%s,%s", options
, optarg
);
4599 g_free(old_options
);
4603 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4604 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4607 error_report("Failed in parsing snapshot param '%s'",
4612 snapshot_name
= optarg
;
4619 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4625 case OPTION_IMAGE_OPTS
:
4629 if (!strcmp(optarg
, "json")) {
4630 output_format
= OFORMAT_JSON
;
4631 } else if (!strcmp(optarg
, "human")) {
4632 output_format
= OFORMAT_HUMAN
;
4634 error_report("--output must be used with human or json "
4643 sval
= cvtnum(optarg
);
4645 if (sval
== -ERANGE
) {
4646 error_report("Image size must be less than 8 EiB!");
4648 error_report("Invalid image size specified! You may use "
4649 "k, M, G, T, P or E suffixes for ");
4650 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4651 "petabytes and exabytes.");
4655 img_size
= (uint64_t)sval
;
4661 if (qemu_opts_foreach(&qemu_object_opts
,
4662 user_creatable_add_opts_foreach
,
4667 if (argc
- optind
> 1) {
4668 error_report("At most one filename argument is allowed.");
4670 } else if (argc
- optind
== 1) {
4671 filename
= argv
[optind
];
4675 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4676 error_report("--object, --image-opts, -f, and -l "
4677 "require a filename argument.");
4680 if (filename
&& img_size
!= UINT64_MAX
) {
4681 error_report("--size N cannot be used together with a filename.");
4684 if (!filename
&& img_size
== UINT64_MAX
) {
4685 error_report("Either --size N or one filename must be specified.");
4690 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4691 false, false, force_share
);
4697 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4698 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4699 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4701 } else if (snapshot_name
!= NULL
) {
4702 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4703 snapshot_name
, &local_err
);
4706 error_reportf_err(local_err
, "Failed to load snapshot: ");
4711 drv
= bdrv_find_format(out_fmt
);
4713 error_report("Unknown file format '%s'", out_fmt
);
4716 if (!drv
->create_opts
) {
4717 error_report("Format driver '%s' does not support image creation",
4722 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4723 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4724 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4726 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4728 error_report_err(local_err
);
4729 error_report("Invalid options for file format '%s'", out_fmt
);
4733 if (img_size
!= UINT64_MAX
) {
4734 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4737 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4739 error_report_err(local_err
);
4743 if (output_format
== OFORMAT_HUMAN
) {
4744 printf("required size: %" PRIu64
"\n", info
->required
);
4745 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4747 dump_json_block_measure_info(info
);
4753 qapi_free_BlockMeasureInfo(info
);
4754 qemu_opts_del(object_opts
);
4755 qemu_opts_del(opts
);
4756 qemu_opts_del(sn_opts
);
4757 qemu_opts_free(create_opts
);
4763 static const img_cmd_t img_cmds
[] = {
4764 #define DEF(option, callback, arg_string) \
4765 { option, callback },
4766 #include "qemu-img-cmds.h"
4771 int main(int argc
, char **argv
)
4773 const img_cmd_t
*cmd
;
4774 const char *cmdname
;
4775 Error
*local_error
= NULL
;
4776 char *trace_file
= NULL
;
4778 static const struct option long_options
[] = {
4779 {"help", no_argument
, 0, 'h'},
4780 {"version", no_argument
, 0, 'V'},
4781 {"trace", required_argument
, NULL
, 'T'},
4786 signal(SIGPIPE
, SIG_IGN
);
4789 module_call_init(MODULE_INIT_TRACE
);
4790 error_set_progname(argv
[0]);
4791 qemu_init_exec_dir(argv
[0]);
4793 if (qemu_init_main_loop(&local_error
)) {
4794 error_report_err(local_error
);
4798 qcrypto_init(&error_fatal
);
4800 module_call_init(MODULE_INIT_QOM
);
4803 error_exit("Not enough arguments");
4806 qemu_add_opts(&qemu_object_opts
);
4807 qemu_add_opts(&qemu_source_opts
);
4808 qemu_add_opts(&qemu_trace_opts
);
4810 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4813 missing_argument(argv
[optind
- 1]);
4816 unrecognized_option(argv
[optind
- 1]);
4822 printf(QEMU_IMG_VERSION
);
4826 trace_file
= trace_opt_parse(optarg
);
4831 cmdname
= argv
[optind
];
4833 /* reset getopt_long scanning */
4841 if (!trace_init_backends()) {
4844 trace_init_file(trace_file
);
4845 qemu_set_log(LOG_TRACE
);
4847 /* find the command */
4848 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4849 if (!strcmp(cmdname
, cmd
->name
)) {
4850 return cmd
->handler(argc
, argv
);
4855 error_exit("Command not found: %s", cmdname
);