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,
69 typedef enum OutputFormat
{
74 /* Default to cache=writeback as data integrity is not important for qemu-img */
75 #define BDRV_DEFAULT_CACHE "writeback"
77 static void format_print(void *opaque
, const char *name
)
82 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
86 error_printf("qemu-img: ");
89 error_vprintf(fmt
, ap
);
92 error_printf("\nTry 'qemu-img --help' for more information\n");
96 static void QEMU_NORETURN
missing_argument(const char *option
)
98 error_exit("missing argument for option '%s'", option
);
101 static void QEMU_NORETURN
unrecognized_option(const char *option
)
103 error_exit("unrecognized option '%s'", option
);
106 /* Please keep in synch with qemu-img.texi */
107 static void QEMU_NORETURN
help(void)
109 const char *help_msg
=
111 "usage: qemu-img [standard options] command [command options]\n"
112 "QEMU disk image utility\n"
114 " '-h', '--help' display this help and exit\n"
115 " '-V', '--version' output version information and exit\n"
116 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
117 " specify tracing options\n"
120 #define DEF(option, callback, arg_string) \
122 #include "qemu-img-cmds.h"
126 "Command parameters:\n"
127 " 'filename' is a disk image filename\n"
128 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
129 " manual page for a description of the object properties. The most common\n"
130 " object type is a 'secret', which is used to supply passwords and/or\n"
131 " encryption keys.\n"
132 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
133 " 'cache' is the cache mode used to write the output disk image, the valid\n"
134 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
135 " 'directsync' and 'unsafe' (default for convert)\n"
136 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
137 " options are the same as for the 'cache' option\n"
138 " 'size' is the disk image size in bytes. Optional suffixes\n"
139 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
140 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
141 " supported. 'b' is ignored.\n"
142 " 'output_filename' is the destination disk image filename\n"
143 " 'output_fmt' is the destination format\n"
144 " 'options' is a comma separated list of format specific options in a\n"
145 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " 'snapshot_param' is param used for internal snapshot, format\n"
148 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
152 " '-c' indicates that target image must be compressed (qcow format only)\n"
153 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
154 " new backing file match exactly. The image doesn't need a working\n"
155 " backing file before rebasing in this case (useful for renaming the\n"
156 " backing file). For image creation, allow creating without attempting\n"
157 " to open the backing file.\n"
158 " '-h' with or without a command shows this help and lists the supported formats\n"
159 " '-p' show progress of command (only certain commands)\n"
160 " '-q' use Quiet mode - do not print any output (except errors)\n"
161 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
162 " contain only zeros for qemu-img to create a sparse image during\n"
163 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
164 " unallocated or zero sectors, and the destination image will always be\n"
166 " '--output' takes the format in which the output must be done (human or json)\n"
167 " '-n' skips the target volume creation (useful if the volume is created\n"
168 " prior to running qemu-img)\n"
170 "Parameters to check subcommand:\n"
171 " '-r' tries to repair any inconsistencies that are found during the check.\n"
172 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
173 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
174 " hiding corruption that has already occurred.\n"
176 "Parameters to convert subcommand:\n"
177 " '-m' specifies how many coroutines work in parallel during the convert\n"
178 " process (defaults to 8)\n"
179 " '-W' allow to write to the target out of order rather than sequential\n"
181 "Parameters to snapshot subcommand:\n"
182 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
183 " '-a' applies a snapshot (revert disk to saved state)\n"
184 " '-c' creates a snapshot\n"
185 " '-d' deletes a snapshot\n"
186 " '-l' lists all snapshots in the given image\n"
188 "Parameters to compare subcommand:\n"
189 " '-f' first image format\n"
190 " '-F' second image format\n"
191 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "Parameters to dd subcommand:\n"
194 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 " 'count=N' copy only N input blocks\n"
197 " 'if=FILE' read from FILE\n"
198 " 'of=FILE' write to FILE\n"
199 " 'skip=N' skip N bs-sized blocks at the start of input\n";
201 printf("%s\nSupported formats:", help_msg
);
202 bdrv_iterate_format(format_print
, NULL
);
203 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
207 static QemuOptsList qemu_object_opts
= {
209 .implied_opt_name
= "qom-type",
210 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
216 static QemuOptsList qemu_source_opts
= {
218 .implied_opt_name
= "file",
219 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
225 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
231 ret
= vprintf(fmt
, args
);
238 static int print_block_option_help(const char *filename
, const char *fmt
)
240 BlockDriver
*drv
, *proto_drv
;
241 QemuOptsList
*create_opts
= NULL
;
242 Error
*local_err
= NULL
;
244 /* Find driver and parse its options */
245 drv
= bdrv_find_format(fmt
);
247 error_report("Unknown file format '%s'", fmt
);
251 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
253 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
255 error_report_err(local_err
);
256 qemu_opts_free(create_opts
);
259 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
262 qemu_opts_print_help(create_opts
);
263 qemu_opts_free(create_opts
);
268 static BlockBackend
*img_open_opts(const char *optstr
,
269 QemuOpts
*opts
, int flags
, bool writethrough
,
270 bool quiet
, bool force_share
)
273 Error
*local_err
= NULL
;
275 options
= qemu_opts_to_qdict(opts
, NULL
);
277 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
278 && !qdict_get_bool(options
, BDRV_OPT_FORCE_SHARE
)) {
279 error_report("--force-share/-U conflicts with image options");
283 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
285 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
287 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
290 blk_set_enable_write_cache(blk
, !writethrough
);
295 static BlockBackend
*img_open_file(const char *filename
,
297 const char *fmt
, int flags
,
298 bool writethrough
, bool quiet
,
302 Error
*local_err
= NULL
;
305 options
= qdict_new();
308 qdict_put_str(options
, "driver", fmt
);
312 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
314 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
316 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
319 blk_set_enable_write_cache(blk
, !writethrough
);
325 static int img_add_key_secrets(void *opaque
,
326 const char *name
, const char *value
,
329 QDict
*options
= opaque
;
331 if (g_str_has_suffix(name
, "key-secret")) {
332 qdict_put_str(options
, name
, value
);
338 static BlockBackend
*img_open_new_file(const char *filename
,
339 QemuOpts
*create_opts
,
340 const char *fmt
, int flags
,
341 bool writethrough
, bool quiet
,
344 QDict
*options
= NULL
;
346 options
= qdict_new();
347 qemu_opt_foreach(create_opts
, img_add_key_secrets
, options
, &error_abort
);
349 return img_open_file(filename
, options
, fmt
, flags
, writethrough
, quiet
,
354 static BlockBackend
*img_open(bool image_opts
,
355 const char *filename
,
356 const char *fmt
, int flags
, bool writethrough
,
357 bool quiet
, bool force_share
)
363 error_report("--image-opts and --format are mutually exclusive");
366 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
371 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
374 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
381 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
382 const char *base_filename
,
383 const char *base_fmt
)
388 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
390 error_report("Backing file not supported for file format '%s'",
397 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
399 error_report("Backing file format not supported for file "
408 static int64_t cvtnum(const char *s
)
413 err
= qemu_strtosz(s
, NULL
, &value
);
417 if (value
> INT64_MAX
) {
423 static int img_create(int argc
, char **argv
)
426 uint64_t img_size
= -1;
427 const char *fmt
= "raw";
428 const char *base_fmt
= NULL
;
429 const char *filename
;
430 const char *base_filename
= NULL
;
431 char *options
= NULL
;
432 Error
*local_err
= NULL
;
437 static const struct option long_options
[] = {
438 {"help", no_argument
, 0, 'h'},
439 {"object", required_argument
, 0, OPTION_OBJECT
},
442 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
449 missing_argument(argv
[optind
- 1]);
452 unrecognized_option(argv
[optind
- 1]);
461 base_filename
= optarg
;
467 if (!is_valid_option_list(optarg
)) {
468 error_report("Invalid option list: %s", optarg
);
472 options
= g_strdup(optarg
);
474 char *old_options
= options
;
475 options
= g_strdup_printf("%s,%s", options
, optarg
);
483 flags
|= BDRV_O_NO_BACKING
;
485 case OPTION_OBJECT
: {
487 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
496 /* Get the filename */
497 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
498 if (options
&& has_help_option(options
)) {
500 return print_block_option_help(filename
, fmt
);
503 if (optind
>= argc
) {
504 error_exit("Expecting image file name");
508 if (qemu_opts_foreach(&qemu_object_opts
,
509 user_creatable_add_opts_foreach
,
514 /* Get image size, if specified */
518 sval
= cvtnum(argv
[optind
++]);
520 if (sval
== -ERANGE
) {
521 error_report("Image size must be less than 8 EiB!");
523 error_report("Invalid image size specified! You may use k, M, "
524 "G, T, P or E suffixes for ");
525 error_report("kilobytes, megabytes, gigabytes, terabytes, "
526 "petabytes and exabytes.");
530 img_size
= (uint64_t)sval
;
532 if (optind
!= argc
) {
533 error_exit("Unexpected argument: %s", argv
[optind
]);
536 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
537 options
, img_size
, flags
, quiet
, &local_err
);
539 error_reportf_err(local_err
, "%s: ", filename
);
551 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
555 Visitor
*v
= qobject_output_visitor_new(&obj
);
557 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
558 visit_complete(v
, &obj
);
559 str
= qobject_to_json_pretty(obj
);
561 qprintf(quiet
, "%s\n", qstring_get_str(str
));
567 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
569 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
570 qprintf(quiet
, "No errors were found on the image.\n");
572 if (check
->corruptions
) {
573 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
574 "Data may be corrupted, or further writes to the image "
581 "\n%" PRId64
" leaked clusters were found on the image.\n"
582 "This means waste of disk space, but no harm to data.\n",
586 if (check
->check_errors
) {
589 " internal errors have occurred during the check.\n",
590 check
->check_errors
);
594 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
595 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
596 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
597 check
->allocated_clusters
, check
->total_clusters
,
598 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
599 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
600 check
->compressed_clusters
* 100.0 /
601 check
->allocated_clusters
);
604 if (check
->image_end_offset
) {
606 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
610 static int collect_image_check(BlockDriverState
*bs
,
612 const char *filename
,
617 BdrvCheckResult result
;
619 ret
= bdrv_check(bs
, &result
, fix
);
624 check
->filename
= g_strdup(filename
);
625 check
->format
= g_strdup(bdrv_get_format_name(bs
));
626 check
->check_errors
= result
.check_errors
;
627 check
->corruptions
= result
.corruptions
;
628 check
->has_corruptions
= result
.corruptions
!= 0;
629 check
->leaks
= result
.leaks
;
630 check
->has_leaks
= result
.leaks
!= 0;
631 check
->corruptions_fixed
= result
.corruptions_fixed
;
632 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
633 check
->leaks_fixed
= result
.leaks_fixed
;
634 check
->has_leaks_fixed
= result
.leaks
!= 0;
635 check
->image_end_offset
= result
.image_end_offset
;
636 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
637 check
->total_clusters
= result
.bfi
.total_clusters
;
638 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
639 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
640 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
641 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
642 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
643 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
644 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
650 * Checks an image for consistency. Exit codes:
652 * 0 - Check completed, image is good
653 * 1 - Check not completed because of internal errors
654 * 2 - Check completed, image is corrupted
655 * 3 - Check completed, image has leaked clusters, but is good otherwise
656 * 63 - Checks are not supported by the image format
658 static int img_check(int argc
, char **argv
)
661 OutputFormat output_format
= OFORMAT_HUMAN
;
662 const char *filename
, *fmt
, *output
, *cache
;
664 BlockDriverState
*bs
;
666 int flags
= BDRV_O_CHECK
;
670 bool image_opts
= false;
671 bool force_share
= false;
675 cache
= BDRV_DEFAULT_CACHE
;
678 int option_index
= 0;
679 static const struct option long_options
[] = {
680 {"help", no_argument
, 0, 'h'},
681 {"format", required_argument
, 0, 'f'},
682 {"repair", required_argument
, 0, 'r'},
683 {"output", required_argument
, 0, OPTION_OUTPUT
},
684 {"object", required_argument
, 0, OPTION_OBJECT
},
685 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
686 {"force-share", no_argument
, 0, 'U'},
689 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
690 long_options
, &option_index
);
696 missing_argument(argv
[optind
- 1]);
699 unrecognized_option(argv
[optind
- 1]);
708 flags
|= BDRV_O_RDWR
;
710 if (!strcmp(optarg
, "leaks")) {
711 fix
= BDRV_FIX_LEAKS
;
712 } else if (!strcmp(optarg
, "all")) {
713 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
715 error_exit("Unknown option value for -r "
716 "(expecting 'leaks' or 'all'): %s", optarg
);
731 case OPTION_OBJECT
: {
733 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
739 case OPTION_IMAGE_OPTS
:
744 if (optind
!= argc
- 1) {
745 error_exit("Expecting one image file name");
747 filename
= argv
[optind
++];
749 if (output
&& !strcmp(output
, "json")) {
750 output_format
= OFORMAT_JSON
;
751 } else if (output
&& !strcmp(output
, "human")) {
752 output_format
= OFORMAT_HUMAN
;
754 error_report("--output must be used with human or json as argument.");
758 if (qemu_opts_foreach(&qemu_object_opts
,
759 user_creatable_add_opts_foreach
,
764 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
766 error_report("Invalid source cache option: %s", cache
);
770 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
777 check
= g_new0(ImageCheck
, 1);
778 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
780 if (ret
== -ENOTSUP
) {
781 error_report("This image format does not support checks");
786 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
787 int corruptions_fixed
, leaks_fixed
;
789 leaks_fixed
= check
->leaks_fixed
;
790 corruptions_fixed
= check
->corruptions_fixed
;
792 if (output_format
== OFORMAT_HUMAN
) {
794 "The following inconsistencies were found and repaired:\n\n"
795 " %" PRId64
" leaked clusters\n"
796 " %" PRId64
" corruptions\n\n"
797 "Double checking the fixed image now...\n",
799 check
->corruptions_fixed
);
802 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
804 check
->leaks_fixed
= leaks_fixed
;
805 check
->corruptions_fixed
= corruptions_fixed
;
809 switch (output_format
) {
811 dump_human_image_check(check
, quiet
);
814 dump_json_image_check(check
, quiet
);
819 if (ret
|| check
->check_errors
) {
821 error_report("Check failed: %s", strerror(-ret
));
823 error_report("Check failed");
829 if (check
->corruptions
) {
831 } else if (check
->leaks
) {
838 qapi_free_ImageCheck(check
);
843 typedef struct CommonBlockJobCBInfo
{
844 BlockDriverState
*bs
;
846 } CommonBlockJobCBInfo
;
848 static void common_block_job_cb(void *opaque
, int ret
)
850 CommonBlockJobCBInfo
*cbi
= opaque
;
853 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
857 static void run_block_job(BlockJob
*job
, Error
**errp
)
859 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
862 aio_context_acquire(aio_context
);
865 aio_poll(aio_context
, true);
866 qemu_progress_print(job
->len
?
867 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
868 } while (!job
->ready
&& !job
->completed
);
870 if (!job
->completed
) {
871 ret
= block_job_complete_sync(job
, errp
);
875 block_job_unref(job
);
876 aio_context_release(aio_context
);
878 /* publish completion progress only when success */
880 qemu_progress_print(100.f
, 0);
884 static int img_commit(int argc
, char **argv
)
887 const char *filename
, *fmt
, *cache
, *base
;
889 BlockDriverState
*bs
, *base_bs
;
891 bool progress
= false, quiet
= false, drop
= false;
893 Error
*local_err
= NULL
;
894 CommonBlockJobCBInfo cbi
;
895 bool image_opts
= false;
896 AioContext
*aio_context
;
899 cache
= BDRV_DEFAULT_CACHE
;
902 static const struct option long_options
[] = {
903 {"help", no_argument
, 0, 'h'},
904 {"object", required_argument
, 0, OPTION_OBJECT
},
905 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
908 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
915 missing_argument(argv
[optind
- 1]);
918 unrecognized_option(argv
[optind
- 1]);
943 case OPTION_OBJECT
: {
945 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
951 case OPTION_IMAGE_OPTS
:
957 /* Progress is not shown in Quiet mode */
962 if (optind
!= argc
- 1) {
963 error_exit("Expecting one image file name");
965 filename
= argv
[optind
++];
967 if (qemu_opts_foreach(&qemu_object_opts
,
968 user_creatable_add_opts_foreach
,
973 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
974 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
976 error_report("Invalid cache option: %s", cache
);
980 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
987 qemu_progress_init(progress
, 1.f
);
988 qemu_progress_print(0.f
, 100);
991 base_bs
= bdrv_find_backing_image(bs
, base
);
993 error_setg(&local_err
,
994 "Did not find '%s' in the backing chain of '%s'",
999 /* This is different from QMP, which by default uses the deepest file in
1000 * the backing chain (i.e., the very base); however, the traditional
1001 * behavior of qemu-img commit is using the immediate backing file. */
1002 base_bs
= backing_bs(bs
);
1004 error_setg(&local_err
, "Image does not have a backing file");
1009 cbi
= (CommonBlockJobCBInfo
){
1014 aio_context
= bdrv_get_aio_context(bs
);
1015 aio_context_acquire(aio_context
);
1016 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1017 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1018 &cbi
, false, &local_err
);
1019 aio_context_release(aio_context
);
1024 /* When the block job completes, the BlockBackend reference will point to
1025 * the old backing file. In order to avoid that the top image is already
1026 * deleted, so we can still empty it afterwards, increment the reference
1027 * counter here preemptively. */
1032 job
= block_job_get("commit");
1033 run_block_job(job
, &local_err
);
1038 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1039 ret
= bs
->drv
->bdrv_make_empty(bs
);
1041 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1053 qemu_progress_end();
1058 error_report_err(local_err
);
1062 qprintf(quiet
, "Image committed.\n");
1067 * Returns true iff the first sector pointed to by 'buf' contains at least
1070 * 'pnum' is set to the number of sectors (including and immediately following
1071 * the first one) that are known to be in the same allocated/unallocated state.
1073 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1082 is_zero
= buffer_is_zero(buf
, 512);
1083 for(i
= 1; i
< n
; i
++) {
1085 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1094 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1095 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1096 * breaking up write requests for only small sparse areas.
1098 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1102 int num_checked
, num_used
;
1108 ret
= is_allocated_sectors(buf
, n
, pnum
);
1114 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1116 num_checked
= num_used
;
1119 ret
= is_allocated_sectors(buf
, n
, pnum
);
1121 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1123 num_checked
+= *pnum
;
1125 num_used
= num_checked
;
1126 } else if (*pnum
>= min
) {
1136 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1137 * buffers matches, non-zero otherwise.
1139 * pnum is set to the number of sectors (including and immediately following
1140 * the first one) that are known to have the same comparison result
1142 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1153 res
= !!memcmp(buf1
, buf2
, 512);
1154 for(i
= 1; i
< n
; i
++) {
1158 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1167 #define IO_BUF_SIZE (2 * 1024 * 1024)
1169 static int64_t sectors_to_bytes(int64_t sectors
)
1171 return sectors
<< BDRV_SECTOR_BITS
;
1174 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1176 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1180 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1182 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1183 * data and negative value on error.
1185 * @param blk: BlockBackend for the image
1186 * @param sect_num: Number of first sector to check
1187 * @param sect_count: Number of sectors to check
1188 * @param filename: Name of disk file we are checking (logging purpose)
1189 * @param buffer: Allocated buffer for storing read data
1190 * @param quiet: Flag for quiet mode
1192 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1193 int sect_count
, const char *filename
,
1194 uint8_t *buffer
, bool quiet
)
1197 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1198 sect_count
<< BDRV_SECTOR_BITS
);
1200 error_report("Error while reading offset %" PRId64
" of %s: %s",
1201 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1204 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1205 if (ret
|| pnum
!= sect_count
) {
1206 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1207 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1215 * Compares two images. Exit codes:
1217 * 0 - Images are identical
1219 * >1 - Error occurred
1221 static int img_compare(int argc
, char **argv
)
1223 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1224 BlockBackend
*blk1
, *blk2
;
1225 BlockDriverState
*bs1
, *bs2
;
1226 int64_t total_sectors1
, total_sectors2
;
1227 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1229 int allocated1
, allocated2
;
1230 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1231 bool progress
= false, quiet
= false, strict
= false;
1234 int64_t total_sectors
;
1235 int64_t sector_num
= 0;
1238 uint64_t progress_base
;
1239 bool image_opts
= false;
1240 bool force_share
= false;
1242 cache
= BDRV_DEFAULT_CACHE
;
1244 static const struct option long_options
[] = {
1245 {"help", no_argument
, 0, 'h'},
1246 {"object", required_argument
, 0, OPTION_OBJECT
},
1247 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1248 {"force-share", no_argument
, 0, 'U'},
1251 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1252 long_options
, NULL
);
1258 missing_argument(argv
[optind
- 1]);
1261 unrecognized_option(argv
[optind
- 1]);
1287 case OPTION_OBJECT
: {
1289 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1296 case OPTION_IMAGE_OPTS
:
1302 /* Progress is not shown in Quiet mode */
1308 if (optind
!= argc
- 2) {
1309 error_exit("Expecting two image file names");
1311 filename1
= argv
[optind
++];
1312 filename2
= argv
[optind
++];
1314 if (qemu_opts_foreach(&qemu_object_opts
,
1315 user_creatable_add_opts_foreach
,
1321 /* Initialize before goto out */
1322 qemu_progress_init(progress
, 2.0);
1325 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1327 error_report("Invalid source cache option: %s", cache
);
1332 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1339 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1348 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1349 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1350 total_sectors1
= blk_nb_sectors(blk1
);
1351 if (total_sectors1
< 0) {
1352 error_report("Can't get size of %s: %s",
1353 filename1
, strerror(-total_sectors1
));
1357 total_sectors2
= blk_nb_sectors(blk2
);
1358 if (total_sectors2
< 0) {
1359 error_report("Can't get size of %s: %s",
1360 filename2
, strerror(-total_sectors2
));
1364 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1365 progress_base
= MAX(total_sectors1
, total_sectors2
);
1367 qemu_progress_print(0, 100);
1369 if (strict
&& total_sectors1
!= total_sectors2
) {
1371 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1376 int64_t status1
, status2
;
1377 BlockDriverState
*file
;
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 BlockDriverState
*file
;
1602 if (s
->target_has_backing
) {
1603 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1604 sector_num
- src_cur_offset
,
1607 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1608 sector_num
- src_cur_offset
,
1615 if (ret
& BDRV_BLOCK_ZERO
) {
1616 s
->status
= BLK_ZERO
;
1617 } else if (ret
& BDRV_BLOCK_DATA
) {
1618 s
->status
= BLK_DATA
;
1620 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1623 s
->sector_next_status
= sector_num
+ n
;
1626 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1627 if (s
->status
== BLK_DATA
) {
1628 n
= MIN(n
, s
->buf_sectors
);
1631 /* We need to write complete clusters for compressed images, so if an
1632 * unallocated area is shorter than that, we must consider the whole
1633 * cluster allocated. */
1634 if (s
->compressed
) {
1635 if (n
< s
->cluster_sectors
) {
1636 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1637 s
->status
= BLK_DATA
;
1639 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1646 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1647 int nb_sectors
, uint8_t *buf
)
1653 assert(nb_sectors
<= s
->buf_sectors
);
1654 while (nb_sectors
> 0) {
1657 int64_t bs_sectors
, src_cur_offset
;
1659 /* In the case of compression with multiple source files, we can get a
1660 * nb_sectors that spreads into the next part. So we must be able to
1661 * read across multiple BDSes for one convert_read() call. */
1662 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1663 blk
= s
->src
[src_cur
];
1664 bs_sectors
= s
->src_sectors
[src_cur
];
1666 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1668 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1669 qemu_iovec_init_external(&qiov
, &iov
, 1);
1671 ret
= blk_co_preadv(
1672 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1673 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1680 buf
+= n
* BDRV_SECTOR_SIZE
;
1687 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1688 int nb_sectors
, uint8_t *buf
,
1689 enum ImgConvertBlockStatus status
)
1695 while (nb_sectors
> 0) {
1697 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1700 case BLK_BACKING_FILE
:
1701 /* If we have a backing file, leave clusters unallocated that are
1702 * unallocated in the source image, so that the backing file is
1703 * visible at the respective offset. */
1704 assert(s
->target_has_backing
);
1708 /* If we're told to keep the target fully allocated (-S 0) or there
1709 * is real non-zero data, we must write it. Otherwise we can treat
1710 * it as zero sectors.
1711 * Compressed clusters need to be written as a whole, so in that
1712 * case we can only save the write if the buffer is completely
1714 if (!s
->min_sparse
||
1716 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1718 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1721 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1722 qemu_iovec_init_external(&qiov
, &iov
, 1);
1724 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1725 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1734 if (s
->has_zero_init
) {
1735 assert(!s
->target_has_backing
);
1738 ret
= blk_co_pwrite_zeroes(s
->target
,
1739 sector_num
<< BDRV_SECTOR_BITS
,
1740 n
<< BDRV_SECTOR_BITS
, 0);
1749 buf
+= n
* BDRV_SECTOR_SIZE
;
1755 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1757 ImgConvertState
*s
= opaque
;
1758 uint8_t *buf
= NULL
;
1762 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1763 if (s
->co
[i
] == qemu_coroutine_self()) {
1770 s
->running_coroutines
++;
1771 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1776 enum ImgConvertBlockStatus status
;
1778 qemu_co_mutex_lock(&s
->lock
);
1779 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1780 qemu_co_mutex_unlock(&s
->lock
);
1783 n
= convert_iteration_sectors(s
, s
->sector_num
);
1785 qemu_co_mutex_unlock(&s
->lock
);
1789 /* save current sector and allocation status to local variables */
1790 sector_num
= s
->sector_num
;
1792 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1793 n
= MIN(n
, s
->buf_sectors
);
1795 /* increment global sector counter so that other coroutines can
1796 * already continue reading beyond this request */
1798 qemu_co_mutex_unlock(&s
->lock
);
1800 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1801 s
->allocated_done
+= n
;
1802 qemu_progress_print(100.0 * s
->allocated_done
/
1803 s
->allocated_sectors
, 0);
1806 if (status
== BLK_DATA
) {
1807 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1809 error_report("error while reading sector %" PRId64
1810 ": %s", sector_num
, strerror(-ret
));
1813 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1815 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1818 if (s
->wr_in_order
) {
1819 /* keep writes in order */
1820 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1821 s
->wait_sector_num
[index
] = sector_num
;
1822 qemu_coroutine_yield();
1824 s
->wait_sector_num
[index
] = -1;
1827 if (s
->ret
== -EINPROGRESS
) {
1828 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1830 error_report("error while writing sector %" PRId64
1831 ": %s", sector_num
, strerror(-ret
));
1836 if (s
->wr_in_order
) {
1837 /* reenter the coroutine that might have waited
1838 * for this write to complete */
1839 s
->wr_offs
= sector_num
+ n
;
1840 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1841 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1843 * A -> B -> A cannot occur because A has
1844 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1845 * B will never enter A during this time window.
1847 qemu_coroutine_enter(s
->co
[i
]);
1855 s
->co
[index
] = NULL
;
1856 s
->running_coroutines
--;
1857 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1858 /* the convert job finished successfully */
1863 static int convert_do_copy(ImgConvertState
*s
)
1866 int64_t sector_num
= 0;
1868 /* Check whether we have zero initialisation or can get it efficiently */
1869 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1870 ? bdrv_has_zero_init(blk_bs(s
->target
))
1873 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1874 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1876 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1878 s
->has_zero_init
= true;
1882 /* Allocate buffer for copied data. For compressed images, only one cluster
1883 * can be copied at a time. */
1884 if (s
->compressed
) {
1885 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1886 error_report("invalid cluster size");
1889 s
->buf_sectors
= s
->cluster_sectors
;
1892 while (sector_num
< s
->total_sectors
) {
1893 n
= convert_iteration_sectors(s
, sector_num
);
1897 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1899 s
->allocated_sectors
+= n
;
1905 s
->sector_next_status
= 0;
1906 s
->ret
= -EINPROGRESS
;
1908 qemu_co_mutex_init(&s
->lock
);
1909 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1910 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1911 s
->wait_sector_num
[i
] = -1;
1912 qemu_coroutine_enter(s
->co
[i
]);
1915 while (s
->running_coroutines
) {
1916 main_loop_wait(false);
1919 if (s
->compressed
&& !s
->ret
) {
1920 /* signal EOF to align */
1921 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1930 static int img_convert(int argc
, char **argv
)
1932 int c
, bs_i
, flags
, src_flags
= 0;
1933 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1934 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1935 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1936 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1937 BlockDriverInfo bdi
;
1938 BlockDriverState
*out_bs
;
1939 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1940 QemuOptsList
*create_opts
= NULL
;
1941 char *options
= NULL
;
1942 Error
*local_err
= NULL
;
1943 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1944 skip_create
= false, progress
= false, tgt_image_opts
= false;
1945 int64_t ret
= -EINVAL
;
1946 bool force_share
= false;
1948 ImgConvertState s
= (ImgConvertState
) {
1949 /* Need at least 4k of zeros for sparse detection */
1951 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1952 .wr_in_order
= true,
1953 .num_coroutines
= 8,
1957 static const struct option long_options
[] = {
1958 {"help", no_argument
, 0, 'h'},
1959 {"object", required_argument
, 0, OPTION_OBJECT
},
1960 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1961 {"force-share", no_argument
, 0, 'U'},
1962 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1965 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1966 long_options
, NULL
);
1972 missing_argument(argv
[optind
- 1]);
1975 unrecognized_option(argv
[optind
- 1]);
1987 out_baseimg
= optarg
;
1990 s
.compressed
= true;
1993 if (!is_valid_option_list(optarg
)) {
1994 error_report("Invalid option list: %s", optarg
);
1998 options
= g_strdup(optarg
);
2000 char *old_options
= options
;
2001 options
= g_strdup_printf("%s,%s", options
, optarg
);
2002 g_free(old_options
);
2006 snapshot_name
= optarg
;
2009 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2010 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2013 error_report("Failed in parsing snapshot param '%s'",
2018 snapshot_name
= optarg
;
2025 sval
= cvtnum(optarg
);
2027 error_report("Invalid minimum zero buffer size for sparse output specified");
2031 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2050 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2051 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2052 error_report("Invalid number of coroutines. Allowed number of"
2053 " coroutines is between 1 and %d", MAX_COROUTINES
);
2058 s
.wr_in_order
= false;
2063 case OPTION_OBJECT
: {
2064 QemuOpts
*object_opts
;
2065 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2072 case OPTION_IMAGE_OPTS
:
2075 case OPTION_TARGET_IMAGE_OPTS
:
2076 tgt_image_opts
= true;
2081 if (!out_fmt
&& !tgt_image_opts
) {
2085 if (qemu_opts_foreach(&qemu_object_opts
,
2086 user_creatable_add_opts_foreach
,
2091 if (!s
.wr_in_order
&& s
.compressed
) {
2092 error_report("Out of order write and compress are mutually exclusive");
2096 if (tgt_image_opts
&& !skip_create
) {
2097 error_report("--target-image-opts requires use of -n flag");
2101 s
.src_num
= argc
- optind
- 1;
2102 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2104 if (options
&& has_help_option(options
)) {
2106 ret
= print_block_option_help(out_filename
, out_fmt
);
2109 error_report("Option help requires a format be specified");
2114 if (s
.src_num
< 1) {
2115 error_report("Must specify image file name");
2120 /* ret is still -EINVAL until here */
2121 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2123 error_report("Invalid source cache option: %s", src_cache
);
2127 /* Initialize before goto out */
2131 qemu_progress_init(progress
, 1.0);
2132 qemu_progress_print(0, 100);
2134 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2135 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2137 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2138 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2139 fmt
, src_flags
, src_writethrough
, quiet
,
2145 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2146 if (s
.src_sectors
[bs_i
] < 0) {
2147 error_report("Could not get size of %s: %s",
2148 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2152 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2156 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2157 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2158 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2160 } else if (snapshot_name
!= NULL
) {
2161 if (s
.src_num
> 1) {
2162 error_report("No support for concatenating multiple snapshot");
2167 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2171 error_reportf_err(local_err
, "Failed to load snapshot: ");
2177 /* Find driver and parse its options */
2178 drv
= bdrv_find_format(out_fmt
);
2180 error_report("Unknown file format '%s'", out_fmt
);
2185 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2187 error_report_err(local_err
);
2192 if (!drv
->create_opts
) {
2193 error_report("Format driver '%s' does not support image creation",
2199 if (!proto_drv
->create_opts
) {
2200 error_report("Protocol driver '%s' does not support image creation",
2201 proto_drv
->format_name
);
2206 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2207 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2209 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2211 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2213 error_report_err(local_err
);
2219 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2221 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2227 /* Get backing file name if -o backing_file was used */
2228 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2229 if (out_baseimg_param
) {
2230 out_baseimg
= out_baseimg_param
;
2232 s
.target_has_backing
= (bool) out_baseimg
;
2234 if (s
.src_num
> 1 && out_baseimg
) {
2235 error_report("Having a backing file for the target makes no sense when "
2236 "concatenating multiple input images");
2241 /* Check if compression is supported */
2244 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2245 const char *encryptfmt
=
2246 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2247 const char *preallocation
=
2248 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2250 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2251 error_report("Compression not supported for this file format");
2256 if (encryption
|| encryptfmt
) {
2257 error_report("Compression and encryption not supported at "
2264 && strcmp(preallocation
, "off"))
2266 error_report("Compression and preallocation not supported at "
2274 /* Create the new image */
2275 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2277 error_reportf_err(local_err
, "%s: error while converting %s: ",
2278 out_filename
, out_fmt
);
2283 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2284 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2286 error_report("Invalid cache option: %s", cache
);
2291 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2292 flags
, writethrough
, quiet
, false);
2294 /* TODO ultimately we should allow --target-image-opts
2295 * to be used even when -n is not given.
2296 * That has to wait for bdrv_create to be improved
2297 * to allow filenames in option syntax
2299 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2300 flags
, writethrough
, quiet
, false);
2306 out_bs
= blk_bs(s
.target
);
2308 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2309 error_report("Compression not supported for this file format");
2314 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2315 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2317 s
.buf_sectors
= MIN(32768,
2319 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2320 out_bs
->bl
.pdiscard_alignment
>>
2321 BDRV_SECTOR_BITS
)));
2324 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2325 if (output_sectors
< 0) {
2326 error_report("unable to get output image length: %s",
2327 strerror(-output_sectors
));
2330 } else if (output_sectors
< s
.total_sectors
) {
2331 error_report("output file is smaller than input file");
2337 ret
= bdrv_get_info(out_bs
, &bdi
);
2340 error_report("could not get block driver info");
2344 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2345 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2348 ret
= convert_do_copy(&s
);
2351 qemu_progress_print(100, 0);
2353 qemu_progress_end();
2354 qemu_opts_del(opts
);
2355 qemu_opts_free(create_opts
);
2356 qemu_opts_del(sn_opts
);
2357 blk_unref(s
.target
);
2359 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2360 blk_unref(s
.src
[bs_i
]);
2364 g_free(s
.src_sectors
);
2372 static void dump_snapshots(BlockDriverState
*bs
)
2374 QEMUSnapshotInfo
*sn_tab
, *sn
;
2377 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2380 printf("Snapshot list:\n");
2381 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2383 for(i
= 0; i
< nb_sns
; i
++) {
2385 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2391 static void dump_json_image_info_list(ImageInfoList
*list
)
2395 Visitor
*v
= qobject_output_visitor_new(&obj
);
2397 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2398 visit_complete(v
, &obj
);
2399 str
= qobject_to_json_pretty(obj
);
2400 assert(str
!= NULL
);
2401 printf("%s\n", qstring_get_str(str
));
2402 qobject_decref(obj
);
2407 static void dump_json_image_info(ImageInfo
*info
)
2411 Visitor
*v
= qobject_output_visitor_new(&obj
);
2413 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2414 visit_complete(v
, &obj
);
2415 str
= qobject_to_json_pretty(obj
);
2416 assert(str
!= NULL
);
2417 printf("%s\n", qstring_get_str(str
));
2418 qobject_decref(obj
);
2423 static void dump_human_image_info_list(ImageInfoList
*list
)
2425 ImageInfoList
*elem
;
2428 for (elem
= list
; elem
; elem
= elem
->next
) {
2434 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2438 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2440 return strcmp(a
, b
) == 0;
2444 * Open an image file chain and return an ImageInfoList
2446 * @filename: topmost image filename
2447 * @fmt: topmost image format (may be NULL to autodetect)
2448 * @chain: true - enumerate entire backing file chain
2449 * false - only topmost image file
2451 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2452 * image file. If there was an error a message will have been printed to
2455 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2456 const char *filename
,
2458 bool chain
, bool force_share
)
2460 ImageInfoList
*head
= NULL
;
2461 ImageInfoList
**last
= &head
;
2462 GHashTable
*filenames
;
2465 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2469 BlockDriverState
*bs
;
2471 ImageInfoList
*elem
;
2473 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2474 error_report("Backing file '%s' creates an infinite loop.",
2478 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2480 blk
= img_open(image_opts
, filename
, fmt
,
2481 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2488 bdrv_query_image_info(bs
, &info
, &err
);
2490 error_report_err(err
);
2495 elem
= g_new0(ImageInfoList
, 1);
2502 filename
= fmt
= NULL
;
2504 if (info
->has_full_backing_filename
) {
2505 filename
= info
->full_backing_filename
;
2506 } else if (info
->has_backing_filename
) {
2507 error_report("Could not determine absolute backing filename,"
2508 " but backing filename '%s' present",
2509 info
->backing_filename
);
2512 if (info
->has_backing_filename_format
) {
2513 fmt
= info
->backing_filename_format
;
2517 g_hash_table_destroy(filenames
);
2521 qapi_free_ImageInfoList(head
);
2522 g_hash_table_destroy(filenames
);
2526 static int img_info(int argc
, char **argv
)
2529 OutputFormat output_format
= OFORMAT_HUMAN
;
2531 const char *filename
, *fmt
, *output
;
2532 ImageInfoList
*list
;
2533 bool image_opts
= false;
2534 bool force_share
= false;
2539 int option_index
= 0;
2540 static const struct option long_options
[] = {
2541 {"help", no_argument
, 0, 'h'},
2542 {"format", required_argument
, 0, 'f'},
2543 {"output", required_argument
, 0, OPTION_OUTPUT
},
2544 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2545 {"object", required_argument
, 0, OPTION_OBJECT
},
2546 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2547 {"force-share", no_argument
, 0, 'U'},
2550 c
= getopt_long(argc
, argv
, ":f:hU",
2551 long_options
, &option_index
);
2557 missing_argument(argv
[optind
- 1]);
2560 unrecognized_option(argv
[optind
- 1]);
2574 case OPTION_BACKING_CHAIN
:
2577 case OPTION_OBJECT
: {
2579 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2585 case OPTION_IMAGE_OPTS
:
2590 if (optind
!= argc
- 1) {
2591 error_exit("Expecting one image file name");
2593 filename
= argv
[optind
++];
2595 if (output
&& !strcmp(output
, "json")) {
2596 output_format
= OFORMAT_JSON
;
2597 } else if (output
&& !strcmp(output
, "human")) {
2598 output_format
= OFORMAT_HUMAN
;
2599 } else if (output
) {
2600 error_report("--output must be used with human or json as argument.");
2604 if (qemu_opts_foreach(&qemu_object_opts
,
2605 user_creatable_add_opts_foreach
,
2610 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2616 switch (output_format
) {
2618 dump_human_image_info_list(list
);
2622 dump_json_image_info_list(list
);
2624 dump_json_image_info(list
->value
);
2629 qapi_free_ImageInfoList(list
);
2633 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2636 switch (output_format
) {
2638 if (e
->data
&& !e
->has_offset
) {
2639 error_report("File contains external, encrypted or compressed clusters.");
2642 if (e
->data
&& !e
->zero
) {
2643 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2644 e
->start
, e
->length
,
2645 e
->has_offset
? e
->offset
: 0,
2646 e
->has_filename
? e
->filename
: "");
2648 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2649 * Modify the flags here to allow more coalescing.
2651 if (next
&& (!next
->data
|| next
->zero
)) {
2657 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2658 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2659 (e
->start
== 0 ? "[" : ",\n"),
2660 e
->start
, e
->length
, e
->depth
,
2661 e
->zero
? "true" : "false",
2662 e
->data
? "true" : "false");
2663 if (e
->has_offset
) {
2664 printf(", \"offset\": %"PRId64
"", e
->offset
);
2675 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2676 int nb_sectors
, MapEntry
*e
)
2680 BlockDriverState
*file
;
2683 /* As an optimization, we could cache the current range of unallocated
2684 * clusters in each file of the chain, and avoid querying the same
2690 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2696 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2699 bs
= backing_bs(bs
);
2708 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2711 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2712 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2713 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2714 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2715 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2716 .has_offset
= has_offset
,
2718 .has_filename
= file
&& has_offset
,
2719 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2725 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2727 if (curr
->length
== 0) {
2730 if (curr
->zero
!= next
->zero
||
2731 curr
->data
!= next
->data
||
2732 curr
->depth
!= next
->depth
||
2733 curr
->has_filename
!= next
->has_filename
||
2734 curr
->has_offset
!= next
->has_offset
) {
2737 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2740 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2746 static int img_map(int argc
, char **argv
)
2749 OutputFormat output_format
= OFORMAT_HUMAN
;
2751 BlockDriverState
*bs
;
2752 const char *filename
, *fmt
, *output
;
2754 MapEntry curr
= { .length
= 0 }, next
;
2756 bool image_opts
= false;
2757 bool force_share
= false;
2762 int option_index
= 0;
2763 static const struct option long_options
[] = {
2764 {"help", no_argument
, 0, 'h'},
2765 {"format", required_argument
, 0, 'f'},
2766 {"output", required_argument
, 0, OPTION_OUTPUT
},
2767 {"object", required_argument
, 0, OPTION_OBJECT
},
2768 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2769 {"force-share", no_argument
, 0, 'U'},
2772 c
= getopt_long(argc
, argv
, ":f:hU",
2773 long_options
, &option_index
);
2779 missing_argument(argv
[optind
- 1]);
2782 unrecognized_option(argv
[optind
- 1]);
2796 case OPTION_OBJECT
: {
2798 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2804 case OPTION_IMAGE_OPTS
:
2809 if (optind
!= argc
- 1) {
2810 error_exit("Expecting one image file name");
2812 filename
= argv
[optind
];
2814 if (output
&& !strcmp(output
, "json")) {
2815 output_format
= OFORMAT_JSON
;
2816 } else if (output
&& !strcmp(output
, "human")) {
2817 output_format
= OFORMAT_HUMAN
;
2818 } else if (output
) {
2819 error_report("--output must be used with human or json as argument.");
2823 if (qemu_opts_foreach(&qemu_object_opts
,
2824 user_creatable_add_opts_foreach
,
2829 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2835 if (output_format
== OFORMAT_HUMAN
) {
2836 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2839 length
= blk_getlength(blk
);
2840 while (curr
.start
+ curr
.length
< length
) {
2841 int64_t nsectors_left
;
2845 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2847 /* Probe up to 1 GiB at a time. */
2848 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2849 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2850 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2853 error_report("Could not read file metadata: %s", strerror(-ret
));
2857 if (entry_mergeable(&curr
, &next
)) {
2858 curr
.length
+= next
.length
;
2862 if (curr
.length
> 0) {
2863 dump_map_entry(output_format
, &curr
, &next
);
2868 dump_map_entry(output_format
, &curr
, NULL
);
2875 #define SNAPSHOT_LIST 1
2876 #define SNAPSHOT_CREATE 2
2877 #define SNAPSHOT_APPLY 3
2878 #define SNAPSHOT_DELETE 4
2880 static int img_snapshot(int argc
, char **argv
)
2883 BlockDriverState
*bs
;
2884 QEMUSnapshotInfo sn
;
2885 char *filename
, *snapshot_name
= NULL
;
2886 int c
, ret
= 0, bdrv_oflags
;
2891 bool image_opts
= false;
2892 bool force_share
= false;
2894 bdrv_oflags
= BDRV_O_RDWR
;
2895 /* Parse commandline parameters */
2897 static const struct option long_options
[] = {
2898 {"help", no_argument
, 0, 'h'},
2899 {"object", required_argument
, 0, OPTION_OBJECT
},
2900 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2901 {"force-share", no_argument
, 0, 'U'},
2904 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2905 long_options
, NULL
);
2911 missing_argument(argv
[optind
- 1]);
2914 unrecognized_option(argv
[optind
- 1]);
2921 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2924 action
= SNAPSHOT_LIST
;
2925 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2929 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2932 action
= SNAPSHOT_APPLY
;
2933 snapshot_name
= optarg
;
2937 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2940 action
= SNAPSHOT_CREATE
;
2941 snapshot_name
= optarg
;
2945 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2948 action
= SNAPSHOT_DELETE
;
2949 snapshot_name
= optarg
;
2957 case OPTION_OBJECT
: {
2959 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2965 case OPTION_IMAGE_OPTS
:
2971 if (optind
!= argc
- 1) {
2972 error_exit("Expecting one image file name");
2974 filename
= argv
[optind
++];
2976 if (qemu_opts_foreach(&qemu_object_opts
,
2977 user_creatable_add_opts_foreach
,
2982 /* Open the image */
2983 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
2990 /* Perform the requested action */
2996 case SNAPSHOT_CREATE
:
2997 memset(&sn
, 0, sizeof(sn
));
2998 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3000 qemu_gettimeofday(&tv
);
3001 sn
.date_sec
= tv
.tv_sec
;
3002 sn
.date_nsec
= tv
.tv_usec
* 1000;
3004 ret
= bdrv_snapshot_create(bs
, &sn
);
3006 error_report("Could not create snapshot '%s': %d (%s)",
3007 snapshot_name
, ret
, strerror(-ret
));
3011 case SNAPSHOT_APPLY
:
3012 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
3014 error_report("Could not apply snapshot '%s': %d (%s)",
3015 snapshot_name
, ret
, strerror(-ret
));
3019 case SNAPSHOT_DELETE
:
3020 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3022 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3037 static int img_rebase(int argc
, char **argv
)
3039 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3040 uint8_t *buf_old
= NULL
;
3041 uint8_t *buf_new
= NULL
;
3042 BlockDriverState
*bs
= NULL
;
3044 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3045 int c
, flags
, src_flags
, ret
;
3046 bool writethrough
, src_writethrough
;
3048 bool force_share
= false;
3051 Error
*local_err
= NULL
;
3052 bool image_opts
= false;
3054 /* Parse commandline parameters */
3056 cache
= BDRV_DEFAULT_CACHE
;
3057 src_cache
= BDRV_DEFAULT_CACHE
;
3061 static const struct option long_options
[] = {
3062 {"help", no_argument
, 0, 'h'},
3063 {"object", required_argument
, 0, OPTION_OBJECT
},
3064 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3065 {"force-share", no_argument
, 0, 'U'},
3068 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3069 long_options
, NULL
);
3075 missing_argument(argv
[optind
- 1]);
3078 unrecognized_option(argv
[optind
- 1]);
3087 out_basefmt
= optarg
;
3090 out_baseimg
= optarg
;
3107 case OPTION_OBJECT
: {
3109 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3115 case OPTION_IMAGE_OPTS
:
3128 if (optind
!= argc
- 1) {
3129 error_exit("Expecting one image file name");
3131 if (!unsafe
&& !out_baseimg
) {
3132 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3134 filename
= argv
[optind
++];
3136 if (qemu_opts_foreach(&qemu_object_opts
,
3137 user_creatable_add_opts_foreach
,
3142 qemu_progress_init(progress
, 2.0);
3143 qemu_progress_print(0, 100);
3145 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3146 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3148 error_report("Invalid cache option: %s", cache
);
3153 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3155 error_report("Invalid source cache option: %s", src_cache
);
3159 /* The source files are opened read-only, don't care about WCE */
3160 assert((src_flags
& BDRV_O_RDWR
) == 0);
3161 (void) src_writethrough
;
3166 * Ignore the old backing file for unsafe rebase in case we want to correct
3167 * the reference to a renamed or moved backing file.
3169 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3177 if (out_basefmt
!= NULL
) {
3178 if (bdrv_find_format(out_basefmt
) == NULL
) {
3179 error_report("Invalid format name: '%s'", out_basefmt
);
3185 /* For safe rebasing we need to compare old and new backing file */
3187 char backing_name
[PATH_MAX
];
3188 QDict
*options
= NULL
;
3190 if (bs
->backing_format
[0] != '\0') {
3191 options
= qdict_new();
3192 qdict_put_str(options
, "driver", bs
->backing_format
);
3197 options
= qdict_new();
3199 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3201 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3202 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3203 options
, src_flags
, &local_err
);
3204 if (!blk_old_backing
) {
3205 error_reportf_err(local_err
,
3206 "Could not open old backing file '%s': ",
3212 if (out_baseimg
[0]) {
3213 options
= qdict_new();
3215 qdict_put_str(options
, "driver", out_basefmt
);
3218 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3221 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3222 options
, src_flags
, &local_err
);
3223 if (!blk_new_backing
) {
3224 error_reportf_err(local_err
,
3225 "Could not open new backing file '%s': ",
3234 * Check each unallocated cluster in the COW file. If it is unallocated,
3235 * accesses go to the backing file. We must therefore compare this cluster
3236 * in the old and new backing file, and if they differ we need to copy it
3237 * from the old backing file into the COW file.
3239 * If qemu-img crashes during this step, no harm is done. The content of
3240 * the image is the same as the original one at any time.
3243 int64_t num_sectors
;
3244 int64_t old_backing_num_sectors
;
3245 int64_t new_backing_num_sectors
= 0;
3249 float local_progress
= 0;
3251 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3252 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3254 num_sectors
= blk_nb_sectors(blk
);
3255 if (num_sectors
< 0) {
3256 error_report("Could not get size of '%s': %s",
3257 filename
, strerror(-num_sectors
));
3261 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
3262 if (old_backing_num_sectors
< 0) {
3263 char backing_name
[PATH_MAX
];
3265 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3266 error_report("Could not get size of '%s': %s",
3267 backing_name
, strerror(-old_backing_num_sectors
));
3271 if (blk_new_backing
) {
3272 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3273 if (new_backing_num_sectors
< 0) {
3274 error_report("Could not get size of '%s': %s",
3275 out_baseimg
, strerror(-new_backing_num_sectors
));
3281 if (num_sectors
!= 0) {
3282 local_progress
= (float)100 /
3283 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3286 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3288 /* How many sectors can we handle with the next read? */
3289 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3290 n
= (IO_BUF_SIZE
/ 512);
3292 n
= num_sectors
- sector
;
3295 /* If the cluster is allocated, we don't need to take action */
3296 ret
= bdrv_is_allocated(bs
, sector
<< BDRV_SECTOR_BITS
,
3297 n
<< BDRV_SECTOR_BITS
, &count
);
3299 error_report("error while reading image metadata: %s",
3303 /* TODO relax this once bdrv_is_allocated does not enforce
3304 * sector alignment */
3305 assert(QEMU_IS_ALIGNED(count
, BDRV_SECTOR_SIZE
));
3306 n
= count
>> BDRV_SECTOR_BITS
;
3312 * Read old and new backing file and take into consideration that
3313 * backing files may be smaller than the COW image.
3315 if (sector
>= old_backing_num_sectors
) {
3316 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3318 if (sector
+ n
> old_backing_num_sectors
) {
3319 n
= old_backing_num_sectors
- sector
;
3322 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3323 buf_old
, n
<< BDRV_SECTOR_BITS
);
3325 error_report("error while reading from old backing file");
3330 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3331 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3333 if (sector
+ n
> new_backing_num_sectors
) {
3334 n
= new_backing_num_sectors
- sector
;
3337 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3338 buf_new
, n
<< BDRV_SECTOR_BITS
);
3340 error_report("error while reading from new backing file");
3345 /* If they differ, we need to write to the COW file */
3346 uint64_t written
= 0;
3348 while (written
< n
) {
3351 if (compare_sectors(buf_old
+ written
* 512,
3352 buf_new
+ written
* 512, n
- written
, &pnum
))
3354 ret
= blk_pwrite(blk
,
3355 (sector
+ written
) << BDRV_SECTOR_BITS
,
3356 buf_old
+ written
* 512,
3357 pnum
<< BDRV_SECTOR_BITS
, 0);
3359 error_report("Error while writing to COW image: %s",
3367 qemu_progress_print(local_progress
, 100);
3372 * Change the backing file. All clusters that are different from the old
3373 * backing file are overwritten in the COW file now, so the visible content
3374 * doesn't change when we switch the backing file.
3376 if (out_baseimg
&& *out_baseimg
) {
3377 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3379 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3382 if (ret
== -ENOSPC
) {
3383 error_report("Could not change the backing file to '%s': No "
3384 "space left in the file header", out_baseimg
);
3385 } else if (ret
< 0) {
3386 error_report("Could not change the backing file to '%s': %s",
3387 out_baseimg
, strerror(-ret
));
3390 qemu_progress_print(100, 0);
3392 * TODO At this point it is possible to check if any clusters that are
3393 * allocated in the COW file are the same in the backing file. If so, they
3394 * could be dropped from the COW file. Don't do this before switching the
3395 * backing file, in case of a crash this would lead to corruption.
3398 qemu_progress_end();
3401 blk_unref(blk_old_backing
);
3402 blk_unref(blk_new_backing
);
3404 qemu_vfree(buf_old
);
3405 qemu_vfree(buf_new
);
3414 static int img_resize(int argc
, char **argv
)
3417 int c
, ret
, relative
;
3418 const char *filename
, *fmt
, *size
;
3419 int64_t n
, total_size
, current_size
;
3421 BlockBackend
*blk
= NULL
;
3422 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3425 static QemuOptsList resize_options
= {
3426 .name
= "resize_options",
3427 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3430 .name
= BLOCK_OPT_SIZE
,
3431 .type
= QEMU_OPT_SIZE
,
3432 .help
= "Virtual disk size"
3438 bool image_opts
= false;
3440 /* Remove size from argv manually so that negative numbers are not treated
3441 * as options by getopt. */
3443 error_exit("Not enough arguments");
3447 size
= argv
[--argc
];
3449 /* Parse getopt arguments */
3452 static const struct option long_options
[] = {
3453 {"help", no_argument
, 0, 'h'},
3454 {"object", required_argument
, 0, OPTION_OBJECT
},
3455 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3456 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3459 c
= getopt_long(argc
, argv
, ":f:hq",
3460 long_options
, NULL
);
3466 missing_argument(argv
[optind
- 1]);
3469 unrecognized_option(argv
[optind
- 1]);
3480 case OPTION_OBJECT
: {
3482 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3488 case OPTION_IMAGE_OPTS
:
3491 case OPTION_PREALLOCATION
:
3492 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3493 PREALLOC_MODE__MAX
, NULL
);
3494 if (prealloc
== PREALLOC_MODE__MAX
) {
3495 error_report("Invalid preallocation mode '%s'", optarg
);
3501 if (optind
!= argc
- 1) {
3502 error_exit("Expecting one image file name");
3504 filename
= argv
[optind
++];
3506 if (qemu_opts_foreach(&qemu_object_opts
,
3507 user_creatable_add_opts_foreach
,
3512 /* Choose grow, shrink, or absolute resize mode */
3528 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3529 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3531 error_report_err(err
);
3533 qemu_opts_del(param
);
3536 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3537 qemu_opts_del(param
);
3539 blk
= img_open(image_opts
, filename
, fmt
,
3540 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3547 current_size
= blk_getlength(blk
);
3548 if (current_size
< 0) {
3549 error_report("Failed to inquire current image length: %s",
3550 strerror(-current_size
));
3556 total_size
= current_size
+ n
* relative
;
3560 if (total_size
<= 0) {
3561 error_report("New image size must be positive");
3566 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3567 error_report("Preallocation can only be used for growing images");
3572 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3574 qprintf(quiet
, "Image resized.\n");
3576 error_report_err(err
);
3586 static void amend_status_cb(BlockDriverState
*bs
,
3587 int64_t offset
, int64_t total_work_size
,
3590 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3593 static int img_amend(int argc
, char **argv
)
3597 char *options
= NULL
;
3598 QemuOptsList
*create_opts
= NULL
;
3599 QemuOpts
*opts
= NULL
;
3600 const char *fmt
= NULL
, *filename
, *cache
;
3603 bool quiet
= false, progress
= false;
3604 BlockBackend
*blk
= NULL
;
3605 BlockDriverState
*bs
= NULL
;
3606 bool image_opts
= false;
3608 cache
= BDRV_DEFAULT_CACHE
;
3610 static const struct option long_options
[] = {
3611 {"help", no_argument
, 0, 'h'},
3612 {"object", required_argument
, 0, OPTION_OBJECT
},
3613 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3616 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3617 long_options
, NULL
);
3624 missing_argument(argv
[optind
- 1]);
3627 unrecognized_option(argv
[optind
- 1]);
3633 if (!is_valid_option_list(optarg
)) {
3634 error_report("Invalid option list: %s", optarg
);
3636 goto out_no_progress
;
3639 options
= g_strdup(optarg
);
3641 char *old_options
= options
;
3642 options
= g_strdup_printf("%s,%s", options
, optarg
);
3643 g_free(old_options
);
3659 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3663 goto out_no_progress
;
3666 case OPTION_IMAGE_OPTS
:
3673 error_exit("Must specify options (-o)");
3676 if (qemu_opts_foreach(&qemu_object_opts
,
3677 user_creatable_add_opts_foreach
,
3680 goto out_no_progress
;
3686 qemu_progress_init(progress
, 1.0);
3688 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3689 if (fmt
&& has_help_option(options
)) {
3690 /* If a format is explicitly specified (and possibly no filename is
3691 * given), print option help here */
3692 ret
= print_block_option_help(filename
, fmt
);
3696 if (optind
!= argc
- 1) {
3697 error_report("Expecting one image file name");
3702 flags
= BDRV_O_RDWR
;
3703 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3705 error_report("Invalid cache option: %s", cache
);
3709 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3717 fmt
= bs
->drv
->format_name
;
3719 if (has_help_option(options
)) {
3720 /* If the format was auto-detected, print option help here */
3721 ret
= print_block_option_help(filename
, fmt
);
3725 if (!bs
->drv
->create_opts
) {
3726 error_report("Format driver '%s' does not support any options to amend",
3732 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3733 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3734 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3736 error_report_err(err
);
3741 /* In case the driver does not call amend_status_cb() */
3742 qemu_progress_print(0.f
, 0);
3743 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3744 qemu_progress_print(100.f
, 0);
3746 error_report("Error while amending options: %s", strerror(-ret
));
3751 qemu_progress_end();
3755 qemu_opts_del(opts
);
3756 qemu_opts_free(create_opts
);
3765 typedef struct BenchData
{
3767 uint64_t image_size
;
3774 bool drain_on_flush
;
3783 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3786 error_report("Failed flush request: %s", strerror(-ret
));
3791 static void bench_cb(void *opaque
, int ret
)
3793 BenchData
*b
= opaque
;
3797 error_report("Failed request: %s", strerror(-ret
));
3802 /* Just finished a flush with drained queue: Start next requests */
3803 assert(b
->in_flight
== 0);
3804 b
->in_flush
= false;
3805 } else if (b
->in_flight
> 0) {
3806 int remaining
= b
->n
- b
->in_flight
;
3811 /* Time for flush? Drain queue if requested, then flush */
3812 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3813 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3814 BlockCompletionFunc
*cb
;
3816 if (b
->drain_on_flush
) {
3820 cb
= bench_undrained_flush_cb
;
3823 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3825 error_report("Failed to issue flush request");
3829 if (b
->drain_on_flush
) {
3835 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3836 int64_t offset
= b
->offset
;
3837 /* blk_aio_* might look for completed I/Os and kick bench_cb
3838 * again, so make sure this operation is counted by in_flight
3839 * and b->offset is ready for the next submission.
3842 b
->offset
+= b
->step
;
3843 b
->offset
%= b
->image_size
;
3845 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3847 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3850 error_report("Failed to issue request");
3856 static int img_bench(int argc
, char **argv
)
3859 const char *fmt
= NULL
, *filename
;
3861 bool image_opts
= false;
3862 bool is_write
= false;
3866 size_t bufsize
= 4096;
3869 int flush_interval
= 0;
3870 bool drain_on_flush
= true;
3872 BlockBackend
*blk
= NULL
;
3873 BenchData data
= {};
3875 bool writethrough
= false;
3876 struct timeval t1
, t2
;
3878 bool force_share
= false;
3881 static const struct option long_options
[] = {
3882 {"help", no_argument
, 0, 'h'},
3883 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3884 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3885 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3886 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3887 {"force-share", no_argument
, 0, 'U'},
3890 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3897 missing_argument(argv
[optind
- 1]);
3900 unrecognized_option(argv
[optind
- 1]);
3909 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3910 error_report("Invalid request count specified");
3920 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3921 error_report("Invalid queue depth specified");
3931 flags
|= BDRV_O_NATIVE_AIO
;
3935 offset
= cvtnum(optarg
);
3937 error_report("Invalid offset specified");
3950 sval
= cvtnum(optarg
);
3951 if (sval
< 0 || sval
> INT_MAX
) {
3952 error_report("Invalid buffer size specified");
3963 sval
= cvtnum(optarg
);
3964 if (sval
< 0 || sval
> INT_MAX
) {
3965 error_report("Invalid step size specified");
3973 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3975 error_report("Invalid cache mode");
3981 flags
|= BDRV_O_RDWR
;
3987 case OPTION_PATTERN
:
3991 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3992 error_report("Invalid pattern byte specified");
3998 case OPTION_FLUSH_INTERVAL
:
4002 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4003 error_report("Invalid flush interval specified");
4006 flush_interval
= res
;
4009 case OPTION_NO_DRAIN
:
4010 drain_on_flush
= false;
4012 case OPTION_IMAGE_OPTS
:
4018 if (optind
!= argc
- 1) {
4019 error_exit("Expecting one image file name");
4021 filename
= argv
[argc
- 1];
4023 if (!is_write
&& flush_interval
) {
4024 error_report("--flush-interval is only available in write tests");
4028 if (flush_interval
&& flush_interval
< depth
) {
4029 error_report("Flush interval can't be smaller than depth");
4034 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4041 image_size
= blk_getlength(blk
);
4042 if (image_size
< 0) {
4047 data
= (BenchData
) {
4049 .image_size
= image_size
,
4051 .step
= step
?: bufsize
,
4056 .flush_interval
= flush_interval
,
4057 .drain_on_flush
= drain_on_flush
,
4059 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4060 "(starting at offset %" PRId64
", step size %d)\n",
4061 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4062 data
.offset
, data
.step
);
4063 if (flush_interval
) {
4064 printf("Sending flush every %d requests\n", flush_interval
);
4067 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
4068 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4070 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4071 for (i
= 0; i
< data
.nrreq
; i
++) {
4072 qemu_iovec_init(&data
.qiov
[i
], 1);
4073 qemu_iovec_add(&data
.qiov
[i
],
4074 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4077 gettimeofday(&t1
, NULL
);
4080 while (data
.n
> 0) {
4081 main_loop_wait(false);
4083 gettimeofday(&t2
, NULL
);
4085 printf("Run completed in %3.3f seconds.\n",
4086 (t2
.tv_sec
- t1
.tv_sec
)
4087 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4090 qemu_vfree(data
.buf
);
4111 int bsz
; /* Block size */
4119 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4123 static int img_dd_bs(const char *arg
,
4124 struct DdIo
*in
, struct DdIo
*out
,
4131 if (res
<= 0 || res
> INT_MAX
) {
4132 error_report("invalid number: '%s'", arg
);
4135 in
->bsz
= out
->bsz
= res
;
4140 static int img_dd_count(const char *arg
,
4141 struct DdIo
*in
, struct DdIo
*out
,
4144 dd
->count
= cvtnum(arg
);
4146 if (dd
->count
< 0) {
4147 error_report("invalid number: '%s'", arg
);
4154 static int img_dd_if(const char *arg
,
4155 struct DdIo
*in
, struct DdIo
*out
,
4158 in
->filename
= g_strdup(arg
);
4163 static int img_dd_of(const char *arg
,
4164 struct DdIo
*in
, struct DdIo
*out
,
4167 out
->filename
= g_strdup(arg
);
4172 static int img_dd_skip(const char *arg
,
4173 struct DdIo
*in
, struct DdIo
*out
,
4176 in
->offset
= cvtnum(arg
);
4178 if (in
->offset
< 0) {
4179 error_report("invalid number: '%s'", arg
);
4186 static int img_dd(int argc
, char **argv
)
4191 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4192 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4193 QemuOpts
*opts
= NULL
;
4194 QemuOptsList
*create_opts
= NULL
;
4195 Error
*local_err
= NULL
;
4196 bool image_opts
= false;
4198 const char *out_fmt
= "raw";
4199 const char *fmt
= NULL
;
4201 int64_t block_count
= 0, out_pos
, in_pos
;
4202 bool force_share
= false;
4203 struct DdInfo dd
= {
4208 .bsz
= 512, /* Block size is by default 512 bytes */
4220 const struct DdOpts options
[] = {
4221 { "bs", img_dd_bs
, C_BS
},
4222 { "count", img_dd_count
, C_COUNT
},
4223 { "if", img_dd_if
, C_IF
},
4224 { "of", img_dd_of
, C_OF
},
4225 { "skip", img_dd_skip
, C_SKIP
},
4228 const struct option long_options
[] = {
4229 { "help", no_argument
, 0, 'h'},
4230 { "object", required_argument
, 0, OPTION_OBJECT
},
4231 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4232 { "force-share", no_argument
, 0, 'U'},
4236 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4248 missing_argument(argv
[optind
- 1]);
4251 unrecognized_option(argv
[optind
- 1]);
4260 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4265 case OPTION_IMAGE_OPTS
:
4271 for (i
= optind
; i
< argc
; i
++) {
4273 arg
= g_strdup(argv
[i
]);
4275 tmp
= strchr(arg
, '=');
4277 error_report("unrecognized operand %s", arg
);
4284 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4285 if (!strcmp(arg
, options
[j
].name
)) {
4289 if (options
[j
].name
== NULL
) {
4290 error_report("unrecognized operand %s", arg
);
4295 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4299 dd
.flags
|= options
[j
].flag
;
4304 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4305 error_report("Must specify both input and output files");
4310 if (qemu_opts_foreach(&qemu_object_opts
,
4311 user_creatable_add_opts_foreach
,
4317 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4325 drv
= bdrv_find_format(out_fmt
);
4327 error_report("Unknown file format");
4331 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4334 error_report_err(local_err
);
4338 if (!drv
->create_opts
) {
4339 error_report("Format driver '%s' does not support image creation",
4344 if (!proto_drv
->create_opts
) {
4345 error_report("Protocol driver '%s' does not support image creation",
4346 proto_drv
->format_name
);
4350 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4351 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4353 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4355 size
= blk_getlength(blk1
);
4357 error_report("Failed to get size for '%s'", in
.filename
);
4362 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4363 dd
.count
* in
.bsz
< size
) {
4364 size
= dd
.count
* in
.bsz
;
4367 /* Overflow means the specified offset is beyond input image's size */
4368 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4369 size
< in
.bsz
* in
.offset
)) {
4370 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4372 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4373 size
- in
.bsz
* in
.offset
, &error_abort
);
4376 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4378 error_reportf_err(local_err
,
4379 "%s: error while creating output image: ",
4385 /* TODO, we can't honour --image-opts for the target,
4386 * since it needs to be given in a format compatible
4387 * with the bdrv_create() call above which does not
4388 * support image-opts style.
4390 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4391 false, false, false);
4398 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4399 size
< in
.offset
* in
.bsz
)) {
4400 /* We give a warning if the skip option is bigger than the input
4401 * size and create an empty output disk image (i.e. like dd(1)).
4403 error_report("%s: cannot skip to specified offset", in
.filename
);
4406 in_pos
= in
.offset
* in
.bsz
;
4409 in
.buf
= g_new(uint8_t, in
.bsz
);
4411 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4412 int in_ret
, out_ret
;
4414 if (in_pos
+ in
.bsz
> size
) {
4415 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4417 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4420 error_report("error while reading from input image file: %s",
4427 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4430 error_report("error while writing to output image file: %s",
4431 strerror(-out_ret
));
4440 qemu_opts_del(opts
);
4441 qemu_opts_free(create_opts
);
4444 g_free(in
.filename
);
4445 g_free(out
.filename
);
4455 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4459 Visitor
*v
= qobject_output_visitor_new(&obj
);
4461 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4462 visit_complete(v
, &obj
);
4463 str
= qobject_to_json_pretty(obj
);
4464 assert(str
!= NULL
);
4465 printf("%s\n", qstring_get_str(str
));
4466 qobject_decref(obj
);
4471 static int img_measure(int argc
, char **argv
)
4473 static const struct option long_options
[] = {
4474 {"help", no_argument
, 0, 'h'},
4475 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4476 {"object", required_argument
, 0, OPTION_OBJECT
},
4477 {"output", required_argument
, 0, OPTION_OUTPUT
},
4478 {"size", required_argument
, 0, OPTION_SIZE
},
4479 {"force-share", no_argument
, 0, 'U'},
4482 OutputFormat output_format
= OFORMAT_HUMAN
;
4483 BlockBackend
*in_blk
= NULL
;
4485 const char *filename
= NULL
;
4486 const char *fmt
= NULL
;
4487 const char *out_fmt
= "raw";
4488 char *options
= NULL
;
4489 char *snapshot_name
= NULL
;
4490 bool force_share
= false;
4491 QemuOpts
*opts
= NULL
;
4492 QemuOpts
*object_opts
= NULL
;
4493 QemuOpts
*sn_opts
= NULL
;
4494 QemuOptsList
*create_opts
= NULL
;
4495 bool image_opts
= false;
4496 uint64_t img_size
= UINT64_MAX
;
4497 BlockMeasureInfo
*info
= NULL
;
4498 Error
*local_err
= NULL
;
4502 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4503 long_options
, NULL
)) != -1) {
4516 if (!is_valid_option_list(optarg
)) {
4517 error_report("Invalid option list: %s", optarg
);
4521 options
= g_strdup(optarg
);
4523 char *old_options
= options
;
4524 options
= g_strdup_printf("%s,%s", options
, optarg
);
4525 g_free(old_options
);
4529 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4530 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4533 error_report("Failed in parsing snapshot param '%s'",
4538 snapshot_name
= optarg
;
4545 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4551 case OPTION_IMAGE_OPTS
:
4555 if (!strcmp(optarg
, "json")) {
4556 output_format
= OFORMAT_JSON
;
4557 } else if (!strcmp(optarg
, "human")) {
4558 output_format
= OFORMAT_HUMAN
;
4560 error_report("--output must be used with human or json "
4569 sval
= cvtnum(optarg
);
4571 if (sval
== -ERANGE
) {
4572 error_report("Image size must be less than 8 EiB!");
4574 error_report("Invalid image size specified! You may use "
4575 "k, M, G, T, P or E suffixes for ");
4576 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4577 "petabytes and exabytes.");
4581 img_size
= (uint64_t)sval
;
4587 if (qemu_opts_foreach(&qemu_object_opts
,
4588 user_creatable_add_opts_foreach
,
4593 if (argc
- optind
> 1) {
4594 error_report("At most one filename argument is allowed.");
4596 } else if (argc
- optind
== 1) {
4597 filename
= argv
[optind
];
4601 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4602 error_report("--object, --image-opts, -f, and -l "
4603 "require a filename argument.");
4606 if (filename
&& img_size
!= UINT64_MAX
) {
4607 error_report("--size N cannot be used together with a filename.");
4610 if (!filename
&& img_size
== UINT64_MAX
) {
4611 error_report("Either --size N or one filename must be specified.");
4616 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4617 false, false, force_share
);
4623 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4624 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4625 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4627 } else if (snapshot_name
!= NULL
) {
4628 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4629 snapshot_name
, &local_err
);
4632 error_reportf_err(local_err
, "Failed to load snapshot: ");
4637 drv
= bdrv_find_format(out_fmt
);
4639 error_report("Unknown file format '%s'", out_fmt
);
4642 if (!drv
->create_opts
) {
4643 error_report("Format driver '%s' does not support image creation",
4648 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4649 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4650 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4652 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4654 error_report_err(local_err
);
4655 error_report("Invalid options for file format '%s'", out_fmt
);
4659 if (img_size
!= UINT64_MAX
) {
4660 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4663 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4665 error_report_err(local_err
);
4669 if (output_format
== OFORMAT_HUMAN
) {
4670 printf("required size: %" PRIu64
"\n", info
->required
);
4671 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4673 dump_json_block_measure_info(info
);
4679 qapi_free_BlockMeasureInfo(info
);
4680 qemu_opts_del(object_opts
);
4681 qemu_opts_del(opts
);
4682 qemu_opts_del(sn_opts
);
4683 qemu_opts_free(create_opts
);
4689 static const img_cmd_t img_cmds
[] = {
4690 #define DEF(option, callback, arg_string) \
4691 { option, callback },
4692 #include "qemu-img-cmds.h"
4698 int main(int argc
, char **argv
)
4700 const img_cmd_t
*cmd
;
4701 const char *cmdname
;
4702 Error
*local_error
= NULL
;
4703 char *trace_file
= NULL
;
4705 static const struct option long_options
[] = {
4706 {"help", no_argument
, 0, 'h'},
4707 {"version", no_argument
, 0, 'V'},
4708 {"trace", required_argument
, NULL
, 'T'},
4713 signal(SIGPIPE
, SIG_IGN
);
4716 module_call_init(MODULE_INIT_TRACE
);
4717 error_set_progname(argv
[0]);
4718 qemu_init_exec_dir(argv
[0]);
4720 if (qemu_init_main_loop(&local_error
)) {
4721 error_report_err(local_error
);
4725 qcrypto_init(&error_fatal
);
4727 module_call_init(MODULE_INIT_QOM
);
4730 error_exit("Not enough arguments");
4733 qemu_add_opts(&qemu_object_opts
);
4734 qemu_add_opts(&qemu_source_opts
);
4735 qemu_add_opts(&qemu_trace_opts
);
4737 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4740 missing_argument(argv
[optind
- 1]);
4743 unrecognized_option(argv
[optind
- 1]);
4749 printf(QEMU_IMG_VERSION
);
4753 trace_file
= trace_opt_parse(optarg
);
4758 cmdname
= argv
[optind
];
4760 /* reset getopt_long scanning */
4768 if (!trace_init_backends()) {
4771 trace_init_file(trace_file
);
4772 qemu_set_log(LOG_TRACE
);
4774 /* find the command */
4775 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4776 if (!strcmp(cmdname
, cmd
->name
)) {
4777 return cmd
->handler(argc
, argv
);
4782 error_exit("Command not found: %s", cmdname
);