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:he6o:q",
474 missing_argument(argv
[optind
- 1]);
477 unrecognized_option(argv
[optind
- 1]);
486 base_filename
= optarg
;
492 error_report("option -e is deprecated, please use \'-o "
493 "encryption\' instead!");
496 error_report("option -6 is deprecated, please use \'-o "
497 "compat6\' instead!");
500 if (!is_valid_option_list(optarg
)) {
501 error_report("Invalid option list: %s", optarg
);
505 options
= g_strdup(optarg
);
507 char *old_options
= options
;
508 options
= g_strdup_printf("%s,%s", options
, optarg
);
515 case OPTION_OBJECT
: {
517 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
526 /* Get the filename */
527 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
528 if (options
&& has_help_option(options
)) {
530 return print_block_option_help(filename
, fmt
);
533 if (optind
>= argc
) {
534 error_exit("Expecting image file name");
538 if (qemu_opts_foreach(&qemu_object_opts
,
539 user_creatable_add_opts_foreach
,
544 /* Get image size, if specified */
548 sval
= cvtnum(argv
[optind
++]);
550 if (sval
== -ERANGE
) {
551 error_report("Image size must be less than 8 EiB!");
553 error_report("Invalid image size specified! You may use k, M, "
554 "G, T, P or E suffixes for ");
555 error_report("kilobytes, megabytes, gigabytes, terabytes, "
556 "petabytes and exabytes.");
560 img_size
= (uint64_t)sval
;
562 if (optind
!= argc
) {
563 error_exit("Unexpected argument: %s", argv
[optind
]);
566 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
567 options
, img_size
, 0, quiet
, &local_err
);
569 error_reportf_err(local_err
, "%s: ", filename
);
581 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
585 Visitor
*v
= qobject_output_visitor_new(&obj
);
587 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
588 visit_complete(v
, &obj
);
589 str
= qobject_to_json_pretty(obj
);
591 qprintf(quiet
, "%s\n", qstring_get_str(str
));
597 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
599 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
600 qprintf(quiet
, "No errors were found on the image.\n");
602 if (check
->corruptions
) {
603 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
604 "Data may be corrupted, or further writes to the image "
611 "\n%" PRId64
" leaked clusters were found on the image.\n"
612 "This means waste of disk space, but no harm to data.\n",
616 if (check
->check_errors
) {
619 " internal errors have occurred during the check.\n",
620 check
->check_errors
);
624 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
625 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
626 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
627 check
->allocated_clusters
, check
->total_clusters
,
628 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
629 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
630 check
->compressed_clusters
* 100.0 /
631 check
->allocated_clusters
);
634 if (check
->image_end_offset
) {
636 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
640 static int collect_image_check(BlockDriverState
*bs
,
642 const char *filename
,
647 BdrvCheckResult result
;
649 ret
= bdrv_check(bs
, &result
, fix
);
654 check
->filename
= g_strdup(filename
);
655 check
->format
= g_strdup(bdrv_get_format_name(bs
));
656 check
->check_errors
= result
.check_errors
;
657 check
->corruptions
= result
.corruptions
;
658 check
->has_corruptions
= result
.corruptions
!= 0;
659 check
->leaks
= result
.leaks
;
660 check
->has_leaks
= result
.leaks
!= 0;
661 check
->corruptions_fixed
= result
.corruptions_fixed
;
662 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
663 check
->leaks_fixed
= result
.leaks_fixed
;
664 check
->has_leaks_fixed
= result
.leaks
!= 0;
665 check
->image_end_offset
= result
.image_end_offset
;
666 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
667 check
->total_clusters
= result
.bfi
.total_clusters
;
668 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
669 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
670 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
671 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
672 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
673 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
674 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
680 * Checks an image for consistency. Exit codes:
682 * 0 - Check completed, image is good
683 * 1 - Check not completed because of internal errors
684 * 2 - Check completed, image is corrupted
685 * 3 - Check completed, image has leaked clusters, but is good otherwise
686 * 63 - Checks are not supported by the image format
688 static int img_check(int argc
, char **argv
)
691 OutputFormat output_format
= OFORMAT_HUMAN
;
692 const char *filename
, *fmt
, *output
, *cache
;
694 BlockDriverState
*bs
;
696 int flags
= BDRV_O_CHECK
;
700 bool image_opts
= false;
701 bool force_share
= false;
705 cache
= BDRV_DEFAULT_CACHE
;
708 int option_index
= 0;
709 static const struct option long_options
[] = {
710 {"help", no_argument
, 0, 'h'},
711 {"format", required_argument
, 0, 'f'},
712 {"repair", required_argument
, 0, 'r'},
713 {"output", required_argument
, 0, OPTION_OUTPUT
},
714 {"object", required_argument
, 0, OPTION_OBJECT
},
715 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
716 {"force-share", no_argument
, 0, 'U'},
719 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
720 long_options
, &option_index
);
726 missing_argument(argv
[optind
- 1]);
729 unrecognized_option(argv
[optind
- 1]);
738 flags
|= BDRV_O_RDWR
;
740 if (!strcmp(optarg
, "leaks")) {
741 fix
= BDRV_FIX_LEAKS
;
742 } else if (!strcmp(optarg
, "all")) {
743 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
745 error_exit("Unknown option value for -r "
746 "(expecting 'leaks' or 'all'): %s", optarg
);
761 case OPTION_OBJECT
: {
763 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
769 case OPTION_IMAGE_OPTS
:
774 if (optind
!= argc
- 1) {
775 error_exit("Expecting one image file name");
777 filename
= argv
[optind
++];
779 if (output
&& !strcmp(output
, "json")) {
780 output_format
= OFORMAT_JSON
;
781 } else if (output
&& !strcmp(output
, "human")) {
782 output_format
= OFORMAT_HUMAN
;
784 error_report("--output must be used with human or json as argument.");
788 if (qemu_opts_foreach(&qemu_object_opts
,
789 user_creatable_add_opts_foreach
,
794 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
796 error_report("Invalid source cache option: %s", cache
);
800 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
807 check
= g_new0(ImageCheck
, 1);
808 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
810 if (ret
== -ENOTSUP
) {
811 error_report("This image format does not support checks");
816 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
817 int corruptions_fixed
, leaks_fixed
;
819 leaks_fixed
= check
->leaks_fixed
;
820 corruptions_fixed
= check
->corruptions_fixed
;
822 if (output_format
== OFORMAT_HUMAN
) {
824 "The following inconsistencies were found and repaired:\n\n"
825 " %" PRId64
" leaked clusters\n"
826 " %" PRId64
" corruptions\n\n"
827 "Double checking the fixed image now...\n",
829 check
->corruptions_fixed
);
832 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
834 check
->leaks_fixed
= leaks_fixed
;
835 check
->corruptions_fixed
= corruptions_fixed
;
839 switch (output_format
) {
841 dump_human_image_check(check
, quiet
);
844 dump_json_image_check(check
, quiet
);
849 if (ret
|| check
->check_errors
) {
851 error_report("Check failed: %s", strerror(-ret
));
853 error_report("Check failed");
859 if (check
->corruptions
) {
861 } else if (check
->leaks
) {
868 qapi_free_ImageCheck(check
);
873 typedef struct CommonBlockJobCBInfo
{
874 BlockDriverState
*bs
;
876 } CommonBlockJobCBInfo
;
878 static void common_block_job_cb(void *opaque
, int ret
)
880 CommonBlockJobCBInfo
*cbi
= opaque
;
883 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
887 static void run_block_job(BlockJob
*job
, Error
**errp
)
889 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
891 /* FIXME In error cases, the job simply goes away and we access a dangling
893 aio_context_acquire(aio_context
);
895 aio_poll(aio_context
, true);
896 qemu_progress_print(job
->len
?
897 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
898 } while (!job
->ready
);
900 block_job_complete_sync(job
, errp
);
901 aio_context_release(aio_context
);
903 /* A block job may finish instantaneously without publishing any progress,
904 * so just signal completion here */
905 qemu_progress_print(100.f
, 0);
908 static int img_commit(int argc
, char **argv
)
911 const char *filename
, *fmt
, *cache
, *base
;
913 BlockDriverState
*bs
, *base_bs
;
915 bool progress
= false, quiet
= false, drop
= false;
917 Error
*local_err
= NULL
;
918 CommonBlockJobCBInfo cbi
;
919 bool image_opts
= false;
920 AioContext
*aio_context
;
923 cache
= BDRV_DEFAULT_CACHE
;
926 static const struct option long_options
[] = {
927 {"help", no_argument
, 0, 'h'},
928 {"object", required_argument
, 0, OPTION_OBJECT
},
929 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
932 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
939 missing_argument(argv
[optind
- 1]);
942 unrecognized_option(argv
[optind
- 1]);
967 case OPTION_OBJECT
: {
969 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
975 case OPTION_IMAGE_OPTS
:
981 /* Progress is not shown in Quiet mode */
986 if (optind
!= argc
- 1) {
987 error_exit("Expecting one image file name");
989 filename
= argv
[optind
++];
991 if (qemu_opts_foreach(&qemu_object_opts
,
992 user_creatable_add_opts_foreach
,
997 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
998 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1000 error_report("Invalid cache option: %s", cache
);
1004 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1011 qemu_progress_init(progress
, 1.f
);
1012 qemu_progress_print(0.f
, 100);
1015 base_bs
= bdrv_find_backing_image(bs
, base
);
1017 error_setg(&local_err
,
1018 "Did not find '%s' in the backing chain of '%s'",
1023 /* This is different from QMP, which by default uses the deepest file in
1024 * the backing chain (i.e., the very base); however, the traditional
1025 * behavior of qemu-img commit is using the immediate backing file. */
1026 base_bs
= backing_bs(bs
);
1028 error_setg(&local_err
, "Image does not have a backing file");
1033 cbi
= (CommonBlockJobCBInfo
){
1038 aio_context
= bdrv_get_aio_context(bs
);
1039 aio_context_acquire(aio_context
);
1040 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1041 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1042 &cbi
, false, &local_err
);
1043 aio_context_release(aio_context
);
1048 /* When the block job completes, the BlockBackend reference will point to
1049 * the old backing file. In order to avoid that the top image is already
1050 * deleted, so we can still empty it afterwards, increment the reference
1051 * counter here preemptively. */
1056 job
= block_job_get("commit");
1057 run_block_job(job
, &local_err
);
1062 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1063 ret
= bs
->drv
->bdrv_make_empty(bs
);
1065 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1077 qemu_progress_end();
1082 error_report_err(local_err
);
1086 qprintf(quiet
, "Image committed.\n");
1091 * Returns true iff the first sector pointed to by 'buf' contains at least
1094 * 'pnum' is set to the number of sectors (including and immediately following
1095 * the first one) that are known to be in the same allocated/unallocated state.
1097 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1106 is_zero
= buffer_is_zero(buf
, 512);
1107 for(i
= 1; i
< n
; i
++) {
1109 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1118 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1119 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1120 * breaking up write requests for only small sparse areas.
1122 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1126 int num_checked
, num_used
;
1132 ret
= is_allocated_sectors(buf
, n
, pnum
);
1138 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1140 num_checked
= num_used
;
1143 ret
= is_allocated_sectors(buf
, n
, pnum
);
1145 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1147 num_checked
+= *pnum
;
1149 num_used
= num_checked
;
1150 } else if (*pnum
>= min
) {
1160 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1161 * buffers matches, non-zero otherwise.
1163 * pnum is set to the number of sectors (including and immediately following
1164 * the first one) that are known to have the same comparison result
1166 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1177 res
= !!memcmp(buf1
, buf2
, 512);
1178 for(i
= 1; i
< n
; i
++) {
1182 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1191 #define IO_BUF_SIZE (2 * 1024 * 1024)
1193 static int64_t sectors_to_bytes(int64_t sectors
)
1195 return sectors
<< BDRV_SECTOR_BITS
;
1198 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1200 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1204 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1206 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1207 * data and negative value on error.
1209 * @param blk: BlockBackend for the image
1210 * @param sect_num: Number of first sector to check
1211 * @param sect_count: Number of sectors to check
1212 * @param filename: Name of disk file we are checking (logging purpose)
1213 * @param buffer: Allocated buffer for storing read data
1214 * @param quiet: Flag for quiet mode
1216 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1217 int sect_count
, const char *filename
,
1218 uint8_t *buffer
, bool quiet
)
1221 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1222 sect_count
<< BDRV_SECTOR_BITS
);
1224 error_report("Error while reading offset %" PRId64
" of %s: %s",
1225 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1228 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1229 if (ret
|| pnum
!= sect_count
) {
1230 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1231 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1239 * Compares two images. Exit codes:
1241 * 0 - Images are identical
1243 * >1 - Error occurred
1245 static int img_compare(int argc
, char **argv
)
1247 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1248 BlockBackend
*blk1
, *blk2
;
1249 BlockDriverState
*bs1
, *bs2
;
1250 int64_t total_sectors1
, total_sectors2
;
1251 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1253 int allocated1
, allocated2
;
1254 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1255 bool progress
= false, quiet
= false, strict
= false;
1258 int64_t total_sectors
;
1259 int64_t sector_num
= 0;
1262 uint64_t progress_base
;
1263 bool image_opts
= false;
1264 bool force_share
= false;
1266 cache
= BDRV_DEFAULT_CACHE
;
1268 static const struct option long_options
[] = {
1269 {"help", no_argument
, 0, 'h'},
1270 {"object", required_argument
, 0, OPTION_OBJECT
},
1271 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1272 {"force-share", no_argument
, 0, 'U'},
1275 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1276 long_options
, NULL
);
1282 missing_argument(argv
[optind
- 1]);
1285 unrecognized_option(argv
[optind
- 1]);
1311 case OPTION_OBJECT
: {
1313 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1320 case OPTION_IMAGE_OPTS
:
1326 /* Progress is not shown in Quiet mode */
1332 if (optind
!= argc
- 2) {
1333 error_exit("Expecting two image file names");
1335 filename1
= argv
[optind
++];
1336 filename2
= argv
[optind
++];
1338 if (qemu_opts_foreach(&qemu_object_opts
,
1339 user_creatable_add_opts_foreach
,
1345 /* Initialize before goto out */
1346 qemu_progress_init(progress
, 2.0);
1349 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1351 error_report("Invalid source cache option: %s", cache
);
1356 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1363 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1372 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1373 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1374 total_sectors1
= blk_nb_sectors(blk1
);
1375 if (total_sectors1
< 0) {
1376 error_report("Can't get size of %s: %s",
1377 filename1
, strerror(-total_sectors1
));
1381 total_sectors2
= blk_nb_sectors(blk2
);
1382 if (total_sectors2
< 0) {
1383 error_report("Can't get size of %s: %s",
1384 filename2
, strerror(-total_sectors2
));
1388 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1389 progress_base
= MAX(total_sectors1
, total_sectors2
);
1391 qemu_progress_print(0, 100);
1393 if (strict
&& total_sectors1
!= total_sectors2
) {
1395 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1400 int64_t status1
, status2
;
1401 BlockDriverState
*file
;
1403 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1404 if (nb_sectors
<= 0) {
1407 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1408 total_sectors1
- sector_num
,
1412 error_report("Sector allocation test failed for %s", filename1
);
1415 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1417 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1418 total_sectors2
- sector_num
,
1422 error_report("Sector allocation test failed for %s", filename2
);
1425 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1427 nb_sectors
= MIN(nb_sectors
, pnum1
);
1430 nb_sectors
= MIN(nb_sectors
, pnum2
);
1434 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1435 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1437 qprintf(quiet
, "Strict mode: Offset %" PRId64
1438 " block status mismatch!\n",
1439 sectors_to_bytes(sector_num
));
1443 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1444 nb_sectors
= MIN(pnum1
, pnum2
);
1445 } else if (allocated1
== allocated2
) {
1447 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1448 nb_sectors
<< BDRV_SECTOR_BITS
);
1450 error_report("Error while reading offset %" PRId64
" of %s:"
1451 " %s", sectors_to_bytes(sector_num
), filename1
,
1456 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1457 nb_sectors
<< BDRV_SECTOR_BITS
);
1459 error_report("Error while reading offset %" PRId64
1460 " of %s: %s", sectors_to_bytes(sector_num
),
1461 filename2
, strerror(-ret
));
1465 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1466 if (ret
|| pnum
!= nb_sectors
) {
1467 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1469 ret
? sector_num
: sector_num
+ pnum
));
1477 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1478 filename1
, buf1
, quiet
);
1480 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1481 filename2
, buf1
, quiet
);
1485 error_report("Error while reading offset %" PRId64
": %s",
1486 sectors_to_bytes(sector_num
), strerror(-ret
));
1492 sector_num
+= nb_sectors
;
1493 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1496 if (total_sectors1
!= total_sectors2
) {
1497 BlockBackend
*blk_over
;
1498 int64_t total_sectors_over
;
1499 const char *filename_over
;
1501 qprintf(quiet
, "Warning: Image size mismatch!\n");
1502 if (total_sectors1
> total_sectors2
) {
1503 total_sectors_over
= total_sectors1
;
1505 filename_over
= filename1
;
1507 total_sectors_over
= total_sectors2
;
1509 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
, sector_num
,
1521 error_report("Sector allocation test failed for %s",
1528 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1529 filename_over
, buf1
, quiet
);
1532 error_report("Error while reading offset %" PRId64
1533 " of %s: %s", sectors_to_bytes(sector_num
),
1534 filename_over
, strerror(-ret
));
1540 sector_num
+= nb_sectors
;
1541 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1545 qprintf(quiet
, "Images are identical.\n");
1555 qemu_progress_end();
1560 enum ImgConvertBlockStatus
{
1566 #define MAX_COROUTINES 16
1568 typedef struct ImgConvertState
{
1570 int64_t *src_sectors
;
1572 int64_t total_sectors
;
1573 int64_t allocated_sectors
;
1574 int64_t allocated_done
;
1577 enum ImgConvertBlockStatus status
;
1578 int64_t sector_next_status
;
1579 BlockBackend
*target
;
1582 bool target_has_backing
;
1585 size_t cluster_sectors
;
1587 long num_coroutines
;
1588 int running_coroutines
;
1589 Coroutine
*co
[MAX_COROUTINES
];
1590 int64_t wait_sector_num
[MAX_COROUTINES
];
1595 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1596 int *src_cur
, int64_t *src_cur_offset
)
1599 *src_cur_offset
= 0;
1600 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1601 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1603 assert(*src_cur
< s
->src_num
);
1607 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1609 int64_t ret
, src_cur_offset
;
1612 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1614 assert(s
->total_sectors
> sector_num
);
1615 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1617 if (s
->sector_next_status
<= sector_num
) {
1618 BlockDriverState
*file
;
1619 if (s
->target_has_backing
) {
1620 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1621 sector_num
- src_cur_offset
,
1624 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1625 sector_num
- src_cur_offset
,
1632 if (ret
& BDRV_BLOCK_ZERO
) {
1633 s
->status
= BLK_ZERO
;
1634 } else if (ret
& BDRV_BLOCK_DATA
) {
1635 s
->status
= BLK_DATA
;
1637 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1640 s
->sector_next_status
= sector_num
+ n
;
1643 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1644 if (s
->status
== BLK_DATA
) {
1645 n
= MIN(n
, s
->buf_sectors
);
1648 /* We need to write complete clusters for compressed images, so if an
1649 * unallocated area is shorter than that, we must consider the whole
1650 * cluster allocated. */
1651 if (s
->compressed
) {
1652 if (n
< s
->cluster_sectors
) {
1653 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1654 s
->status
= BLK_DATA
;
1656 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1663 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1664 int nb_sectors
, uint8_t *buf
)
1670 assert(nb_sectors
<= s
->buf_sectors
);
1671 while (nb_sectors
> 0) {
1674 int64_t bs_sectors
, src_cur_offset
;
1676 /* In the case of compression with multiple source files, we can get a
1677 * nb_sectors that spreads into the next part. So we must be able to
1678 * read across multiple BDSes for one convert_read() call. */
1679 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1680 blk
= s
->src
[src_cur
];
1681 bs_sectors
= s
->src_sectors
[src_cur
];
1683 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1685 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1686 qemu_iovec_init_external(&qiov
, &iov
, 1);
1688 ret
= blk_co_preadv(
1689 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1690 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1697 buf
+= n
* BDRV_SECTOR_SIZE
;
1704 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1705 int nb_sectors
, uint8_t *buf
,
1706 enum ImgConvertBlockStatus status
)
1712 while (nb_sectors
> 0) {
1714 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1717 case BLK_BACKING_FILE
:
1718 /* If we have a backing file, leave clusters unallocated that are
1719 * unallocated in the source image, so that the backing file is
1720 * visible at the respective offset. */
1721 assert(s
->target_has_backing
);
1725 /* If we're told to keep the target fully allocated (-S 0) or there
1726 * is real non-zero data, we must write it. Otherwise we can treat
1727 * it as zero sectors.
1728 * Compressed clusters need to be written as a whole, so in that
1729 * case we can only save the write if the buffer is completely
1731 if (!s
->min_sparse
||
1733 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1735 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1738 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1739 qemu_iovec_init_external(&qiov
, &iov
, 1);
1741 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1742 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1751 if (s
->has_zero_init
) {
1752 assert(!s
->target_has_backing
);
1755 ret
= blk_co_pwrite_zeroes(s
->target
,
1756 sector_num
<< BDRV_SECTOR_BITS
,
1757 n
<< BDRV_SECTOR_BITS
, 0);
1766 buf
+= n
* BDRV_SECTOR_SIZE
;
1772 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1774 ImgConvertState
*s
= opaque
;
1775 uint8_t *buf
= NULL
;
1779 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1780 if (s
->co
[i
] == qemu_coroutine_self()) {
1787 s
->running_coroutines
++;
1788 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1793 enum ImgConvertBlockStatus status
;
1795 qemu_co_mutex_lock(&s
->lock
);
1796 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1797 qemu_co_mutex_unlock(&s
->lock
);
1800 n
= convert_iteration_sectors(s
, s
->sector_num
);
1802 qemu_co_mutex_unlock(&s
->lock
);
1806 /* save current sector and allocation status to local variables */
1807 sector_num
= s
->sector_num
;
1809 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1810 n
= MIN(n
, s
->buf_sectors
);
1812 /* increment global sector counter so that other coroutines can
1813 * already continue reading beyond this request */
1815 qemu_co_mutex_unlock(&s
->lock
);
1817 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1818 s
->allocated_done
+= n
;
1819 qemu_progress_print(100.0 * s
->allocated_done
/
1820 s
->allocated_sectors
, 0);
1823 if (status
== BLK_DATA
) {
1824 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1826 error_report("error while reading sector %" PRId64
1827 ": %s", sector_num
, strerror(-ret
));
1830 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1832 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1835 if (s
->wr_in_order
) {
1836 /* keep writes in order */
1837 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1838 s
->wait_sector_num
[index
] = sector_num
;
1839 qemu_coroutine_yield();
1841 s
->wait_sector_num
[index
] = -1;
1844 if (s
->ret
== -EINPROGRESS
) {
1845 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1847 error_report("error while writing sector %" PRId64
1848 ": %s", sector_num
, strerror(-ret
));
1853 if (s
->wr_in_order
) {
1854 /* reenter the coroutine that might have waited
1855 * for this write to complete */
1856 s
->wr_offs
= sector_num
+ n
;
1857 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1858 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1860 * A -> B -> A cannot occur because A has
1861 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1862 * B will never enter A during this time window.
1864 qemu_coroutine_enter(s
->co
[i
]);
1872 s
->co
[index
] = NULL
;
1873 s
->running_coroutines
--;
1874 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1875 /* the convert job finished successfully */
1880 static int convert_do_copy(ImgConvertState
*s
)
1883 int64_t sector_num
= 0;
1885 /* Check whether we have zero initialisation or can get it efficiently */
1886 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1887 ? bdrv_has_zero_init(blk_bs(s
->target
))
1890 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1891 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1893 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1895 s
->has_zero_init
= true;
1899 /* Allocate buffer for copied data. For compressed images, only one cluster
1900 * can be copied at a time. */
1901 if (s
->compressed
) {
1902 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1903 error_report("invalid cluster size");
1906 s
->buf_sectors
= s
->cluster_sectors
;
1909 while (sector_num
< s
->total_sectors
) {
1910 n
= convert_iteration_sectors(s
, sector_num
);
1914 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1916 s
->allocated_sectors
+= n
;
1922 s
->sector_next_status
= 0;
1923 s
->ret
= -EINPROGRESS
;
1925 qemu_co_mutex_init(&s
->lock
);
1926 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1927 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1928 s
->wait_sector_num
[i
] = -1;
1929 qemu_coroutine_enter(s
->co
[i
]);
1932 while (s
->running_coroutines
) {
1933 main_loop_wait(false);
1936 if (s
->compressed
&& !s
->ret
) {
1937 /* signal EOF to align */
1938 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1947 static int img_convert(int argc
, char **argv
)
1949 int c
, bs_i
, flags
, src_flags
= 0;
1950 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1951 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1952 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1953 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1954 BlockDriverInfo bdi
;
1955 BlockDriverState
*out_bs
;
1956 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1957 QemuOptsList
*create_opts
= NULL
;
1958 char *options
= NULL
;
1959 Error
*local_err
= NULL
;
1960 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1961 skip_create
= false, progress
= false, tgt_image_opts
= false;
1962 int64_t ret
= -EINVAL
;
1963 bool force_share
= false;
1965 ImgConvertState s
= (ImgConvertState
) {
1966 /* Need at least 4k of zeros for sparse detection */
1968 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1969 .wr_in_order
= true,
1970 .num_coroutines
= 8,
1974 static const struct option long_options
[] = {
1975 {"help", no_argument
, 0, 'h'},
1976 {"object", required_argument
, 0, OPTION_OBJECT
},
1977 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1978 {"force-share", no_argument
, 0, 'U'},
1979 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1982 c
= getopt_long(argc
, argv
, ":hf:O:B:ce6o:s:l:S:pt:T:qnm:WU",
1983 long_options
, NULL
);
1989 missing_argument(argv
[optind
- 1]);
1992 unrecognized_option(argv
[optind
- 1]);
2004 out_baseimg
= optarg
;
2007 s
.compressed
= true;
2010 error_report("option -e is deprecated, please use \'-o "
2011 "encryption\' instead!");
2014 error_report("option -6 is deprecated, please use \'-o "
2015 "compat6\' instead!");
2018 if (!is_valid_option_list(optarg
)) {
2019 error_report("Invalid option list: %s", optarg
);
2023 options
= g_strdup(optarg
);
2025 char *old_options
= options
;
2026 options
= g_strdup_printf("%s,%s", options
, optarg
);
2027 g_free(old_options
);
2031 snapshot_name
= optarg
;
2034 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2035 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2038 error_report("Failed in parsing snapshot param '%s'",
2043 snapshot_name
= optarg
;
2050 sval
= cvtnum(optarg
);
2052 error_report("Invalid minimum zero buffer size for sparse output specified");
2056 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2075 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2076 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2077 error_report("Invalid number of coroutines. Allowed number of"
2078 " coroutines is between 1 and %d", MAX_COROUTINES
);
2083 s
.wr_in_order
= false;
2088 case OPTION_OBJECT
: {
2089 QemuOpts
*object_opts
;
2090 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2097 case OPTION_IMAGE_OPTS
:
2100 case OPTION_TARGET_IMAGE_OPTS
:
2101 tgt_image_opts
= true;
2106 if (!out_fmt
&& !tgt_image_opts
) {
2110 if (qemu_opts_foreach(&qemu_object_opts
,
2111 user_creatable_add_opts_foreach
,
2116 if (!s
.wr_in_order
&& s
.compressed
) {
2117 error_report("Out of order write and compress are mutually exclusive");
2121 if (tgt_image_opts
&& !skip_create
) {
2122 error_report("--target-image-opts requires use of -n flag");
2126 s
.src_num
= argc
- optind
- 1;
2127 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2129 if (options
&& has_help_option(options
)) {
2131 ret
= print_block_option_help(out_filename
, out_fmt
);
2134 error_report("Option help requires a format be specified");
2139 if (s
.src_num
< 1) {
2140 error_report("Must specify image file name");
2145 /* ret is still -EINVAL until here */
2146 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2148 error_report("Invalid source cache option: %s", src_cache
);
2152 /* Initialize before goto out */
2156 qemu_progress_init(progress
, 1.0);
2157 qemu_progress_print(0, 100);
2159 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2160 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2162 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2163 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2164 fmt
, src_flags
, src_writethrough
, quiet
,
2170 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2171 if (s
.src_sectors
[bs_i
] < 0) {
2172 error_report("Could not get size of %s: %s",
2173 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2177 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2181 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2182 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2183 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2185 } else if (snapshot_name
!= NULL
) {
2186 if (s
.src_num
> 1) {
2187 error_report("No support for concatenating multiple snapshot");
2192 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2196 error_reportf_err(local_err
, "Failed to load snapshot: ");
2202 /* Find driver and parse its options */
2203 drv
= bdrv_find_format(out_fmt
);
2205 error_report("Unknown file format '%s'", out_fmt
);
2210 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2212 error_report_err(local_err
);
2217 if (!drv
->create_opts
) {
2218 error_report("Format driver '%s' does not support image creation",
2224 if (!proto_drv
->create_opts
) {
2225 error_report("Protocol driver '%s' does not support image creation",
2226 proto_drv
->format_name
);
2231 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2232 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2234 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2236 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2238 error_report_err(local_err
);
2244 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2246 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2252 /* Get backing file name if -o backing_file was used */
2253 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2254 if (out_baseimg_param
) {
2255 out_baseimg
= out_baseimg_param
;
2257 s
.target_has_backing
= (bool) out_baseimg
;
2259 if (s
.src_num
> 1 && out_baseimg
) {
2260 error_report("Having a backing file for the target makes no sense when "
2261 "concatenating multiple input images");
2266 /* Check if compression is supported */
2269 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2270 const char *preallocation
=
2271 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2273 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2274 error_report("Compression not supported for this file format");
2280 error_report("Compression and encryption not supported at "
2287 && strcmp(preallocation
, "off"))
2289 error_report("Compression and preallocation not supported at "
2297 /* Create the new image */
2298 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2300 error_reportf_err(local_err
, "%s: error while converting %s: ",
2301 out_filename
, out_fmt
);
2306 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2307 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2309 error_report("Invalid cache option: %s", cache
);
2314 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2315 flags
, writethrough
, quiet
, false);
2317 /* TODO ultimately we should allow --target-image-opts
2318 * to be used even when -n is not given.
2319 * That has to wait for bdrv_create to be improved
2320 * to allow filenames in option syntax
2322 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2323 flags
, writethrough
, quiet
, false);
2329 out_bs
= blk_bs(s
.target
);
2331 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2332 error_report("Compression not supported for this file format");
2337 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2338 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2340 s
.buf_sectors
= MIN(32768,
2342 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2343 out_bs
->bl
.pdiscard_alignment
>>
2344 BDRV_SECTOR_BITS
)));
2347 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2348 if (output_sectors
< 0) {
2349 error_report("unable to get output image length: %s",
2350 strerror(-output_sectors
));
2353 } else if (output_sectors
< s
.total_sectors
) {
2354 error_report("output file is smaller than input file");
2360 ret
= bdrv_get_info(out_bs
, &bdi
);
2363 error_report("could not get block driver info");
2367 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2368 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2371 ret
= convert_do_copy(&s
);
2374 qemu_progress_print(100, 0);
2376 qemu_progress_end();
2377 qemu_opts_del(opts
);
2378 qemu_opts_free(create_opts
);
2379 qemu_opts_del(sn_opts
);
2380 blk_unref(s
.target
);
2382 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2383 blk_unref(s
.src
[bs_i
]);
2387 g_free(s
.src_sectors
);
2395 static void dump_snapshots(BlockDriverState
*bs
)
2397 QEMUSnapshotInfo
*sn_tab
, *sn
;
2400 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2403 printf("Snapshot list:\n");
2404 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2406 for(i
= 0; i
< nb_sns
; i
++) {
2408 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2414 static void dump_json_image_info_list(ImageInfoList
*list
)
2418 Visitor
*v
= qobject_output_visitor_new(&obj
);
2420 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2421 visit_complete(v
, &obj
);
2422 str
= qobject_to_json_pretty(obj
);
2423 assert(str
!= NULL
);
2424 printf("%s\n", qstring_get_str(str
));
2425 qobject_decref(obj
);
2430 static void dump_json_image_info(ImageInfo
*info
)
2434 Visitor
*v
= qobject_output_visitor_new(&obj
);
2436 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2437 visit_complete(v
, &obj
);
2438 str
= qobject_to_json_pretty(obj
);
2439 assert(str
!= NULL
);
2440 printf("%s\n", qstring_get_str(str
));
2441 qobject_decref(obj
);
2446 static void dump_human_image_info_list(ImageInfoList
*list
)
2448 ImageInfoList
*elem
;
2451 for (elem
= list
; elem
; elem
= elem
->next
) {
2457 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2461 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2463 return strcmp(a
, b
) == 0;
2467 * Open an image file chain and return an ImageInfoList
2469 * @filename: topmost image filename
2470 * @fmt: topmost image format (may be NULL to autodetect)
2471 * @chain: true - enumerate entire backing file chain
2472 * false - only topmost image file
2474 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2475 * image file. If there was an error a message will have been printed to
2478 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2479 const char *filename
,
2481 bool chain
, bool force_share
)
2483 ImageInfoList
*head
= NULL
;
2484 ImageInfoList
**last
= &head
;
2485 GHashTable
*filenames
;
2488 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2492 BlockDriverState
*bs
;
2494 ImageInfoList
*elem
;
2496 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2497 error_report("Backing file '%s' creates an infinite loop.",
2501 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2503 blk
= img_open(image_opts
, filename
, fmt
,
2504 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2511 bdrv_query_image_info(bs
, &info
, &err
);
2513 error_report_err(err
);
2518 elem
= g_new0(ImageInfoList
, 1);
2525 filename
= fmt
= NULL
;
2527 if (info
->has_full_backing_filename
) {
2528 filename
= info
->full_backing_filename
;
2529 } else if (info
->has_backing_filename
) {
2530 error_report("Could not determine absolute backing filename,"
2531 " but backing filename '%s' present",
2532 info
->backing_filename
);
2535 if (info
->has_backing_filename_format
) {
2536 fmt
= info
->backing_filename_format
;
2540 g_hash_table_destroy(filenames
);
2544 qapi_free_ImageInfoList(head
);
2545 g_hash_table_destroy(filenames
);
2549 static int img_info(int argc
, char **argv
)
2552 OutputFormat output_format
= OFORMAT_HUMAN
;
2554 const char *filename
, *fmt
, *output
;
2555 ImageInfoList
*list
;
2556 bool image_opts
= false;
2557 bool force_share
= false;
2562 int option_index
= 0;
2563 static const struct option long_options
[] = {
2564 {"help", no_argument
, 0, 'h'},
2565 {"format", required_argument
, 0, 'f'},
2566 {"output", required_argument
, 0, OPTION_OUTPUT
},
2567 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2568 {"object", required_argument
, 0, OPTION_OBJECT
},
2569 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2570 {"force-share", no_argument
, 0, 'U'},
2573 c
= getopt_long(argc
, argv
, ":f:hU",
2574 long_options
, &option_index
);
2580 missing_argument(argv
[optind
- 1]);
2583 unrecognized_option(argv
[optind
- 1]);
2597 case OPTION_BACKING_CHAIN
:
2600 case OPTION_OBJECT
: {
2602 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2608 case OPTION_IMAGE_OPTS
:
2613 if (optind
!= argc
- 1) {
2614 error_exit("Expecting one image file name");
2616 filename
= argv
[optind
++];
2618 if (output
&& !strcmp(output
, "json")) {
2619 output_format
= OFORMAT_JSON
;
2620 } else if (output
&& !strcmp(output
, "human")) {
2621 output_format
= OFORMAT_HUMAN
;
2622 } else if (output
) {
2623 error_report("--output must be used with human or json as argument.");
2627 if (qemu_opts_foreach(&qemu_object_opts
,
2628 user_creatable_add_opts_foreach
,
2633 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2639 switch (output_format
) {
2641 dump_human_image_info_list(list
);
2645 dump_json_image_info_list(list
);
2647 dump_json_image_info(list
->value
);
2652 qapi_free_ImageInfoList(list
);
2656 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2659 switch (output_format
) {
2661 if (e
->data
&& !e
->has_offset
) {
2662 error_report("File contains external, encrypted or compressed clusters.");
2665 if (e
->data
&& !e
->zero
) {
2666 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2667 e
->start
, e
->length
,
2668 e
->has_offset
? e
->offset
: 0,
2669 e
->has_filename
? e
->filename
: "");
2671 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2672 * Modify the flags here to allow more coalescing.
2674 if (next
&& (!next
->data
|| next
->zero
)) {
2680 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2681 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2682 (e
->start
== 0 ? "[" : ",\n"),
2683 e
->start
, e
->length
, e
->depth
,
2684 e
->zero
? "true" : "false",
2685 e
->data
? "true" : "false");
2686 if (e
->has_offset
) {
2687 printf(", \"offset\": %"PRId64
"", e
->offset
);
2698 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2699 int nb_sectors
, MapEntry
*e
)
2703 BlockDriverState
*file
;
2706 /* As an optimization, we could cache the current range of unallocated
2707 * clusters in each file of the chain, and avoid querying the same
2713 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2719 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2722 bs
= backing_bs(bs
);
2731 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2734 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2735 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2736 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2737 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2738 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2739 .has_offset
= has_offset
,
2741 .has_filename
= file
&& has_offset
,
2742 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2748 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2750 if (curr
->length
== 0) {
2753 if (curr
->zero
!= next
->zero
||
2754 curr
->data
!= next
->data
||
2755 curr
->depth
!= next
->depth
||
2756 curr
->has_filename
!= next
->has_filename
||
2757 curr
->has_offset
!= next
->has_offset
) {
2760 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2763 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2769 static int img_map(int argc
, char **argv
)
2772 OutputFormat output_format
= OFORMAT_HUMAN
;
2774 BlockDriverState
*bs
;
2775 const char *filename
, *fmt
, *output
;
2777 MapEntry curr
= { .length
= 0 }, next
;
2779 bool image_opts
= false;
2780 bool force_share
= false;
2785 int option_index
= 0;
2786 static const struct option long_options
[] = {
2787 {"help", no_argument
, 0, 'h'},
2788 {"format", required_argument
, 0, 'f'},
2789 {"output", required_argument
, 0, OPTION_OUTPUT
},
2790 {"object", required_argument
, 0, OPTION_OBJECT
},
2791 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2792 {"force-share", no_argument
, 0, 'U'},
2795 c
= getopt_long(argc
, argv
, ":f:hU",
2796 long_options
, &option_index
);
2802 missing_argument(argv
[optind
- 1]);
2805 unrecognized_option(argv
[optind
- 1]);
2819 case OPTION_OBJECT
: {
2821 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2827 case OPTION_IMAGE_OPTS
:
2832 if (optind
!= argc
- 1) {
2833 error_exit("Expecting one image file name");
2835 filename
= argv
[optind
];
2837 if (output
&& !strcmp(output
, "json")) {
2838 output_format
= OFORMAT_JSON
;
2839 } else if (output
&& !strcmp(output
, "human")) {
2840 output_format
= OFORMAT_HUMAN
;
2841 } else if (output
) {
2842 error_report("--output must be used with human or json as argument.");
2846 if (qemu_opts_foreach(&qemu_object_opts
,
2847 user_creatable_add_opts_foreach
,
2852 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2858 if (output_format
== OFORMAT_HUMAN
) {
2859 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2862 length
= blk_getlength(blk
);
2863 while (curr
.start
+ curr
.length
< length
) {
2864 int64_t nsectors_left
;
2868 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2870 /* Probe up to 1 GiB at a time. */
2871 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2872 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2873 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2876 error_report("Could not read file metadata: %s", strerror(-ret
));
2880 if (entry_mergeable(&curr
, &next
)) {
2881 curr
.length
+= next
.length
;
2885 if (curr
.length
> 0) {
2886 dump_map_entry(output_format
, &curr
, &next
);
2891 dump_map_entry(output_format
, &curr
, NULL
);
2898 #define SNAPSHOT_LIST 1
2899 #define SNAPSHOT_CREATE 2
2900 #define SNAPSHOT_APPLY 3
2901 #define SNAPSHOT_DELETE 4
2903 static int img_snapshot(int argc
, char **argv
)
2906 BlockDriverState
*bs
;
2907 QEMUSnapshotInfo sn
;
2908 char *filename
, *snapshot_name
= NULL
;
2909 int c
, ret
= 0, bdrv_oflags
;
2914 bool image_opts
= false;
2915 bool force_share
= false;
2917 bdrv_oflags
= BDRV_O_RDWR
;
2918 /* Parse commandline parameters */
2920 static const struct option long_options
[] = {
2921 {"help", no_argument
, 0, 'h'},
2922 {"object", required_argument
, 0, OPTION_OBJECT
},
2923 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2924 {"force-share", no_argument
, 0, 'U'},
2927 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2928 long_options
, NULL
);
2934 missing_argument(argv
[optind
- 1]);
2937 unrecognized_option(argv
[optind
- 1]);
2944 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2947 action
= SNAPSHOT_LIST
;
2948 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2952 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2955 action
= SNAPSHOT_APPLY
;
2956 snapshot_name
= optarg
;
2960 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2963 action
= SNAPSHOT_CREATE
;
2964 snapshot_name
= optarg
;
2968 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2971 action
= SNAPSHOT_DELETE
;
2972 snapshot_name
= optarg
;
2980 case OPTION_OBJECT
: {
2982 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2988 case OPTION_IMAGE_OPTS
:
2994 if (optind
!= argc
- 1) {
2995 error_exit("Expecting one image file name");
2997 filename
= argv
[optind
++];
2999 if (qemu_opts_foreach(&qemu_object_opts
,
3000 user_creatable_add_opts_foreach
,
3005 /* Open the image */
3006 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3013 /* Perform the requested action */
3019 case SNAPSHOT_CREATE
:
3020 memset(&sn
, 0, sizeof(sn
));
3021 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3023 qemu_gettimeofday(&tv
);
3024 sn
.date_sec
= tv
.tv_sec
;
3025 sn
.date_nsec
= tv
.tv_usec
* 1000;
3027 ret
= bdrv_snapshot_create(bs
, &sn
);
3029 error_report("Could not create snapshot '%s': %d (%s)",
3030 snapshot_name
, ret
, strerror(-ret
));
3034 case SNAPSHOT_APPLY
:
3035 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
3037 error_report("Could not apply snapshot '%s': %d (%s)",
3038 snapshot_name
, ret
, strerror(-ret
));
3042 case SNAPSHOT_DELETE
:
3043 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3045 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3060 static int img_rebase(int argc
, char **argv
)
3062 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3063 uint8_t *buf_old
= NULL
;
3064 uint8_t *buf_new
= NULL
;
3065 BlockDriverState
*bs
= NULL
;
3067 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3068 int c
, flags
, src_flags
, ret
;
3069 bool writethrough
, src_writethrough
;
3071 bool force_share
= false;
3074 Error
*local_err
= NULL
;
3075 bool image_opts
= false;
3077 /* Parse commandline parameters */
3079 cache
= BDRV_DEFAULT_CACHE
;
3080 src_cache
= BDRV_DEFAULT_CACHE
;
3084 static const struct option long_options
[] = {
3085 {"help", no_argument
, 0, 'h'},
3086 {"object", required_argument
, 0, OPTION_OBJECT
},
3087 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3088 {"force-share", no_argument
, 0, 'U'},
3091 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3092 long_options
, NULL
);
3098 missing_argument(argv
[optind
- 1]);
3101 unrecognized_option(argv
[optind
- 1]);
3110 out_basefmt
= optarg
;
3113 out_baseimg
= optarg
;
3130 case OPTION_OBJECT
: {
3132 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3138 case OPTION_IMAGE_OPTS
:
3151 if (optind
!= argc
- 1) {
3152 error_exit("Expecting one image file name");
3154 if (!unsafe
&& !out_baseimg
) {
3155 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3157 filename
= argv
[optind
++];
3159 if (qemu_opts_foreach(&qemu_object_opts
,
3160 user_creatable_add_opts_foreach
,
3165 qemu_progress_init(progress
, 2.0);
3166 qemu_progress_print(0, 100);
3168 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3169 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3171 error_report("Invalid cache option: %s", cache
);
3176 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3178 error_report("Invalid source cache option: %s", src_cache
);
3182 /* The source files are opened read-only, don't care about WCE */
3183 assert((src_flags
& BDRV_O_RDWR
) == 0);
3184 (void) src_writethrough
;
3189 * Ignore the old backing file for unsafe rebase in case we want to correct
3190 * the reference to a renamed or moved backing file.
3192 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3200 if (out_basefmt
!= NULL
) {
3201 if (bdrv_find_format(out_basefmt
) == NULL
) {
3202 error_report("Invalid format name: '%s'", out_basefmt
);
3208 /* For safe rebasing we need to compare old and new backing file */
3210 char backing_name
[PATH_MAX
];
3211 QDict
*options
= NULL
;
3213 if (bs
->backing_format
[0] != '\0') {
3214 options
= qdict_new();
3215 qdict_put_str(options
, "driver", bs
->backing_format
);
3220 options
= qdict_new();
3222 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3224 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3225 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3226 options
, src_flags
, &local_err
);
3227 if (!blk_old_backing
) {
3228 error_reportf_err(local_err
,
3229 "Could not open old backing file '%s': ",
3235 if (out_baseimg
[0]) {
3236 options
= qdict_new();
3238 qdict_put_str(options
, "driver", out_basefmt
);
3241 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3244 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3245 options
, src_flags
, &local_err
);
3246 if (!blk_new_backing
) {
3247 error_reportf_err(local_err
,
3248 "Could not open new backing file '%s': ",
3257 * Check each unallocated cluster in the COW file. If it is unallocated,
3258 * accesses go to the backing file. We must therefore compare this cluster
3259 * in the old and new backing file, and if they differ we need to copy it
3260 * from the old backing file into the COW file.
3262 * If qemu-img crashes during this step, no harm is done. The content of
3263 * the image is the same as the original one at any time.
3266 int64_t num_sectors
;
3267 int64_t old_backing_num_sectors
;
3268 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
, n
, &n
);
3320 error_report("error while reading image metadata: %s",
3329 * Read old and new backing file and take into consideration that
3330 * backing files may be smaller than the COW image.
3332 if (sector
>= old_backing_num_sectors
) {
3333 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3335 if (sector
+ n
> old_backing_num_sectors
) {
3336 n
= old_backing_num_sectors
- sector
;
3339 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3340 buf_old
, n
<< BDRV_SECTOR_BITS
);
3342 error_report("error while reading from old backing file");
3347 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3348 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3350 if (sector
+ n
> new_backing_num_sectors
) {
3351 n
= new_backing_num_sectors
- sector
;
3354 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3355 buf_new
, n
<< BDRV_SECTOR_BITS
);
3357 error_report("error while reading from new backing file");
3362 /* If they differ, we need to write to the COW file */
3363 uint64_t written
= 0;
3365 while (written
< n
) {
3368 if (compare_sectors(buf_old
+ written
* 512,
3369 buf_new
+ written
* 512, n
- written
, &pnum
))
3371 ret
= blk_pwrite(blk
,
3372 (sector
+ written
) << BDRV_SECTOR_BITS
,
3373 buf_old
+ written
* 512,
3374 pnum
<< BDRV_SECTOR_BITS
, 0);
3376 error_report("Error while writing to COW image: %s",
3384 qemu_progress_print(local_progress
, 100);
3389 * Change the backing file. All clusters that are different from the old
3390 * backing file are overwritten in the COW file now, so the visible content
3391 * doesn't change when we switch the backing file.
3393 if (out_baseimg
&& *out_baseimg
) {
3394 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3396 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3399 if (ret
== -ENOSPC
) {
3400 error_report("Could not change the backing file to '%s': No "
3401 "space left in the file header", out_baseimg
);
3402 } else if (ret
< 0) {
3403 error_report("Could not change the backing file to '%s': %s",
3404 out_baseimg
, strerror(-ret
));
3407 qemu_progress_print(100, 0);
3409 * TODO At this point it is possible to check if any clusters that are
3410 * allocated in the COW file are the same in the backing file. If so, they
3411 * could be dropped from the COW file. Don't do this before switching the
3412 * backing file, in case of a crash this would lead to corruption.
3415 qemu_progress_end();
3418 blk_unref(blk_old_backing
);
3419 blk_unref(blk_new_backing
);
3421 qemu_vfree(buf_old
);
3422 qemu_vfree(buf_new
);
3431 static int img_resize(int argc
, char **argv
)
3434 int c
, ret
, relative
;
3435 const char *filename
, *fmt
, *size
;
3436 int64_t n
, total_size
;
3438 BlockBackend
*blk
= NULL
;
3441 static QemuOptsList resize_options
= {
3442 .name
= "resize_options",
3443 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3446 .name
= BLOCK_OPT_SIZE
,
3447 .type
= QEMU_OPT_SIZE
,
3448 .help
= "Virtual disk size"
3454 bool image_opts
= false;
3456 /* Remove size from argv manually so that negative numbers are not treated
3457 * as options by getopt. */
3459 error_exit("Not enough arguments");
3463 size
= argv
[--argc
];
3465 /* Parse getopt arguments */
3468 static const struct option long_options
[] = {
3469 {"help", no_argument
, 0, 'h'},
3470 {"object", required_argument
, 0, OPTION_OBJECT
},
3471 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3474 c
= getopt_long(argc
, argv
, ":f:hq",
3475 long_options
, NULL
);
3481 missing_argument(argv
[optind
- 1]);
3484 unrecognized_option(argv
[optind
- 1]);
3495 case OPTION_OBJECT
: {
3497 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3503 case OPTION_IMAGE_OPTS
:
3508 if (optind
!= argc
- 1) {
3509 error_exit("Expecting one image file name");
3511 filename
= argv
[optind
++];
3513 if (qemu_opts_foreach(&qemu_object_opts
,
3514 user_creatable_add_opts_foreach
,
3519 /* Choose grow, shrink, or absolute resize mode */
3535 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3536 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3538 error_report_err(err
);
3540 qemu_opts_del(param
);
3543 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3544 qemu_opts_del(param
);
3546 blk
= img_open(image_opts
, filename
, fmt
,
3547 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3555 total_size
= blk_getlength(blk
) + n
* relative
;
3559 if (total_size
<= 0) {
3560 error_report("New image size must be positive");
3565 ret
= blk_truncate(blk
, total_size
, &err
);
3567 qprintf(quiet
, "Image resized.\n");
3569 error_report_err(err
);
3579 static void amend_status_cb(BlockDriverState
*bs
,
3580 int64_t offset
, int64_t total_work_size
,
3583 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3586 static int img_amend(int argc
, char **argv
)
3590 char *options
= NULL
;
3591 QemuOptsList
*create_opts
= NULL
;
3592 QemuOpts
*opts
= NULL
;
3593 const char *fmt
= NULL
, *filename
, *cache
;
3596 bool quiet
= false, progress
= false;
3597 BlockBackend
*blk
= NULL
;
3598 BlockDriverState
*bs
= NULL
;
3599 bool image_opts
= false;
3601 cache
= BDRV_DEFAULT_CACHE
;
3603 static const struct option long_options
[] = {
3604 {"help", no_argument
, 0, 'h'},
3605 {"object", required_argument
, 0, OPTION_OBJECT
},
3606 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3609 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3610 long_options
, NULL
);
3617 missing_argument(argv
[optind
- 1]);
3620 unrecognized_option(argv
[optind
- 1]);
3626 if (!is_valid_option_list(optarg
)) {
3627 error_report("Invalid option list: %s", optarg
);
3629 goto out_no_progress
;
3632 options
= g_strdup(optarg
);
3634 char *old_options
= options
;
3635 options
= g_strdup_printf("%s,%s", options
, optarg
);
3636 g_free(old_options
);
3652 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3656 goto out_no_progress
;
3659 case OPTION_IMAGE_OPTS
:
3666 error_exit("Must specify options (-o)");
3669 if (qemu_opts_foreach(&qemu_object_opts
,
3670 user_creatable_add_opts_foreach
,
3673 goto out_no_progress
;
3679 qemu_progress_init(progress
, 1.0);
3681 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3682 if (fmt
&& has_help_option(options
)) {
3683 /* If a format is explicitly specified (and possibly no filename is
3684 * given), print option help here */
3685 ret
= print_block_option_help(filename
, fmt
);
3689 if (optind
!= argc
- 1) {
3690 error_report("Expecting one image file name");
3695 flags
= BDRV_O_RDWR
;
3696 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3698 error_report("Invalid cache option: %s", cache
);
3702 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3710 fmt
= bs
->drv
->format_name
;
3712 if (has_help_option(options
)) {
3713 /* If the format was auto-detected, print option help here */
3714 ret
= print_block_option_help(filename
, fmt
);
3718 if (!bs
->drv
->create_opts
) {
3719 error_report("Format driver '%s' does not support any options to amend",
3725 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3726 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3727 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3729 error_report_err(err
);
3734 /* In case the driver does not call amend_status_cb() */
3735 qemu_progress_print(0.f
, 0);
3736 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3737 qemu_progress_print(100.f
, 0);
3739 error_report("Error while amending options: %s", strerror(-ret
));
3744 qemu_progress_end();
3748 qemu_opts_del(opts
);
3749 qemu_opts_free(create_opts
);
3758 typedef struct BenchData
{
3760 uint64_t image_size
;
3767 bool drain_on_flush
;
3776 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3779 error_report("Failed flush request: %s", strerror(-ret
));
3784 static void bench_cb(void *opaque
, int ret
)
3786 BenchData
*b
= opaque
;
3790 error_report("Failed request: %s", strerror(-ret
));
3795 /* Just finished a flush with drained queue: Start next requests */
3796 assert(b
->in_flight
== 0);
3797 b
->in_flush
= false;
3798 } else if (b
->in_flight
> 0) {
3799 int remaining
= b
->n
- b
->in_flight
;
3804 /* Time for flush? Drain queue if requested, then flush */
3805 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3806 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3807 BlockCompletionFunc
*cb
;
3809 if (b
->drain_on_flush
) {
3813 cb
= bench_undrained_flush_cb
;
3816 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3818 error_report("Failed to issue flush request");
3822 if (b
->drain_on_flush
) {
3828 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3829 int64_t offset
= b
->offset
;
3830 /* blk_aio_* might look for completed I/Os and kick bench_cb
3831 * again, so make sure this operation is counted by in_flight
3832 * and b->offset is ready for the next submission.
3835 b
->offset
+= b
->step
;
3836 b
->offset
%= b
->image_size
;
3838 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3840 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3843 error_report("Failed to issue request");
3849 static int img_bench(int argc
, char **argv
)
3852 const char *fmt
= NULL
, *filename
;
3854 bool image_opts
= false;
3855 bool is_write
= false;
3859 size_t bufsize
= 4096;
3862 int flush_interval
= 0;
3863 bool drain_on_flush
= true;
3865 BlockBackend
*blk
= NULL
;
3866 BenchData data
= {};
3868 bool writethrough
= false;
3869 struct timeval t1
, t2
;
3871 bool force_share
= false;
3874 static const struct option long_options
[] = {
3875 {"help", no_argument
, 0, 'h'},
3876 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3877 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3878 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3879 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3880 {"force-share", no_argument
, 0, 'U'},
3883 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3890 missing_argument(argv
[optind
- 1]);
3893 unrecognized_option(argv
[optind
- 1]);
3902 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3903 error_report("Invalid request count specified");
3913 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3914 error_report("Invalid queue depth specified");
3924 flags
|= BDRV_O_NATIVE_AIO
;
3928 offset
= cvtnum(optarg
);
3930 error_report("Invalid offset specified");
3943 sval
= cvtnum(optarg
);
3944 if (sval
< 0 || sval
> INT_MAX
) {
3945 error_report("Invalid buffer size specified");
3956 sval
= cvtnum(optarg
);
3957 if (sval
< 0 || sval
> INT_MAX
) {
3958 error_report("Invalid step size specified");
3966 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3968 error_report("Invalid cache mode");
3974 flags
|= BDRV_O_RDWR
;
3980 case OPTION_PATTERN
:
3984 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3985 error_report("Invalid pattern byte specified");
3991 case OPTION_FLUSH_INTERVAL
:
3995 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3996 error_report("Invalid flush interval specified");
3999 flush_interval
= res
;
4002 case OPTION_NO_DRAIN
:
4003 drain_on_flush
= false;
4005 case OPTION_IMAGE_OPTS
:
4011 if (optind
!= argc
- 1) {
4012 error_exit("Expecting one image file name");
4014 filename
= argv
[argc
- 1];
4016 if (!is_write
&& flush_interval
) {
4017 error_report("--flush-interval is only available in write tests");
4021 if (flush_interval
&& flush_interval
< depth
) {
4022 error_report("Flush interval can't be smaller than depth");
4027 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4034 image_size
= blk_getlength(blk
);
4035 if (image_size
< 0) {
4040 data
= (BenchData
) {
4042 .image_size
= image_size
,
4044 .step
= step
?: bufsize
,
4049 .flush_interval
= flush_interval
,
4050 .drain_on_flush
= drain_on_flush
,
4052 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4053 "(starting at offset %" PRId64
", step size %d)\n",
4054 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4055 data
.offset
, data
.step
);
4056 if (flush_interval
) {
4057 printf("Sending flush every %d requests\n", flush_interval
);
4060 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
4061 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4063 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4064 for (i
= 0; i
< data
.nrreq
; i
++) {
4065 qemu_iovec_init(&data
.qiov
[i
], 1);
4066 qemu_iovec_add(&data
.qiov
[i
],
4067 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4070 gettimeofday(&t1
, NULL
);
4073 while (data
.n
> 0) {
4074 main_loop_wait(false);
4076 gettimeofday(&t2
, NULL
);
4078 printf("Run completed in %3.3f seconds.\n",
4079 (t2
.tv_sec
- t1
.tv_sec
)
4080 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4083 qemu_vfree(data
.buf
);
4104 int bsz
; /* Block size */
4112 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4116 static int img_dd_bs(const char *arg
,
4117 struct DdIo
*in
, struct DdIo
*out
,
4124 if (res
<= 0 || res
> INT_MAX
) {
4125 error_report("invalid number: '%s'", arg
);
4128 in
->bsz
= out
->bsz
= res
;
4133 static int img_dd_count(const char *arg
,
4134 struct DdIo
*in
, struct DdIo
*out
,
4137 dd
->count
= cvtnum(arg
);
4139 if (dd
->count
< 0) {
4140 error_report("invalid number: '%s'", arg
);
4147 static int img_dd_if(const char *arg
,
4148 struct DdIo
*in
, struct DdIo
*out
,
4151 in
->filename
= g_strdup(arg
);
4156 static int img_dd_of(const char *arg
,
4157 struct DdIo
*in
, struct DdIo
*out
,
4160 out
->filename
= g_strdup(arg
);
4165 static int img_dd_skip(const char *arg
,
4166 struct DdIo
*in
, struct DdIo
*out
,
4169 in
->offset
= cvtnum(arg
);
4171 if (in
->offset
< 0) {
4172 error_report("invalid number: '%s'", arg
);
4179 static int img_dd(int argc
, char **argv
)
4184 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4185 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4186 QemuOpts
*opts
= NULL
;
4187 QemuOptsList
*create_opts
= NULL
;
4188 Error
*local_err
= NULL
;
4189 bool image_opts
= false;
4191 const char *out_fmt
= "raw";
4192 const char *fmt
= NULL
;
4194 int64_t block_count
= 0, out_pos
, in_pos
;
4195 bool force_share
= false;
4196 struct DdInfo dd
= {
4201 .bsz
= 512, /* Block size is by default 512 bytes */
4213 const struct DdOpts options
[] = {
4214 { "bs", img_dd_bs
, C_BS
},
4215 { "count", img_dd_count
, C_COUNT
},
4216 { "if", img_dd_if
, C_IF
},
4217 { "of", img_dd_of
, C_OF
},
4218 { "skip", img_dd_skip
, C_SKIP
},
4221 const struct option long_options
[] = {
4222 { "help", no_argument
, 0, 'h'},
4223 { "object", required_argument
, 0, OPTION_OBJECT
},
4224 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4225 { "force-share", no_argument
, 0, 'U'},
4229 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4241 missing_argument(argv
[optind
- 1]);
4244 unrecognized_option(argv
[optind
- 1]);
4252 case OPTION_OBJECT
: {
4254 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4261 case OPTION_IMAGE_OPTS
:
4267 for (i
= optind
; i
< argc
; i
++) {
4269 arg
= g_strdup(argv
[i
]);
4271 tmp
= strchr(arg
, '=');
4273 error_report("unrecognized operand %s", arg
);
4280 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4281 if (!strcmp(arg
, options
[j
].name
)) {
4285 if (options
[j
].name
== NULL
) {
4286 error_report("unrecognized operand %s", arg
);
4291 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4295 dd
.flags
|= options
[j
].flag
;
4300 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4301 error_report("Must specify both input and output files");
4306 if (qemu_opts_foreach(&qemu_object_opts
,
4307 user_creatable_add_opts_foreach
,
4313 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4321 drv
= bdrv_find_format(out_fmt
);
4323 error_report("Unknown file format");
4327 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4330 error_report_err(local_err
);
4334 if (!drv
->create_opts
) {
4335 error_report("Format driver '%s' does not support image creation",
4340 if (!proto_drv
->create_opts
) {
4341 error_report("Protocol driver '%s' does not support image creation",
4342 proto_drv
->format_name
);
4346 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4347 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4349 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4351 size
= blk_getlength(blk1
);
4353 error_report("Failed to get size for '%s'", in
.filename
);
4358 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4359 dd
.count
* in
.bsz
< size
) {
4360 size
= dd
.count
* in
.bsz
;
4363 /* Overflow means the specified offset is beyond input image's size */
4364 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4365 size
< in
.bsz
* in
.offset
)) {
4366 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4368 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4369 size
- in
.bsz
* in
.offset
, &error_abort
);
4372 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4374 error_reportf_err(local_err
,
4375 "%s: error while creating output image: ",
4381 /* TODO, we can't honour --image-opts for the target,
4382 * since it needs to be given in a format compatible
4383 * with the bdrv_create() call above which does not
4384 * support image-opts style.
4386 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4387 false, false, false);
4394 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4395 size
< in
.offset
* in
.bsz
)) {
4396 /* We give a warning if the skip option is bigger than the input
4397 * size and create an empty output disk image (i.e. like dd(1)).
4399 error_report("%s: cannot skip to specified offset", in
.filename
);
4402 in_pos
= in
.offset
* in
.bsz
;
4405 in
.buf
= g_new(uint8_t, in
.bsz
);
4407 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4408 int in_ret
, out_ret
;
4410 if (in_pos
+ in
.bsz
> size
) {
4411 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4413 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4416 error_report("error while reading from input image file: %s",
4423 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4426 error_report("error while writing to output image file: %s",
4427 strerror(-out_ret
));
4436 qemu_opts_del(opts
);
4437 qemu_opts_free(create_opts
);
4440 g_free(in
.filename
);
4441 g_free(out
.filename
);
4452 static const img_cmd_t img_cmds
[] = {
4453 #define DEF(option, callback, arg_string) \
4454 { option, callback },
4455 #include "qemu-img-cmds.h"
4461 int main(int argc
, char **argv
)
4463 const img_cmd_t
*cmd
;
4464 const char *cmdname
;
4465 Error
*local_error
= NULL
;
4466 char *trace_file
= NULL
;
4468 static const struct option long_options
[] = {
4469 {"help", no_argument
, 0, 'h'},
4470 {"version", no_argument
, 0, 'V'},
4471 {"trace", required_argument
, NULL
, 'T'},
4476 signal(SIGPIPE
, SIG_IGN
);
4479 module_call_init(MODULE_INIT_TRACE
);
4480 error_set_progname(argv
[0]);
4481 qemu_init_exec_dir(argv
[0]);
4483 if (qemu_init_main_loop(&local_error
)) {
4484 error_report_err(local_error
);
4488 qcrypto_init(&error_fatal
);
4490 module_call_init(MODULE_INIT_QOM
);
4493 error_exit("Not enough arguments");
4496 qemu_add_opts(&qemu_object_opts
);
4497 qemu_add_opts(&qemu_source_opts
);
4498 qemu_add_opts(&qemu_trace_opts
);
4500 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4503 missing_argument(argv
[optind
- 1]);
4506 unrecognized_option(argv
[optind
- 1]);
4512 printf(QEMU_IMG_VERSION
);
4516 trace_file
= trace_opt_parse(optarg
);
4521 cmdname
= argv
[optind
];
4523 /* reset getopt_long scanning */
4531 if (!trace_init_backends()) {
4534 trace_init_file(trace_file
);
4535 qemu_set_log(LOG_TRACE
);
4537 /* find the command */
4538 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4539 if (!strcmp(cmdname
, cmd
->name
)) {
4540 return cmd
->handler(argc
, argv
);
4545 error_exit("Command not found: %s", cmdname
);