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
24 #include "qemu/osdep.h"
27 #include "qemu-version.h"
28 #include "qapi/error.h"
29 #include "qapi-visit.h"
30 #include "qapi/qobject-output-visitor.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qemu/cutils.h"
35 #include "qemu/config-file.h"
36 #include "qemu/option.h"
37 #include "qemu/error-report.h"
39 #include "qom/object_interfaces.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/block-backend.h"
42 #include "block/block_int.h"
43 #include "block/blockjob.h"
44 #include "block/qapi.h"
45 #include "crypto/init.h"
46 #include "trace/control.h"
48 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
49 "\n" QEMU_COPYRIGHT "\n"
51 typedef struct img_cmd_t
{
53 int (*handler
)(int argc
, char **argv
);
58 OPTION_BACKING_CHAIN
= 257,
60 OPTION_IMAGE_OPTS
= 259,
62 OPTION_FLUSH_INTERVAL
= 261,
63 OPTION_NO_DRAIN
= 262,
64 OPTION_TARGET_IMAGE_OPTS
= 263,
66 OPTION_PREALLOCATION
= 265,
70 typedef enum OutputFormat
{
75 /* Default to cache=writeback as data integrity is not important for qemu-img */
76 #define BDRV_DEFAULT_CACHE "writeback"
78 static void format_print(void *opaque
, const char *name
)
83 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
87 error_printf("qemu-img: ");
90 error_vprintf(fmt
, ap
);
93 error_printf("\nTry 'qemu-img --help' for more information\n");
97 static void QEMU_NORETURN
missing_argument(const char *option
)
99 error_exit("missing argument for option '%s'", option
);
102 static void QEMU_NORETURN
unrecognized_option(const char *option
)
104 error_exit("unrecognized option '%s'", option
);
107 /* Please keep in synch with qemu-img.texi */
108 static void QEMU_NORETURN
help(void)
110 const char *help_msg
=
112 "usage: qemu-img [standard options] command [command options]\n"
113 "QEMU disk image utility\n"
115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
121 #define DEF(option, callback, arg_string) \
123 #include "qemu-img-cmds.h"
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 && !qdict_get_bool(options
, BDRV_OPT_FORCE_SHARE
)) {
280 error_report("--force-share/-U conflicts with image options");
284 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
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 aio_poll(aio_context
, true);
867 qemu_progress_print(job
->len
?
868 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
869 } while (!job
->ready
&& !job
->completed
);
871 if (!job
->completed
) {
872 ret
= block_job_complete_sync(job
, errp
);
876 block_job_unref(job
);
877 aio_context_release(aio_context
);
879 /* publish completion progress only when success */
881 qemu_progress_print(100.f
, 0);
885 static int img_commit(int argc
, char **argv
)
888 const char *filename
, *fmt
, *cache
, *base
;
890 BlockDriverState
*bs
, *base_bs
;
892 bool progress
= false, quiet
= false, drop
= false;
894 Error
*local_err
= NULL
;
895 CommonBlockJobCBInfo cbi
;
896 bool image_opts
= false;
897 AioContext
*aio_context
;
900 cache
= BDRV_DEFAULT_CACHE
;
903 static const struct option long_options
[] = {
904 {"help", no_argument
, 0, 'h'},
905 {"object", required_argument
, 0, OPTION_OBJECT
},
906 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
909 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
916 missing_argument(argv
[optind
- 1]);
919 unrecognized_option(argv
[optind
- 1]);
944 case OPTION_OBJECT
: {
946 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
952 case OPTION_IMAGE_OPTS
:
958 /* Progress is not shown in Quiet mode */
963 if (optind
!= argc
- 1) {
964 error_exit("Expecting one image file name");
966 filename
= argv
[optind
++];
968 if (qemu_opts_foreach(&qemu_object_opts
,
969 user_creatable_add_opts_foreach
,
974 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
975 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
977 error_report("Invalid cache option: %s", cache
);
981 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
988 qemu_progress_init(progress
, 1.f
);
989 qemu_progress_print(0.f
, 100);
992 base_bs
= bdrv_find_backing_image(bs
, base
);
994 error_setg(&local_err
,
995 "Did not find '%s' in the backing chain of '%s'",
1000 /* This is different from QMP, which by default uses the deepest file in
1001 * the backing chain (i.e., the very base); however, the traditional
1002 * behavior of qemu-img commit is using the immediate backing file. */
1003 base_bs
= backing_bs(bs
);
1005 error_setg(&local_err
, "Image does not have a backing file");
1010 cbi
= (CommonBlockJobCBInfo
){
1015 aio_context
= bdrv_get_aio_context(bs
);
1016 aio_context_acquire(aio_context
);
1017 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1018 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1019 &cbi
, false, &local_err
);
1020 aio_context_release(aio_context
);
1025 /* When the block job completes, the BlockBackend reference will point to
1026 * the old backing file. In order to avoid that the top image is already
1027 * deleted, so we can still empty it afterwards, increment the reference
1028 * counter here preemptively. */
1033 job
= block_job_get("commit");
1034 run_block_job(job
, &local_err
);
1039 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1040 ret
= bs
->drv
->bdrv_make_empty(bs
);
1042 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1054 qemu_progress_end();
1059 error_report_err(local_err
);
1063 qprintf(quiet
, "Image committed.\n");
1068 * Returns true iff the first sector pointed to by 'buf' contains at least
1071 * 'pnum' is set to the number of sectors (including and immediately following
1072 * the first one) that are known to be in the same allocated/unallocated state.
1074 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1083 is_zero
= buffer_is_zero(buf
, 512);
1084 for(i
= 1; i
< n
; i
++) {
1086 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1095 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1096 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1097 * breaking up write requests for only small sparse areas.
1099 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1103 int num_checked
, num_used
;
1109 ret
= is_allocated_sectors(buf
, n
, pnum
);
1115 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1117 num_checked
= num_used
;
1120 ret
= is_allocated_sectors(buf
, n
, pnum
);
1122 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1124 num_checked
+= *pnum
;
1126 num_used
= num_checked
;
1127 } else if (*pnum
>= min
) {
1137 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1138 * buffers matches, non-zero otherwise.
1140 * pnum is set to the number of sectors (including and immediately following
1141 * the first one) that are known to have the same comparison result
1143 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1154 res
= !!memcmp(buf1
, buf2
, 512);
1155 for(i
= 1; i
< n
; i
++) {
1159 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1168 #define IO_BUF_SIZE (2 * 1024 * 1024)
1170 static int64_t sectors_to_bytes(int64_t sectors
)
1172 return sectors
<< BDRV_SECTOR_BITS
;
1175 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1177 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1181 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1183 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1184 * data and negative value on error.
1186 * @param blk: BlockBackend for the image
1187 * @param sect_num: Number of first sector to check
1188 * @param sect_count: Number of sectors to check
1189 * @param filename: Name of disk file we are checking (logging purpose)
1190 * @param buffer: Allocated buffer for storing read data
1191 * @param quiet: Flag for quiet mode
1193 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1194 int sect_count
, const char *filename
,
1195 uint8_t *buffer
, bool quiet
)
1198 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1199 sect_count
<< BDRV_SECTOR_BITS
);
1201 error_report("Error while reading offset %" PRId64
" of %s: %s",
1202 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1205 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1206 if (ret
|| pnum
!= sect_count
) {
1207 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1208 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1216 * Compares two images. Exit codes:
1218 * 0 - Images are identical
1220 * >1 - Error occurred
1222 static int img_compare(int argc
, char **argv
)
1224 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1225 BlockBackend
*blk1
, *blk2
;
1226 BlockDriverState
*bs1
, *bs2
;
1227 int64_t total_sectors1
, total_sectors2
;
1228 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1230 int allocated1
, allocated2
;
1231 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1232 bool progress
= false, quiet
= false, strict
= false;
1235 int64_t total_sectors
;
1236 int64_t sector_num
= 0;
1239 uint64_t progress_base
;
1240 bool image_opts
= false;
1241 bool force_share
= false;
1243 cache
= BDRV_DEFAULT_CACHE
;
1245 static const struct option long_options
[] = {
1246 {"help", no_argument
, 0, 'h'},
1247 {"object", required_argument
, 0, OPTION_OBJECT
},
1248 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1249 {"force-share", no_argument
, 0, 'U'},
1252 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1253 long_options
, NULL
);
1259 missing_argument(argv
[optind
- 1]);
1262 unrecognized_option(argv
[optind
- 1]);
1288 case OPTION_OBJECT
: {
1290 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1297 case OPTION_IMAGE_OPTS
:
1303 /* Progress is not shown in Quiet mode */
1309 if (optind
!= argc
- 2) {
1310 error_exit("Expecting two image file names");
1312 filename1
= argv
[optind
++];
1313 filename2
= argv
[optind
++];
1315 if (qemu_opts_foreach(&qemu_object_opts
,
1316 user_creatable_add_opts_foreach
,
1322 /* Initialize before goto out */
1323 qemu_progress_init(progress
, 2.0);
1326 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1328 error_report("Invalid source cache option: %s", cache
);
1333 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1340 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1349 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1350 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1351 total_sectors1
= blk_nb_sectors(blk1
);
1352 if (total_sectors1
< 0) {
1353 error_report("Can't get size of %s: %s",
1354 filename1
, strerror(-total_sectors1
));
1358 total_sectors2
= blk_nb_sectors(blk2
);
1359 if (total_sectors2
< 0) {
1360 error_report("Can't get size of %s: %s",
1361 filename2
, strerror(-total_sectors2
));
1365 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1366 progress_base
= MAX(total_sectors1
, total_sectors2
);
1368 qemu_progress_print(0, 100);
1370 if (strict
&& total_sectors1
!= total_sectors2
) {
1372 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1377 int64_t status1
, status2
;
1379 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1380 if (nb_sectors
<= 0) {
1383 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1384 total_sectors1
- sector_num
,
1388 error_report("Sector allocation test failed for %s", filename1
);
1391 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1393 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1394 total_sectors2
- sector_num
,
1398 error_report("Sector allocation test failed for %s", filename2
);
1401 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1403 nb_sectors
= MIN(nb_sectors
, pnum1
);
1406 nb_sectors
= MIN(nb_sectors
, pnum2
);
1410 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1411 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1413 qprintf(quiet
, "Strict mode: Offset %" PRId64
1414 " block status mismatch!\n",
1415 sectors_to_bytes(sector_num
));
1419 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1420 nb_sectors
= MIN(pnum1
, pnum2
);
1421 } else if (allocated1
== allocated2
) {
1423 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1424 nb_sectors
<< BDRV_SECTOR_BITS
);
1426 error_report("Error while reading offset %" PRId64
" of %s:"
1427 " %s", sectors_to_bytes(sector_num
), filename1
,
1432 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1433 nb_sectors
<< BDRV_SECTOR_BITS
);
1435 error_report("Error while reading offset %" PRId64
1436 " of %s: %s", sectors_to_bytes(sector_num
),
1437 filename2
, strerror(-ret
));
1441 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1442 if (ret
|| pnum
!= nb_sectors
) {
1443 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1445 ret
? sector_num
: sector_num
+ pnum
));
1453 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1454 filename1
, buf1
, quiet
);
1456 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1457 filename2
, buf1
, quiet
);
1461 error_report("Error while reading offset %" PRId64
": %s",
1462 sectors_to_bytes(sector_num
), strerror(-ret
));
1468 sector_num
+= nb_sectors
;
1469 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1472 if (total_sectors1
!= total_sectors2
) {
1473 BlockBackend
*blk_over
;
1474 int64_t total_sectors_over
;
1475 const char *filename_over
;
1477 qprintf(quiet
, "Warning: Image size mismatch!\n");
1478 if (total_sectors1
> total_sectors2
) {
1479 total_sectors_over
= total_sectors1
;
1481 filename_over
= filename1
;
1483 total_sectors_over
= total_sectors2
;
1485 filename_over
= filename2
;
1491 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1492 if (nb_sectors
<= 0) {
1495 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
,
1496 sector_num
* BDRV_SECTOR_SIZE
,
1497 nb_sectors
* BDRV_SECTOR_SIZE
,
1501 error_report("Sector allocation test failed for %s",
1506 /* TODO relax this once bdrv_is_allocated_above does not enforce
1507 * sector alignment */
1508 assert(QEMU_IS_ALIGNED(count
, BDRV_SECTOR_SIZE
));
1509 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1511 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1512 filename_over
, buf1
, quiet
);
1515 error_report("Error while reading offset %" PRId64
1516 " of %s: %s", sectors_to_bytes(sector_num
),
1517 filename_over
, strerror(-ret
));
1523 sector_num
+= nb_sectors
;
1524 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1528 qprintf(quiet
, "Images are identical.\n");
1538 qemu_progress_end();
1543 enum ImgConvertBlockStatus
{
1549 #define MAX_COROUTINES 16
1551 typedef struct ImgConvertState
{
1553 int64_t *src_sectors
;
1555 int64_t total_sectors
;
1556 int64_t allocated_sectors
;
1557 int64_t allocated_done
;
1560 enum ImgConvertBlockStatus status
;
1561 int64_t sector_next_status
;
1562 BlockBackend
*target
;
1565 bool target_has_backing
;
1568 size_t cluster_sectors
;
1570 long num_coroutines
;
1571 int running_coroutines
;
1572 Coroutine
*co
[MAX_COROUTINES
];
1573 int64_t wait_sector_num
[MAX_COROUTINES
];
1578 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1579 int *src_cur
, int64_t *src_cur_offset
)
1582 *src_cur_offset
= 0;
1583 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1584 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1586 assert(*src_cur
< s
->src_num
);
1590 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1592 int64_t ret
, src_cur_offset
;
1595 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1597 assert(s
->total_sectors
> sector_num
);
1598 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1600 if (s
->sector_next_status
<= sector_num
) {
1601 if (s
->target_has_backing
) {
1602 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1603 sector_num
- src_cur_offset
,
1606 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1607 sector_num
- src_cur_offset
,
1614 if (ret
& BDRV_BLOCK_ZERO
) {
1615 s
->status
= BLK_ZERO
;
1616 } else if (ret
& BDRV_BLOCK_DATA
) {
1617 s
->status
= BLK_DATA
;
1619 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1622 s
->sector_next_status
= sector_num
+ n
;
1625 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1626 if (s
->status
== BLK_DATA
) {
1627 n
= MIN(n
, s
->buf_sectors
);
1630 /* We need to write complete clusters for compressed images, so if an
1631 * unallocated area is shorter than that, we must consider the whole
1632 * cluster allocated. */
1633 if (s
->compressed
) {
1634 if (n
< s
->cluster_sectors
) {
1635 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1636 s
->status
= BLK_DATA
;
1638 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1645 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1646 int nb_sectors
, uint8_t *buf
)
1652 assert(nb_sectors
<= s
->buf_sectors
);
1653 while (nb_sectors
> 0) {
1656 int64_t bs_sectors
, src_cur_offset
;
1658 /* In the case of compression with multiple source files, we can get a
1659 * nb_sectors that spreads into the next part. So we must be able to
1660 * read across multiple BDSes for one convert_read() call. */
1661 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1662 blk
= s
->src
[src_cur
];
1663 bs_sectors
= s
->src_sectors
[src_cur
];
1665 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1667 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1668 qemu_iovec_init_external(&qiov
, &iov
, 1);
1670 ret
= blk_co_preadv(
1671 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1672 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1679 buf
+= n
* BDRV_SECTOR_SIZE
;
1686 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1687 int nb_sectors
, uint8_t *buf
,
1688 enum ImgConvertBlockStatus status
)
1694 while (nb_sectors
> 0) {
1696 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1699 case BLK_BACKING_FILE
:
1700 /* If we have a backing file, leave clusters unallocated that are
1701 * unallocated in the source image, so that the backing file is
1702 * visible at the respective offset. */
1703 assert(s
->target_has_backing
);
1707 /* If we're told to keep the target fully allocated (-S 0) or there
1708 * is real non-zero data, we must write it. Otherwise we can treat
1709 * it as zero sectors.
1710 * Compressed clusters need to be written as a whole, so in that
1711 * case we can only save the write if the buffer is completely
1713 if (!s
->min_sparse
||
1715 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1717 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1720 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1721 qemu_iovec_init_external(&qiov
, &iov
, 1);
1723 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1724 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1733 if (s
->has_zero_init
) {
1734 assert(!s
->target_has_backing
);
1737 ret
= blk_co_pwrite_zeroes(s
->target
,
1738 sector_num
<< BDRV_SECTOR_BITS
,
1739 n
<< BDRV_SECTOR_BITS
, 0);
1748 buf
+= n
* BDRV_SECTOR_SIZE
;
1754 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1756 ImgConvertState
*s
= opaque
;
1757 uint8_t *buf
= NULL
;
1761 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1762 if (s
->co
[i
] == qemu_coroutine_self()) {
1769 s
->running_coroutines
++;
1770 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1775 enum ImgConvertBlockStatus status
;
1777 qemu_co_mutex_lock(&s
->lock
);
1778 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1779 qemu_co_mutex_unlock(&s
->lock
);
1782 n
= convert_iteration_sectors(s
, s
->sector_num
);
1784 qemu_co_mutex_unlock(&s
->lock
);
1788 /* save current sector and allocation status to local variables */
1789 sector_num
= s
->sector_num
;
1791 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1792 n
= MIN(n
, s
->buf_sectors
);
1794 /* increment global sector counter so that other coroutines can
1795 * already continue reading beyond this request */
1797 qemu_co_mutex_unlock(&s
->lock
);
1799 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1800 s
->allocated_done
+= n
;
1801 qemu_progress_print(100.0 * s
->allocated_done
/
1802 s
->allocated_sectors
, 0);
1805 if (status
== BLK_DATA
) {
1806 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1808 error_report("error while reading sector %" PRId64
1809 ": %s", sector_num
, strerror(-ret
));
1812 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1814 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1817 if (s
->wr_in_order
) {
1818 /* keep writes in order */
1819 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1820 s
->wait_sector_num
[index
] = sector_num
;
1821 qemu_coroutine_yield();
1823 s
->wait_sector_num
[index
] = -1;
1826 if (s
->ret
== -EINPROGRESS
) {
1827 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1829 error_report("error while writing sector %" PRId64
1830 ": %s", sector_num
, strerror(-ret
));
1835 if (s
->wr_in_order
) {
1836 /* reenter the coroutine that might have waited
1837 * for this write to complete */
1838 s
->wr_offs
= sector_num
+ n
;
1839 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1840 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1842 * A -> B -> A cannot occur because A has
1843 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1844 * B will never enter A during this time window.
1846 qemu_coroutine_enter(s
->co
[i
]);
1854 s
->co
[index
] = NULL
;
1855 s
->running_coroutines
--;
1856 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1857 /* the convert job finished successfully */
1862 static int convert_do_copy(ImgConvertState
*s
)
1865 int64_t sector_num
= 0;
1867 /* Check whether we have zero initialisation or can get it efficiently */
1868 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1869 ? bdrv_has_zero_init(blk_bs(s
->target
))
1872 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1873 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1875 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1877 s
->has_zero_init
= true;
1881 /* Allocate buffer for copied data. For compressed images, only one cluster
1882 * can be copied at a time. */
1883 if (s
->compressed
) {
1884 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1885 error_report("invalid cluster size");
1888 s
->buf_sectors
= s
->cluster_sectors
;
1891 while (sector_num
< s
->total_sectors
) {
1892 n
= convert_iteration_sectors(s
, sector_num
);
1896 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1898 s
->allocated_sectors
+= n
;
1904 s
->sector_next_status
= 0;
1905 s
->ret
= -EINPROGRESS
;
1907 qemu_co_mutex_init(&s
->lock
);
1908 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1909 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1910 s
->wait_sector_num
[i
] = -1;
1911 qemu_coroutine_enter(s
->co
[i
]);
1914 while (s
->running_coroutines
) {
1915 main_loop_wait(false);
1918 if (s
->compressed
&& !s
->ret
) {
1919 /* signal EOF to align */
1920 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1929 static int img_convert(int argc
, char **argv
)
1931 int c
, bs_i
, flags
, src_flags
= 0;
1932 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1933 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1934 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1935 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1936 BlockDriverInfo bdi
;
1937 BlockDriverState
*out_bs
;
1938 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1939 QemuOptsList
*create_opts
= NULL
;
1940 char *options
= NULL
;
1941 Error
*local_err
= NULL
;
1942 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1943 skip_create
= false, progress
= false, tgt_image_opts
= false;
1944 int64_t ret
= -EINVAL
;
1945 bool force_share
= false;
1947 ImgConvertState s
= (ImgConvertState
) {
1948 /* Need at least 4k of zeros for sparse detection */
1950 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1951 .wr_in_order
= true,
1952 .num_coroutines
= 8,
1956 static const struct option long_options
[] = {
1957 {"help", no_argument
, 0, 'h'},
1958 {"object", required_argument
, 0, OPTION_OBJECT
},
1959 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1960 {"force-share", no_argument
, 0, 'U'},
1961 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1964 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1965 long_options
, NULL
);
1971 missing_argument(argv
[optind
- 1]);
1974 unrecognized_option(argv
[optind
- 1]);
1986 out_baseimg
= optarg
;
1989 s
.compressed
= true;
1992 if (!is_valid_option_list(optarg
)) {
1993 error_report("Invalid option list: %s", optarg
);
1997 options
= g_strdup(optarg
);
1999 char *old_options
= options
;
2000 options
= g_strdup_printf("%s,%s", options
, optarg
);
2001 g_free(old_options
);
2005 snapshot_name
= optarg
;
2008 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2009 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2012 error_report("Failed in parsing snapshot param '%s'",
2017 snapshot_name
= optarg
;
2024 sval
= cvtnum(optarg
);
2026 error_report("Invalid minimum zero buffer size for sparse output specified");
2030 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2049 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2050 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2051 error_report("Invalid number of coroutines. Allowed number of"
2052 " coroutines is between 1 and %d", MAX_COROUTINES
);
2057 s
.wr_in_order
= false;
2062 case OPTION_OBJECT
: {
2063 QemuOpts
*object_opts
;
2064 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2071 case OPTION_IMAGE_OPTS
:
2074 case OPTION_TARGET_IMAGE_OPTS
:
2075 tgt_image_opts
= true;
2080 if (!out_fmt
&& !tgt_image_opts
) {
2084 if (qemu_opts_foreach(&qemu_object_opts
,
2085 user_creatable_add_opts_foreach
,
2090 if (!s
.wr_in_order
&& s
.compressed
) {
2091 error_report("Out of order write and compress are mutually exclusive");
2095 if (tgt_image_opts
&& !skip_create
) {
2096 error_report("--target-image-opts requires use of -n flag");
2100 s
.src_num
= argc
- optind
- 1;
2101 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2103 if (options
&& has_help_option(options
)) {
2105 ret
= print_block_option_help(out_filename
, out_fmt
);
2108 error_report("Option help requires a format be specified");
2113 if (s
.src_num
< 1) {
2114 error_report("Must specify image file name");
2119 /* ret is still -EINVAL until here */
2120 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2122 error_report("Invalid source cache option: %s", src_cache
);
2126 /* Initialize before goto out */
2130 qemu_progress_init(progress
, 1.0);
2131 qemu_progress_print(0, 100);
2133 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2134 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2136 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2137 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2138 fmt
, src_flags
, src_writethrough
, quiet
,
2144 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2145 if (s
.src_sectors
[bs_i
] < 0) {
2146 error_report("Could not get size of %s: %s",
2147 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2151 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2155 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2156 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2157 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2159 } else if (snapshot_name
!= NULL
) {
2160 if (s
.src_num
> 1) {
2161 error_report("No support for concatenating multiple snapshot");
2166 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2170 error_reportf_err(local_err
, "Failed to load snapshot: ");
2176 /* Find driver and parse its options */
2177 drv
= bdrv_find_format(out_fmt
);
2179 error_report("Unknown file format '%s'", out_fmt
);
2184 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2186 error_report_err(local_err
);
2191 if (!drv
->create_opts
) {
2192 error_report("Format driver '%s' does not support image creation",
2198 if (!proto_drv
->create_opts
) {
2199 error_report("Protocol driver '%s' does not support image creation",
2200 proto_drv
->format_name
);
2205 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2206 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2208 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2210 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2212 error_report_err(local_err
);
2218 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2220 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2226 /* Get backing file name if -o backing_file was used */
2227 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2228 if (out_baseimg_param
) {
2229 out_baseimg
= out_baseimg_param
;
2231 s
.target_has_backing
= (bool) out_baseimg
;
2233 if (s
.src_num
> 1 && out_baseimg
) {
2234 error_report("Having a backing file for the target makes no sense when "
2235 "concatenating multiple input images");
2240 /* Check if compression is supported */
2243 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2244 const char *encryptfmt
=
2245 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2246 const char *preallocation
=
2247 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2249 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2250 error_report("Compression not supported for this file format");
2255 if (encryption
|| encryptfmt
) {
2256 error_report("Compression and encryption not supported at "
2263 && strcmp(preallocation
, "off"))
2265 error_report("Compression and preallocation not supported at "
2273 /* Create the new image */
2274 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2276 error_reportf_err(local_err
, "%s: error while converting %s: ",
2277 out_filename
, out_fmt
);
2282 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2283 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2285 error_report("Invalid cache option: %s", cache
);
2290 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2291 flags
, writethrough
, quiet
, false);
2293 /* TODO ultimately we should allow --target-image-opts
2294 * to be used even when -n is not given.
2295 * That has to wait for bdrv_create to be improved
2296 * to allow filenames in option syntax
2298 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2299 flags
, writethrough
, quiet
, false);
2305 out_bs
= blk_bs(s
.target
);
2307 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2308 error_report("Compression not supported for this file format");
2313 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2314 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2316 s
.buf_sectors
= MIN(32768,
2318 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2319 out_bs
->bl
.pdiscard_alignment
>>
2320 BDRV_SECTOR_BITS
)));
2323 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2324 if (output_sectors
< 0) {
2325 error_report("unable to get output image length: %s",
2326 strerror(-output_sectors
));
2329 } else if (output_sectors
< s
.total_sectors
) {
2330 error_report("output file is smaller than input file");
2336 ret
= bdrv_get_info(out_bs
, &bdi
);
2339 error_report("could not get block driver info");
2343 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2344 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2347 ret
= convert_do_copy(&s
);
2350 qemu_progress_print(100, 0);
2352 qemu_progress_end();
2353 qemu_opts_del(opts
);
2354 qemu_opts_free(create_opts
);
2355 qemu_opts_del(sn_opts
);
2356 blk_unref(s
.target
);
2358 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2359 blk_unref(s
.src
[bs_i
]);
2363 g_free(s
.src_sectors
);
2371 static void dump_snapshots(BlockDriverState
*bs
)
2373 QEMUSnapshotInfo
*sn_tab
, *sn
;
2376 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2379 printf("Snapshot list:\n");
2380 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2382 for(i
= 0; i
< nb_sns
; i
++) {
2384 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2390 static void dump_json_image_info_list(ImageInfoList
*list
)
2394 Visitor
*v
= qobject_output_visitor_new(&obj
);
2396 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2397 visit_complete(v
, &obj
);
2398 str
= qobject_to_json_pretty(obj
);
2399 assert(str
!= NULL
);
2400 printf("%s\n", qstring_get_str(str
));
2401 qobject_decref(obj
);
2406 static void dump_json_image_info(ImageInfo
*info
)
2410 Visitor
*v
= qobject_output_visitor_new(&obj
);
2412 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2413 visit_complete(v
, &obj
);
2414 str
= qobject_to_json_pretty(obj
);
2415 assert(str
!= NULL
);
2416 printf("%s\n", qstring_get_str(str
));
2417 qobject_decref(obj
);
2422 static void dump_human_image_info_list(ImageInfoList
*list
)
2424 ImageInfoList
*elem
;
2427 for (elem
= list
; elem
; elem
= elem
->next
) {
2433 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2437 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2439 return strcmp(a
, b
) == 0;
2443 * Open an image file chain and return an ImageInfoList
2445 * @filename: topmost image filename
2446 * @fmt: topmost image format (may be NULL to autodetect)
2447 * @chain: true - enumerate entire backing file chain
2448 * false - only topmost image file
2450 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2451 * image file. If there was an error a message will have been printed to
2454 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2455 const char *filename
,
2457 bool chain
, bool force_share
)
2459 ImageInfoList
*head
= NULL
;
2460 ImageInfoList
**last
= &head
;
2461 GHashTable
*filenames
;
2464 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2468 BlockDriverState
*bs
;
2470 ImageInfoList
*elem
;
2472 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2473 error_report("Backing file '%s' creates an infinite loop.",
2477 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2479 blk
= img_open(image_opts
, filename
, fmt
,
2480 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2487 bdrv_query_image_info(bs
, &info
, &err
);
2489 error_report_err(err
);
2494 elem
= g_new0(ImageInfoList
, 1);
2501 filename
= fmt
= NULL
;
2503 if (info
->has_full_backing_filename
) {
2504 filename
= info
->full_backing_filename
;
2505 } else if (info
->has_backing_filename
) {
2506 error_report("Could not determine absolute backing filename,"
2507 " but backing filename '%s' present",
2508 info
->backing_filename
);
2511 if (info
->has_backing_filename_format
) {
2512 fmt
= info
->backing_filename_format
;
2516 g_hash_table_destroy(filenames
);
2520 qapi_free_ImageInfoList(head
);
2521 g_hash_table_destroy(filenames
);
2525 static int img_info(int argc
, char **argv
)
2528 OutputFormat output_format
= OFORMAT_HUMAN
;
2530 const char *filename
, *fmt
, *output
;
2531 ImageInfoList
*list
;
2532 bool image_opts
= false;
2533 bool force_share
= false;
2538 int option_index
= 0;
2539 static const struct option long_options
[] = {
2540 {"help", no_argument
, 0, 'h'},
2541 {"format", required_argument
, 0, 'f'},
2542 {"output", required_argument
, 0, OPTION_OUTPUT
},
2543 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2544 {"object", required_argument
, 0, OPTION_OBJECT
},
2545 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2546 {"force-share", no_argument
, 0, 'U'},
2549 c
= getopt_long(argc
, argv
, ":f:hU",
2550 long_options
, &option_index
);
2556 missing_argument(argv
[optind
- 1]);
2559 unrecognized_option(argv
[optind
- 1]);
2573 case OPTION_BACKING_CHAIN
:
2576 case OPTION_OBJECT
: {
2578 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2584 case OPTION_IMAGE_OPTS
:
2589 if (optind
!= argc
- 1) {
2590 error_exit("Expecting one image file name");
2592 filename
= argv
[optind
++];
2594 if (output
&& !strcmp(output
, "json")) {
2595 output_format
= OFORMAT_JSON
;
2596 } else if (output
&& !strcmp(output
, "human")) {
2597 output_format
= OFORMAT_HUMAN
;
2598 } else if (output
) {
2599 error_report("--output must be used with human or json as argument.");
2603 if (qemu_opts_foreach(&qemu_object_opts
,
2604 user_creatable_add_opts_foreach
,
2609 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2615 switch (output_format
) {
2617 dump_human_image_info_list(list
);
2621 dump_json_image_info_list(list
);
2623 dump_json_image_info(list
->value
);
2628 qapi_free_ImageInfoList(list
);
2632 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2635 switch (output_format
) {
2637 if (e
->data
&& !e
->has_offset
) {
2638 error_report("File contains external, encrypted or compressed clusters.");
2641 if (e
->data
&& !e
->zero
) {
2642 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2643 e
->start
, e
->length
,
2644 e
->has_offset
? e
->offset
: 0,
2645 e
->has_filename
? e
->filename
: "");
2647 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2648 * Modify the flags here to allow more coalescing.
2650 if (next
&& (!next
->data
|| next
->zero
)) {
2656 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2657 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2658 (e
->start
== 0 ? "[" : ",\n"),
2659 e
->start
, e
->length
, e
->depth
,
2660 e
->zero
? "true" : "false",
2661 e
->data
? "true" : "false");
2662 if (e
->has_offset
) {
2663 printf(", \"offset\": %"PRId64
"", e
->offset
);
2674 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2675 int64_t bytes
, MapEntry
*e
)
2679 BlockDriverState
*file
;
2681 int nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
2683 assert(bytes
< INT_MAX
);
2684 /* As an optimization, we could cache the current range of unallocated
2685 * clusters in each file of the chain, and avoid querying the same
2691 ret
= bdrv_get_block_status(bs
, offset
>> BDRV_SECTOR_BITS
, nb_sectors
,
2692 &nb_sectors
, &file
);
2697 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2700 bs
= backing_bs(bs
);
2709 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2713 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2714 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2715 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2716 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2717 .has_offset
= has_offset
,
2719 .has_filename
= file
&& has_offset
,
2720 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2726 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2728 if (curr
->length
== 0) {
2731 if (curr
->zero
!= next
->zero
||
2732 curr
->data
!= next
->data
||
2733 curr
->depth
!= next
->depth
||
2734 curr
->has_filename
!= next
->has_filename
||
2735 curr
->has_offset
!= next
->has_offset
) {
2738 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2741 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2747 static int img_map(int argc
, char **argv
)
2750 OutputFormat output_format
= OFORMAT_HUMAN
;
2752 BlockDriverState
*bs
;
2753 const char *filename
, *fmt
, *output
;
2755 MapEntry curr
= { .length
= 0 }, next
;
2757 bool image_opts
= false;
2758 bool force_share
= false;
2763 int option_index
= 0;
2764 static const struct option long_options
[] = {
2765 {"help", no_argument
, 0, 'h'},
2766 {"format", required_argument
, 0, 'f'},
2767 {"output", required_argument
, 0, OPTION_OUTPUT
},
2768 {"object", required_argument
, 0, OPTION_OBJECT
},
2769 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2770 {"force-share", no_argument
, 0, 'U'},
2773 c
= getopt_long(argc
, argv
, ":f:hU",
2774 long_options
, &option_index
);
2780 missing_argument(argv
[optind
- 1]);
2783 unrecognized_option(argv
[optind
- 1]);
2797 case OPTION_OBJECT
: {
2799 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2805 case OPTION_IMAGE_OPTS
:
2810 if (optind
!= argc
- 1) {
2811 error_exit("Expecting one image file name");
2813 filename
= argv
[optind
];
2815 if (output
&& !strcmp(output
, "json")) {
2816 output_format
= OFORMAT_JSON
;
2817 } else if (output
&& !strcmp(output
, "human")) {
2818 output_format
= OFORMAT_HUMAN
;
2819 } else if (output
) {
2820 error_report("--output must be used with human or json as argument.");
2824 if (qemu_opts_foreach(&qemu_object_opts
,
2825 user_creatable_add_opts_foreach
,
2830 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2836 if (output_format
== OFORMAT_HUMAN
) {
2837 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2840 length
= blk_getlength(blk
);
2841 while (curr
.start
+ curr
.length
< length
) {
2842 int64_t offset
= curr
.start
+ curr
.length
;
2845 /* Probe up to 1 GiB at a time. */
2846 n
= QEMU_ALIGN_DOWN(MIN(1 << 30, length
- offset
), BDRV_SECTOR_SIZE
);
2847 ret
= get_block_status(bs
, offset
, n
, &next
);
2850 error_report("Could not read file metadata: %s", strerror(-ret
));
2854 if (entry_mergeable(&curr
, &next
)) {
2855 curr
.length
+= next
.length
;
2859 if (curr
.length
> 0) {
2860 dump_map_entry(output_format
, &curr
, &next
);
2865 dump_map_entry(output_format
, &curr
, NULL
);
2872 #define SNAPSHOT_LIST 1
2873 #define SNAPSHOT_CREATE 2
2874 #define SNAPSHOT_APPLY 3
2875 #define SNAPSHOT_DELETE 4
2877 static int img_snapshot(int argc
, char **argv
)
2880 BlockDriverState
*bs
;
2881 QEMUSnapshotInfo sn
;
2882 char *filename
, *snapshot_name
= NULL
;
2883 int c
, ret
= 0, bdrv_oflags
;
2888 bool image_opts
= false;
2889 bool force_share
= false;
2891 bdrv_oflags
= BDRV_O_RDWR
;
2892 /* Parse commandline parameters */
2894 static const struct option long_options
[] = {
2895 {"help", no_argument
, 0, 'h'},
2896 {"object", required_argument
, 0, OPTION_OBJECT
},
2897 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2898 {"force-share", no_argument
, 0, 'U'},
2901 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2902 long_options
, NULL
);
2908 missing_argument(argv
[optind
- 1]);
2911 unrecognized_option(argv
[optind
- 1]);
2918 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2921 action
= SNAPSHOT_LIST
;
2922 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2926 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2929 action
= SNAPSHOT_APPLY
;
2930 snapshot_name
= optarg
;
2934 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2937 action
= SNAPSHOT_CREATE
;
2938 snapshot_name
= optarg
;
2942 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2945 action
= SNAPSHOT_DELETE
;
2946 snapshot_name
= optarg
;
2954 case OPTION_OBJECT
: {
2956 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2962 case OPTION_IMAGE_OPTS
:
2968 if (optind
!= argc
- 1) {
2969 error_exit("Expecting one image file name");
2971 filename
= argv
[optind
++];
2973 if (qemu_opts_foreach(&qemu_object_opts
,
2974 user_creatable_add_opts_foreach
,
2979 /* Open the image */
2980 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
2987 /* Perform the requested action */
2993 case SNAPSHOT_CREATE
:
2994 memset(&sn
, 0, sizeof(sn
));
2995 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2997 qemu_gettimeofday(&tv
);
2998 sn
.date_sec
= tv
.tv_sec
;
2999 sn
.date_nsec
= tv
.tv_usec
* 1000;
3001 ret
= bdrv_snapshot_create(bs
, &sn
);
3003 error_report("Could not create snapshot '%s': %d (%s)",
3004 snapshot_name
, ret
, strerror(-ret
));
3008 case SNAPSHOT_APPLY
:
3009 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
3011 error_report("Could not apply snapshot '%s': %d (%s)",
3012 snapshot_name
, ret
, strerror(-ret
));
3016 case SNAPSHOT_DELETE
:
3017 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3019 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3034 static int img_rebase(int argc
, char **argv
)
3036 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3037 uint8_t *buf_old
= NULL
;
3038 uint8_t *buf_new
= NULL
;
3039 BlockDriverState
*bs
= NULL
;
3041 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3042 int c
, flags
, src_flags
, ret
;
3043 bool writethrough
, src_writethrough
;
3045 bool force_share
= false;
3048 Error
*local_err
= NULL
;
3049 bool image_opts
= false;
3051 /* Parse commandline parameters */
3053 cache
= BDRV_DEFAULT_CACHE
;
3054 src_cache
= BDRV_DEFAULT_CACHE
;
3058 static const struct option long_options
[] = {
3059 {"help", no_argument
, 0, 'h'},
3060 {"object", required_argument
, 0, OPTION_OBJECT
},
3061 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3062 {"force-share", no_argument
, 0, 'U'},
3065 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3066 long_options
, NULL
);
3072 missing_argument(argv
[optind
- 1]);
3075 unrecognized_option(argv
[optind
- 1]);
3084 out_basefmt
= optarg
;
3087 out_baseimg
= optarg
;
3104 case OPTION_OBJECT
: {
3106 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3112 case OPTION_IMAGE_OPTS
:
3125 if (optind
!= argc
- 1) {
3126 error_exit("Expecting one image file name");
3128 if (!unsafe
&& !out_baseimg
) {
3129 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3131 filename
= argv
[optind
++];
3133 if (qemu_opts_foreach(&qemu_object_opts
,
3134 user_creatable_add_opts_foreach
,
3139 qemu_progress_init(progress
, 2.0);
3140 qemu_progress_print(0, 100);
3142 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3143 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3145 error_report("Invalid cache option: %s", cache
);
3150 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3152 error_report("Invalid source cache option: %s", src_cache
);
3156 /* The source files are opened read-only, don't care about WCE */
3157 assert((src_flags
& BDRV_O_RDWR
) == 0);
3158 (void) src_writethrough
;
3163 * Ignore the old backing file for unsafe rebase in case we want to correct
3164 * the reference to a renamed or moved backing file.
3166 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3174 if (out_basefmt
!= NULL
) {
3175 if (bdrv_find_format(out_basefmt
) == NULL
) {
3176 error_report("Invalid format name: '%s'", out_basefmt
);
3182 /* For safe rebasing we need to compare old and new backing file */
3184 char backing_name
[PATH_MAX
];
3185 QDict
*options
= NULL
;
3187 if (bs
->backing_format
[0] != '\0') {
3188 options
= qdict_new();
3189 qdict_put_str(options
, "driver", bs
->backing_format
);
3194 options
= qdict_new();
3196 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3198 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3199 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3200 options
, src_flags
, &local_err
);
3201 if (!blk_old_backing
) {
3202 error_reportf_err(local_err
,
3203 "Could not open old backing file '%s': ",
3209 if (out_baseimg
[0]) {
3210 options
= qdict_new();
3212 qdict_put_str(options
, "driver", out_basefmt
);
3215 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3218 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3219 options
, src_flags
, &local_err
);
3220 if (!blk_new_backing
) {
3221 error_reportf_err(local_err
,
3222 "Could not open new backing file '%s': ",
3231 * Check each unallocated cluster in the COW file. If it is unallocated,
3232 * accesses go to the backing file. We must therefore compare this cluster
3233 * in the old and new backing file, and if they differ we need to copy it
3234 * from the old backing file into the COW file.
3236 * If qemu-img crashes during this step, no harm is done. The content of
3237 * the image is the same as the original one at any time.
3240 int64_t num_sectors
;
3241 int64_t old_backing_num_sectors
;
3242 int64_t new_backing_num_sectors
= 0;
3246 float local_progress
= 0;
3248 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3249 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3251 num_sectors
= blk_nb_sectors(blk
);
3252 if (num_sectors
< 0) {
3253 error_report("Could not get size of '%s': %s",
3254 filename
, strerror(-num_sectors
));
3258 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
3259 if (old_backing_num_sectors
< 0) {
3260 char backing_name
[PATH_MAX
];
3262 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3263 error_report("Could not get size of '%s': %s",
3264 backing_name
, strerror(-old_backing_num_sectors
));
3268 if (blk_new_backing
) {
3269 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3270 if (new_backing_num_sectors
< 0) {
3271 error_report("Could not get size of '%s': %s",
3272 out_baseimg
, strerror(-new_backing_num_sectors
));
3278 if (num_sectors
!= 0) {
3279 local_progress
= (float)100 /
3280 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3283 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3285 /* How many sectors can we handle with the next read? */
3286 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3287 n
= (IO_BUF_SIZE
/ 512);
3289 n
= num_sectors
- sector
;
3292 /* If the cluster is allocated, we don't need to take action */
3293 ret
= bdrv_is_allocated(bs
, sector
<< BDRV_SECTOR_BITS
,
3294 n
<< BDRV_SECTOR_BITS
, &count
);
3296 error_report("error while reading image metadata: %s",
3300 /* TODO relax this once bdrv_is_allocated does not enforce
3301 * sector alignment */
3302 assert(QEMU_IS_ALIGNED(count
, BDRV_SECTOR_SIZE
));
3303 n
= count
>> BDRV_SECTOR_BITS
;
3309 * Read old and new backing file and take into consideration that
3310 * backing files may be smaller than the COW image.
3312 if (sector
>= old_backing_num_sectors
) {
3313 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3315 if (sector
+ n
> old_backing_num_sectors
) {
3316 n
= old_backing_num_sectors
- sector
;
3319 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3320 buf_old
, n
<< BDRV_SECTOR_BITS
);
3322 error_report("error while reading from old backing file");
3327 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3328 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3330 if (sector
+ n
> new_backing_num_sectors
) {
3331 n
= new_backing_num_sectors
- sector
;
3334 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3335 buf_new
, n
<< BDRV_SECTOR_BITS
);
3337 error_report("error while reading from new backing file");
3342 /* If they differ, we need to write to the COW file */
3343 uint64_t written
= 0;
3345 while (written
< n
) {
3348 if (compare_sectors(buf_old
+ written
* 512,
3349 buf_new
+ written
* 512, n
- written
, &pnum
))
3351 ret
= blk_pwrite(blk
,
3352 (sector
+ written
) << BDRV_SECTOR_BITS
,
3353 buf_old
+ written
* 512,
3354 pnum
<< BDRV_SECTOR_BITS
, 0);
3356 error_report("Error while writing to COW image: %s",
3364 qemu_progress_print(local_progress
, 100);
3369 * Change the backing file. All clusters that are different from the old
3370 * backing file are overwritten in the COW file now, so the visible content
3371 * doesn't change when we switch the backing file.
3373 if (out_baseimg
&& *out_baseimg
) {
3374 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3376 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3379 if (ret
== -ENOSPC
) {
3380 error_report("Could not change the backing file to '%s': No "
3381 "space left in the file header", out_baseimg
);
3382 } else if (ret
< 0) {
3383 error_report("Could not change the backing file to '%s': %s",
3384 out_baseimg
, strerror(-ret
));
3387 qemu_progress_print(100, 0);
3389 * TODO At this point it is possible to check if any clusters that are
3390 * allocated in the COW file are the same in the backing file. If so, they
3391 * could be dropped from the COW file. Don't do this before switching the
3392 * backing file, in case of a crash this would lead to corruption.
3395 qemu_progress_end();
3398 blk_unref(blk_old_backing
);
3399 blk_unref(blk_new_backing
);
3401 qemu_vfree(buf_old
);
3402 qemu_vfree(buf_new
);
3411 static int img_resize(int argc
, char **argv
)
3414 int c
, ret
, relative
;
3415 const char *filename
, *fmt
, *size
;
3416 int64_t n
, total_size
, current_size
;
3418 BlockBackend
*blk
= NULL
;
3419 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3422 static QemuOptsList resize_options
= {
3423 .name
= "resize_options",
3424 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3427 .name
= BLOCK_OPT_SIZE
,
3428 .type
= QEMU_OPT_SIZE
,
3429 .help
= "Virtual disk size"
3435 bool image_opts
= false;
3436 bool shrink
= false;
3438 /* Remove size from argv manually so that negative numbers are not treated
3439 * as options by getopt. */
3441 error_exit("Not enough arguments");
3445 size
= argv
[--argc
];
3447 /* Parse getopt arguments */
3450 static const struct option long_options
[] = {
3451 {"help", no_argument
, 0, 'h'},
3452 {"object", required_argument
, 0, OPTION_OBJECT
},
3453 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3454 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3455 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3458 c
= getopt_long(argc
, argv
, ":f:hq",
3459 long_options
, NULL
);
3465 missing_argument(argv
[optind
- 1]);
3468 unrecognized_option(argv
[optind
- 1]);
3479 case OPTION_OBJECT
: {
3481 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3487 case OPTION_IMAGE_OPTS
:
3490 case OPTION_PREALLOCATION
:
3491 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3492 PREALLOC_MODE__MAX
, NULL
);
3493 if (prealloc
== PREALLOC_MODE__MAX
) {
3494 error_report("Invalid preallocation mode '%s'", optarg
);
3503 if (optind
!= argc
- 1) {
3504 error_exit("Expecting one image file name");
3506 filename
= argv
[optind
++];
3508 if (qemu_opts_foreach(&qemu_object_opts
,
3509 user_creatable_add_opts_foreach
,
3514 /* Choose grow, shrink, or absolute resize mode */
3530 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3531 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3533 error_report_err(err
);
3535 qemu_opts_del(param
);
3538 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3539 qemu_opts_del(param
);
3541 blk
= img_open(image_opts
, filename
, fmt
,
3542 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3549 current_size
= blk_getlength(blk
);
3550 if (current_size
< 0) {
3551 error_report("Failed to inquire current image length: %s",
3552 strerror(-current_size
));
3558 total_size
= current_size
+ n
* relative
;
3562 if (total_size
<= 0) {
3563 error_report("New image size must be positive");
3568 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3569 error_report("Preallocation can only be used for growing images");
3574 if (total_size
< current_size
&& !shrink
) {
3575 warn_report("Shrinking an image will delete all data beyond the "
3576 "shrunken image's end. Before performing such an "
3577 "operation, make sure there is no important data there.");
3579 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3581 "Use the --shrink option to perform a shrink operation.");
3585 warn_report("Using the --shrink option will suppress this message. "
3586 "Note that future versions of qemu-img may refuse to "
3587 "shrink images without this option.");
3591 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3593 qprintf(quiet
, "Image resized.\n");
3595 error_report_err(err
);
3605 static void amend_status_cb(BlockDriverState
*bs
,
3606 int64_t offset
, int64_t total_work_size
,
3609 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3612 static int img_amend(int argc
, char **argv
)
3616 char *options
= NULL
;
3617 QemuOptsList
*create_opts
= NULL
;
3618 QemuOpts
*opts
= NULL
;
3619 const char *fmt
= NULL
, *filename
, *cache
;
3622 bool quiet
= false, progress
= false;
3623 BlockBackend
*blk
= NULL
;
3624 BlockDriverState
*bs
= NULL
;
3625 bool image_opts
= false;
3627 cache
= BDRV_DEFAULT_CACHE
;
3629 static const struct option long_options
[] = {
3630 {"help", no_argument
, 0, 'h'},
3631 {"object", required_argument
, 0, OPTION_OBJECT
},
3632 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3635 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3636 long_options
, NULL
);
3643 missing_argument(argv
[optind
- 1]);
3646 unrecognized_option(argv
[optind
- 1]);
3652 if (!is_valid_option_list(optarg
)) {
3653 error_report("Invalid option list: %s", optarg
);
3655 goto out_no_progress
;
3658 options
= g_strdup(optarg
);
3660 char *old_options
= options
;
3661 options
= g_strdup_printf("%s,%s", options
, optarg
);
3662 g_free(old_options
);
3678 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3682 goto out_no_progress
;
3685 case OPTION_IMAGE_OPTS
:
3692 error_exit("Must specify options (-o)");
3695 if (qemu_opts_foreach(&qemu_object_opts
,
3696 user_creatable_add_opts_foreach
,
3699 goto out_no_progress
;
3705 qemu_progress_init(progress
, 1.0);
3707 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3708 if (fmt
&& has_help_option(options
)) {
3709 /* If a format is explicitly specified (and possibly no filename is
3710 * given), print option help here */
3711 ret
= print_block_option_help(filename
, fmt
);
3715 if (optind
!= argc
- 1) {
3716 error_report("Expecting one image file name");
3721 flags
= BDRV_O_RDWR
;
3722 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3724 error_report("Invalid cache option: %s", cache
);
3728 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3736 fmt
= bs
->drv
->format_name
;
3738 if (has_help_option(options
)) {
3739 /* If the format was auto-detected, print option help here */
3740 ret
= print_block_option_help(filename
, fmt
);
3744 if (!bs
->drv
->create_opts
) {
3745 error_report("Format driver '%s' does not support any options to amend",
3751 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3752 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3753 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3755 error_report_err(err
);
3760 /* In case the driver does not call amend_status_cb() */
3761 qemu_progress_print(0.f
, 0);
3762 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3763 qemu_progress_print(100.f
, 0);
3765 error_report("Error while amending options: %s", strerror(-ret
));
3770 qemu_progress_end();
3774 qemu_opts_del(opts
);
3775 qemu_opts_free(create_opts
);
3784 typedef struct BenchData
{
3786 uint64_t image_size
;
3793 bool drain_on_flush
;
3802 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3805 error_report("Failed flush request: %s", strerror(-ret
));
3810 static void bench_cb(void *opaque
, int ret
)
3812 BenchData
*b
= opaque
;
3816 error_report("Failed request: %s", strerror(-ret
));
3821 /* Just finished a flush with drained queue: Start next requests */
3822 assert(b
->in_flight
== 0);
3823 b
->in_flush
= false;
3824 } else if (b
->in_flight
> 0) {
3825 int remaining
= b
->n
- b
->in_flight
;
3830 /* Time for flush? Drain queue if requested, then flush */
3831 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3832 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3833 BlockCompletionFunc
*cb
;
3835 if (b
->drain_on_flush
) {
3839 cb
= bench_undrained_flush_cb
;
3842 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3844 error_report("Failed to issue flush request");
3848 if (b
->drain_on_flush
) {
3854 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3855 int64_t offset
= b
->offset
;
3856 /* blk_aio_* might look for completed I/Os and kick bench_cb
3857 * again, so make sure this operation is counted by in_flight
3858 * and b->offset is ready for the next submission.
3861 b
->offset
+= b
->step
;
3862 b
->offset
%= b
->image_size
;
3864 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3866 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3869 error_report("Failed to issue request");
3875 static int img_bench(int argc
, char **argv
)
3878 const char *fmt
= NULL
, *filename
;
3880 bool image_opts
= false;
3881 bool is_write
= false;
3885 size_t bufsize
= 4096;
3888 int flush_interval
= 0;
3889 bool drain_on_flush
= true;
3891 BlockBackend
*blk
= NULL
;
3892 BenchData data
= {};
3894 bool writethrough
= false;
3895 struct timeval t1
, t2
;
3897 bool force_share
= false;
3900 static const struct option long_options
[] = {
3901 {"help", no_argument
, 0, 'h'},
3902 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3903 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3904 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3905 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3906 {"force-share", no_argument
, 0, 'U'},
3909 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3916 missing_argument(argv
[optind
- 1]);
3919 unrecognized_option(argv
[optind
- 1]);
3928 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3929 error_report("Invalid request count specified");
3939 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3940 error_report("Invalid queue depth specified");
3950 flags
|= BDRV_O_NATIVE_AIO
;
3954 offset
= cvtnum(optarg
);
3956 error_report("Invalid offset specified");
3969 sval
= cvtnum(optarg
);
3970 if (sval
< 0 || sval
> INT_MAX
) {
3971 error_report("Invalid buffer size specified");
3982 sval
= cvtnum(optarg
);
3983 if (sval
< 0 || sval
> INT_MAX
) {
3984 error_report("Invalid step size specified");
3992 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3994 error_report("Invalid cache mode");
4000 flags
|= BDRV_O_RDWR
;
4006 case OPTION_PATTERN
:
4010 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4011 error_report("Invalid pattern byte specified");
4017 case OPTION_FLUSH_INTERVAL
:
4021 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4022 error_report("Invalid flush interval specified");
4025 flush_interval
= res
;
4028 case OPTION_NO_DRAIN
:
4029 drain_on_flush
= false;
4031 case OPTION_IMAGE_OPTS
:
4037 if (optind
!= argc
- 1) {
4038 error_exit("Expecting one image file name");
4040 filename
= argv
[argc
- 1];
4042 if (!is_write
&& flush_interval
) {
4043 error_report("--flush-interval is only available in write tests");
4047 if (flush_interval
&& flush_interval
< depth
) {
4048 error_report("Flush interval can't be smaller than depth");
4053 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4060 image_size
= blk_getlength(blk
);
4061 if (image_size
< 0) {
4066 data
= (BenchData
) {
4068 .image_size
= image_size
,
4070 .step
= step
?: bufsize
,
4075 .flush_interval
= flush_interval
,
4076 .drain_on_flush
= drain_on_flush
,
4078 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4079 "(starting at offset %" PRId64
", step size %d)\n",
4080 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4081 data
.offset
, data
.step
);
4082 if (flush_interval
) {
4083 printf("Sending flush every %d requests\n", flush_interval
);
4086 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
4087 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4089 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4090 for (i
= 0; i
< data
.nrreq
; i
++) {
4091 qemu_iovec_init(&data
.qiov
[i
], 1);
4092 qemu_iovec_add(&data
.qiov
[i
],
4093 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4096 gettimeofday(&t1
, NULL
);
4099 while (data
.n
> 0) {
4100 main_loop_wait(false);
4102 gettimeofday(&t2
, NULL
);
4104 printf("Run completed in %3.3f seconds.\n",
4105 (t2
.tv_sec
- t1
.tv_sec
)
4106 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4109 qemu_vfree(data
.buf
);
4130 int bsz
; /* Block size */
4138 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4142 static int img_dd_bs(const char *arg
,
4143 struct DdIo
*in
, struct DdIo
*out
,
4150 if (res
<= 0 || res
> INT_MAX
) {
4151 error_report("invalid number: '%s'", arg
);
4154 in
->bsz
= out
->bsz
= res
;
4159 static int img_dd_count(const char *arg
,
4160 struct DdIo
*in
, struct DdIo
*out
,
4163 dd
->count
= cvtnum(arg
);
4165 if (dd
->count
< 0) {
4166 error_report("invalid number: '%s'", arg
);
4173 static int img_dd_if(const char *arg
,
4174 struct DdIo
*in
, struct DdIo
*out
,
4177 in
->filename
= g_strdup(arg
);
4182 static int img_dd_of(const char *arg
,
4183 struct DdIo
*in
, struct DdIo
*out
,
4186 out
->filename
= g_strdup(arg
);
4191 static int img_dd_skip(const char *arg
,
4192 struct DdIo
*in
, struct DdIo
*out
,
4195 in
->offset
= cvtnum(arg
);
4197 if (in
->offset
< 0) {
4198 error_report("invalid number: '%s'", arg
);
4205 static int img_dd(int argc
, char **argv
)
4210 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4211 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4212 QemuOpts
*opts
= NULL
;
4213 QemuOptsList
*create_opts
= NULL
;
4214 Error
*local_err
= NULL
;
4215 bool image_opts
= false;
4217 const char *out_fmt
= "raw";
4218 const char *fmt
= NULL
;
4220 int64_t block_count
= 0, out_pos
, in_pos
;
4221 bool force_share
= false;
4222 struct DdInfo dd
= {
4227 .bsz
= 512, /* Block size is by default 512 bytes */
4239 const struct DdOpts options
[] = {
4240 { "bs", img_dd_bs
, C_BS
},
4241 { "count", img_dd_count
, C_COUNT
},
4242 { "if", img_dd_if
, C_IF
},
4243 { "of", img_dd_of
, C_OF
},
4244 { "skip", img_dd_skip
, C_SKIP
},
4247 const struct option long_options
[] = {
4248 { "help", no_argument
, 0, 'h'},
4249 { "object", required_argument
, 0, OPTION_OBJECT
},
4250 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4251 { "force-share", no_argument
, 0, 'U'},
4255 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4267 missing_argument(argv
[optind
- 1]);
4270 unrecognized_option(argv
[optind
- 1]);
4279 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4284 case OPTION_IMAGE_OPTS
:
4290 for (i
= optind
; i
< argc
; i
++) {
4292 arg
= g_strdup(argv
[i
]);
4294 tmp
= strchr(arg
, '=');
4296 error_report("unrecognized operand %s", arg
);
4303 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4304 if (!strcmp(arg
, options
[j
].name
)) {
4308 if (options
[j
].name
== NULL
) {
4309 error_report("unrecognized operand %s", arg
);
4314 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4318 dd
.flags
|= options
[j
].flag
;
4323 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4324 error_report("Must specify both input and output files");
4329 if (qemu_opts_foreach(&qemu_object_opts
,
4330 user_creatable_add_opts_foreach
,
4336 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4344 drv
= bdrv_find_format(out_fmt
);
4346 error_report("Unknown file format");
4350 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4353 error_report_err(local_err
);
4357 if (!drv
->create_opts
) {
4358 error_report("Format driver '%s' does not support image creation",
4363 if (!proto_drv
->create_opts
) {
4364 error_report("Protocol driver '%s' does not support image creation",
4365 proto_drv
->format_name
);
4369 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4370 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4372 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4374 size
= blk_getlength(blk1
);
4376 error_report("Failed to get size for '%s'", in
.filename
);
4381 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4382 dd
.count
* in
.bsz
< size
) {
4383 size
= dd
.count
* in
.bsz
;
4386 /* Overflow means the specified offset is beyond input image's size */
4387 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4388 size
< in
.bsz
* in
.offset
)) {
4389 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4391 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4392 size
- in
.bsz
* in
.offset
, &error_abort
);
4395 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4397 error_reportf_err(local_err
,
4398 "%s: error while creating output image: ",
4404 /* TODO, we can't honour --image-opts for the target,
4405 * since it needs to be given in a format compatible
4406 * with the bdrv_create() call above which does not
4407 * support image-opts style.
4409 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4410 false, false, false);
4417 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4418 size
< in
.offset
* in
.bsz
)) {
4419 /* We give a warning if the skip option is bigger than the input
4420 * size and create an empty output disk image (i.e. like dd(1)).
4422 error_report("%s: cannot skip to specified offset", in
.filename
);
4425 in_pos
= in
.offset
* in
.bsz
;
4428 in
.buf
= g_new(uint8_t, in
.bsz
);
4430 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4431 int in_ret
, out_ret
;
4433 if (in_pos
+ in
.bsz
> size
) {
4434 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4436 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4439 error_report("error while reading from input image file: %s",
4446 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4449 error_report("error while writing to output image file: %s",
4450 strerror(-out_ret
));
4459 qemu_opts_del(opts
);
4460 qemu_opts_free(create_opts
);
4463 g_free(in
.filename
);
4464 g_free(out
.filename
);
4474 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4478 Visitor
*v
= qobject_output_visitor_new(&obj
);
4480 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4481 visit_complete(v
, &obj
);
4482 str
= qobject_to_json_pretty(obj
);
4483 assert(str
!= NULL
);
4484 printf("%s\n", qstring_get_str(str
));
4485 qobject_decref(obj
);
4490 static int img_measure(int argc
, char **argv
)
4492 static const struct option long_options
[] = {
4493 {"help", no_argument
, 0, 'h'},
4494 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4495 {"object", required_argument
, 0, OPTION_OBJECT
},
4496 {"output", required_argument
, 0, OPTION_OUTPUT
},
4497 {"size", required_argument
, 0, OPTION_SIZE
},
4498 {"force-share", no_argument
, 0, 'U'},
4501 OutputFormat output_format
= OFORMAT_HUMAN
;
4502 BlockBackend
*in_blk
= NULL
;
4504 const char *filename
= NULL
;
4505 const char *fmt
= NULL
;
4506 const char *out_fmt
= "raw";
4507 char *options
= NULL
;
4508 char *snapshot_name
= NULL
;
4509 bool force_share
= false;
4510 QemuOpts
*opts
= NULL
;
4511 QemuOpts
*object_opts
= NULL
;
4512 QemuOpts
*sn_opts
= NULL
;
4513 QemuOptsList
*create_opts
= NULL
;
4514 bool image_opts
= false;
4515 uint64_t img_size
= UINT64_MAX
;
4516 BlockMeasureInfo
*info
= NULL
;
4517 Error
*local_err
= NULL
;
4521 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4522 long_options
, NULL
)) != -1) {
4535 if (!is_valid_option_list(optarg
)) {
4536 error_report("Invalid option list: %s", optarg
);
4540 options
= g_strdup(optarg
);
4542 char *old_options
= options
;
4543 options
= g_strdup_printf("%s,%s", options
, optarg
);
4544 g_free(old_options
);
4548 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4549 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4552 error_report("Failed in parsing snapshot param '%s'",
4557 snapshot_name
= optarg
;
4564 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4570 case OPTION_IMAGE_OPTS
:
4574 if (!strcmp(optarg
, "json")) {
4575 output_format
= OFORMAT_JSON
;
4576 } else if (!strcmp(optarg
, "human")) {
4577 output_format
= OFORMAT_HUMAN
;
4579 error_report("--output must be used with human or json "
4588 sval
= cvtnum(optarg
);
4590 if (sval
== -ERANGE
) {
4591 error_report("Image size must be less than 8 EiB!");
4593 error_report("Invalid image size specified! You may use "
4594 "k, M, G, T, P or E suffixes for ");
4595 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4596 "petabytes and exabytes.");
4600 img_size
= (uint64_t)sval
;
4606 if (qemu_opts_foreach(&qemu_object_opts
,
4607 user_creatable_add_opts_foreach
,
4612 if (argc
- optind
> 1) {
4613 error_report("At most one filename argument is allowed.");
4615 } else if (argc
- optind
== 1) {
4616 filename
= argv
[optind
];
4620 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4621 error_report("--object, --image-opts, -f, and -l "
4622 "require a filename argument.");
4625 if (filename
&& img_size
!= UINT64_MAX
) {
4626 error_report("--size N cannot be used together with a filename.");
4629 if (!filename
&& img_size
== UINT64_MAX
) {
4630 error_report("Either --size N or one filename must be specified.");
4635 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4636 false, false, force_share
);
4642 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4643 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4644 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4646 } else if (snapshot_name
!= NULL
) {
4647 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4648 snapshot_name
, &local_err
);
4651 error_reportf_err(local_err
, "Failed to load snapshot: ");
4656 drv
= bdrv_find_format(out_fmt
);
4658 error_report("Unknown file format '%s'", out_fmt
);
4661 if (!drv
->create_opts
) {
4662 error_report("Format driver '%s' does not support image creation",
4667 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4668 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4669 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4671 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4673 error_report_err(local_err
);
4674 error_report("Invalid options for file format '%s'", out_fmt
);
4678 if (img_size
!= UINT64_MAX
) {
4679 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4682 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4684 error_report_err(local_err
);
4688 if (output_format
== OFORMAT_HUMAN
) {
4689 printf("required size: %" PRIu64
"\n", info
->required
);
4690 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4692 dump_json_block_measure_info(info
);
4698 qapi_free_BlockMeasureInfo(info
);
4699 qemu_opts_del(object_opts
);
4700 qemu_opts_del(opts
);
4701 qemu_opts_del(sn_opts
);
4702 qemu_opts_free(create_opts
);
4708 static const img_cmd_t img_cmds
[] = {
4709 #define DEF(option, callback, arg_string) \
4710 { option, callback },
4711 #include "qemu-img-cmds.h"
4717 int main(int argc
, char **argv
)
4719 const img_cmd_t
*cmd
;
4720 const char *cmdname
;
4721 Error
*local_error
= NULL
;
4722 char *trace_file
= NULL
;
4724 static const struct option long_options
[] = {
4725 {"help", no_argument
, 0, 'h'},
4726 {"version", no_argument
, 0, 'V'},
4727 {"trace", required_argument
, NULL
, 'T'},
4732 signal(SIGPIPE
, SIG_IGN
);
4735 module_call_init(MODULE_INIT_TRACE
);
4736 error_set_progname(argv
[0]);
4737 qemu_init_exec_dir(argv
[0]);
4739 if (qemu_init_main_loop(&local_error
)) {
4740 error_report_err(local_error
);
4744 qcrypto_init(&error_fatal
);
4746 module_call_init(MODULE_INIT_QOM
);
4749 error_exit("Not enough arguments");
4752 qemu_add_opts(&qemu_object_opts
);
4753 qemu_add_opts(&qemu_source_opts
);
4754 qemu_add_opts(&qemu_trace_opts
);
4756 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4759 missing_argument(argv
[optind
- 1]);
4762 unrecognized_option(argv
[optind
- 1]);
4768 printf(QEMU_IMG_VERSION
);
4772 trace_file
= trace_opt_parse(optarg
);
4777 cmdname
= argv
[optind
];
4779 /* reset getopt_long scanning */
4787 if (!trace_init_backends()) {
4790 trace_init_file(trace_file
);
4791 qemu_set_log(LOG_TRACE
);
4793 /* find the command */
4794 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4795 if (!strcmp(cmdname
, cmd
->name
)) {
4796 return cmd
->handler(argc
, argv
);
4801 error_exit("Command not found: %s", cmdname
);