2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
27 #include "qemu-version.h"
28 #include "qapi/error.h"
29 #include "qapi-visit.h"
30 #include "qapi/qobject-output-visitor.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qemu/cutils.h"
35 #include "qemu/config-file.h"
36 #include "qemu/option.h"
37 #include "qemu/error-report.h"
39 #include "qom/object_interfaces.h"
40 #include "sysemu/sysemu.h"
41 #include "sysemu/block-backend.h"
42 #include "block/block_int.h"
43 #include "block/blockjob.h"
44 #include "block/qapi.h"
45 #include "crypto/init.h"
46 #include "trace/control.h"
48 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
49 "\n" QEMU_COPYRIGHT "\n"
51 typedef struct img_cmd_t
{
53 int (*handler
)(int argc
, char **argv
);
58 OPTION_BACKING_CHAIN
= 257,
60 OPTION_IMAGE_OPTS
= 259,
62 OPTION_FLUSH_INTERVAL
= 261,
63 OPTION_NO_DRAIN
= 262,
64 OPTION_TARGET_IMAGE_OPTS
= 263,
66 OPTION_PREALLOCATION
= 265,
70 typedef enum OutputFormat
{
75 /* Default to cache=writeback as data integrity is not important for qemu-img */
76 #define BDRV_DEFAULT_CACHE "writeback"
78 static void format_print(void *opaque
, const char *name
)
83 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
87 error_printf("qemu-img: ");
90 error_vprintf(fmt
, ap
);
93 error_printf("\nTry 'qemu-img --help' for more information\n");
97 static void QEMU_NORETURN
missing_argument(const char *option
)
99 error_exit("missing argument for option '%s'", option
);
102 static void QEMU_NORETURN
unrecognized_option(const char *option
)
104 error_exit("unrecognized option '%s'", option
);
107 /* Please keep in synch with qemu-img.texi */
108 static void QEMU_NORETURN
help(void)
110 const char *help_msg
=
112 "usage: qemu-img [standard options] command [command options]\n"
113 "QEMU disk image utility\n"
115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
121 #define DEF(option, callback, arg_string) \
123 #include "qemu-img-cmds.h"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
151 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
153 " '-c' indicates that target image must be compressed (qcow format only)\n"
154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
159 " '-h' with or without a command shows this help and lists the supported formats\n"
160 " '-p' show progress of command (only certain commands)\n"
161 " '-q' use Quiet mode - do not print any output (except errors)\n"
162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
167 " '--output' takes the format in which the output must be done (human or json)\n"
168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
175 " hiding corruption that has already occurred.\n"
177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
187 " '-l' lists all snapshots in the given image\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
202 printf("%s\nSupported formats:", help_msg
);
203 bdrv_iterate_format(format_print
, NULL
);
204 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
208 static QemuOptsList qemu_object_opts
= {
210 .implied_opt_name
= "qom-type",
211 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
217 static QemuOptsList qemu_source_opts
= {
219 .implied_opt_name
= "file",
220 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
226 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
232 ret
= vprintf(fmt
, args
);
239 static int print_block_option_help(const char *filename
, const char *fmt
)
241 BlockDriver
*drv
, *proto_drv
;
242 QemuOptsList
*create_opts
= NULL
;
243 Error
*local_err
= NULL
;
245 /* Find driver and parse its options */
246 drv
= bdrv_find_format(fmt
);
248 error_report("Unknown file format '%s'", fmt
);
252 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
254 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
256 error_report_err(local_err
);
257 qemu_opts_free(create_opts
);
260 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
263 qemu_opts_print_help(create_opts
);
264 qemu_opts_free(create_opts
);
269 static BlockBackend
*img_open_opts(const char *optstr
,
270 QemuOpts
*opts
, int flags
, bool writethrough
,
271 bool quiet
, bool force_share
)
274 Error
*local_err
= NULL
;
276 options
= qemu_opts_to_qdict(opts
, NULL
);
278 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
279 && !qdict_get_bool(options
, BDRV_OPT_FORCE_SHARE
)) {
280 error_report("--force-share/-U conflicts with image options");
284 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
286 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
288 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
291 blk_set_enable_write_cache(blk
, !writethrough
);
296 static BlockBackend
*img_open_file(const char *filename
,
298 const char *fmt
, int flags
,
299 bool writethrough
, bool quiet
,
303 Error
*local_err
= NULL
;
306 options
= qdict_new();
309 qdict_put_str(options
, "driver", fmt
);
313 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
315 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
317 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
320 blk_set_enable_write_cache(blk
, !writethrough
);
326 static int img_add_key_secrets(void *opaque
,
327 const char *name
, const char *value
,
330 QDict
*options
= opaque
;
332 if (g_str_has_suffix(name
, "key-secret")) {
333 qdict_put_str(options
, name
, value
);
339 static BlockBackend
*img_open_new_file(const char *filename
,
340 QemuOpts
*create_opts
,
341 const char *fmt
, int flags
,
342 bool writethrough
, bool quiet
,
345 QDict
*options
= NULL
;
347 options
= qdict_new();
348 qemu_opt_foreach(create_opts
, img_add_key_secrets
, options
, &error_abort
);
350 return img_open_file(filename
, options
, fmt
, flags
, writethrough
, quiet
,
355 static BlockBackend
*img_open(bool image_opts
,
356 const char *filename
,
357 const char *fmt
, int flags
, bool writethrough
,
358 bool quiet
, bool force_share
)
364 error_report("--image-opts and --format are mutually exclusive");
367 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
372 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
375 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
382 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
383 const char *base_filename
,
384 const char *base_fmt
)
389 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
391 error_report("Backing file not supported for file format '%s'",
398 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
400 error_report("Backing file format not supported for file "
409 static int64_t cvtnum(const char *s
)
414 err
= qemu_strtosz(s
, NULL
, &value
);
418 if (value
> INT64_MAX
) {
424 static int img_create(int argc
, char **argv
)
427 uint64_t img_size
= -1;
428 const char *fmt
= "raw";
429 const char *base_fmt
= NULL
;
430 const char *filename
;
431 const char *base_filename
= NULL
;
432 char *options
= NULL
;
433 Error
*local_err
= NULL
;
438 static const struct option long_options
[] = {
439 {"help", no_argument
, 0, 'h'},
440 {"object", required_argument
, 0, OPTION_OBJECT
},
443 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
450 missing_argument(argv
[optind
- 1]);
453 unrecognized_option(argv
[optind
- 1]);
462 base_filename
= optarg
;
468 if (!is_valid_option_list(optarg
)) {
469 error_report("Invalid option list: %s", optarg
);
473 options
= g_strdup(optarg
);
475 char *old_options
= options
;
476 options
= g_strdup_printf("%s,%s", options
, optarg
);
484 flags
|= BDRV_O_NO_BACKING
;
486 case OPTION_OBJECT
: {
488 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
497 /* Get the filename */
498 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
499 if (options
&& has_help_option(options
)) {
501 return print_block_option_help(filename
, fmt
);
504 if (optind
>= argc
) {
505 error_exit("Expecting image file name");
509 if (qemu_opts_foreach(&qemu_object_opts
,
510 user_creatable_add_opts_foreach
,
515 /* Get image size, if specified */
519 sval
= cvtnum(argv
[optind
++]);
521 if (sval
== -ERANGE
) {
522 error_report("Image size must be less than 8 EiB!");
524 error_report("Invalid image size specified! You may use k, M, "
525 "G, T, P or E suffixes for ");
526 error_report("kilobytes, megabytes, gigabytes, terabytes, "
527 "petabytes and exabytes.");
531 img_size
= (uint64_t)sval
;
533 if (optind
!= argc
) {
534 error_exit("Unexpected argument: %s", argv
[optind
]);
537 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
538 options
, img_size
, flags
, quiet
, &local_err
);
540 error_reportf_err(local_err
, "%s: ", filename
);
552 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
556 Visitor
*v
= qobject_output_visitor_new(&obj
);
558 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
559 visit_complete(v
, &obj
);
560 str
= qobject_to_json_pretty(obj
);
562 qprintf(quiet
, "%s\n", qstring_get_str(str
));
568 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
570 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
571 qprintf(quiet
, "No errors were found on the image.\n");
573 if (check
->corruptions
) {
574 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
575 "Data may be corrupted, or further writes to the image "
582 "\n%" PRId64
" leaked clusters were found on the image.\n"
583 "This means waste of disk space, but no harm to data.\n",
587 if (check
->check_errors
) {
590 " internal errors have occurred during the check.\n",
591 check
->check_errors
);
595 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
596 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
597 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
598 check
->allocated_clusters
, check
->total_clusters
,
599 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
600 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
601 check
->compressed_clusters
* 100.0 /
602 check
->allocated_clusters
);
605 if (check
->image_end_offset
) {
607 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
611 static int collect_image_check(BlockDriverState
*bs
,
613 const char *filename
,
618 BdrvCheckResult result
;
620 ret
= bdrv_check(bs
, &result
, fix
);
625 check
->filename
= g_strdup(filename
);
626 check
->format
= g_strdup(bdrv_get_format_name(bs
));
627 check
->check_errors
= result
.check_errors
;
628 check
->corruptions
= result
.corruptions
;
629 check
->has_corruptions
= result
.corruptions
!= 0;
630 check
->leaks
= result
.leaks
;
631 check
->has_leaks
= result
.leaks
!= 0;
632 check
->corruptions_fixed
= result
.corruptions_fixed
;
633 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
634 check
->leaks_fixed
= result
.leaks_fixed
;
635 check
->has_leaks_fixed
= result
.leaks
!= 0;
636 check
->image_end_offset
= result
.image_end_offset
;
637 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
638 check
->total_clusters
= result
.bfi
.total_clusters
;
639 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
640 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
641 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
642 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
643 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
644 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
645 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
651 * Checks an image for consistency. Exit codes:
653 * 0 - Check completed, image is good
654 * 1 - Check not completed because of internal errors
655 * 2 - Check completed, image is corrupted
656 * 3 - Check completed, image has leaked clusters, but is good otherwise
657 * 63 - Checks are not supported by the image format
659 static int img_check(int argc
, char **argv
)
662 OutputFormat output_format
= OFORMAT_HUMAN
;
663 const char *filename
, *fmt
, *output
, *cache
;
665 BlockDriverState
*bs
;
667 int flags
= BDRV_O_CHECK
;
671 bool image_opts
= false;
672 bool force_share
= false;
676 cache
= BDRV_DEFAULT_CACHE
;
679 int option_index
= 0;
680 static const struct option long_options
[] = {
681 {"help", no_argument
, 0, 'h'},
682 {"format", required_argument
, 0, 'f'},
683 {"repair", required_argument
, 0, 'r'},
684 {"output", required_argument
, 0, OPTION_OUTPUT
},
685 {"object", required_argument
, 0, OPTION_OBJECT
},
686 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
687 {"force-share", no_argument
, 0, 'U'},
690 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
691 long_options
, &option_index
);
697 missing_argument(argv
[optind
- 1]);
700 unrecognized_option(argv
[optind
- 1]);
709 flags
|= BDRV_O_RDWR
;
711 if (!strcmp(optarg
, "leaks")) {
712 fix
= BDRV_FIX_LEAKS
;
713 } else if (!strcmp(optarg
, "all")) {
714 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
716 error_exit("Unknown option value for -r "
717 "(expecting 'leaks' or 'all'): %s", optarg
);
732 case OPTION_OBJECT
: {
734 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
740 case OPTION_IMAGE_OPTS
:
745 if (optind
!= argc
- 1) {
746 error_exit("Expecting one image file name");
748 filename
= argv
[optind
++];
750 if (output
&& !strcmp(output
, "json")) {
751 output_format
= OFORMAT_JSON
;
752 } else if (output
&& !strcmp(output
, "human")) {
753 output_format
= OFORMAT_HUMAN
;
755 error_report("--output must be used with human or json as argument.");
759 if (qemu_opts_foreach(&qemu_object_opts
,
760 user_creatable_add_opts_foreach
,
765 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
767 error_report("Invalid source cache option: %s", cache
);
771 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
778 check
= g_new0(ImageCheck
, 1);
779 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
781 if (ret
== -ENOTSUP
) {
782 error_report("This image format does not support checks");
787 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
788 int corruptions_fixed
, leaks_fixed
;
790 leaks_fixed
= check
->leaks_fixed
;
791 corruptions_fixed
= check
->corruptions_fixed
;
793 if (output_format
== OFORMAT_HUMAN
) {
795 "The following inconsistencies were found and repaired:\n\n"
796 " %" PRId64
" leaked clusters\n"
797 " %" PRId64
" corruptions\n\n"
798 "Double checking the fixed image now...\n",
800 check
->corruptions_fixed
);
803 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
805 check
->leaks_fixed
= leaks_fixed
;
806 check
->corruptions_fixed
= corruptions_fixed
;
810 switch (output_format
) {
812 dump_human_image_check(check
, quiet
);
815 dump_json_image_check(check
, quiet
);
820 if (ret
|| check
->check_errors
) {
822 error_report("Check failed: %s", strerror(-ret
));
824 error_report("Check failed");
830 if (check
->corruptions
) {
832 } else if (check
->leaks
) {
839 qapi_free_ImageCheck(check
);
844 typedef struct CommonBlockJobCBInfo
{
845 BlockDriverState
*bs
;
847 } CommonBlockJobCBInfo
;
849 static void common_block_job_cb(void *opaque
, int ret
)
851 CommonBlockJobCBInfo
*cbi
= opaque
;
854 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
858 static void run_block_job(BlockJob
*job
, Error
**errp
)
860 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
863 aio_context_acquire(aio_context
);
866 aio_poll(aio_context
, true);
867 qemu_progress_print(job
->len
?
868 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
869 } while (!job
->ready
&& !job
->completed
);
871 if (!job
->completed
) {
872 ret
= block_job_complete_sync(job
, errp
);
876 block_job_unref(job
);
877 aio_context_release(aio_context
);
879 /* publish completion progress only when success */
881 qemu_progress_print(100.f
, 0);
885 static int img_commit(int argc
, char **argv
)
888 const char *filename
, *fmt
, *cache
, *base
;
890 BlockDriverState
*bs
, *base_bs
;
892 bool progress
= false, quiet
= false, drop
= false;
894 Error
*local_err
= NULL
;
895 CommonBlockJobCBInfo cbi
;
896 bool image_opts
= false;
897 AioContext
*aio_context
;
900 cache
= BDRV_DEFAULT_CACHE
;
903 static const struct option long_options
[] = {
904 {"help", no_argument
, 0, 'h'},
905 {"object", required_argument
, 0, OPTION_OBJECT
},
906 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
909 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
916 missing_argument(argv
[optind
- 1]);
919 unrecognized_option(argv
[optind
- 1]);
944 case OPTION_OBJECT
: {
946 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
952 case OPTION_IMAGE_OPTS
:
958 /* Progress is not shown in Quiet mode */
963 if (optind
!= argc
- 1) {
964 error_exit("Expecting one image file name");
966 filename
= argv
[optind
++];
968 if (qemu_opts_foreach(&qemu_object_opts
,
969 user_creatable_add_opts_foreach
,
974 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
975 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
977 error_report("Invalid cache option: %s", cache
);
981 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
988 qemu_progress_init(progress
, 1.f
);
989 qemu_progress_print(0.f
, 100);
992 base_bs
= bdrv_find_backing_image(bs
, base
);
994 error_setg(&local_err
,
995 "Did not find '%s' in the backing chain of '%s'",
1000 /* This is different from QMP, which by default uses the deepest file in
1001 * the backing chain (i.e., the very base); however, the traditional
1002 * behavior of qemu-img commit is using the immediate backing file. */
1003 base_bs
= backing_bs(bs
);
1005 error_setg(&local_err
, "Image does not have a backing file");
1010 cbi
= (CommonBlockJobCBInfo
){
1015 aio_context
= bdrv_get_aio_context(bs
);
1016 aio_context_acquire(aio_context
);
1017 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1018 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1019 &cbi
, false, &local_err
);
1020 aio_context_release(aio_context
);
1025 /* When the block job completes, the BlockBackend reference will point to
1026 * the old backing file. In order to avoid that the top image is already
1027 * deleted, so we can still empty it afterwards, increment the reference
1028 * counter here preemptively. */
1033 job
= block_job_get("commit");
1034 run_block_job(job
, &local_err
);
1039 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1040 ret
= bs
->drv
->bdrv_make_empty(bs
);
1042 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1054 qemu_progress_end();
1059 error_report_err(local_err
);
1063 qprintf(quiet
, "Image committed.\n");
1068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1073 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1076 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1078 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1079 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1083 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1090 * Returns true iff the first sector pointed to by 'buf' contains at least
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
1096 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1105 is_zero
= buffer_is_zero(buf
, 512);
1106 for(i
= 1; i
< n
; i
++) {
1108 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1117 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1118 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1119 * breaking up write requests for only small sparse areas.
1121 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1125 int num_checked
, num_used
;
1131 ret
= is_allocated_sectors(buf
, n
, pnum
);
1137 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1139 num_checked
= num_used
;
1142 ret
= is_allocated_sectors(buf
, n
, pnum
);
1144 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1146 num_checked
+= *pnum
;
1148 num_used
= num_checked
;
1149 } else if (*pnum
>= min
) {
1159 * Compares two buffers sector by sector. Returns 0 if the first
1160 * sector of each buffer matches, non-zero otherwise.
1162 * pnum is set to the sector-aligned size of the buffer prefix that
1163 * has the same matching status as the first sector.
1165 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1166 int64_t bytes
, int64_t *pnum
)
1169 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1173 res
= !!memcmp(buf1
, buf2
, i
);
1175 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1177 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1187 #define IO_BUF_SIZE (2 * 1024 * 1024)
1190 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1192 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1193 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1194 * failure), and 4 on error (the exit status for read errors), after emitting
1197 * @param blk: BlockBackend for the image
1198 * @param offset: Starting offset to check
1199 * @param bytes: Number of bytes to check
1200 * @param filename: Name of disk file we are checking (logging purpose)
1201 * @param buffer: Allocated buffer for storing read data
1202 * @param quiet: Flag for quiet mode
1204 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1205 int64_t bytes
, const char *filename
,
1206 uint8_t *buffer
, bool quiet
)
1211 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1213 error_report("Error while reading offset %" PRId64
" of %s: %s",
1214 offset
, filename
, strerror(-ret
));
1217 idx
= find_nonzero(buffer
, bytes
);
1219 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1228 * Compares two images. Exit codes:
1230 * 0 - Images are identical
1232 * >1 - Error occurred
1234 static int img_compare(int argc
, char **argv
)
1236 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1237 BlockBackend
*blk1
, *blk2
;
1238 BlockDriverState
*bs1
, *bs2
;
1239 int64_t total_size1
, total_size2
;
1240 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1241 int64_t pnum1
, pnum2
;
1242 int allocated1
, allocated2
;
1243 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1244 bool progress
= false, quiet
= false, strict
= false;
1251 uint64_t progress_base
;
1252 bool image_opts
= false;
1253 bool force_share
= false;
1255 cache
= BDRV_DEFAULT_CACHE
;
1257 static const struct option long_options
[] = {
1258 {"help", no_argument
, 0, 'h'},
1259 {"object", required_argument
, 0, OPTION_OBJECT
},
1260 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1261 {"force-share", no_argument
, 0, 'U'},
1264 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1265 long_options
, NULL
);
1271 missing_argument(argv
[optind
- 1]);
1274 unrecognized_option(argv
[optind
- 1]);
1300 case OPTION_OBJECT
: {
1302 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1309 case OPTION_IMAGE_OPTS
:
1315 /* Progress is not shown in Quiet mode */
1321 if (optind
!= argc
- 2) {
1322 error_exit("Expecting two image file names");
1324 filename1
= argv
[optind
++];
1325 filename2
= argv
[optind
++];
1327 if (qemu_opts_foreach(&qemu_object_opts
,
1328 user_creatable_add_opts_foreach
,
1334 /* Initialize before goto out */
1335 qemu_progress_init(progress
, 2.0);
1338 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1340 error_report("Invalid source cache option: %s", cache
);
1345 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1352 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1361 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1362 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1363 total_size1
= blk_getlength(blk1
);
1364 if (total_size1
< 0) {
1365 error_report("Can't get size of %s: %s",
1366 filename1
, strerror(-total_size1
));
1370 total_size2
= blk_getlength(blk2
);
1371 if (total_size2
< 0) {
1372 error_report("Can't get size of %s: %s",
1373 filename2
, strerror(-total_size2
));
1377 total_size
= MIN(total_size1
, total_size2
);
1378 progress_base
= MAX(total_size1
, total_size2
);
1380 qemu_progress_print(0, 100);
1382 if (strict
&& total_size1
!= total_size2
) {
1384 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1388 while (offset
< total_size
) {
1389 int status1
, status2
;
1391 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1392 total_size1
- offset
, &pnum1
, NULL
,
1396 error_report("Sector allocation test failed for %s", filename1
);
1399 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1401 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1402 total_size2
- offset
, &pnum2
, NULL
,
1406 error_report("Sector allocation test failed for %s", filename2
);
1409 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1411 assert(pnum1
&& pnum2
);
1412 chunk
= MIN(pnum1
, pnum2
);
1415 if (status1
!= status2
) {
1417 qprintf(quiet
, "Strict mode: Offset %" PRId64
1418 " block status mismatch!\n", offset
);
1422 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1424 } else if (allocated1
== allocated2
) {
1428 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1429 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1431 error_report("Error while reading offset %" PRId64
1433 offset
, filename1
, strerror(-ret
));
1437 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1439 error_report("Error while reading offset %" PRId64
1441 offset
, filename2
, strerror(-ret
));
1445 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1446 if (ret
|| pnum
!= chunk
) {
1447 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1448 offset
+ (ret
? 0 : pnum
));
1454 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1456 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1457 filename1
, buf1
, quiet
);
1459 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1460 filename2
, buf1
, quiet
);
1467 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1470 if (total_size1
!= total_size2
) {
1471 BlockBackend
*blk_over
;
1472 const char *filename_over
;
1474 qprintf(quiet
, "Warning: Image size mismatch!\n");
1475 if (total_size1
> total_size2
) {
1477 filename_over
= filename1
;
1480 filename_over
= filename2
;
1483 while (offset
< progress_base
) {
1484 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1485 progress_base
- offset
, &chunk
,
1489 error_report("Sector allocation test failed for %s",
1494 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1495 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1496 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1497 filename_over
, buf1
, quiet
);
1503 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1507 qprintf(quiet
, "Images are identical.\n");
1517 qemu_progress_end();
1522 enum ImgConvertBlockStatus
{
1528 #define MAX_COROUTINES 16
1530 typedef struct ImgConvertState
{
1532 int64_t *src_sectors
;
1534 int64_t total_sectors
;
1535 int64_t allocated_sectors
;
1536 int64_t allocated_done
;
1539 enum ImgConvertBlockStatus status
;
1540 int64_t sector_next_status
;
1541 BlockBackend
*target
;
1544 bool target_has_backing
;
1547 size_t cluster_sectors
;
1549 long num_coroutines
;
1550 int running_coroutines
;
1551 Coroutine
*co
[MAX_COROUTINES
];
1552 int64_t wait_sector_num
[MAX_COROUTINES
];
1557 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1558 int *src_cur
, int64_t *src_cur_offset
)
1561 *src_cur_offset
= 0;
1562 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1563 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1565 assert(*src_cur
< s
->src_num
);
1569 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1571 int64_t src_cur_offset
;
1572 int ret
, n
, src_cur
;
1574 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1576 assert(s
->total_sectors
> sector_num
);
1577 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1579 if (s
->sector_next_status
<= sector_num
) {
1580 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1582 if (s
->target_has_backing
) {
1584 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1585 (sector_num
- src_cur_offset
) *
1587 count
, &count
, NULL
, NULL
);
1589 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1590 (sector_num
- src_cur_offset
) *
1592 count
, &count
, NULL
, NULL
);
1597 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1599 if (ret
& BDRV_BLOCK_ZERO
) {
1600 s
->status
= BLK_ZERO
;
1601 } else if (ret
& BDRV_BLOCK_DATA
) {
1602 s
->status
= BLK_DATA
;
1604 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1607 s
->sector_next_status
= sector_num
+ n
;
1610 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1611 if (s
->status
== BLK_DATA
) {
1612 n
= MIN(n
, s
->buf_sectors
);
1615 /* We need to write complete clusters for compressed images, so if an
1616 * unallocated area is shorter than that, we must consider the whole
1617 * cluster allocated. */
1618 if (s
->compressed
) {
1619 if (n
< s
->cluster_sectors
) {
1620 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1621 s
->status
= BLK_DATA
;
1623 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1630 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1631 int nb_sectors
, uint8_t *buf
)
1637 assert(nb_sectors
<= s
->buf_sectors
);
1638 while (nb_sectors
> 0) {
1641 int64_t bs_sectors
, src_cur_offset
;
1643 /* In the case of compression with multiple source files, we can get a
1644 * nb_sectors that spreads into the next part. So we must be able to
1645 * read across multiple BDSes for one convert_read() call. */
1646 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1647 blk
= s
->src
[src_cur
];
1648 bs_sectors
= s
->src_sectors
[src_cur
];
1650 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1652 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1653 qemu_iovec_init_external(&qiov
, &iov
, 1);
1655 ret
= blk_co_preadv(
1656 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1657 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1664 buf
+= n
* BDRV_SECTOR_SIZE
;
1671 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1672 int nb_sectors
, uint8_t *buf
,
1673 enum ImgConvertBlockStatus status
)
1679 while (nb_sectors
> 0) {
1681 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1684 case BLK_BACKING_FILE
:
1685 /* If we have a backing file, leave clusters unallocated that are
1686 * unallocated in the source image, so that the backing file is
1687 * visible at the respective offset. */
1688 assert(s
->target_has_backing
);
1692 /* If we're told to keep the target fully allocated (-S 0) or there
1693 * is real non-zero data, we must write it. Otherwise we can treat
1694 * it as zero sectors.
1695 * Compressed clusters need to be written as a whole, so in that
1696 * case we can only save the write if the buffer is completely
1698 if (!s
->min_sparse
||
1700 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1702 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1705 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1706 qemu_iovec_init_external(&qiov
, &iov
, 1);
1708 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1709 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1718 if (s
->has_zero_init
) {
1719 assert(!s
->target_has_backing
);
1722 ret
= blk_co_pwrite_zeroes(s
->target
,
1723 sector_num
<< BDRV_SECTOR_BITS
,
1724 n
<< BDRV_SECTOR_BITS
, 0);
1733 buf
+= n
* BDRV_SECTOR_SIZE
;
1739 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1741 ImgConvertState
*s
= opaque
;
1742 uint8_t *buf
= NULL
;
1746 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1747 if (s
->co
[i
] == qemu_coroutine_self()) {
1754 s
->running_coroutines
++;
1755 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1760 enum ImgConvertBlockStatus status
;
1762 qemu_co_mutex_lock(&s
->lock
);
1763 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1764 qemu_co_mutex_unlock(&s
->lock
);
1767 n
= convert_iteration_sectors(s
, s
->sector_num
);
1769 qemu_co_mutex_unlock(&s
->lock
);
1773 /* save current sector and allocation status to local variables */
1774 sector_num
= s
->sector_num
;
1776 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1777 n
= MIN(n
, s
->buf_sectors
);
1779 /* increment global sector counter so that other coroutines can
1780 * already continue reading beyond this request */
1782 qemu_co_mutex_unlock(&s
->lock
);
1784 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1785 s
->allocated_done
+= n
;
1786 qemu_progress_print(100.0 * s
->allocated_done
/
1787 s
->allocated_sectors
, 0);
1790 if (status
== BLK_DATA
) {
1791 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1793 error_report("error while reading sector %" PRId64
1794 ": %s", sector_num
, strerror(-ret
));
1797 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1799 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1802 if (s
->wr_in_order
) {
1803 /* keep writes in order */
1804 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1805 s
->wait_sector_num
[index
] = sector_num
;
1806 qemu_coroutine_yield();
1808 s
->wait_sector_num
[index
] = -1;
1811 if (s
->ret
== -EINPROGRESS
) {
1812 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1814 error_report("error while writing sector %" PRId64
1815 ": %s", sector_num
, strerror(-ret
));
1820 if (s
->wr_in_order
) {
1821 /* reenter the coroutine that might have waited
1822 * for this write to complete */
1823 s
->wr_offs
= sector_num
+ n
;
1824 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1825 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1827 * A -> B -> A cannot occur because A has
1828 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1829 * B will never enter A during this time window.
1831 qemu_coroutine_enter(s
->co
[i
]);
1839 s
->co
[index
] = NULL
;
1840 s
->running_coroutines
--;
1841 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1842 /* the convert job finished successfully */
1847 static int convert_do_copy(ImgConvertState
*s
)
1850 int64_t sector_num
= 0;
1852 /* Check whether we have zero initialisation or can get it efficiently */
1853 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1854 ? bdrv_has_zero_init(blk_bs(s
->target
))
1857 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1858 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1860 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1862 s
->has_zero_init
= true;
1866 /* Allocate buffer for copied data. For compressed images, only one cluster
1867 * can be copied at a time. */
1868 if (s
->compressed
) {
1869 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1870 error_report("invalid cluster size");
1873 s
->buf_sectors
= s
->cluster_sectors
;
1876 while (sector_num
< s
->total_sectors
) {
1877 n
= convert_iteration_sectors(s
, sector_num
);
1881 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1883 s
->allocated_sectors
+= n
;
1889 s
->sector_next_status
= 0;
1890 s
->ret
= -EINPROGRESS
;
1892 qemu_co_mutex_init(&s
->lock
);
1893 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1894 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1895 s
->wait_sector_num
[i
] = -1;
1896 qemu_coroutine_enter(s
->co
[i
]);
1899 while (s
->running_coroutines
) {
1900 main_loop_wait(false);
1903 if (s
->compressed
&& !s
->ret
) {
1904 /* signal EOF to align */
1905 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1914 static int img_convert(int argc
, char **argv
)
1916 int c
, bs_i
, flags
, src_flags
= 0;
1917 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1918 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1919 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1920 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1921 BlockDriverInfo bdi
;
1922 BlockDriverState
*out_bs
;
1923 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1924 QemuOptsList
*create_opts
= NULL
;
1925 char *options
= NULL
;
1926 Error
*local_err
= NULL
;
1927 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1928 skip_create
= false, progress
= false, tgt_image_opts
= false;
1929 int64_t ret
= -EINVAL
;
1930 bool force_share
= false;
1932 ImgConvertState s
= (ImgConvertState
) {
1933 /* Need at least 4k of zeros for sparse detection */
1935 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1936 .wr_in_order
= true,
1937 .num_coroutines
= 8,
1941 static const struct option long_options
[] = {
1942 {"help", no_argument
, 0, 'h'},
1943 {"object", required_argument
, 0, OPTION_OBJECT
},
1944 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1945 {"force-share", no_argument
, 0, 'U'},
1946 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1949 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1950 long_options
, NULL
);
1956 missing_argument(argv
[optind
- 1]);
1959 unrecognized_option(argv
[optind
- 1]);
1971 out_baseimg
= optarg
;
1974 s
.compressed
= true;
1977 if (!is_valid_option_list(optarg
)) {
1978 error_report("Invalid option list: %s", optarg
);
1982 options
= g_strdup(optarg
);
1984 char *old_options
= options
;
1985 options
= g_strdup_printf("%s,%s", options
, optarg
);
1986 g_free(old_options
);
1990 snapshot_name
= optarg
;
1993 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1994 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
1997 error_report("Failed in parsing snapshot param '%s'",
2002 snapshot_name
= optarg
;
2009 sval
= cvtnum(optarg
);
2011 error_report("Invalid minimum zero buffer size for sparse output specified");
2015 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2034 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2035 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2036 error_report("Invalid number of coroutines. Allowed number of"
2037 " coroutines is between 1 and %d", MAX_COROUTINES
);
2042 s
.wr_in_order
= false;
2047 case OPTION_OBJECT
: {
2048 QemuOpts
*object_opts
;
2049 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2056 case OPTION_IMAGE_OPTS
:
2059 case OPTION_TARGET_IMAGE_OPTS
:
2060 tgt_image_opts
= true;
2065 if (!out_fmt
&& !tgt_image_opts
) {
2069 if (qemu_opts_foreach(&qemu_object_opts
,
2070 user_creatable_add_opts_foreach
,
2075 if (!s
.wr_in_order
&& s
.compressed
) {
2076 error_report("Out of order write and compress are mutually exclusive");
2080 if (tgt_image_opts
&& !skip_create
) {
2081 error_report("--target-image-opts requires use of -n flag");
2085 s
.src_num
= argc
- optind
- 1;
2086 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2088 if (options
&& has_help_option(options
)) {
2090 ret
= print_block_option_help(out_filename
, out_fmt
);
2093 error_report("Option help requires a format be specified");
2098 if (s
.src_num
< 1) {
2099 error_report("Must specify image file name");
2104 /* ret is still -EINVAL until here */
2105 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2107 error_report("Invalid source cache option: %s", src_cache
);
2111 /* Initialize before goto out */
2115 qemu_progress_init(progress
, 1.0);
2116 qemu_progress_print(0, 100);
2118 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2119 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2121 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2122 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2123 fmt
, src_flags
, src_writethrough
, quiet
,
2129 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2130 if (s
.src_sectors
[bs_i
] < 0) {
2131 error_report("Could not get size of %s: %s",
2132 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2136 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2140 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2141 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2142 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2144 } else if (snapshot_name
!= NULL
) {
2145 if (s
.src_num
> 1) {
2146 error_report("No support for concatenating multiple snapshot");
2151 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2155 error_reportf_err(local_err
, "Failed to load snapshot: ");
2161 /* Find driver and parse its options */
2162 drv
= bdrv_find_format(out_fmt
);
2164 error_report("Unknown file format '%s'", out_fmt
);
2169 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2171 error_report_err(local_err
);
2176 if (!drv
->create_opts
) {
2177 error_report("Format driver '%s' does not support image creation",
2183 if (!proto_drv
->create_opts
) {
2184 error_report("Protocol driver '%s' does not support image creation",
2185 proto_drv
->format_name
);
2190 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2191 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2193 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2195 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2197 error_report_err(local_err
);
2203 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2205 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2211 /* Get backing file name if -o backing_file was used */
2212 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2213 if (out_baseimg_param
) {
2214 out_baseimg
= out_baseimg_param
;
2216 s
.target_has_backing
= (bool) out_baseimg
;
2218 if (s
.src_num
> 1 && out_baseimg
) {
2219 error_report("Having a backing file for the target makes no sense when "
2220 "concatenating multiple input images");
2225 /* Check if compression is supported */
2228 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2229 const char *encryptfmt
=
2230 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2231 const char *preallocation
=
2232 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2234 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2235 error_report("Compression not supported for this file format");
2240 if (encryption
|| encryptfmt
) {
2241 error_report("Compression and encryption not supported at "
2248 && strcmp(preallocation
, "off"))
2250 error_report("Compression and preallocation not supported at "
2258 /* Create the new image */
2259 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2261 error_reportf_err(local_err
, "%s: error while converting %s: ",
2262 out_filename
, out_fmt
);
2267 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2268 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2270 error_report("Invalid cache option: %s", cache
);
2275 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2276 flags
, writethrough
, quiet
, false);
2278 /* TODO ultimately we should allow --target-image-opts
2279 * to be used even when -n is not given.
2280 * That has to wait for bdrv_create to be improved
2281 * to allow filenames in option syntax
2283 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2284 flags
, writethrough
, quiet
, false);
2290 out_bs
= blk_bs(s
.target
);
2292 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2293 error_report("Compression not supported for this file format");
2298 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2299 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2301 s
.buf_sectors
= MIN(32768,
2303 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2304 out_bs
->bl
.pdiscard_alignment
>>
2305 BDRV_SECTOR_BITS
)));
2308 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2309 if (output_sectors
< 0) {
2310 error_report("unable to get output image length: %s",
2311 strerror(-output_sectors
));
2314 } else if (output_sectors
< s
.total_sectors
) {
2315 error_report("output file is smaller than input file");
2321 ret
= bdrv_get_info(out_bs
, &bdi
);
2324 error_report("could not get block driver info");
2328 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2329 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2332 ret
= convert_do_copy(&s
);
2335 qemu_progress_print(100, 0);
2337 qemu_progress_end();
2338 qemu_opts_del(opts
);
2339 qemu_opts_free(create_opts
);
2340 qemu_opts_del(sn_opts
);
2341 blk_unref(s
.target
);
2343 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2344 blk_unref(s
.src
[bs_i
]);
2348 g_free(s
.src_sectors
);
2356 static void dump_snapshots(BlockDriverState
*bs
)
2358 QEMUSnapshotInfo
*sn_tab
, *sn
;
2361 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2364 printf("Snapshot list:\n");
2365 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2367 for(i
= 0; i
< nb_sns
; i
++) {
2369 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2375 static void dump_json_image_info_list(ImageInfoList
*list
)
2379 Visitor
*v
= qobject_output_visitor_new(&obj
);
2381 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2382 visit_complete(v
, &obj
);
2383 str
= qobject_to_json_pretty(obj
);
2384 assert(str
!= NULL
);
2385 printf("%s\n", qstring_get_str(str
));
2386 qobject_decref(obj
);
2391 static void dump_json_image_info(ImageInfo
*info
)
2395 Visitor
*v
= qobject_output_visitor_new(&obj
);
2397 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2398 visit_complete(v
, &obj
);
2399 str
= qobject_to_json_pretty(obj
);
2400 assert(str
!= NULL
);
2401 printf("%s\n", qstring_get_str(str
));
2402 qobject_decref(obj
);
2407 static void dump_human_image_info_list(ImageInfoList
*list
)
2409 ImageInfoList
*elem
;
2412 for (elem
= list
; elem
; elem
= elem
->next
) {
2418 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2422 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2424 return strcmp(a
, b
) == 0;
2428 * Open an image file chain and return an ImageInfoList
2430 * @filename: topmost image filename
2431 * @fmt: topmost image format (may be NULL to autodetect)
2432 * @chain: true - enumerate entire backing file chain
2433 * false - only topmost image file
2435 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2436 * image file. If there was an error a message will have been printed to
2439 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2440 const char *filename
,
2442 bool chain
, bool force_share
)
2444 ImageInfoList
*head
= NULL
;
2445 ImageInfoList
**last
= &head
;
2446 GHashTable
*filenames
;
2449 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2453 BlockDriverState
*bs
;
2455 ImageInfoList
*elem
;
2457 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2458 error_report("Backing file '%s' creates an infinite loop.",
2462 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2464 blk
= img_open(image_opts
, filename
, fmt
,
2465 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2472 bdrv_query_image_info(bs
, &info
, &err
);
2474 error_report_err(err
);
2479 elem
= g_new0(ImageInfoList
, 1);
2486 filename
= fmt
= NULL
;
2488 if (info
->has_full_backing_filename
) {
2489 filename
= info
->full_backing_filename
;
2490 } else if (info
->has_backing_filename
) {
2491 error_report("Could not determine absolute backing filename,"
2492 " but backing filename '%s' present",
2493 info
->backing_filename
);
2496 if (info
->has_backing_filename_format
) {
2497 fmt
= info
->backing_filename_format
;
2501 g_hash_table_destroy(filenames
);
2505 qapi_free_ImageInfoList(head
);
2506 g_hash_table_destroy(filenames
);
2510 static int img_info(int argc
, char **argv
)
2513 OutputFormat output_format
= OFORMAT_HUMAN
;
2515 const char *filename
, *fmt
, *output
;
2516 ImageInfoList
*list
;
2517 bool image_opts
= false;
2518 bool force_share
= false;
2523 int option_index
= 0;
2524 static const struct option long_options
[] = {
2525 {"help", no_argument
, 0, 'h'},
2526 {"format", required_argument
, 0, 'f'},
2527 {"output", required_argument
, 0, OPTION_OUTPUT
},
2528 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2529 {"object", required_argument
, 0, OPTION_OBJECT
},
2530 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2531 {"force-share", no_argument
, 0, 'U'},
2534 c
= getopt_long(argc
, argv
, ":f:hU",
2535 long_options
, &option_index
);
2541 missing_argument(argv
[optind
- 1]);
2544 unrecognized_option(argv
[optind
- 1]);
2558 case OPTION_BACKING_CHAIN
:
2561 case OPTION_OBJECT
: {
2563 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2569 case OPTION_IMAGE_OPTS
:
2574 if (optind
!= argc
- 1) {
2575 error_exit("Expecting one image file name");
2577 filename
= argv
[optind
++];
2579 if (output
&& !strcmp(output
, "json")) {
2580 output_format
= OFORMAT_JSON
;
2581 } else if (output
&& !strcmp(output
, "human")) {
2582 output_format
= OFORMAT_HUMAN
;
2583 } else if (output
) {
2584 error_report("--output must be used with human or json as argument.");
2588 if (qemu_opts_foreach(&qemu_object_opts
,
2589 user_creatable_add_opts_foreach
,
2594 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2600 switch (output_format
) {
2602 dump_human_image_info_list(list
);
2606 dump_json_image_info_list(list
);
2608 dump_json_image_info(list
->value
);
2613 qapi_free_ImageInfoList(list
);
2617 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2620 switch (output_format
) {
2622 if (e
->data
&& !e
->has_offset
) {
2623 error_report("File contains external, encrypted or compressed clusters.");
2626 if (e
->data
&& !e
->zero
) {
2627 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2628 e
->start
, e
->length
,
2629 e
->has_offset
? e
->offset
: 0,
2630 e
->has_filename
? e
->filename
: "");
2632 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2633 * Modify the flags here to allow more coalescing.
2635 if (next
&& (!next
->data
|| next
->zero
)) {
2641 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2642 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2643 (e
->start
== 0 ? "[" : ",\n"),
2644 e
->start
, e
->length
, e
->depth
,
2645 e
->zero
? "true" : "false",
2646 e
->data
? "true" : "false");
2647 if (e
->has_offset
) {
2648 printf(", \"offset\": %"PRId64
"", e
->offset
);
2659 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2660 int64_t bytes
, MapEntry
*e
)
2664 BlockDriverState
*file
;
2668 /* As an optimization, we could cache the current range of unallocated
2669 * clusters in each file of the chain, and avoid querying the same
2675 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2680 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2683 bs
= backing_bs(bs
);
2692 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2697 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2698 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2700 .has_offset
= has_offset
,
2702 .has_filename
= file
&& has_offset
,
2703 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2709 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2711 if (curr
->length
== 0) {
2714 if (curr
->zero
!= next
->zero
||
2715 curr
->data
!= next
->data
||
2716 curr
->depth
!= next
->depth
||
2717 curr
->has_filename
!= next
->has_filename
||
2718 curr
->has_offset
!= next
->has_offset
) {
2721 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2724 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2730 static int img_map(int argc
, char **argv
)
2733 OutputFormat output_format
= OFORMAT_HUMAN
;
2735 BlockDriverState
*bs
;
2736 const char *filename
, *fmt
, *output
;
2738 MapEntry curr
= { .length
= 0 }, next
;
2740 bool image_opts
= false;
2741 bool force_share
= false;
2746 int option_index
= 0;
2747 static const struct option long_options
[] = {
2748 {"help", no_argument
, 0, 'h'},
2749 {"format", required_argument
, 0, 'f'},
2750 {"output", required_argument
, 0, OPTION_OUTPUT
},
2751 {"object", required_argument
, 0, OPTION_OBJECT
},
2752 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2753 {"force-share", no_argument
, 0, 'U'},
2756 c
= getopt_long(argc
, argv
, ":f:hU",
2757 long_options
, &option_index
);
2763 missing_argument(argv
[optind
- 1]);
2766 unrecognized_option(argv
[optind
- 1]);
2780 case OPTION_OBJECT
: {
2782 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2788 case OPTION_IMAGE_OPTS
:
2793 if (optind
!= argc
- 1) {
2794 error_exit("Expecting one image file name");
2796 filename
= argv
[optind
];
2798 if (output
&& !strcmp(output
, "json")) {
2799 output_format
= OFORMAT_JSON
;
2800 } else if (output
&& !strcmp(output
, "human")) {
2801 output_format
= OFORMAT_HUMAN
;
2802 } else if (output
) {
2803 error_report("--output must be used with human or json as argument.");
2807 if (qemu_opts_foreach(&qemu_object_opts
,
2808 user_creatable_add_opts_foreach
,
2813 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2819 if (output_format
== OFORMAT_HUMAN
) {
2820 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2823 length
= blk_getlength(blk
);
2824 while (curr
.start
+ curr
.length
< length
) {
2825 int64_t offset
= curr
.start
+ curr
.length
;
2828 /* Probe up to 1 GiB at a time. */
2829 n
= QEMU_ALIGN_DOWN(MIN(1 << 30, length
- offset
), BDRV_SECTOR_SIZE
);
2830 ret
= get_block_status(bs
, offset
, n
, &next
);
2833 error_report("Could not read file metadata: %s", strerror(-ret
));
2837 if (entry_mergeable(&curr
, &next
)) {
2838 curr
.length
+= next
.length
;
2842 if (curr
.length
> 0) {
2843 dump_map_entry(output_format
, &curr
, &next
);
2848 dump_map_entry(output_format
, &curr
, NULL
);
2855 #define SNAPSHOT_LIST 1
2856 #define SNAPSHOT_CREATE 2
2857 #define SNAPSHOT_APPLY 3
2858 #define SNAPSHOT_DELETE 4
2860 static int img_snapshot(int argc
, char **argv
)
2863 BlockDriverState
*bs
;
2864 QEMUSnapshotInfo sn
;
2865 char *filename
, *snapshot_name
= NULL
;
2866 int c
, ret
= 0, bdrv_oflags
;
2871 bool image_opts
= false;
2872 bool force_share
= false;
2874 bdrv_oflags
= BDRV_O_RDWR
;
2875 /* Parse commandline parameters */
2877 static const struct option long_options
[] = {
2878 {"help", no_argument
, 0, 'h'},
2879 {"object", required_argument
, 0, OPTION_OBJECT
},
2880 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2881 {"force-share", no_argument
, 0, 'U'},
2884 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2885 long_options
, NULL
);
2891 missing_argument(argv
[optind
- 1]);
2894 unrecognized_option(argv
[optind
- 1]);
2901 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2904 action
= SNAPSHOT_LIST
;
2905 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2909 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2912 action
= SNAPSHOT_APPLY
;
2913 snapshot_name
= optarg
;
2917 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2920 action
= SNAPSHOT_CREATE
;
2921 snapshot_name
= optarg
;
2925 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2928 action
= SNAPSHOT_DELETE
;
2929 snapshot_name
= optarg
;
2937 case OPTION_OBJECT
: {
2939 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2945 case OPTION_IMAGE_OPTS
:
2951 if (optind
!= argc
- 1) {
2952 error_exit("Expecting one image file name");
2954 filename
= argv
[optind
++];
2956 if (qemu_opts_foreach(&qemu_object_opts
,
2957 user_creatable_add_opts_foreach
,
2962 /* Open the image */
2963 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
2970 /* Perform the requested action */
2976 case SNAPSHOT_CREATE
:
2977 memset(&sn
, 0, sizeof(sn
));
2978 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2980 qemu_gettimeofday(&tv
);
2981 sn
.date_sec
= tv
.tv_sec
;
2982 sn
.date_nsec
= tv
.tv_usec
* 1000;
2984 ret
= bdrv_snapshot_create(bs
, &sn
);
2986 error_report("Could not create snapshot '%s': %d (%s)",
2987 snapshot_name
, ret
, strerror(-ret
));
2991 case SNAPSHOT_APPLY
:
2992 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
2994 error_reportf_err(err
, "Could not apply snapshot '%s': ",
2999 case SNAPSHOT_DELETE
:
3000 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3002 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3017 static int img_rebase(int argc
, char **argv
)
3019 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3020 uint8_t *buf_old
= NULL
;
3021 uint8_t *buf_new
= NULL
;
3022 BlockDriverState
*bs
= NULL
;
3024 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3025 int c
, flags
, src_flags
, ret
;
3026 bool writethrough
, src_writethrough
;
3028 bool force_share
= false;
3031 Error
*local_err
= NULL
;
3032 bool image_opts
= false;
3034 /* Parse commandline parameters */
3036 cache
= BDRV_DEFAULT_CACHE
;
3037 src_cache
= BDRV_DEFAULT_CACHE
;
3041 static const struct option long_options
[] = {
3042 {"help", no_argument
, 0, 'h'},
3043 {"object", required_argument
, 0, OPTION_OBJECT
},
3044 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3045 {"force-share", no_argument
, 0, 'U'},
3048 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3049 long_options
, NULL
);
3055 missing_argument(argv
[optind
- 1]);
3058 unrecognized_option(argv
[optind
- 1]);
3067 out_basefmt
= optarg
;
3070 out_baseimg
= optarg
;
3087 case OPTION_OBJECT
: {
3089 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3095 case OPTION_IMAGE_OPTS
:
3108 if (optind
!= argc
- 1) {
3109 error_exit("Expecting one image file name");
3111 if (!unsafe
&& !out_baseimg
) {
3112 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3114 filename
= argv
[optind
++];
3116 if (qemu_opts_foreach(&qemu_object_opts
,
3117 user_creatable_add_opts_foreach
,
3122 qemu_progress_init(progress
, 2.0);
3123 qemu_progress_print(0, 100);
3125 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3126 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3128 error_report("Invalid cache option: %s", cache
);
3133 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3135 error_report("Invalid source cache option: %s", src_cache
);
3139 /* The source files are opened read-only, don't care about WCE */
3140 assert((src_flags
& BDRV_O_RDWR
) == 0);
3141 (void) src_writethrough
;
3146 * Ignore the old backing file for unsafe rebase in case we want to correct
3147 * the reference to a renamed or moved backing file.
3149 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3157 if (out_basefmt
!= NULL
) {
3158 if (bdrv_find_format(out_basefmt
) == NULL
) {
3159 error_report("Invalid format name: '%s'", out_basefmt
);
3165 /* For safe rebasing we need to compare old and new backing file */
3167 char backing_name
[PATH_MAX
];
3168 QDict
*options
= NULL
;
3170 if (bs
->backing_format
[0] != '\0') {
3171 options
= qdict_new();
3172 qdict_put_str(options
, "driver", bs
->backing_format
);
3177 options
= qdict_new();
3179 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3181 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3182 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3183 options
, src_flags
, &local_err
);
3184 if (!blk_old_backing
) {
3185 error_reportf_err(local_err
,
3186 "Could not open old backing file '%s': ",
3192 if (out_baseimg
[0]) {
3193 options
= qdict_new();
3195 qdict_put_str(options
, "driver", out_basefmt
);
3198 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3201 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3202 options
, src_flags
, &local_err
);
3203 if (!blk_new_backing
) {
3204 error_reportf_err(local_err
,
3205 "Could not open new backing file '%s': ",
3214 * Check each unallocated cluster in the COW file. If it is unallocated,
3215 * accesses go to the backing file. We must therefore compare this cluster
3216 * in the old and new backing file, and if they differ we need to copy it
3217 * from the old backing file into the COW file.
3219 * If qemu-img crashes during this step, no harm is done. The content of
3220 * the image is the same as the original one at any time.
3224 int64_t old_backing_size
;
3225 int64_t new_backing_size
= 0;
3228 float local_progress
= 0;
3230 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3231 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3233 size
= blk_getlength(blk
);
3235 error_report("Could not get size of '%s': %s",
3236 filename
, strerror(-size
));
3240 old_backing_size
= blk_getlength(blk_old_backing
);
3241 if (old_backing_size
< 0) {
3242 char backing_name
[PATH_MAX
];
3244 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3245 error_report("Could not get size of '%s': %s",
3246 backing_name
, strerror(-old_backing_size
));
3250 if (blk_new_backing
) {
3251 new_backing_size
= blk_getlength(blk_new_backing
);
3252 if (new_backing_size
< 0) {
3253 error_report("Could not get size of '%s': %s",
3254 out_baseimg
, strerror(-new_backing_size
));
3261 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3264 for (offset
= 0; offset
< size
; offset
+= n
) {
3265 /* How many bytes can we handle with the next read? */
3266 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3268 /* If the cluster is allocated, we don't need to take action */
3269 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3271 error_report("error while reading image metadata: %s",
3280 * Read old and new backing file and take into consideration that
3281 * backing files may be smaller than the COW image.
3283 if (offset
>= old_backing_size
) {
3284 memset(buf_old
, 0, n
);
3286 if (offset
+ n
> old_backing_size
) {
3287 n
= old_backing_size
- offset
;
3290 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3292 error_report("error while reading from old backing file");
3297 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3298 memset(buf_new
, 0, n
);
3300 if (offset
+ n
> new_backing_size
) {
3301 n
= new_backing_size
- offset
;
3304 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3306 error_report("error while reading from new backing file");
3311 /* If they differ, we need to write to the COW file */
3312 uint64_t written
= 0;
3314 while (written
< n
) {
3317 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3318 n
- written
, &pnum
))
3320 ret
= blk_pwrite(blk
, offset
+ written
,
3321 buf_old
+ written
, pnum
, 0);
3323 error_report("Error while writing to COW image: %s",
3331 qemu_progress_print(local_progress
, 100);
3336 * Change the backing file. All clusters that are different from the old
3337 * backing file are overwritten in the COW file now, so the visible content
3338 * doesn't change when we switch the backing file.
3340 if (out_baseimg
&& *out_baseimg
) {
3341 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3343 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3346 if (ret
== -ENOSPC
) {
3347 error_report("Could not change the backing file to '%s': No "
3348 "space left in the file header", out_baseimg
);
3349 } else if (ret
< 0) {
3350 error_report("Could not change the backing file to '%s': %s",
3351 out_baseimg
, strerror(-ret
));
3354 qemu_progress_print(100, 0);
3356 * TODO At this point it is possible to check if any clusters that are
3357 * allocated in the COW file are the same in the backing file. If so, they
3358 * could be dropped from the COW file. Don't do this before switching the
3359 * backing file, in case of a crash this would lead to corruption.
3362 qemu_progress_end();
3365 blk_unref(blk_old_backing
);
3366 blk_unref(blk_new_backing
);
3368 qemu_vfree(buf_old
);
3369 qemu_vfree(buf_new
);
3378 static int img_resize(int argc
, char **argv
)
3381 int c
, ret
, relative
;
3382 const char *filename
, *fmt
, *size
;
3383 int64_t n
, total_size
, current_size
;
3385 BlockBackend
*blk
= NULL
;
3386 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3389 static QemuOptsList resize_options
= {
3390 .name
= "resize_options",
3391 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3394 .name
= BLOCK_OPT_SIZE
,
3395 .type
= QEMU_OPT_SIZE
,
3396 .help
= "Virtual disk size"
3402 bool image_opts
= false;
3403 bool shrink
= false;
3405 /* Remove size from argv manually so that negative numbers are not treated
3406 * as options by getopt. */
3408 error_exit("Not enough arguments");
3412 size
= argv
[--argc
];
3414 /* Parse getopt arguments */
3417 static const struct option long_options
[] = {
3418 {"help", no_argument
, 0, 'h'},
3419 {"object", required_argument
, 0, OPTION_OBJECT
},
3420 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3421 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3422 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3425 c
= getopt_long(argc
, argv
, ":f:hq",
3426 long_options
, NULL
);
3432 missing_argument(argv
[optind
- 1]);
3435 unrecognized_option(argv
[optind
- 1]);
3446 case OPTION_OBJECT
: {
3448 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3454 case OPTION_IMAGE_OPTS
:
3457 case OPTION_PREALLOCATION
:
3458 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3459 PREALLOC_MODE__MAX
, NULL
);
3460 if (prealloc
== PREALLOC_MODE__MAX
) {
3461 error_report("Invalid preallocation mode '%s'", optarg
);
3470 if (optind
!= argc
- 1) {
3471 error_exit("Expecting one image file name");
3473 filename
= argv
[optind
++];
3475 if (qemu_opts_foreach(&qemu_object_opts
,
3476 user_creatable_add_opts_foreach
,
3481 /* Choose grow, shrink, or absolute resize mode */
3497 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3498 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3500 error_report_err(err
);
3502 qemu_opts_del(param
);
3505 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3506 qemu_opts_del(param
);
3508 blk
= img_open(image_opts
, filename
, fmt
,
3509 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3516 current_size
= blk_getlength(blk
);
3517 if (current_size
< 0) {
3518 error_report("Failed to inquire current image length: %s",
3519 strerror(-current_size
));
3525 total_size
= current_size
+ n
* relative
;
3529 if (total_size
<= 0) {
3530 error_report("New image size must be positive");
3535 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3536 error_report("Preallocation can only be used for growing images");
3541 if (total_size
< current_size
&& !shrink
) {
3542 warn_report("Shrinking an image will delete all data beyond the "
3543 "shrunken image's end. Before performing such an "
3544 "operation, make sure there is no important data there.");
3546 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3548 "Use the --shrink option to perform a shrink operation.");
3552 warn_report("Using the --shrink option will suppress this message. "
3553 "Note that future versions of qemu-img may refuse to "
3554 "shrink images without this option.");
3558 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3560 qprintf(quiet
, "Image resized.\n");
3562 error_report_err(err
);
3572 static void amend_status_cb(BlockDriverState
*bs
,
3573 int64_t offset
, int64_t total_work_size
,
3576 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3579 static int img_amend(int argc
, char **argv
)
3583 char *options
= NULL
;
3584 QemuOptsList
*create_opts
= NULL
;
3585 QemuOpts
*opts
= NULL
;
3586 const char *fmt
= NULL
, *filename
, *cache
;
3589 bool quiet
= false, progress
= false;
3590 BlockBackend
*blk
= NULL
;
3591 BlockDriverState
*bs
= NULL
;
3592 bool image_opts
= false;
3594 cache
= BDRV_DEFAULT_CACHE
;
3596 static const struct option long_options
[] = {
3597 {"help", no_argument
, 0, 'h'},
3598 {"object", required_argument
, 0, OPTION_OBJECT
},
3599 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3602 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3603 long_options
, NULL
);
3610 missing_argument(argv
[optind
- 1]);
3613 unrecognized_option(argv
[optind
- 1]);
3619 if (!is_valid_option_list(optarg
)) {
3620 error_report("Invalid option list: %s", optarg
);
3622 goto out_no_progress
;
3625 options
= g_strdup(optarg
);
3627 char *old_options
= options
;
3628 options
= g_strdup_printf("%s,%s", options
, optarg
);
3629 g_free(old_options
);
3645 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3649 goto out_no_progress
;
3652 case OPTION_IMAGE_OPTS
:
3659 error_exit("Must specify options (-o)");
3662 if (qemu_opts_foreach(&qemu_object_opts
,
3663 user_creatable_add_opts_foreach
,
3666 goto out_no_progress
;
3672 qemu_progress_init(progress
, 1.0);
3674 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3675 if (fmt
&& has_help_option(options
)) {
3676 /* If a format is explicitly specified (and possibly no filename is
3677 * given), print option help here */
3678 ret
= print_block_option_help(filename
, fmt
);
3682 if (optind
!= argc
- 1) {
3683 error_report("Expecting one image file name");
3688 flags
= BDRV_O_RDWR
;
3689 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3691 error_report("Invalid cache option: %s", cache
);
3695 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3703 fmt
= bs
->drv
->format_name
;
3705 if (has_help_option(options
)) {
3706 /* If the format was auto-detected, print option help here */
3707 ret
= print_block_option_help(filename
, fmt
);
3711 if (!bs
->drv
->create_opts
) {
3712 error_report("Format driver '%s' does not support any options to amend",
3718 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3719 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3720 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3722 error_report_err(err
);
3727 /* In case the driver does not call amend_status_cb() */
3728 qemu_progress_print(0.f
, 0);
3729 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3730 qemu_progress_print(100.f
, 0);
3732 error_report("Error while amending options: %s", strerror(-ret
));
3737 qemu_progress_end();
3741 qemu_opts_del(opts
);
3742 qemu_opts_free(create_opts
);
3751 typedef struct BenchData
{
3753 uint64_t image_size
;
3760 bool drain_on_flush
;
3769 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3772 error_report("Failed flush request: %s", strerror(-ret
));
3777 static void bench_cb(void *opaque
, int ret
)
3779 BenchData
*b
= opaque
;
3783 error_report("Failed request: %s", strerror(-ret
));
3788 /* Just finished a flush with drained queue: Start next requests */
3789 assert(b
->in_flight
== 0);
3790 b
->in_flush
= false;
3791 } else if (b
->in_flight
> 0) {
3792 int remaining
= b
->n
- b
->in_flight
;
3797 /* Time for flush? Drain queue if requested, then flush */
3798 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3799 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3800 BlockCompletionFunc
*cb
;
3802 if (b
->drain_on_flush
) {
3806 cb
= bench_undrained_flush_cb
;
3809 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3811 error_report("Failed to issue flush request");
3815 if (b
->drain_on_flush
) {
3821 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3822 int64_t offset
= b
->offset
;
3823 /* blk_aio_* might look for completed I/Os and kick bench_cb
3824 * again, so make sure this operation is counted by in_flight
3825 * and b->offset is ready for the next submission.
3828 b
->offset
+= b
->step
;
3829 b
->offset
%= b
->image_size
;
3831 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3833 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3836 error_report("Failed to issue request");
3842 static int img_bench(int argc
, char **argv
)
3845 const char *fmt
= NULL
, *filename
;
3847 bool image_opts
= false;
3848 bool is_write
= false;
3852 size_t bufsize
= 4096;
3855 int flush_interval
= 0;
3856 bool drain_on_flush
= true;
3858 BlockBackend
*blk
= NULL
;
3859 BenchData data
= {};
3861 bool writethrough
= false;
3862 struct timeval t1
, t2
;
3864 bool force_share
= false;
3868 static const struct option long_options
[] = {
3869 {"help", no_argument
, 0, 'h'},
3870 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3871 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3872 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3873 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3874 {"force-share", no_argument
, 0, 'U'},
3877 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3884 missing_argument(argv
[optind
- 1]);
3887 unrecognized_option(argv
[optind
- 1]);
3896 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3897 error_report("Invalid request count specified");
3907 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3908 error_report("Invalid queue depth specified");
3918 flags
|= BDRV_O_NATIVE_AIO
;
3922 offset
= cvtnum(optarg
);
3924 error_report("Invalid offset specified");
3937 sval
= cvtnum(optarg
);
3938 if (sval
< 0 || sval
> INT_MAX
) {
3939 error_report("Invalid buffer size specified");
3950 sval
= cvtnum(optarg
);
3951 if (sval
< 0 || sval
> INT_MAX
) {
3952 error_report("Invalid step size specified");
3960 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3962 error_report("Invalid cache mode");
3968 flags
|= BDRV_O_RDWR
;
3974 case OPTION_PATTERN
:
3978 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3979 error_report("Invalid pattern byte specified");
3985 case OPTION_FLUSH_INTERVAL
:
3989 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3990 error_report("Invalid flush interval specified");
3993 flush_interval
= res
;
3996 case OPTION_NO_DRAIN
:
3997 drain_on_flush
= false;
3999 case OPTION_IMAGE_OPTS
:
4005 if (optind
!= argc
- 1) {
4006 error_exit("Expecting one image file name");
4008 filename
= argv
[argc
- 1];
4010 if (!is_write
&& flush_interval
) {
4011 error_report("--flush-interval is only available in write tests");
4015 if (flush_interval
&& flush_interval
< depth
) {
4016 error_report("Flush interval can't be smaller than depth");
4021 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4028 image_size
= blk_getlength(blk
);
4029 if (image_size
< 0) {
4034 data
= (BenchData
) {
4036 .image_size
= image_size
,
4038 .step
= step
?: bufsize
,
4043 .flush_interval
= flush_interval
,
4044 .drain_on_flush
= drain_on_flush
,
4046 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4047 "(starting at offset %" PRId64
", step size %d)\n",
4048 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4049 data
.offset
, data
.step
);
4050 if (flush_interval
) {
4051 printf("Sending flush every %d requests\n", flush_interval
);
4054 buf_size
= data
.nrreq
* data
.bufsize
;
4055 data
.buf
= blk_blockalign(blk
, buf_size
);
4056 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4058 blk_register_buf(blk
, data
.buf
, buf_size
);
4060 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4061 for (i
= 0; i
< data
.nrreq
; i
++) {
4062 qemu_iovec_init(&data
.qiov
[i
], 1);
4063 qemu_iovec_add(&data
.qiov
[i
],
4064 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4067 gettimeofday(&t1
, NULL
);
4070 while (data
.n
> 0) {
4071 main_loop_wait(false);
4073 gettimeofday(&t2
, NULL
);
4075 printf("Run completed in %3.3f seconds.\n",
4076 (t2
.tv_sec
- t1
.tv_sec
)
4077 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4081 blk_unregister_buf(blk
, data
.buf
);
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]);
4253 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4258 case OPTION_IMAGE_OPTS
:
4264 for (i
= optind
; i
< argc
; i
++) {
4266 arg
= g_strdup(argv
[i
]);
4268 tmp
= strchr(arg
, '=');
4270 error_report("unrecognized operand %s", arg
);
4277 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4278 if (!strcmp(arg
, options
[j
].name
)) {
4282 if (options
[j
].name
== NULL
) {
4283 error_report("unrecognized operand %s", arg
);
4288 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4292 dd
.flags
|= options
[j
].flag
;
4297 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4298 error_report("Must specify both input and output files");
4303 if (qemu_opts_foreach(&qemu_object_opts
,
4304 user_creatable_add_opts_foreach
,
4310 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4318 drv
= bdrv_find_format(out_fmt
);
4320 error_report("Unknown file format");
4324 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4327 error_report_err(local_err
);
4331 if (!drv
->create_opts
) {
4332 error_report("Format driver '%s' does not support image creation",
4337 if (!proto_drv
->create_opts
) {
4338 error_report("Protocol driver '%s' does not support image creation",
4339 proto_drv
->format_name
);
4343 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4344 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4346 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4348 size
= blk_getlength(blk1
);
4350 error_report("Failed to get size for '%s'", in
.filename
);
4355 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4356 dd
.count
* in
.bsz
< size
) {
4357 size
= dd
.count
* in
.bsz
;
4360 /* Overflow means the specified offset is beyond input image's size */
4361 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4362 size
< in
.bsz
* in
.offset
)) {
4363 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4365 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4366 size
- in
.bsz
* in
.offset
, &error_abort
);
4369 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4371 error_reportf_err(local_err
,
4372 "%s: error while creating output image: ",
4378 /* TODO, we can't honour --image-opts for the target,
4379 * since it needs to be given in a format compatible
4380 * with the bdrv_create() call above which does not
4381 * support image-opts style.
4383 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4384 false, false, false);
4391 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4392 size
< in
.offset
* in
.bsz
)) {
4393 /* We give a warning if the skip option is bigger than the input
4394 * size and create an empty output disk image (i.e. like dd(1)).
4396 error_report("%s: cannot skip to specified offset", in
.filename
);
4399 in_pos
= in
.offset
* in
.bsz
;
4402 in
.buf
= g_new(uint8_t, in
.bsz
);
4404 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4405 int in_ret
, out_ret
;
4407 if (in_pos
+ in
.bsz
> size
) {
4408 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4410 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4413 error_report("error while reading from input image file: %s",
4420 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4423 error_report("error while writing to output image file: %s",
4424 strerror(-out_ret
));
4433 qemu_opts_del(opts
);
4434 qemu_opts_free(create_opts
);
4437 g_free(in
.filename
);
4438 g_free(out
.filename
);
4448 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4452 Visitor
*v
= qobject_output_visitor_new(&obj
);
4454 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4455 visit_complete(v
, &obj
);
4456 str
= qobject_to_json_pretty(obj
);
4457 assert(str
!= NULL
);
4458 printf("%s\n", qstring_get_str(str
));
4459 qobject_decref(obj
);
4464 static int img_measure(int argc
, char **argv
)
4466 static const struct option long_options
[] = {
4467 {"help", no_argument
, 0, 'h'},
4468 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4469 {"object", required_argument
, 0, OPTION_OBJECT
},
4470 {"output", required_argument
, 0, OPTION_OUTPUT
},
4471 {"size", required_argument
, 0, OPTION_SIZE
},
4472 {"force-share", no_argument
, 0, 'U'},
4475 OutputFormat output_format
= OFORMAT_HUMAN
;
4476 BlockBackend
*in_blk
= NULL
;
4478 const char *filename
= NULL
;
4479 const char *fmt
= NULL
;
4480 const char *out_fmt
= "raw";
4481 char *options
= NULL
;
4482 char *snapshot_name
= NULL
;
4483 bool force_share
= false;
4484 QemuOpts
*opts
= NULL
;
4485 QemuOpts
*object_opts
= NULL
;
4486 QemuOpts
*sn_opts
= NULL
;
4487 QemuOptsList
*create_opts
= NULL
;
4488 bool image_opts
= false;
4489 uint64_t img_size
= UINT64_MAX
;
4490 BlockMeasureInfo
*info
= NULL
;
4491 Error
*local_err
= NULL
;
4495 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4496 long_options
, NULL
)) != -1) {
4509 if (!is_valid_option_list(optarg
)) {
4510 error_report("Invalid option list: %s", optarg
);
4514 options
= g_strdup(optarg
);
4516 char *old_options
= options
;
4517 options
= g_strdup_printf("%s,%s", options
, optarg
);
4518 g_free(old_options
);
4522 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4523 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4526 error_report("Failed in parsing snapshot param '%s'",
4531 snapshot_name
= optarg
;
4538 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4544 case OPTION_IMAGE_OPTS
:
4548 if (!strcmp(optarg
, "json")) {
4549 output_format
= OFORMAT_JSON
;
4550 } else if (!strcmp(optarg
, "human")) {
4551 output_format
= OFORMAT_HUMAN
;
4553 error_report("--output must be used with human or json "
4562 sval
= cvtnum(optarg
);
4564 if (sval
== -ERANGE
) {
4565 error_report("Image size must be less than 8 EiB!");
4567 error_report("Invalid image size specified! You may use "
4568 "k, M, G, T, P or E suffixes for ");
4569 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4570 "petabytes and exabytes.");
4574 img_size
= (uint64_t)sval
;
4580 if (qemu_opts_foreach(&qemu_object_opts
,
4581 user_creatable_add_opts_foreach
,
4586 if (argc
- optind
> 1) {
4587 error_report("At most one filename argument is allowed.");
4589 } else if (argc
- optind
== 1) {
4590 filename
= argv
[optind
];
4594 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4595 error_report("--object, --image-opts, -f, and -l "
4596 "require a filename argument.");
4599 if (filename
&& img_size
!= UINT64_MAX
) {
4600 error_report("--size N cannot be used together with a filename.");
4603 if (!filename
&& img_size
== UINT64_MAX
) {
4604 error_report("Either --size N or one filename must be specified.");
4609 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4610 false, false, force_share
);
4616 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4617 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4618 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4620 } else if (snapshot_name
!= NULL
) {
4621 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4622 snapshot_name
, &local_err
);
4625 error_reportf_err(local_err
, "Failed to load snapshot: ");
4630 drv
= bdrv_find_format(out_fmt
);
4632 error_report("Unknown file format '%s'", out_fmt
);
4635 if (!drv
->create_opts
) {
4636 error_report("Format driver '%s' does not support image creation",
4641 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4642 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4643 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4645 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4647 error_report_err(local_err
);
4648 error_report("Invalid options for file format '%s'", out_fmt
);
4652 if (img_size
!= UINT64_MAX
) {
4653 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4656 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4658 error_report_err(local_err
);
4662 if (output_format
== OFORMAT_HUMAN
) {
4663 printf("required size: %" PRIu64
"\n", info
->required
);
4664 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4666 dump_json_block_measure_info(info
);
4672 qapi_free_BlockMeasureInfo(info
);
4673 qemu_opts_del(object_opts
);
4674 qemu_opts_del(opts
);
4675 qemu_opts_del(sn_opts
);
4676 qemu_opts_free(create_opts
);
4682 static const img_cmd_t img_cmds
[] = {
4683 #define DEF(option, callback, arg_string) \
4684 { option, callback },
4685 #include "qemu-img-cmds.h"
4691 int main(int argc
, char **argv
)
4693 const img_cmd_t
*cmd
;
4694 const char *cmdname
;
4695 Error
*local_error
= NULL
;
4696 char *trace_file
= NULL
;
4698 static const struct option long_options
[] = {
4699 {"help", no_argument
, 0, 'h'},
4700 {"version", no_argument
, 0, 'V'},
4701 {"trace", required_argument
, NULL
, 'T'},
4706 signal(SIGPIPE
, SIG_IGN
);
4709 module_call_init(MODULE_INIT_TRACE
);
4710 error_set_progname(argv
[0]);
4711 qemu_init_exec_dir(argv
[0]);
4713 if (qemu_init_main_loop(&local_error
)) {
4714 error_report_err(local_error
);
4718 qcrypto_init(&error_fatal
);
4720 module_call_init(MODULE_INIT_QOM
);
4723 error_exit("Not enough arguments");
4726 qemu_add_opts(&qemu_object_opts
);
4727 qemu_add_opts(&qemu_source_opts
);
4728 qemu_add_opts(&qemu_trace_opts
);
4730 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4733 missing_argument(argv
[optind
- 1]);
4736 unrecognized_option(argv
[optind
- 1]);
4742 printf(QEMU_IMG_VERSION
);
4746 trace_file
= trace_opt_parse(optarg
);
4751 cmdname
= argv
[optind
];
4753 /* reset getopt_long scanning */
4761 if (!trace_init_backends()) {
4764 trace_init_file(trace_file
);
4765 qemu_set_log(LOG_TRACE
);
4767 /* find the command */
4768 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4769 if (!strcmp(cmdname
, cmd
->name
)) {
4770 return cmd
->handler(argc
, argv
);
4775 error_exit("Command not found: %s", cmdname
);