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"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi-visit.h"
28 #include "qapi/qobject-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qemu/cutils.h"
33 #include "qemu/config-file.h"
34 #include "qemu/option.h"
35 #include "qemu/error-report.h"
37 #include "qom/object_interfaces.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/block-backend.h"
40 #include "block/block_int.h"
41 #include "block/blockjob.h"
42 #include "block/qapi.h"
43 #include "crypto/init.h"
44 #include "trace/control.h"
47 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
48 "\n" QEMU_COPYRIGHT "\n"
50 typedef struct img_cmd_t
{
52 int (*handler
)(int argc
, char **argv
);
57 OPTION_BACKING_CHAIN
= 257,
59 OPTION_IMAGE_OPTS
= 259,
61 OPTION_FLUSH_INTERVAL
= 261,
62 OPTION_NO_DRAIN
= 262,
63 OPTION_TARGET_IMAGE_OPTS
= 263,
66 typedef enum OutputFormat
{
71 /* Default to cache=writeback as data integrity is not important for qemu-img */
72 #define BDRV_DEFAULT_CACHE "writeback"
74 static void format_print(void *opaque
, const char *name
)
79 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
83 error_printf("qemu-img: ");
86 error_vprintf(fmt
, ap
);
89 error_printf("\nTry 'qemu-img --help' for more information\n");
93 static void QEMU_NORETURN
missing_argument(const char *option
)
95 error_exit("missing argument for option '%s'", option
);
98 static void QEMU_NORETURN
unrecognized_option(const char *option
)
100 error_exit("unrecognized option '%s'", option
);
103 /* Please keep in synch with qemu-img.texi */
104 static void QEMU_NORETURN
help(void)
106 const char *help_msg
=
108 "usage: qemu-img [standard options] command [command options]\n"
109 "QEMU disk image utility\n"
111 " '-h', '--help' display this help and exit\n"
112 " '-V', '--version' output version information and exit\n"
113 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
114 " specify tracing options\n"
117 #define DEF(option, callback, arg_string) \
119 #include "qemu-img-cmds.h"
123 "Command parameters:\n"
124 " 'filename' is a disk image filename\n"
125 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
126 " manual page for a description of the object properties. The most common\n"
127 " object type is a 'secret', which is used to supply passwords and/or\n"
128 " encryption keys.\n"
129 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
130 " 'cache' is the cache mode used to write the output disk image, the valid\n"
131 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
132 " 'directsync' and 'unsafe' (default for convert)\n"
133 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
134 " options are the same as for the 'cache' option\n"
135 " 'size' is the disk image size in bytes. Optional suffixes\n"
136 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
137 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
138 " supported. 'b' is ignored.\n"
139 " 'output_filename' is the destination disk image filename\n"
140 " 'output_fmt' is the destination format\n"
141 " 'options' is a comma separated list of format specific options in a\n"
142 " name=value format. Use -o ? for an overview of the options supported by the\n"
144 " 'snapshot_param' is param used for internal snapshot, format\n"
145 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
147 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
149 " '-c' indicates that target image must be compressed (qcow format only)\n"
150 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
151 " match exactly. The image doesn't need a working backing file before\n"
152 " rebasing in this case (useful for renaming the backing file)\n"
153 " '-h' with or without a command shows this help and lists the supported formats\n"
154 " '-p' show progress of command (only certain commands)\n"
155 " '-q' use Quiet mode - do not print any output (except errors)\n"
156 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
157 " contain only zeros for qemu-img to create a sparse image during\n"
158 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
159 " unallocated or zero sectors, and the destination image will always be\n"
161 " '--output' takes the format in which the output must be done (human or json)\n"
162 " '-n' skips the target volume creation (useful if the volume is created\n"
163 " prior to running qemu-img)\n"
165 "Parameters to check subcommand:\n"
166 " '-r' tries to repair any inconsistencies that are found during the check.\n"
167 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
168 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
169 " hiding corruption that has already occurred.\n"
171 "Parameters to convert subcommand:\n"
172 " '-m' specifies how many coroutines work in parallel during the convert\n"
173 " process (defaults to 8)\n"
174 " '-W' allow to write to the target out of order rather than sequential\n"
176 "Parameters to snapshot subcommand:\n"
177 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
178 " '-a' applies a snapshot (revert disk to saved state)\n"
179 " '-c' creates a snapshot\n"
180 " '-d' deletes a snapshot\n"
181 " '-l' lists all snapshots in the given image\n"
183 "Parameters to compare subcommand:\n"
184 " '-f' first image format\n"
185 " '-F' second image format\n"
186 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
188 "Parameters to dd subcommand:\n"
189 " 'bs=BYTES' read and write up to BYTES bytes at a time "
191 " 'count=N' copy only N input blocks\n"
192 " 'if=FILE' read from FILE\n"
193 " 'of=FILE' write to FILE\n"
194 " 'skip=N' skip N bs-sized blocks at the start of input\n";
196 printf("%s\nSupported formats:", help_msg
);
197 bdrv_iterate_format(format_print
, NULL
);
202 static QemuOptsList qemu_object_opts
= {
204 .implied_opt_name
= "qom-type",
205 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
211 static QemuOptsList qemu_source_opts
= {
213 .implied_opt_name
= "file",
214 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
220 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
226 ret
= vprintf(fmt
, args
);
233 static int print_block_option_help(const char *filename
, const char *fmt
)
235 BlockDriver
*drv
, *proto_drv
;
236 QemuOptsList
*create_opts
= NULL
;
237 Error
*local_err
= NULL
;
239 /* Find driver and parse its options */
240 drv
= bdrv_find_format(fmt
);
242 error_report("Unknown file format '%s'", fmt
);
246 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
248 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
250 error_report_err(local_err
);
251 qemu_opts_free(create_opts
);
254 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
257 qemu_opts_print_help(create_opts
);
258 qemu_opts_free(create_opts
);
263 static int img_open_password(BlockBackend
*blk
, const char *filename
,
264 int flags
, bool quiet
)
266 BlockDriverState
*bs
;
270 if (bdrv_is_encrypted(bs
) && bdrv_key_required(bs
) &&
271 !(flags
& BDRV_O_NO_IO
)) {
272 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
273 if (qemu_read_password(password
, sizeof(password
)) < 0) {
274 error_report("No password given");
277 if (bdrv_set_key(bs
, password
) < 0) {
278 error_report("invalid password");
286 static BlockBackend
*img_open_opts(const char *optstr
,
287 QemuOpts
*opts
, int flags
, bool writethrough
,
288 bool quiet
, bool force_share
)
291 Error
*local_err
= NULL
;
293 options
= qemu_opts_to_qdict(opts
, NULL
);
295 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
296 && !qdict_get_bool(options
, BDRV_OPT_FORCE_SHARE
)) {
297 error_report("--force-share/-U conflicts with image options");
301 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
303 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
305 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
308 blk_set_enable_write_cache(blk
, !writethrough
);
310 if (img_open_password(blk
, optstr
, flags
, quiet
) < 0) {
317 static BlockBackend
*img_open_file(const char *filename
,
319 const char *fmt
, int flags
,
320 bool writethrough
, bool quiet
,
324 Error
*local_err
= NULL
;
327 options
= qdict_new();
330 qdict_put_str(options
, "driver", fmt
);
334 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
336 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
338 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
341 blk_set_enable_write_cache(blk
, !writethrough
);
343 if (img_open_password(blk
, filename
, flags
, quiet
) < 0) {
351 static int img_add_key_secrets(void *opaque
,
352 const char *name
, const char *value
,
355 QDict
*options
= opaque
;
357 if (g_str_has_suffix(name
, "key-secret")) {
358 qdict_put(options
, name
, qstring_from_str(value
));
364 static BlockBackend
*img_open_new_file(const char *filename
,
365 QemuOpts
*create_opts
,
366 const char *fmt
, int flags
,
367 bool writethrough
, bool quiet
,
370 QDict
*options
= NULL
;
372 options
= qdict_new();
373 qemu_opt_foreach(create_opts
, img_add_key_secrets
, options
, &error_abort
);
375 return img_open_file(filename
, options
, fmt
, flags
, writethrough
, quiet
,
380 static BlockBackend
*img_open(bool image_opts
,
381 const char *filename
,
382 const char *fmt
, int flags
, bool writethrough
,
383 bool quiet
, bool force_share
)
389 error_report("--image-opts and --format are mutually exclusive");
392 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
397 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
400 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
407 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
408 const char *base_filename
,
409 const char *base_fmt
)
414 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
416 error_report("Backing file not supported for file format '%s'",
423 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
425 error_report("Backing file format not supported for file "
434 static int64_t cvtnum(const char *s
)
439 err
= qemu_strtosz(s
, NULL
, &value
);
443 if (value
> INT64_MAX
) {
449 static int img_create(int argc
, char **argv
)
452 uint64_t img_size
= -1;
453 const char *fmt
= "raw";
454 const char *base_fmt
= NULL
;
455 const char *filename
;
456 const char *base_filename
= NULL
;
457 char *options
= NULL
;
458 Error
*local_err
= NULL
;
462 static const struct option long_options
[] = {
463 {"help", no_argument
, 0, 'h'},
464 {"object", required_argument
, 0, OPTION_OBJECT
},
467 c
= getopt_long(argc
, argv
, ":F:b:f:ho:q",
474 missing_argument(argv
[optind
- 1]);
477 unrecognized_option(argv
[optind
- 1]);
486 base_filename
= optarg
;
492 if (!is_valid_option_list(optarg
)) {
493 error_report("Invalid option list: %s", optarg
);
497 options
= g_strdup(optarg
);
499 char *old_options
= options
;
500 options
= g_strdup_printf("%s,%s", options
, optarg
);
507 case OPTION_OBJECT
: {
509 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
518 /* Get the filename */
519 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
520 if (options
&& has_help_option(options
)) {
522 return print_block_option_help(filename
, fmt
);
525 if (optind
>= argc
) {
526 error_exit("Expecting image file name");
530 if (qemu_opts_foreach(&qemu_object_opts
,
531 user_creatable_add_opts_foreach
,
536 /* Get image size, if specified */
540 sval
= cvtnum(argv
[optind
++]);
542 if (sval
== -ERANGE
) {
543 error_report("Image size must be less than 8 EiB!");
545 error_report("Invalid image size specified! You may use k, M, "
546 "G, T, P or E suffixes for ");
547 error_report("kilobytes, megabytes, gigabytes, terabytes, "
548 "petabytes and exabytes.");
552 img_size
= (uint64_t)sval
;
554 if (optind
!= argc
) {
555 error_exit("Unexpected argument: %s", argv
[optind
]);
558 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
559 options
, img_size
, 0, quiet
, &local_err
);
561 error_reportf_err(local_err
, "%s: ", filename
);
573 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
577 Visitor
*v
= qobject_output_visitor_new(&obj
);
579 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
580 visit_complete(v
, &obj
);
581 str
= qobject_to_json_pretty(obj
);
583 qprintf(quiet
, "%s\n", qstring_get_str(str
));
589 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
591 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
592 qprintf(quiet
, "No errors were found on the image.\n");
594 if (check
->corruptions
) {
595 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
596 "Data may be corrupted, or further writes to the image "
603 "\n%" PRId64
" leaked clusters were found on the image.\n"
604 "This means waste of disk space, but no harm to data.\n",
608 if (check
->check_errors
) {
611 " internal errors have occurred during the check.\n",
612 check
->check_errors
);
616 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
617 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
618 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
619 check
->allocated_clusters
, check
->total_clusters
,
620 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
621 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
622 check
->compressed_clusters
* 100.0 /
623 check
->allocated_clusters
);
626 if (check
->image_end_offset
) {
628 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
632 static int collect_image_check(BlockDriverState
*bs
,
634 const char *filename
,
639 BdrvCheckResult result
;
641 ret
= bdrv_check(bs
, &result
, fix
);
646 check
->filename
= g_strdup(filename
);
647 check
->format
= g_strdup(bdrv_get_format_name(bs
));
648 check
->check_errors
= result
.check_errors
;
649 check
->corruptions
= result
.corruptions
;
650 check
->has_corruptions
= result
.corruptions
!= 0;
651 check
->leaks
= result
.leaks
;
652 check
->has_leaks
= result
.leaks
!= 0;
653 check
->corruptions_fixed
= result
.corruptions_fixed
;
654 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
655 check
->leaks_fixed
= result
.leaks_fixed
;
656 check
->has_leaks_fixed
= result
.leaks
!= 0;
657 check
->image_end_offset
= result
.image_end_offset
;
658 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
659 check
->total_clusters
= result
.bfi
.total_clusters
;
660 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
661 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
662 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
663 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
664 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
665 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
666 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
672 * Checks an image for consistency. Exit codes:
674 * 0 - Check completed, image is good
675 * 1 - Check not completed because of internal errors
676 * 2 - Check completed, image is corrupted
677 * 3 - Check completed, image has leaked clusters, but is good otherwise
678 * 63 - Checks are not supported by the image format
680 static int img_check(int argc
, char **argv
)
683 OutputFormat output_format
= OFORMAT_HUMAN
;
684 const char *filename
, *fmt
, *output
, *cache
;
686 BlockDriverState
*bs
;
688 int flags
= BDRV_O_CHECK
;
692 bool image_opts
= false;
693 bool force_share
= false;
697 cache
= BDRV_DEFAULT_CACHE
;
700 int option_index
= 0;
701 static const struct option long_options
[] = {
702 {"help", no_argument
, 0, 'h'},
703 {"format", required_argument
, 0, 'f'},
704 {"repair", required_argument
, 0, 'r'},
705 {"output", required_argument
, 0, OPTION_OUTPUT
},
706 {"object", required_argument
, 0, OPTION_OBJECT
},
707 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
708 {"force-share", no_argument
, 0, 'U'},
711 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
712 long_options
, &option_index
);
718 missing_argument(argv
[optind
- 1]);
721 unrecognized_option(argv
[optind
- 1]);
730 flags
|= BDRV_O_RDWR
;
732 if (!strcmp(optarg
, "leaks")) {
733 fix
= BDRV_FIX_LEAKS
;
734 } else if (!strcmp(optarg
, "all")) {
735 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
737 error_exit("Unknown option value for -r "
738 "(expecting 'leaks' or 'all'): %s", optarg
);
753 case OPTION_OBJECT
: {
755 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
761 case OPTION_IMAGE_OPTS
:
766 if (optind
!= argc
- 1) {
767 error_exit("Expecting one image file name");
769 filename
= argv
[optind
++];
771 if (output
&& !strcmp(output
, "json")) {
772 output_format
= OFORMAT_JSON
;
773 } else if (output
&& !strcmp(output
, "human")) {
774 output_format
= OFORMAT_HUMAN
;
776 error_report("--output must be used with human or json as argument.");
780 if (qemu_opts_foreach(&qemu_object_opts
,
781 user_creatable_add_opts_foreach
,
786 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
788 error_report("Invalid source cache option: %s", cache
);
792 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
799 check
= g_new0(ImageCheck
, 1);
800 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
802 if (ret
== -ENOTSUP
) {
803 error_report("This image format does not support checks");
808 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
809 int corruptions_fixed
, leaks_fixed
;
811 leaks_fixed
= check
->leaks_fixed
;
812 corruptions_fixed
= check
->corruptions_fixed
;
814 if (output_format
== OFORMAT_HUMAN
) {
816 "The following inconsistencies were found and repaired:\n\n"
817 " %" PRId64
" leaked clusters\n"
818 " %" PRId64
" corruptions\n\n"
819 "Double checking the fixed image now...\n",
821 check
->corruptions_fixed
);
824 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
826 check
->leaks_fixed
= leaks_fixed
;
827 check
->corruptions_fixed
= corruptions_fixed
;
831 switch (output_format
) {
833 dump_human_image_check(check
, quiet
);
836 dump_json_image_check(check
, quiet
);
841 if (ret
|| check
->check_errors
) {
843 error_report("Check failed: %s", strerror(-ret
));
845 error_report("Check failed");
851 if (check
->corruptions
) {
853 } else if (check
->leaks
) {
860 qapi_free_ImageCheck(check
);
865 typedef struct CommonBlockJobCBInfo
{
866 BlockDriverState
*bs
;
868 } CommonBlockJobCBInfo
;
870 static void common_block_job_cb(void *opaque
, int ret
)
872 CommonBlockJobCBInfo
*cbi
= opaque
;
875 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
879 static void run_block_job(BlockJob
*job
, Error
**errp
)
881 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
884 aio_context_acquire(aio_context
);
887 aio_poll(aio_context
, true);
888 qemu_progress_print(job
->len
?
889 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
890 } while (!job
->ready
&& !job
->completed
);
892 if (!job
->completed
) {
893 ret
= block_job_complete_sync(job
, errp
);
897 block_job_unref(job
);
898 aio_context_release(aio_context
);
900 /* publish completion progress only when success */
902 qemu_progress_print(100.f
, 0);
906 static int img_commit(int argc
, char **argv
)
909 const char *filename
, *fmt
, *cache
, *base
;
911 BlockDriverState
*bs
, *base_bs
;
913 bool progress
= false, quiet
= false, drop
= false;
915 Error
*local_err
= NULL
;
916 CommonBlockJobCBInfo cbi
;
917 bool image_opts
= false;
918 AioContext
*aio_context
;
921 cache
= BDRV_DEFAULT_CACHE
;
924 static const struct option long_options
[] = {
925 {"help", no_argument
, 0, 'h'},
926 {"object", required_argument
, 0, OPTION_OBJECT
},
927 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
930 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
937 missing_argument(argv
[optind
- 1]);
940 unrecognized_option(argv
[optind
- 1]);
965 case OPTION_OBJECT
: {
967 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
973 case OPTION_IMAGE_OPTS
:
979 /* Progress is not shown in Quiet mode */
984 if (optind
!= argc
- 1) {
985 error_exit("Expecting one image file name");
987 filename
= argv
[optind
++];
989 if (qemu_opts_foreach(&qemu_object_opts
,
990 user_creatable_add_opts_foreach
,
995 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
996 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
998 error_report("Invalid cache option: %s", cache
);
1002 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1009 qemu_progress_init(progress
, 1.f
);
1010 qemu_progress_print(0.f
, 100);
1013 base_bs
= bdrv_find_backing_image(bs
, base
);
1015 error_setg(&local_err
,
1016 "Did not find '%s' in the backing chain of '%s'",
1021 /* This is different from QMP, which by default uses the deepest file in
1022 * the backing chain (i.e., the very base); however, the traditional
1023 * behavior of qemu-img commit is using the immediate backing file. */
1024 base_bs
= backing_bs(bs
);
1026 error_setg(&local_err
, "Image does not have a backing file");
1031 cbi
= (CommonBlockJobCBInfo
){
1036 aio_context
= bdrv_get_aio_context(bs
);
1037 aio_context_acquire(aio_context
);
1038 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1039 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1040 &cbi
, false, &local_err
);
1041 aio_context_release(aio_context
);
1046 /* When the block job completes, the BlockBackend reference will point to
1047 * the old backing file. In order to avoid that the top image is already
1048 * deleted, so we can still empty it afterwards, increment the reference
1049 * counter here preemptively. */
1054 job
= block_job_get("commit");
1055 run_block_job(job
, &local_err
);
1060 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1061 ret
= bs
->drv
->bdrv_make_empty(bs
);
1063 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1075 qemu_progress_end();
1080 error_report_err(local_err
);
1084 qprintf(quiet
, "Image committed.\n");
1089 * Returns true iff the first sector pointed to by 'buf' contains at least
1092 * 'pnum' is set to the number of sectors (including and immediately following
1093 * the first one) that are known to be in the same allocated/unallocated state.
1095 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1104 is_zero
= buffer_is_zero(buf
, 512);
1105 for(i
= 1; i
< n
; i
++) {
1107 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1116 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1117 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1118 * breaking up write requests for only small sparse areas.
1120 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1124 int num_checked
, num_used
;
1130 ret
= is_allocated_sectors(buf
, n
, pnum
);
1136 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1138 num_checked
= num_used
;
1141 ret
= is_allocated_sectors(buf
, n
, pnum
);
1143 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1145 num_checked
+= *pnum
;
1147 num_used
= num_checked
;
1148 } else if (*pnum
>= min
) {
1158 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1159 * buffers matches, non-zero otherwise.
1161 * pnum is set to the number of sectors (including and immediately following
1162 * the first one) that are known to have the same comparison result
1164 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1175 res
= !!memcmp(buf1
, buf2
, 512);
1176 for(i
= 1; i
< n
; i
++) {
1180 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1189 #define IO_BUF_SIZE (2 * 1024 * 1024)
1191 static int64_t sectors_to_bytes(int64_t sectors
)
1193 return sectors
<< BDRV_SECTOR_BITS
;
1196 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1198 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1202 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1204 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1205 * data and negative value on error.
1207 * @param blk: BlockBackend for the image
1208 * @param sect_num: Number of first sector to check
1209 * @param sect_count: Number of sectors to check
1210 * @param filename: Name of disk file we are checking (logging purpose)
1211 * @param buffer: Allocated buffer for storing read data
1212 * @param quiet: Flag for quiet mode
1214 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1215 int sect_count
, const char *filename
,
1216 uint8_t *buffer
, bool quiet
)
1219 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1220 sect_count
<< BDRV_SECTOR_BITS
);
1222 error_report("Error while reading offset %" PRId64
" of %s: %s",
1223 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1226 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1227 if (ret
|| pnum
!= sect_count
) {
1228 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1229 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1237 * Compares two images. Exit codes:
1239 * 0 - Images are identical
1241 * >1 - Error occurred
1243 static int img_compare(int argc
, char **argv
)
1245 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1246 BlockBackend
*blk1
, *blk2
;
1247 BlockDriverState
*bs1
, *bs2
;
1248 int64_t total_sectors1
, total_sectors2
;
1249 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1251 int allocated1
, allocated2
;
1252 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1253 bool progress
= false, quiet
= false, strict
= false;
1256 int64_t total_sectors
;
1257 int64_t sector_num
= 0;
1260 uint64_t progress_base
;
1261 bool image_opts
= false;
1262 bool force_share
= false;
1264 cache
= BDRV_DEFAULT_CACHE
;
1266 static const struct option long_options
[] = {
1267 {"help", no_argument
, 0, 'h'},
1268 {"object", required_argument
, 0, OPTION_OBJECT
},
1269 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1270 {"force-share", no_argument
, 0, 'U'},
1273 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1274 long_options
, NULL
);
1280 missing_argument(argv
[optind
- 1]);
1283 unrecognized_option(argv
[optind
- 1]);
1309 case OPTION_OBJECT
: {
1311 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1318 case OPTION_IMAGE_OPTS
:
1324 /* Progress is not shown in Quiet mode */
1330 if (optind
!= argc
- 2) {
1331 error_exit("Expecting two image file names");
1333 filename1
= argv
[optind
++];
1334 filename2
= argv
[optind
++];
1336 if (qemu_opts_foreach(&qemu_object_opts
,
1337 user_creatable_add_opts_foreach
,
1343 /* Initialize before goto out */
1344 qemu_progress_init(progress
, 2.0);
1347 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1349 error_report("Invalid source cache option: %s", cache
);
1354 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1361 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1370 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1371 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1372 total_sectors1
= blk_nb_sectors(blk1
);
1373 if (total_sectors1
< 0) {
1374 error_report("Can't get size of %s: %s",
1375 filename1
, strerror(-total_sectors1
));
1379 total_sectors2
= blk_nb_sectors(blk2
);
1380 if (total_sectors2
< 0) {
1381 error_report("Can't get size of %s: %s",
1382 filename2
, strerror(-total_sectors2
));
1386 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1387 progress_base
= MAX(total_sectors1
, total_sectors2
);
1389 qemu_progress_print(0, 100);
1391 if (strict
&& total_sectors1
!= total_sectors2
) {
1393 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1398 int64_t status1
, status2
;
1399 BlockDriverState
*file
;
1401 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1402 if (nb_sectors
<= 0) {
1405 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1406 total_sectors1
- sector_num
,
1410 error_report("Sector allocation test failed for %s", filename1
);
1413 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1415 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1416 total_sectors2
- sector_num
,
1420 error_report("Sector allocation test failed for %s", filename2
);
1423 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1425 nb_sectors
= MIN(nb_sectors
, pnum1
);
1428 nb_sectors
= MIN(nb_sectors
, pnum2
);
1432 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1433 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1435 qprintf(quiet
, "Strict mode: Offset %" PRId64
1436 " block status mismatch!\n",
1437 sectors_to_bytes(sector_num
));
1441 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1442 nb_sectors
= MIN(pnum1
, pnum2
);
1443 } else if (allocated1
== allocated2
) {
1445 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1446 nb_sectors
<< BDRV_SECTOR_BITS
);
1448 error_report("Error while reading offset %" PRId64
" of %s:"
1449 " %s", sectors_to_bytes(sector_num
), filename1
,
1454 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1455 nb_sectors
<< BDRV_SECTOR_BITS
);
1457 error_report("Error while reading offset %" PRId64
1458 " of %s: %s", sectors_to_bytes(sector_num
),
1459 filename2
, strerror(-ret
));
1463 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1464 if (ret
|| pnum
!= nb_sectors
) {
1465 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1467 ret
? sector_num
: sector_num
+ pnum
));
1475 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1476 filename1
, buf1
, quiet
);
1478 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1479 filename2
, buf1
, quiet
);
1483 error_report("Error while reading offset %" PRId64
": %s",
1484 sectors_to_bytes(sector_num
), strerror(-ret
));
1490 sector_num
+= nb_sectors
;
1491 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1494 if (total_sectors1
!= total_sectors2
) {
1495 BlockBackend
*blk_over
;
1496 int64_t total_sectors_over
;
1497 const char *filename_over
;
1499 qprintf(quiet
, "Warning: Image size mismatch!\n");
1500 if (total_sectors1
> total_sectors2
) {
1501 total_sectors_over
= total_sectors1
;
1503 filename_over
= filename1
;
1505 total_sectors_over
= total_sectors2
;
1507 filename_over
= filename2
;
1513 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1514 if (nb_sectors
<= 0) {
1517 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
,
1518 sector_num
* BDRV_SECTOR_SIZE
,
1519 nb_sectors
* BDRV_SECTOR_SIZE
,
1523 error_report("Sector allocation test failed for %s",
1528 /* TODO relax this once bdrv_is_allocated_above does not enforce
1529 * sector alignment */
1530 assert(QEMU_IS_ALIGNED(count
, BDRV_SECTOR_SIZE
));
1531 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1533 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1534 filename_over
, buf1
, quiet
);
1537 error_report("Error while reading offset %" PRId64
1538 " of %s: %s", sectors_to_bytes(sector_num
),
1539 filename_over
, strerror(-ret
));
1545 sector_num
+= nb_sectors
;
1546 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1550 qprintf(quiet
, "Images are identical.\n");
1560 qemu_progress_end();
1565 enum ImgConvertBlockStatus
{
1571 #define MAX_COROUTINES 16
1573 typedef struct ImgConvertState
{
1575 int64_t *src_sectors
;
1577 int64_t total_sectors
;
1578 int64_t allocated_sectors
;
1579 int64_t allocated_done
;
1582 enum ImgConvertBlockStatus status
;
1583 int64_t sector_next_status
;
1584 BlockBackend
*target
;
1587 bool target_has_backing
;
1590 size_t cluster_sectors
;
1592 long num_coroutines
;
1593 int running_coroutines
;
1594 Coroutine
*co
[MAX_COROUTINES
];
1595 int64_t wait_sector_num
[MAX_COROUTINES
];
1600 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1601 int *src_cur
, int64_t *src_cur_offset
)
1604 *src_cur_offset
= 0;
1605 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1606 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1608 assert(*src_cur
< s
->src_num
);
1612 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1614 int64_t ret
, src_cur_offset
;
1617 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1619 assert(s
->total_sectors
> sector_num
);
1620 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1622 if (s
->sector_next_status
<= sector_num
) {
1623 BlockDriverState
*file
;
1624 if (s
->target_has_backing
) {
1625 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1626 sector_num
- src_cur_offset
,
1629 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1630 sector_num
- src_cur_offset
,
1637 if (ret
& BDRV_BLOCK_ZERO
) {
1638 s
->status
= BLK_ZERO
;
1639 } else if (ret
& BDRV_BLOCK_DATA
) {
1640 s
->status
= BLK_DATA
;
1642 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1645 s
->sector_next_status
= sector_num
+ n
;
1648 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1649 if (s
->status
== BLK_DATA
) {
1650 n
= MIN(n
, s
->buf_sectors
);
1653 /* We need to write complete clusters for compressed images, so if an
1654 * unallocated area is shorter than that, we must consider the whole
1655 * cluster allocated. */
1656 if (s
->compressed
) {
1657 if (n
< s
->cluster_sectors
) {
1658 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1659 s
->status
= BLK_DATA
;
1661 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1668 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1669 int nb_sectors
, uint8_t *buf
)
1675 assert(nb_sectors
<= s
->buf_sectors
);
1676 while (nb_sectors
> 0) {
1679 int64_t bs_sectors
, src_cur_offset
;
1681 /* In the case of compression with multiple source files, we can get a
1682 * nb_sectors that spreads into the next part. So we must be able to
1683 * read across multiple BDSes for one convert_read() call. */
1684 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1685 blk
= s
->src
[src_cur
];
1686 bs_sectors
= s
->src_sectors
[src_cur
];
1688 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1690 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1691 qemu_iovec_init_external(&qiov
, &iov
, 1);
1693 ret
= blk_co_preadv(
1694 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1695 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1702 buf
+= n
* BDRV_SECTOR_SIZE
;
1709 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1710 int nb_sectors
, uint8_t *buf
,
1711 enum ImgConvertBlockStatus status
)
1717 while (nb_sectors
> 0) {
1719 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1722 case BLK_BACKING_FILE
:
1723 /* If we have a backing file, leave clusters unallocated that are
1724 * unallocated in the source image, so that the backing file is
1725 * visible at the respective offset. */
1726 assert(s
->target_has_backing
);
1730 /* If we're told to keep the target fully allocated (-S 0) or there
1731 * is real non-zero data, we must write it. Otherwise we can treat
1732 * it as zero sectors.
1733 * Compressed clusters need to be written as a whole, so in that
1734 * case we can only save the write if the buffer is completely
1736 if (!s
->min_sparse
||
1738 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1740 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1743 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1744 qemu_iovec_init_external(&qiov
, &iov
, 1);
1746 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1747 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1756 if (s
->has_zero_init
) {
1757 assert(!s
->target_has_backing
);
1760 ret
= blk_co_pwrite_zeroes(s
->target
,
1761 sector_num
<< BDRV_SECTOR_BITS
,
1762 n
<< BDRV_SECTOR_BITS
, 0);
1771 buf
+= n
* BDRV_SECTOR_SIZE
;
1777 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1779 ImgConvertState
*s
= opaque
;
1780 uint8_t *buf
= NULL
;
1784 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1785 if (s
->co
[i
] == qemu_coroutine_self()) {
1792 s
->running_coroutines
++;
1793 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1798 enum ImgConvertBlockStatus status
;
1800 qemu_co_mutex_lock(&s
->lock
);
1801 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1802 qemu_co_mutex_unlock(&s
->lock
);
1805 n
= convert_iteration_sectors(s
, s
->sector_num
);
1807 qemu_co_mutex_unlock(&s
->lock
);
1811 /* save current sector and allocation status to local variables */
1812 sector_num
= s
->sector_num
;
1814 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1815 n
= MIN(n
, s
->buf_sectors
);
1817 /* increment global sector counter so that other coroutines can
1818 * already continue reading beyond this request */
1820 qemu_co_mutex_unlock(&s
->lock
);
1822 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1823 s
->allocated_done
+= n
;
1824 qemu_progress_print(100.0 * s
->allocated_done
/
1825 s
->allocated_sectors
, 0);
1828 if (status
== BLK_DATA
) {
1829 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1831 error_report("error while reading sector %" PRId64
1832 ": %s", sector_num
, strerror(-ret
));
1835 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1837 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1840 if (s
->wr_in_order
) {
1841 /* keep writes in order */
1842 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1843 s
->wait_sector_num
[index
] = sector_num
;
1844 qemu_coroutine_yield();
1846 s
->wait_sector_num
[index
] = -1;
1849 if (s
->ret
== -EINPROGRESS
) {
1850 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1852 error_report("error while writing sector %" PRId64
1853 ": %s", sector_num
, strerror(-ret
));
1858 if (s
->wr_in_order
) {
1859 /* reenter the coroutine that might have waited
1860 * for this write to complete */
1861 s
->wr_offs
= sector_num
+ n
;
1862 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1863 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1865 * A -> B -> A cannot occur because A has
1866 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1867 * B will never enter A during this time window.
1869 qemu_coroutine_enter(s
->co
[i
]);
1877 s
->co
[index
] = NULL
;
1878 s
->running_coroutines
--;
1879 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1880 /* the convert job finished successfully */
1885 static int convert_do_copy(ImgConvertState
*s
)
1888 int64_t sector_num
= 0;
1890 /* Check whether we have zero initialisation or can get it efficiently */
1891 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1892 ? bdrv_has_zero_init(blk_bs(s
->target
))
1895 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1896 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1898 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1900 s
->has_zero_init
= true;
1904 /* Allocate buffer for copied data. For compressed images, only one cluster
1905 * can be copied at a time. */
1906 if (s
->compressed
) {
1907 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1908 error_report("invalid cluster size");
1911 s
->buf_sectors
= s
->cluster_sectors
;
1914 while (sector_num
< s
->total_sectors
) {
1915 n
= convert_iteration_sectors(s
, sector_num
);
1919 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1921 s
->allocated_sectors
+= n
;
1927 s
->sector_next_status
= 0;
1928 s
->ret
= -EINPROGRESS
;
1930 qemu_co_mutex_init(&s
->lock
);
1931 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1932 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1933 s
->wait_sector_num
[i
] = -1;
1934 qemu_coroutine_enter(s
->co
[i
]);
1937 while (s
->running_coroutines
) {
1938 main_loop_wait(false);
1941 if (s
->compressed
&& !s
->ret
) {
1942 /* signal EOF to align */
1943 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1952 static int img_convert(int argc
, char **argv
)
1954 int c
, bs_i
, flags
, src_flags
= 0;
1955 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1956 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1957 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1958 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1959 BlockDriverInfo bdi
;
1960 BlockDriverState
*out_bs
;
1961 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1962 QemuOptsList
*create_opts
= NULL
;
1963 char *options
= NULL
;
1964 Error
*local_err
= NULL
;
1965 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1966 skip_create
= false, progress
= false, tgt_image_opts
= false;
1967 int64_t ret
= -EINVAL
;
1968 bool force_share
= false;
1970 ImgConvertState s
= (ImgConvertState
) {
1971 /* Need at least 4k of zeros for sparse detection */
1973 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1974 .wr_in_order
= true,
1975 .num_coroutines
= 8,
1979 static const struct option long_options
[] = {
1980 {"help", no_argument
, 0, 'h'},
1981 {"object", required_argument
, 0, OPTION_OBJECT
},
1982 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1983 {"force-share", no_argument
, 0, 'U'},
1984 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1987 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1988 long_options
, NULL
);
1994 missing_argument(argv
[optind
- 1]);
1997 unrecognized_option(argv
[optind
- 1]);
2009 out_baseimg
= optarg
;
2012 s
.compressed
= true;
2015 if (!is_valid_option_list(optarg
)) {
2016 error_report("Invalid option list: %s", optarg
);
2020 options
= g_strdup(optarg
);
2022 char *old_options
= options
;
2023 options
= g_strdup_printf("%s,%s", options
, optarg
);
2024 g_free(old_options
);
2028 snapshot_name
= optarg
;
2031 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2032 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2035 error_report("Failed in parsing snapshot param '%s'",
2040 snapshot_name
= optarg
;
2047 sval
= cvtnum(optarg
);
2049 error_report("Invalid minimum zero buffer size for sparse output specified");
2053 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2072 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2073 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2074 error_report("Invalid number of coroutines. Allowed number of"
2075 " coroutines is between 1 and %d", MAX_COROUTINES
);
2080 s
.wr_in_order
= false;
2085 case OPTION_OBJECT
: {
2086 QemuOpts
*object_opts
;
2087 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2094 case OPTION_IMAGE_OPTS
:
2097 case OPTION_TARGET_IMAGE_OPTS
:
2098 tgt_image_opts
= true;
2103 if (!out_fmt
&& !tgt_image_opts
) {
2107 if (qemu_opts_foreach(&qemu_object_opts
,
2108 user_creatable_add_opts_foreach
,
2113 if (!s
.wr_in_order
&& s
.compressed
) {
2114 error_report("Out of order write and compress are mutually exclusive");
2118 if (tgt_image_opts
&& !skip_create
) {
2119 error_report("--target-image-opts requires use of -n flag");
2123 s
.src_num
= argc
- optind
- 1;
2124 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2126 if (options
&& has_help_option(options
)) {
2128 ret
= print_block_option_help(out_filename
, out_fmt
);
2131 error_report("Option help requires a format be specified");
2136 if (s
.src_num
< 1) {
2137 error_report("Must specify image file name");
2142 /* ret is still -EINVAL until here */
2143 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2145 error_report("Invalid source cache option: %s", src_cache
);
2149 /* Initialize before goto out */
2153 qemu_progress_init(progress
, 1.0);
2154 qemu_progress_print(0, 100);
2156 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2157 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2159 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2160 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2161 fmt
, src_flags
, src_writethrough
, quiet
,
2167 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2168 if (s
.src_sectors
[bs_i
] < 0) {
2169 error_report("Could not get size of %s: %s",
2170 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2174 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2178 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2179 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2180 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2182 } else if (snapshot_name
!= NULL
) {
2183 if (s
.src_num
> 1) {
2184 error_report("No support for concatenating multiple snapshot");
2189 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2193 error_reportf_err(local_err
, "Failed to load snapshot: ");
2199 /* Find driver and parse its options */
2200 drv
= bdrv_find_format(out_fmt
);
2202 error_report("Unknown file format '%s'", out_fmt
);
2207 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2209 error_report_err(local_err
);
2214 if (!drv
->create_opts
) {
2215 error_report("Format driver '%s' does not support image creation",
2221 if (!proto_drv
->create_opts
) {
2222 error_report("Protocol driver '%s' does not support image creation",
2223 proto_drv
->format_name
);
2228 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2229 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2231 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2233 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2235 error_report_err(local_err
);
2241 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2243 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2249 /* Get backing file name if -o backing_file was used */
2250 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2251 if (out_baseimg_param
) {
2252 out_baseimg
= out_baseimg_param
;
2254 s
.target_has_backing
= (bool) out_baseimg
;
2256 if (s
.src_num
> 1 && out_baseimg
) {
2257 error_report("Having a backing file for the target makes no sense when "
2258 "concatenating multiple input images");
2263 /* Check if compression is supported */
2266 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2267 const char *encryptfmt
=
2268 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2269 const char *preallocation
=
2270 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2272 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2273 error_report("Compression not supported for this file format");
2278 if (encryption
|| encryptfmt
) {
2279 error_report("Compression and encryption not supported at "
2286 && strcmp(preallocation
, "off"))
2288 error_report("Compression and preallocation not supported at "
2296 /* Create the new image */
2297 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2299 error_reportf_err(local_err
, "%s: error while converting %s: ",
2300 out_filename
, out_fmt
);
2305 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2306 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2308 error_report("Invalid cache option: %s", cache
);
2313 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2314 flags
, writethrough
, quiet
, false);
2316 /* TODO ultimately we should allow --target-image-opts
2317 * to be used even when -n is not given.
2318 * That has to wait for bdrv_create to be improved
2319 * to allow filenames in option syntax
2321 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2322 flags
, writethrough
, quiet
, false);
2328 out_bs
= blk_bs(s
.target
);
2330 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2331 error_report("Compression not supported for this file format");
2336 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2337 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2339 s
.buf_sectors
= MIN(32768,
2341 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2342 out_bs
->bl
.pdiscard_alignment
>>
2343 BDRV_SECTOR_BITS
)));
2346 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2347 if (output_sectors
< 0) {
2348 error_report("unable to get output image length: %s",
2349 strerror(-output_sectors
));
2352 } else if (output_sectors
< s
.total_sectors
) {
2353 error_report("output file is smaller than input file");
2359 ret
= bdrv_get_info(out_bs
, &bdi
);
2362 error_report("could not get block driver info");
2366 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2367 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2370 ret
= convert_do_copy(&s
);
2373 qemu_progress_print(100, 0);
2375 qemu_progress_end();
2376 qemu_opts_del(opts
);
2377 qemu_opts_free(create_opts
);
2378 qemu_opts_del(sn_opts
);
2379 blk_unref(s
.target
);
2381 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2382 blk_unref(s
.src
[bs_i
]);
2386 g_free(s
.src_sectors
);
2394 static void dump_snapshots(BlockDriverState
*bs
)
2396 QEMUSnapshotInfo
*sn_tab
, *sn
;
2399 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2402 printf("Snapshot list:\n");
2403 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2405 for(i
= 0; i
< nb_sns
; i
++) {
2407 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2413 static void dump_json_image_info_list(ImageInfoList
*list
)
2417 Visitor
*v
= qobject_output_visitor_new(&obj
);
2419 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2420 visit_complete(v
, &obj
);
2421 str
= qobject_to_json_pretty(obj
);
2422 assert(str
!= NULL
);
2423 printf("%s\n", qstring_get_str(str
));
2424 qobject_decref(obj
);
2429 static void dump_json_image_info(ImageInfo
*info
)
2433 Visitor
*v
= qobject_output_visitor_new(&obj
);
2435 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2436 visit_complete(v
, &obj
);
2437 str
= qobject_to_json_pretty(obj
);
2438 assert(str
!= NULL
);
2439 printf("%s\n", qstring_get_str(str
));
2440 qobject_decref(obj
);
2445 static void dump_human_image_info_list(ImageInfoList
*list
)
2447 ImageInfoList
*elem
;
2450 for (elem
= list
; elem
; elem
= elem
->next
) {
2456 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2460 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2462 return strcmp(a
, b
) == 0;
2466 * Open an image file chain and return an ImageInfoList
2468 * @filename: topmost image filename
2469 * @fmt: topmost image format (may be NULL to autodetect)
2470 * @chain: true - enumerate entire backing file chain
2471 * false - only topmost image file
2473 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2474 * image file. If there was an error a message will have been printed to
2477 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2478 const char *filename
,
2480 bool chain
, bool force_share
)
2482 ImageInfoList
*head
= NULL
;
2483 ImageInfoList
**last
= &head
;
2484 GHashTable
*filenames
;
2487 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2491 BlockDriverState
*bs
;
2493 ImageInfoList
*elem
;
2495 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2496 error_report("Backing file '%s' creates an infinite loop.",
2500 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2502 blk
= img_open(image_opts
, filename
, fmt
,
2503 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2510 bdrv_query_image_info(bs
, &info
, &err
);
2512 error_report_err(err
);
2517 elem
= g_new0(ImageInfoList
, 1);
2524 filename
= fmt
= NULL
;
2526 if (info
->has_full_backing_filename
) {
2527 filename
= info
->full_backing_filename
;
2528 } else if (info
->has_backing_filename
) {
2529 error_report("Could not determine absolute backing filename,"
2530 " but backing filename '%s' present",
2531 info
->backing_filename
);
2534 if (info
->has_backing_filename_format
) {
2535 fmt
= info
->backing_filename_format
;
2539 g_hash_table_destroy(filenames
);
2543 qapi_free_ImageInfoList(head
);
2544 g_hash_table_destroy(filenames
);
2548 static int img_info(int argc
, char **argv
)
2551 OutputFormat output_format
= OFORMAT_HUMAN
;
2553 const char *filename
, *fmt
, *output
;
2554 ImageInfoList
*list
;
2555 bool image_opts
= false;
2556 bool force_share
= false;
2561 int option_index
= 0;
2562 static const struct option long_options
[] = {
2563 {"help", no_argument
, 0, 'h'},
2564 {"format", required_argument
, 0, 'f'},
2565 {"output", required_argument
, 0, OPTION_OUTPUT
},
2566 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2567 {"object", required_argument
, 0, OPTION_OBJECT
},
2568 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2569 {"force-share", no_argument
, 0, 'U'},
2572 c
= getopt_long(argc
, argv
, ":f:hU",
2573 long_options
, &option_index
);
2579 missing_argument(argv
[optind
- 1]);
2582 unrecognized_option(argv
[optind
- 1]);
2596 case OPTION_BACKING_CHAIN
:
2599 case OPTION_OBJECT
: {
2601 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2607 case OPTION_IMAGE_OPTS
:
2612 if (optind
!= argc
- 1) {
2613 error_exit("Expecting one image file name");
2615 filename
= argv
[optind
++];
2617 if (output
&& !strcmp(output
, "json")) {
2618 output_format
= OFORMAT_JSON
;
2619 } else if (output
&& !strcmp(output
, "human")) {
2620 output_format
= OFORMAT_HUMAN
;
2621 } else if (output
) {
2622 error_report("--output must be used with human or json as argument.");
2626 if (qemu_opts_foreach(&qemu_object_opts
,
2627 user_creatable_add_opts_foreach
,
2632 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2638 switch (output_format
) {
2640 dump_human_image_info_list(list
);
2644 dump_json_image_info_list(list
);
2646 dump_json_image_info(list
->value
);
2651 qapi_free_ImageInfoList(list
);
2655 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2658 switch (output_format
) {
2660 if (e
->data
&& !e
->has_offset
) {
2661 error_report("File contains external, encrypted or compressed clusters.");
2664 if (e
->data
&& !e
->zero
) {
2665 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2666 e
->start
, e
->length
,
2667 e
->has_offset
? e
->offset
: 0,
2668 e
->has_filename
? e
->filename
: "");
2670 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2671 * Modify the flags here to allow more coalescing.
2673 if (next
&& (!next
->data
|| next
->zero
)) {
2679 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2680 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2681 (e
->start
== 0 ? "[" : ",\n"),
2682 e
->start
, e
->length
, e
->depth
,
2683 e
->zero
? "true" : "false",
2684 e
->data
? "true" : "false");
2685 if (e
->has_offset
) {
2686 printf(", \"offset\": %"PRId64
"", e
->offset
);
2697 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2698 int nb_sectors
, MapEntry
*e
)
2702 BlockDriverState
*file
;
2705 /* As an optimization, we could cache the current range of unallocated
2706 * clusters in each file of the chain, and avoid querying the same
2712 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2718 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2721 bs
= backing_bs(bs
);
2730 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2733 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2734 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2735 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2736 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2737 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2738 .has_offset
= has_offset
,
2740 .has_filename
= file
&& has_offset
,
2741 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2747 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2749 if (curr
->length
== 0) {
2752 if (curr
->zero
!= next
->zero
||
2753 curr
->data
!= next
->data
||
2754 curr
->depth
!= next
->depth
||
2755 curr
->has_filename
!= next
->has_filename
||
2756 curr
->has_offset
!= next
->has_offset
) {
2759 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2762 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2768 static int img_map(int argc
, char **argv
)
2771 OutputFormat output_format
= OFORMAT_HUMAN
;
2773 BlockDriverState
*bs
;
2774 const char *filename
, *fmt
, *output
;
2776 MapEntry curr
= { .length
= 0 }, next
;
2778 bool image_opts
= false;
2779 bool force_share
= false;
2784 int option_index
= 0;
2785 static const struct option long_options
[] = {
2786 {"help", no_argument
, 0, 'h'},
2787 {"format", required_argument
, 0, 'f'},
2788 {"output", required_argument
, 0, OPTION_OUTPUT
},
2789 {"object", required_argument
, 0, OPTION_OBJECT
},
2790 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2791 {"force-share", no_argument
, 0, 'U'},
2794 c
= getopt_long(argc
, argv
, ":f:hU",
2795 long_options
, &option_index
);
2801 missing_argument(argv
[optind
- 1]);
2804 unrecognized_option(argv
[optind
- 1]);
2818 case OPTION_OBJECT
: {
2820 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2826 case OPTION_IMAGE_OPTS
:
2831 if (optind
!= argc
- 1) {
2832 error_exit("Expecting one image file name");
2834 filename
= argv
[optind
];
2836 if (output
&& !strcmp(output
, "json")) {
2837 output_format
= OFORMAT_JSON
;
2838 } else if (output
&& !strcmp(output
, "human")) {
2839 output_format
= OFORMAT_HUMAN
;
2840 } else if (output
) {
2841 error_report("--output must be used with human or json as argument.");
2845 if (qemu_opts_foreach(&qemu_object_opts
,
2846 user_creatable_add_opts_foreach
,
2851 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2857 if (output_format
== OFORMAT_HUMAN
) {
2858 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2861 length
= blk_getlength(blk
);
2862 while (curr
.start
+ curr
.length
< length
) {
2863 int64_t nsectors_left
;
2867 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2869 /* Probe up to 1 GiB at a time. */
2870 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2871 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2872 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2875 error_report("Could not read file metadata: %s", strerror(-ret
));
2879 if (entry_mergeable(&curr
, &next
)) {
2880 curr
.length
+= next
.length
;
2884 if (curr
.length
> 0) {
2885 dump_map_entry(output_format
, &curr
, &next
);
2890 dump_map_entry(output_format
, &curr
, NULL
);
2897 #define SNAPSHOT_LIST 1
2898 #define SNAPSHOT_CREATE 2
2899 #define SNAPSHOT_APPLY 3
2900 #define SNAPSHOT_DELETE 4
2902 static int img_snapshot(int argc
, char **argv
)
2905 BlockDriverState
*bs
;
2906 QEMUSnapshotInfo sn
;
2907 char *filename
, *snapshot_name
= NULL
;
2908 int c
, ret
= 0, bdrv_oflags
;
2913 bool image_opts
= false;
2914 bool force_share
= false;
2916 bdrv_oflags
= BDRV_O_RDWR
;
2917 /* Parse commandline parameters */
2919 static const struct option long_options
[] = {
2920 {"help", no_argument
, 0, 'h'},
2921 {"object", required_argument
, 0, OPTION_OBJECT
},
2922 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2923 {"force-share", no_argument
, 0, 'U'},
2926 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2927 long_options
, NULL
);
2933 missing_argument(argv
[optind
- 1]);
2936 unrecognized_option(argv
[optind
- 1]);
2943 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2946 action
= SNAPSHOT_LIST
;
2947 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2951 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2954 action
= SNAPSHOT_APPLY
;
2955 snapshot_name
= optarg
;
2959 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2962 action
= SNAPSHOT_CREATE
;
2963 snapshot_name
= optarg
;
2967 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2970 action
= SNAPSHOT_DELETE
;
2971 snapshot_name
= optarg
;
2979 case OPTION_OBJECT
: {
2981 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2987 case OPTION_IMAGE_OPTS
:
2993 if (optind
!= argc
- 1) {
2994 error_exit("Expecting one image file name");
2996 filename
= argv
[optind
++];
2998 if (qemu_opts_foreach(&qemu_object_opts
,
2999 user_creatable_add_opts_foreach
,
3004 /* Open the image */
3005 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3012 /* Perform the requested action */
3018 case SNAPSHOT_CREATE
:
3019 memset(&sn
, 0, sizeof(sn
));
3020 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3022 qemu_gettimeofday(&tv
);
3023 sn
.date_sec
= tv
.tv_sec
;
3024 sn
.date_nsec
= tv
.tv_usec
* 1000;
3026 ret
= bdrv_snapshot_create(bs
, &sn
);
3028 error_report("Could not create snapshot '%s': %d (%s)",
3029 snapshot_name
, ret
, strerror(-ret
));
3033 case SNAPSHOT_APPLY
:
3034 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
3036 error_report("Could not apply snapshot '%s': %d (%s)",
3037 snapshot_name
, ret
, strerror(-ret
));
3041 case SNAPSHOT_DELETE
:
3042 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3044 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3059 static int img_rebase(int argc
, char **argv
)
3061 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3062 uint8_t *buf_old
= NULL
;
3063 uint8_t *buf_new
= NULL
;
3064 BlockDriverState
*bs
= NULL
;
3066 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3067 int c
, flags
, src_flags
, ret
;
3068 bool writethrough
, src_writethrough
;
3070 bool force_share
= false;
3073 Error
*local_err
= NULL
;
3074 bool image_opts
= false;
3076 /* Parse commandline parameters */
3078 cache
= BDRV_DEFAULT_CACHE
;
3079 src_cache
= BDRV_DEFAULT_CACHE
;
3083 static const struct option long_options
[] = {
3084 {"help", no_argument
, 0, 'h'},
3085 {"object", required_argument
, 0, OPTION_OBJECT
},
3086 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3087 {"force-share", no_argument
, 0, 'U'},
3090 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3091 long_options
, NULL
);
3097 missing_argument(argv
[optind
- 1]);
3100 unrecognized_option(argv
[optind
- 1]);
3109 out_basefmt
= optarg
;
3112 out_baseimg
= optarg
;
3129 case OPTION_OBJECT
: {
3131 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3137 case OPTION_IMAGE_OPTS
:
3150 if (optind
!= argc
- 1) {
3151 error_exit("Expecting one image file name");
3153 if (!unsafe
&& !out_baseimg
) {
3154 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3156 filename
= argv
[optind
++];
3158 if (qemu_opts_foreach(&qemu_object_opts
,
3159 user_creatable_add_opts_foreach
,
3164 qemu_progress_init(progress
, 2.0);
3165 qemu_progress_print(0, 100);
3167 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3168 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3170 error_report("Invalid cache option: %s", cache
);
3175 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3177 error_report("Invalid source cache option: %s", src_cache
);
3181 /* The source files are opened read-only, don't care about WCE */
3182 assert((src_flags
& BDRV_O_RDWR
) == 0);
3183 (void) src_writethrough
;
3188 * Ignore the old backing file for unsafe rebase in case we want to correct
3189 * the reference to a renamed or moved backing file.
3191 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3199 if (out_basefmt
!= NULL
) {
3200 if (bdrv_find_format(out_basefmt
) == NULL
) {
3201 error_report("Invalid format name: '%s'", out_basefmt
);
3207 /* For safe rebasing we need to compare old and new backing file */
3209 char backing_name
[PATH_MAX
];
3210 QDict
*options
= NULL
;
3212 if (bs
->backing_format
[0] != '\0') {
3213 options
= qdict_new();
3214 qdict_put_str(options
, "driver", bs
->backing_format
);
3219 options
= qdict_new();
3221 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3223 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3224 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3225 options
, src_flags
, &local_err
);
3226 if (!blk_old_backing
) {
3227 error_reportf_err(local_err
,
3228 "Could not open old backing file '%s': ",
3234 if (out_baseimg
[0]) {
3235 options
= qdict_new();
3237 qdict_put_str(options
, "driver", out_basefmt
);
3240 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3243 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3244 options
, src_flags
, &local_err
);
3245 if (!blk_new_backing
) {
3246 error_reportf_err(local_err
,
3247 "Could not open new backing file '%s': ",
3256 * Check each unallocated cluster in the COW file. If it is unallocated,
3257 * accesses go to the backing file. We must therefore compare this cluster
3258 * in the old and new backing file, and if they differ we need to copy it
3259 * from the old backing file into the COW file.
3261 * If qemu-img crashes during this step, no harm is done. The content of
3262 * the image is the same as the original one at any time.
3265 int64_t num_sectors
;
3266 int64_t old_backing_num_sectors
;
3267 int64_t new_backing_num_sectors
= 0;
3271 float local_progress
= 0;
3273 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3274 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3276 num_sectors
= blk_nb_sectors(blk
);
3277 if (num_sectors
< 0) {
3278 error_report("Could not get size of '%s': %s",
3279 filename
, strerror(-num_sectors
));
3283 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
3284 if (old_backing_num_sectors
< 0) {
3285 char backing_name
[PATH_MAX
];
3287 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3288 error_report("Could not get size of '%s': %s",
3289 backing_name
, strerror(-old_backing_num_sectors
));
3293 if (blk_new_backing
) {
3294 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3295 if (new_backing_num_sectors
< 0) {
3296 error_report("Could not get size of '%s': %s",
3297 out_baseimg
, strerror(-new_backing_num_sectors
));
3303 if (num_sectors
!= 0) {
3304 local_progress
= (float)100 /
3305 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3308 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3310 /* How many sectors can we handle with the next read? */
3311 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3312 n
= (IO_BUF_SIZE
/ 512);
3314 n
= num_sectors
- sector
;
3317 /* If the cluster is allocated, we don't need to take action */
3318 ret
= bdrv_is_allocated(bs
, sector
<< BDRV_SECTOR_BITS
,
3319 n
<< BDRV_SECTOR_BITS
, &count
);
3321 error_report("error while reading image metadata: %s",
3325 /* TODO relax this once bdrv_is_allocated does not enforce
3326 * sector alignment */
3327 assert(QEMU_IS_ALIGNED(count
, BDRV_SECTOR_SIZE
));
3328 n
= count
>> BDRV_SECTOR_BITS
;
3334 * Read old and new backing file and take into consideration that
3335 * backing files may be smaller than the COW image.
3337 if (sector
>= old_backing_num_sectors
) {
3338 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3340 if (sector
+ n
> old_backing_num_sectors
) {
3341 n
= old_backing_num_sectors
- sector
;
3344 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3345 buf_old
, n
<< BDRV_SECTOR_BITS
);
3347 error_report("error while reading from old backing file");
3352 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3353 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3355 if (sector
+ n
> new_backing_num_sectors
) {
3356 n
= new_backing_num_sectors
- sector
;
3359 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3360 buf_new
, n
<< BDRV_SECTOR_BITS
);
3362 error_report("error while reading from new backing file");
3367 /* If they differ, we need to write to the COW file */
3368 uint64_t written
= 0;
3370 while (written
< n
) {
3373 if (compare_sectors(buf_old
+ written
* 512,
3374 buf_new
+ written
* 512, n
- written
, &pnum
))
3376 ret
= blk_pwrite(blk
,
3377 (sector
+ written
) << BDRV_SECTOR_BITS
,
3378 buf_old
+ written
* 512,
3379 pnum
<< BDRV_SECTOR_BITS
, 0);
3381 error_report("Error while writing to COW image: %s",
3389 qemu_progress_print(local_progress
, 100);
3394 * Change the backing file. All clusters that are different from the old
3395 * backing file are overwritten in the COW file now, so the visible content
3396 * doesn't change when we switch the backing file.
3398 if (out_baseimg
&& *out_baseimg
) {
3399 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3401 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3404 if (ret
== -ENOSPC
) {
3405 error_report("Could not change the backing file to '%s': No "
3406 "space left in the file header", out_baseimg
);
3407 } else if (ret
< 0) {
3408 error_report("Could not change the backing file to '%s': %s",
3409 out_baseimg
, strerror(-ret
));
3412 qemu_progress_print(100, 0);
3414 * TODO At this point it is possible to check if any clusters that are
3415 * allocated in the COW file are the same in the backing file. If so, they
3416 * could be dropped from the COW file. Don't do this before switching the
3417 * backing file, in case of a crash this would lead to corruption.
3420 qemu_progress_end();
3423 blk_unref(blk_old_backing
);
3424 blk_unref(blk_new_backing
);
3426 qemu_vfree(buf_old
);
3427 qemu_vfree(buf_new
);
3436 static int img_resize(int argc
, char **argv
)
3439 int c
, ret
, relative
;
3440 const char *filename
, *fmt
, *size
;
3441 int64_t n
, total_size
;
3443 BlockBackend
*blk
= NULL
;
3446 static QemuOptsList resize_options
= {
3447 .name
= "resize_options",
3448 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3451 .name
= BLOCK_OPT_SIZE
,
3452 .type
= QEMU_OPT_SIZE
,
3453 .help
= "Virtual disk size"
3459 bool image_opts
= false;
3461 /* Remove size from argv manually so that negative numbers are not treated
3462 * as options by getopt. */
3464 error_exit("Not enough arguments");
3468 size
= argv
[--argc
];
3470 /* Parse getopt arguments */
3473 static const struct option long_options
[] = {
3474 {"help", no_argument
, 0, 'h'},
3475 {"object", required_argument
, 0, OPTION_OBJECT
},
3476 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3479 c
= getopt_long(argc
, argv
, ":f:hq",
3480 long_options
, NULL
);
3486 missing_argument(argv
[optind
- 1]);
3489 unrecognized_option(argv
[optind
- 1]);
3500 case OPTION_OBJECT
: {
3502 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3508 case OPTION_IMAGE_OPTS
:
3513 if (optind
!= argc
- 1) {
3514 error_exit("Expecting one image file name");
3516 filename
= argv
[optind
++];
3518 if (qemu_opts_foreach(&qemu_object_opts
,
3519 user_creatable_add_opts_foreach
,
3524 /* Choose grow, shrink, or absolute resize mode */
3540 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3541 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3543 error_report_err(err
);
3545 qemu_opts_del(param
);
3548 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3549 qemu_opts_del(param
);
3551 blk
= img_open(image_opts
, filename
, fmt
,
3552 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3560 total_size
= blk_getlength(blk
) + n
* relative
;
3564 if (total_size
<= 0) {
3565 error_report("New image size must be positive");
3570 ret
= blk_truncate(blk
, total_size
, &err
);
3572 qprintf(quiet
, "Image resized.\n");
3574 error_report_err(err
);
3584 static void amend_status_cb(BlockDriverState
*bs
,
3585 int64_t offset
, int64_t total_work_size
,
3588 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3591 static int img_amend(int argc
, char **argv
)
3595 char *options
= NULL
;
3596 QemuOptsList
*create_opts
= NULL
;
3597 QemuOpts
*opts
= NULL
;
3598 const char *fmt
= NULL
, *filename
, *cache
;
3601 bool quiet
= false, progress
= false;
3602 BlockBackend
*blk
= NULL
;
3603 BlockDriverState
*bs
= NULL
;
3604 bool image_opts
= false;
3606 cache
= BDRV_DEFAULT_CACHE
;
3608 static const struct option long_options
[] = {
3609 {"help", no_argument
, 0, 'h'},
3610 {"object", required_argument
, 0, OPTION_OBJECT
},
3611 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3614 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3615 long_options
, NULL
);
3622 missing_argument(argv
[optind
- 1]);
3625 unrecognized_option(argv
[optind
- 1]);
3631 if (!is_valid_option_list(optarg
)) {
3632 error_report("Invalid option list: %s", optarg
);
3634 goto out_no_progress
;
3637 options
= g_strdup(optarg
);
3639 char *old_options
= options
;
3640 options
= g_strdup_printf("%s,%s", options
, optarg
);
3641 g_free(old_options
);
3657 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3661 goto out_no_progress
;
3664 case OPTION_IMAGE_OPTS
:
3671 error_exit("Must specify options (-o)");
3674 if (qemu_opts_foreach(&qemu_object_opts
,
3675 user_creatable_add_opts_foreach
,
3678 goto out_no_progress
;
3684 qemu_progress_init(progress
, 1.0);
3686 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3687 if (fmt
&& has_help_option(options
)) {
3688 /* If a format is explicitly specified (and possibly no filename is
3689 * given), print option help here */
3690 ret
= print_block_option_help(filename
, fmt
);
3694 if (optind
!= argc
- 1) {
3695 error_report("Expecting one image file name");
3700 flags
= BDRV_O_RDWR
;
3701 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3703 error_report("Invalid cache option: %s", cache
);
3707 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3715 fmt
= bs
->drv
->format_name
;
3717 if (has_help_option(options
)) {
3718 /* If the format was auto-detected, print option help here */
3719 ret
= print_block_option_help(filename
, fmt
);
3723 if (!bs
->drv
->create_opts
) {
3724 error_report("Format driver '%s' does not support any options to amend",
3730 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3731 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3732 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3734 error_report_err(err
);
3739 /* In case the driver does not call amend_status_cb() */
3740 qemu_progress_print(0.f
, 0);
3741 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3742 qemu_progress_print(100.f
, 0);
3744 error_report("Error while amending options: %s", strerror(-ret
));
3749 qemu_progress_end();
3753 qemu_opts_del(opts
);
3754 qemu_opts_free(create_opts
);
3763 typedef struct BenchData
{
3765 uint64_t image_size
;
3772 bool drain_on_flush
;
3781 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3784 error_report("Failed flush request: %s", strerror(-ret
));
3789 static void bench_cb(void *opaque
, int ret
)
3791 BenchData
*b
= opaque
;
3795 error_report("Failed request: %s", strerror(-ret
));
3800 /* Just finished a flush with drained queue: Start next requests */
3801 assert(b
->in_flight
== 0);
3802 b
->in_flush
= false;
3803 } else if (b
->in_flight
> 0) {
3804 int remaining
= b
->n
- b
->in_flight
;
3809 /* Time for flush? Drain queue if requested, then flush */
3810 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3811 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3812 BlockCompletionFunc
*cb
;
3814 if (b
->drain_on_flush
) {
3818 cb
= bench_undrained_flush_cb
;
3821 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3823 error_report("Failed to issue flush request");
3827 if (b
->drain_on_flush
) {
3833 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3834 int64_t offset
= b
->offset
;
3835 /* blk_aio_* might look for completed I/Os and kick bench_cb
3836 * again, so make sure this operation is counted by in_flight
3837 * and b->offset is ready for the next submission.
3840 b
->offset
+= b
->step
;
3841 b
->offset
%= b
->image_size
;
3843 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3845 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3848 error_report("Failed to issue request");
3854 static int img_bench(int argc
, char **argv
)
3857 const char *fmt
= NULL
, *filename
;
3859 bool image_opts
= false;
3860 bool is_write
= false;
3864 size_t bufsize
= 4096;
3867 int flush_interval
= 0;
3868 bool drain_on_flush
= true;
3870 BlockBackend
*blk
= NULL
;
3871 BenchData data
= {};
3873 bool writethrough
= false;
3874 struct timeval t1
, t2
;
3876 bool force_share
= false;
3879 static const struct option long_options
[] = {
3880 {"help", no_argument
, 0, 'h'},
3881 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3882 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3883 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3884 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3885 {"force-share", no_argument
, 0, 'U'},
3888 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3895 missing_argument(argv
[optind
- 1]);
3898 unrecognized_option(argv
[optind
- 1]);
3907 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3908 error_report("Invalid request count specified");
3918 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3919 error_report("Invalid queue depth specified");
3929 flags
|= BDRV_O_NATIVE_AIO
;
3933 offset
= cvtnum(optarg
);
3935 error_report("Invalid offset specified");
3948 sval
= cvtnum(optarg
);
3949 if (sval
< 0 || sval
> INT_MAX
) {
3950 error_report("Invalid buffer size specified");
3961 sval
= cvtnum(optarg
);
3962 if (sval
< 0 || sval
> INT_MAX
) {
3963 error_report("Invalid step size specified");
3971 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3973 error_report("Invalid cache mode");
3979 flags
|= BDRV_O_RDWR
;
3985 case OPTION_PATTERN
:
3989 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3990 error_report("Invalid pattern byte specified");
3996 case OPTION_FLUSH_INTERVAL
:
4000 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4001 error_report("Invalid flush interval specified");
4004 flush_interval
= res
;
4007 case OPTION_NO_DRAIN
:
4008 drain_on_flush
= false;
4010 case OPTION_IMAGE_OPTS
:
4016 if (optind
!= argc
- 1) {
4017 error_exit("Expecting one image file name");
4019 filename
= argv
[argc
- 1];
4021 if (!is_write
&& flush_interval
) {
4022 error_report("--flush-interval is only available in write tests");
4026 if (flush_interval
&& flush_interval
< depth
) {
4027 error_report("Flush interval can't be smaller than depth");
4032 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4039 image_size
= blk_getlength(blk
);
4040 if (image_size
< 0) {
4045 data
= (BenchData
) {
4047 .image_size
= image_size
,
4049 .step
= step
?: bufsize
,
4054 .flush_interval
= flush_interval
,
4055 .drain_on_flush
= drain_on_flush
,
4057 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4058 "(starting at offset %" PRId64
", step size %d)\n",
4059 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4060 data
.offset
, data
.step
);
4061 if (flush_interval
) {
4062 printf("Sending flush every %d requests\n", flush_interval
);
4065 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
4066 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4068 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4069 for (i
= 0; i
< data
.nrreq
; i
++) {
4070 qemu_iovec_init(&data
.qiov
[i
], 1);
4071 qemu_iovec_add(&data
.qiov
[i
],
4072 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4075 gettimeofday(&t1
, NULL
);
4078 while (data
.n
> 0) {
4079 main_loop_wait(false);
4081 gettimeofday(&t2
, NULL
);
4083 printf("Run completed in %3.3f seconds.\n",
4084 (t2
.tv_sec
- t1
.tv_sec
)
4085 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4088 qemu_vfree(data
.buf
);
4109 int bsz
; /* Block size */
4117 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4121 static int img_dd_bs(const char *arg
,
4122 struct DdIo
*in
, struct DdIo
*out
,
4129 if (res
<= 0 || res
> INT_MAX
) {
4130 error_report("invalid number: '%s'", arg
);
4133 in
->bsz
= out
->bsz
= res
;
4138 static int img_dd_count(const char *arg
,
4139 struct DdIo
*in
, struct DdIo
*out
,
4142 dd
->count
= cvtnum(arg
);
4144 if (dd
->count
< 0) {
4145 error_report("invalid number: '%s'", arg
);
4152 static int img_dd_if(const char *arg
,
4153 struct DdIo
*in
, struct DdIo
*out
,
4156 in
->filename
= g_strdup(arg
);
4161 static int img_dd_of(const char *arg
,
4162 struct DdIo
*in
, struct DdIo
*out
,
4165 out
->filename
= g_strdup(arg
);
4170 static int img_dd_skip(const char *arg
,
4171 struct DdIo
*in
, struct DdIo
*out
,
4174 in
->offset
= cvtnum(arg
);
4176 if (in
->offset
< 0) {
4177 error_report("invalid number: '%s'", arg
);
4184 static int img_dd(int argc
, char **argv
)
4189 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4190 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4191 QemuOpts
*opts
= NULL
;
4192 QemuOptsList
*create_opts
= NULL
;
4193 Error
*local_err
= NULL
;
4194 bool image_opts
= false;
4196 const char *out_fmt
= "raw";
4197 const char *fmt
= NULL
;
4199 int64_t block_count
= 0, out_pos
, in_pos
;
4200 bool force_share
= false;
4201 struct DdInfo dd
= {
4206 .bsz
= 512, /* Block size is by default 512 bytes */
4218 const struct DdOpts options
[] = {
4219 { "bs", img_dd_bs
, C_BS
},
4220 { "count", img_dd_count
, C_COUNT
},
4221 { "if", img_dd_if
, C_IF
},
4222 { "of", img_dd_of
, C_OF
},
4223 { "skip", img_dd_skip
, C_SKIP
},
4226 const struct option long_options
[] = {
4227 { "help", no_argument
, 0, 'h'},
4228 { "object", required_argument
, 0, OPTION_OBJECT
},
4229 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4230 { "force-share", no_argument
, 0, 'U'},
4234 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4246 missing_argument(argv
[optind
- 1]);
4249 unrecognized_option(argv
[optind
- 1]);
4258 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4263 case OPTION_IMAGE_OPTS
:
4269 for (i
= optind
; i
< argc
; i
++) {
4271 arg
= g_strdup(argv
[i
]);
4273 tmp
= strchr(arg
, '=');
4275 error_report("unrecognized operand %s", arg
);
4282 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4283 if (!strcmp(arg
, options
[j
].name
)) {
4287 if (options
[j
].name
== NULL
) {
4288 error_report("unrecognized operand %s", arg
);
4293 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4297 dd
.flags
|= options
[j
].flag
;
4302 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4303 error_report("Must specify both input and output files");
4308 if (qemu_opts_foreach(&qemu_object_opts
,
4309 user_creatable_add_opts_foreach
,
4315 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4323 drv
= bdrv_find_format(out_fmt
);
4325 error_report("Unknown file format");
4329 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4332 error_report_err(local_err
);
4336 if (!drv
->create_opts
) {
4337 error_report("Format driver '%s' does not support image creation",
4342 if (!proto_drv
->create_opts
) {
4343 error_report("Protocol driver '%s' does not support image creation",
4344 proto_drv
->format_name
);
4348 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4349 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4351 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4353 size
= blk_getlength(blk1
);
4355 error_report("Failed to get size for '%s'", in
.filename
);
4360 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4361 dd
.count
* in
.bsz
< size
) {
4362 size
= dd
.count
* in
.bsz
;
4365 /* Overflow means the specified offset is beyond input image's size */
4366 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4367 size
< in
.bsz
* in
.offset
)) {
4368 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4370 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4371 size
- in
.bsz
* in
.offset
, &error_abort
);
4374 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4376 error_reportf_err(local_err
,
4377 "%s: error while creating output image: ",
4383 /* TODO, we can't honour --image-opts for the target,
4384 * since it needs to be given in a format compatible
4385 * with the bdrv_create() call above which does not
4386 * support image-opts style.
4388 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4389 false, false, false);
4396 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4397 size
< in
.offset
* in
.bsz
)) {
4398 /* We give a warning if the skip option is bigger than the input
4399 * size and create an empty output disk image (i.e. like dd(1)).
4401 error_report("%s: cannot skip to specified offset", in
.filename
);
4404 in_pos
= in
.offset
* in
.bsz
;
4407 in
.buf
= g_new(uint8_t, in
.bsz
);
4409 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4410 int in_ret
, out_ret
;
4412 if (in_pos
+ in
.bsz
> size
) {
4413 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4415 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4418 error_report("error while reading from input image file: %s",
4425 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4428 error_report("error while writing to output image file: %s",
4429 strerror(-out_ret
));
4438 qemu_opts_del(opts
);
4439 qemu_opts_free(create_opts
);
4442 g_free(in
.filename
);
4443 g_free(out
.filename
);
4454 static const img_cmd_t img_cmds
[] = {
4455 #define DEF(option, callback, arg_string) \
4456 { option, callback },
4457 #include "qemu-img-cmds.h"
4463 int main(int argc
, char **argv
)
4465 const img_cmd_t
*cmd
;
4466 const char *cmdname
;
4467 Error
*local_error
= NULL
;
4468 char *trace_file
= NULL
;
4470 static const struct option long_options
[] = {
4471 {"help", no_argument
, 0, 'h'},
4472 {"version", no_argument
, 0, 'V'},
4473 {"trace", required_argument
, NULL
, 'T'},
4478 signal(SIGPIPE
, SIG_IGN
);
4481 module_call_init(MODULE_INIT_TRACE
);
4482 error_set_progname(argv
[0]);
4483 qemu_init_exec_dir(argv
[0]);
4485 if (qemu_init_main_loop(&local_error
)) {
4486 error_report_err(local_error
);
4490 qcrypto_init(&error_fatal
);
4492 module_call_init(MODULE_INIT_QOM
);
4495 error_exit("Not enough arguments");
4498 qemu_add_opts(&qemu_object_opts
);
4499 qemu_add_opts(&qemu_source_opts
);
4500 qemu_add_opts(&qemu_trace_opts
);
4502 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4505 missing_argument(argv
[optind
- 1]);
4508 unrecognized_option(argv
[optind
- 1]);
4514 printf(QEMU_IMG_VERSION
);
4518 trace_file
= trace_opt_parse(optarg
);
4523 cmdname
= argv
[optind
];
4525 /* reset getopt_long scanning */
4533 if (!trace_init_backends()) {
4536 trace_init_file(trace_file
);
4537 qemu_set_log(LOG_TRACE
);
4539 /* find the command */
4540 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4541 if (!strcmp(cmdname
, cmd
->name
)) {
4542 return cmd
->handler(argc
, argv
);
4547 error_exit("Command not found: %s", cmdname
);