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
25 #include "qemu/osdep.h"
28 #include "qemu-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
40 #include "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t
{
54 int (*handler
)(int argc
, char **argv
);
59 OPTION_BACKING_CHAIN
= 257,
61 OPTION_IMAGE_OPTS
= 259,
63 OPTION_FLUSH_INTERVAL
= 261,
64 OPTION_NO_DRAIN
= 262,
65 OPTION_TARGET_IMAGE_OPTS
= 263,
67 OPTION_PREALLOCATION
= 265,
71 typedef enum OutputFormat
{
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque
, const char *name
)
84 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
88 error_printf("qemu-img: ");
91 error_vprintf(fmt
, ap
);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
98 static void QEMU_NORETURN
missing_argument(const char *option
)
100 error_exit("missing argument for option '%s'", option
);
103 static void QEMU_NORETURN
unrecognized_option(const char *option
)
105 error_exit("unrecognized option '%s'", option
);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN
help(void)
111 const char *help_msg
=
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
122 #define DEF(option, callback, arg_string) \
124 #include "qemu-img-cmds.h"
128 "Command parameters:\n"
129 " 'filename' is a disk image filename\n"
130 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
131 " manual page for a description of the object properties. The most common\n"
132 " object type is a 'secret', which is used to supply passwords and/or\n"
133 " encryption keys.\n"
134 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
135 " 'cache' is the cache mode used to write the output disk image, the valid\n"
136 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
137 " 'directsync' and 'unsafe' (default for convert)\n"
138 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
139 " options are the same as for the 'cache' option\n"
140 " 'size' is the disk image size in bytes. Optional suffixes\n"
141 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
142 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
143 " supported. 'b' is ignored.\n"
144 " 'output_filename' is the destination disk image filename\n"
145 " 'output_fmt' is the destination format\n"
146 " 'options' is a comma separated list of format specific options in a\n"
147 " name=value format. Use -o ? for an overview of the options supported by the\n"
149 " 'snapshot_param' is param used for internal snapshot, format\n"
150 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
152 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
154 " '-c' indicates that target image must be compressed (qcow format only)\n"
155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
160 " '-h' with or without a command shows this help and lists the supported formats\n"
161 " '-p' show progress of command (only certain commands)\n"
162 " '-q' use Quiet mode - do not print any output (except errors)\n"
163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
168 " '--output' takes the format in which the output must be done (human or json)\n"
169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
176 " hiding corruption that has already occurred.\n"
178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
188 " '-l' lists all snapshots in the given image\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
203 printf("%s\nSupported formats:", help_msg
);
204 bdrv_iterate_format(format_print
, NULL
);
205 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
209 static QemuOptsList qemu_object_opts
= {
211 .implied_opt_name
= "qom-type",
212 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
218 static QemuOptsList qemu_source_opts
= {
220 .implied_opt_name
= "file",
221 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
227 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
233 ret
= vprintf(fmt
, args
);
240 static int print_block_option_help(const char *filename
, const char *fmt
)
242 BlockDriver
*drv
, *proto_drv
;
243 QemuOptsList
*create_opts
= NULL
;
244 Error
*local_err
= NULL
;
246 /* Find driver and parse its options */
247 drv
= bdrv_find_format(fmt
);
249 error_report("Unknown file format '%s'", fmt
);
253 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
255 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
257 error_report_err(local_err
);
258 qemu_opts_free(create_opts
);
261 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
264 qemu_opts_print_help(create_opts
);
265 qemu_opts_free(create_opts
);
270 static BlockBackend
*img_open_opts(const char *optstr
,
271 QemuOpts
*opts
, int flags
, bool writethrough
,
272 bool quiet
, bool force_share
)
275 Error
*local_err
= NULL
;
277 options
= qemu_opts_to_qdict(opts
, NULL
);
279 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
280 && !qdict_get_bool(options
, BDRV_OPT_FORCE_SHARE
)) {
281 error_report("--force-share/-U conflicts with image options");
282 qobject_unref(options
);
285 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
287 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
289 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
292 blk_set_enable_write_cache(blk
, !writethrough
);
297 static BlockBackend
*img_open_file(const char *filename
,
299 const char *fmt
, int flags
,
300 bool writethrough
, bool quiet
,
304 Error
*local_err
= NULL
;
307 options
= qdict_new();
310 qdict_put_str(options
, "driver", fmt
);
314 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
316 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
318 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
321 blk_set_enable_write_cache(blk
, !writethrough
);
327 static int img_add_key_secrets(void *opaque
,
328 const char *name
, const char *value
,
331 QDict
*options
= opaque
;
333 if (g_str_has_suffix(name
, "key-secret")) {
334 qdict_put_str(options
, name
, value
);
340 static BlockBackend
*img_open_new_file(const char *filename
,
341 QemuOpts
*create_opts
,
342 const char *fmt
, int flags
,
343 bool writethrough
, bool quiet
,
346 QDict
*options
= NULL
;
348 options
= qdict_new();
349 qemu_opt_foreach(create_opts
, img_add_key_secrets
, options
, &error_abort
);
351 return img_open_file(filename
, options
, fmt
, flags
, writethrough
, quiet
,
356 static BlockBackend
*img_open(bool image_opts
,
357 const char *filename
,
358 const char *fmt
, int flags
, bool writethrough
,
359 bool quiet
, bool force_share
)
365 error_report("--image-opts and --format are mutually exclusive");
368 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
373 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
376 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
383 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
384 const char *base_filename
,
385 const char *base_fmt
)
390 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
392 error_report("Backing file not supported for file format '%s'",
399 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
401 error_report("Backing file format not supported for file "
410 static int64_t cvtnum(const char *s
)
415 err
= qemu_strtosz(s
, NULL
, &value
);
419 if (value
> INT64_MAX
) {
425 static int img_create(int argc
, char **argv
)
428 uint64_t img_size
= -1;
429 const char *fmt
= "raw";
430 const char *base_fmt
= NULL
;
431 const char *filename
;
432 const char *base_filename
= NULL
;
433 char *options
= NULL
;
434 Error
*local_err
= NULL
;
439 static const struct option long_options
[] = {
440 {"help", no_argument
, 0, 'h'},
441 {"object", required_argument
, 0, OPTION_OBJECT
},
444 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
451 missing_argument(argv
[optind
- 1]);
454 unrecognized_option(argv
[optind
- 1]);
463 base_filename
= optarg
;
469 if (!is_valid_option_list(optarg
)) {
470 error_report("Invalid option list: %s", optarg
);
474 options
= g_strdup(optarg
);
476 char *old_options
= options
;
477 options
= g_strdup_printf("%s,%s", options
, optarg
);
485 flags
|= BDRV_O_NO_BACKING
;
487 case OPTION_OBJECT
: {
489 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
498 /* Get the filename */
499 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
500 if (options
&& has_help_option(options
)) {
502 return print_block_option_help(filename
, fmt
);
505 if (optind
>= argc
) {
506 error_exit("Expecting image file name");
510 if (qemu_opts_foreach(&qemu_object_opts
,
511 user_creatable_add_opts_foreach
,
516 /* Get image size, if specified */
520 sval
= cvtnum(argv
[optind
++]);
522 if (sval
== -ERANGE
) {
523 error_report("Image size must be less than 8 EiB!");
525 error_report("Invalid image size specified! You may use k, M, "
526 "G, T, P or E suffixes for ");
527 error_report("kilobytes, megabytes, gigabytes, terabytes, "
528 "petabytes and exabytes.");
532 img_size
= (uint64_t)sval
;
534 if (optind
!= argc
) {
535 error_exit("Unexpected argument: %s", argv
[optind
]);
538 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
539 options
, img_size
, flags
, quiet
, &local_err
);
541 error_reportf_err(local_err
, "%s: ", filename
);
553 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
557 Visitor
*v
= qobject_output_visitor_new(&obj
);
559 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
560 visit_complete(v
, &obj
);
561 str
= qobject_to_json_pretty(obj
);
563 qprintf(quiet
, "%s\n", qstring_get_str(str
));
569 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
571 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
572 qprintf(quiet
, "No errors were found on the image.\n");
574 if (check
->corruptions
) {
575 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
576 "Data may be corrupted, or further writes to the image "
583 "\n%" PRId64
" leaked clusters were found on the image.\n"
584 "This means waste of disk space, but no harm to data.\n",
588 if (check
->check_errors
) {
591 " internal errors have occurred during the check.\n",
592 check
->check_errors
);
596 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
597 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
598 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
599 check
->allocated_clusters
, check
->total_clusters
,
600 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
601 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
602 check
->compressed_clusters
* 100.0 /
603 check
->allocated_clusters
);
606 if (check
->image_end_offset
) {
608 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
612 static int collect_image_check(BlockDriverState
*bs
,
614 const char *filename
,
619 BdrvCheckResult result
;
621 ret
= bdrv_check(bs
, &result
, fix
);
626 check
->filename
= g_strdup(filename
);
627 check
->format
= g_strdup(bdrv_get_format_name(bs
));
628 check
->check_errors
= result
.check_errors
;
629 check
->corruptions
= result
.corruptions
;
630 check
->has_corruptions
= result
.corruptions
!= 0;
631 check
->leaks
= result
.leaks
;
632 check
->has_leaks
= result
.leaks
!= 0;
633 check
->corruptions_fixed
= result
.corruptions_fixed
;
634 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
635 check
->leaks_fixed
= result
.leaks_fixed
;
636 check
->has_leaks_fixed
= result
.leaks
!= 0;
637 check
->image_end_offset
= result
.image_end_offset
;
638 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
639 check
->total_clusters
= result
.bfi
.total_clusters
;
640 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
641 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
642 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
643 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
644 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
645 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
646 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
652 * Checks an image for consistency. Exit codes:
654 * 0 - Check completed, image is good
655 * 1 - Check not completed because of internal errors
656 * 2 - Check completed, image is corrupted
657 * 3 - Check completed, image has leaked clusters, but is good otherwise
658 * 63 - Checks are not supported by the image format
660 static int img_check(int argc
, char **argv
)
663 OutputFormat output_format
= OFORMAT_HUMAN
;
664 const char *filename
, *fmt
, *output
, *cache
;
666 BlockDriverState
*bs
;
668 int flags
= BDRV_O_CHECK
;
672 bool image_opts
= false;
673 bool force_share
= false;
677 cache
= BDRV_DEFAULT_CACHE
;
680 int option_index
= 0;
681 static const struct option long_options
[] = {
682 {"help", no_argument
, 0, 'h'},
683 {"format", required_argument
, 0, 'f'},
684 {"repair", required_argument
, 0, 'r'},
685 {"output", required_argument
, 0, OPTION_OUTPUT
},
686 {"object", required_argument
, 0, OPTION_OBJECT
},
687 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
688 {"force-share", no_argument
, 0, 'U'},
691 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
692 long_options
, &option_index
);
698 missing_argument(argv
[optind
- 1]);
701 unrecognized_option(argv
[optind
- 1]);
710 flags
|= BDRV_O_RDWR
;
712 if (!strcmp(optarg
, "leaks")) {
713 fix
= BDRV_FIX_LEAKS
;
714 } else if (!strcmp(optarg
, "all")) {
715 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
717 error_exit("Unknown option value for -r "
718 "(expecting 'leaks' or 'all'): %s", optarg
);
733 case OPTION_OBJECT
: {
735 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
741 case OPTION_IMAGE_OPTS
:
746 if (optind
!= argc
- 1) {
747 error_exit("Expecting one image file name");
749 filename
= argv
[optind
++];
751 if (output
&& !strcmp(output
, "json")) {
752 output_format
= OFORMAT_JSON
;
753 } else if (output
&& !strcmp(output
, "human")) {
754 output_format
= OFORMAT_HUMAN
;
756 error_report("--output must be used with human or json as argument.");
760 if (qemu_opts_foreach(&qemu_object_opts
,
761 user_creatable_add_opts_foreach
,
766 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
768 error_report("Invalid source cache option: %s", cache
);
772 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
779 check
= g_new0(ImageCheck
, 1);
780 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
782 if (ret
== -ENOTSUP
) {
783 error_report("This image format does not support checks");
788 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
789 int corruptions_fixed
, leaks_fixed
;
791 leaks_fixed
= check
->leaks_fixed
;
792 corruptions_fixed
= check
->corruptions_fixed
;
794 if (output_format
== OFORMAT_HUMAN
) {
796 "The following inconsistencies were found and repaired:\n\n"
797 " %" PRId64
" leaked clusters\n"
798 " %" PRId64
" corruptions\n\n"
799 "Double checking the fixed image now...\n",
801 check
->corruptions_fixed
);
804 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
806 check
->leaks_fixed
= leaks_fixed
;
807 check
->corruptions_fixed
= corruptions_fixed
;
811 switch (output_format
) {
813 dump_human_image_check(check
, quiet
);
816 dump_json_image_check(check
, quiet
);
821 if (ret
|| check
->check_errors
) {
823 error_report("Check failed: %s", strerror(-ret
));
825 error_report("Check failed");
831 if (check
->corruptions
) {
833 } else if (check
->leaks
) {
840 qapi_free_ImageCheck(check
);
845 typedef struct CommonBlockJobCBInfo
{
846 BlockDriverState
*bs
;
848 } CommonBlockJobCBInfo
;
850 static void common_block_job_cb(void *opaque
, int ret
)
852 CommonBlockJobCBInfo
*cbi
= opaque
;
855 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
859 static void run_block_job(BlockJob
*job
, Error
**errp
)
861 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
864 aio_context_acquire(aio_context
);
867 aio_poll(aio_context
, true);
868 qemu_progress_print(job
->len
?
869 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
870 } while (!job
->ready
&& !job
->completed
);
872 if (!job
->completed
) {
873 ret
= block_job_complete_sync(job
, errp
);
877 block_job_unref(job
);
878 aio_context_release(aio_context
);
880 /* publish completion progress only when success */
882 qemu_progress_print(100.f
, 0);
886 static int img_commit(int argc
, char **argv
)
889 const char *filename
, *fmt
, *cache
, *base
;
891 BlockDriverState
*bs
, *base_bs
;
893 bool progress
= false, quiet
= false, drop
= false;
895 Error
*local_err
= NULL
;
896 CommonBlockJobCBInfo cbi
;
897 bool image_opts
= false;
898 AioContext
*aio_context
;
901 cache
= BDRV_DEFAULT_CACHE
;
904 static const struct option long_options
[] = {
905 {"help", no_argument
, 0, 'h'},
906 {"object", required_argument
, 0, OPTION_OBJECT
},
907 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
910 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
917 missing_argument(argv
[optind
- 1]);
920 unrecognized_option(argv
[optind
- 1]);
945 case OPTION_OBJECT
: {
947 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
953 case OPTION_IMAGE_OPTS
:
959 /* Progress is not shown in Quiet mode */
964 if (optind
!= argc
- 1) {
965 error_exit("Expecting one image file name");
967 filename
= argv
[optind
++];
969 if (qemu_opts_foreach(&qemu_object_opts
,
970 user_creatable_add_opts_foreach
,
975 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
976 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
978 error_report("Invalid cache option: %s", cache
);
982 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
989 qemu_progress_init(progress
, 1.f
);
990 qemu_progress_print(0.f
, 100);
993 base_bs
= bdrv_find_backing_image(bs
, base
);
995 error_setg(&local_err
,
996 "Did not find '%s' in the backing chain of '%s'",
1001 /* This is different from QMP, which by default uses the deepest file in
1002 * the backing chain (i.e., the very base); however, the traditional
1003 * behavior of qemu-img commit is using the immediate backing file. */
1004 base_bs
= backing_bs(bs
);
1006 error_setg(&local_err
, "Image does not have a backing file");
1011 cbi
= (CommonBlockJobCBInfo
){
1016 aio_context
= bdrv_get_aio_context(bs
);
1017 aio_context_acquire(aio_context
);
1018 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
1019 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1020 &cbi
, false, &local_err
);
1021 aio_context_release(aio_context
);
1026 /* When the block job completes, the BlockBackend reference will point to
1027 * the old backing file. In order to avoid that the top image is already
1028 * deleted, so we can still empty it afterwards, increment the reference
1029 * counter here preemptively. */
1034 job
= block_job_get("commit");
1035 run_block_job(job
, &local_err
);
1040 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1041 ret
= bs
->drv
->bdrv_make_empty(bs
);
1043 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1055 qemu_progress_end();
1060 error_report_err(local_err
);
1064 qprintf(quiet
, "Image committed.\n");
1069 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1070 * of the first sector boundary within buf where the sector contains a
1071 * non-zero byte. This function is robust to a buffer that is not
1074 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1077 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1079 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1080 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1084 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
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
1161 * sector of each buffer matches, non-zero otherwise.
1163 * pnum is set to the sector-aligned size of the buffer prefix that
1164 * has the same matching status as the first sector.
1166 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1167 int64_t bytes
, int64_t *pnum
)
1170 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1174 res
= !!memcmp(buf1
, buf2
, i
);
1176 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1178 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1188 #define IO_BUF_SIZE (2 * 1024 * 1024)
1191 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1193 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1194 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1195 * failure), and 4 on error (the exit status for read errors), after emitting
1198 * @param blk: BlockBackend for the image
1199 * @param offset: Starting offset to check
1200 * @param bytes: Number of bytes to check
1201 * @param filename: Name of disk file we are checking (logging purpose)
1202 * @param buffer: Allocated buffer for storing read data
1203 * @param quiet: Flag for quiet mode
1205 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1206 int64_t bytes
, const char *filename
,
1207 uint8_t *buffer
, bool quiet
)
1212 ret
= blk_pread(blk
, offset
, buffer
, bytes
);
1214 error_report("Error while reading offset %" PRId64
" of %s: %s",
1215 offset
, filename
, strerror(-ret
));
1218 idx
= find_nonzero(buffer
, bytes
);
1220 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1229 * Compares two images. Exit codes:
1231 * 0 - Images are identical
1233 * >1 - Error occurred
1235 static int img_compare(int argc
, char **argv
)
1237 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1238 BlockBackend
*blk1
, *blk2
;
1239 BlockDriverState
*bs1
, *bs2
;
1240 int64_t total_size1
, total_size2
;
1241 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1242 int64_t pnum1
, pnum2
;
1243 int allocated1
, allocated2
;
1244 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1245 bool progress
= false, quiet
= false, strict
= false;
1252 uint64_t progress_base
;
1253 bool image_opts
= false;
1254 bool force_share
= false;
1256 cache
= BDRV_DEFAULT_CACHE
;
1258 static const struct option long_options
[] = {
1259 {"help", no_argument
, 0, 'h'},
1260 {"object", required_argument
, 0, OPTION_OBJECT
},
1261 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1262 {"force-share", no_argument
, 0, 'U'},
1265 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1266 long_options
, NULL
);
1272 missing_argument(argv
[optind
- 1]);
1275 unrecognized_option(argv
[optind
- 1]);
1301 case OPTION_OBJECT
: {
1303 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1310 case OPTION_IMAGE_OPTS
:
1316 /* Progress is not shown in Quiet mode */
1322 if (optind
!= argc
- 2) {
1323 error_exit("Expecting two image file names");
1325 filename1
= argv
[optind
++];
1326 filename2
= argv
[optind
++];
1328 if (qemu_opts_foreach(&qemu_object_opts
,
1329 user_creatable_add_opts_foreach
,
1335 /* Initialize before goto out */
1336 qemu_progress_init(progress
, 2.0);
1339 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1341 error_report("Invalid source cache option: %s", cache
);
1346 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1353 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1362 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1363 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1364 total_size1
= blk_getlength(blk1
);
1365 if (total_size1
< 0) {
1366 error_report("Can't get size of %s: %s",
1367 filename1
, strerror(-total_size1
));
1371 total_size2
= blk_getlength(blk2
);
1372 if (total_size2
< 0) {
1373 error_report("Can't get size of %s: %s",
1374 filename2
, strerror(-total_size2
));
1378 total_size
= MIN(total_size1
, total_size2
);
1379 progress_base
= MAX(total_size1
, total_size2
);
1381 qemu_progress_print(0, 100);
1383 if (strict
&& total_size1
!= total_size2
) {
1385 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1389 while (offset
< total_size
) {
1390 int status1
, status2
;
1392 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1393 total_size1
- offset
, &pnum1
, NULL
,
1397 error_report("Sector allocation test failed for %s", filename1
);
1400 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1402 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1403 total_size2
- offset
, &pnum2
, NULL
,
1407 error_report("Sector allocation test failed for %s", filename2
);
1410 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1412 assert(pnum1
&& pnum2
);
1413 chunk
= MIN(pnum1
, pnum2
);
1416 if (status1
!= status2
) {
1418 qprintf(quiet
, "Strict mode: Offset %" PRId64
1419 " block status mismatch!\n", offset
);
1423 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1425 } else if (allocated1
== allocated2
) {
1429 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1430 ret
= blk_pread(blk1
, offset
, buf1
, chunk
);
1432 error_report("Error while reading offset %" PRId64
1434 offset
, filename1
, strerror(-ret
));
1438 ret
= blk_pread(blk2
, offset
, buf2
, chunk
);
1440 error_report("Error while reading offset %" PRId64
1442 offset
, filename2
, strerror(-ret
));
1446 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1447 if (ret
|| pnum
!= chunk
) {
1448 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1449 offset
+ (ret
? 0 : pnum
));
1455 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1457 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1458 filename1
, buf1
, quiet
);
1460 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1461 filename2
, buf1
, quiet
);
1468 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1471 if (total_size1
!= total_size2
) {
1472 BlockBackend
*blk_over
;
1473 const char *filename_over
;
1475 qprintf(quiet
, "Warning: Image size mismatch!\n");
1476 if (total_size1
> total_size2
) {
1478 filename_over
= filename1
;
1481 filename_over
= filename2
;
1484 while (offset
< progress_base
) {
1485 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1486 progress_base
- offset
, &chunk
,
1490 error_report("Sector allocation test failed for %s",
1495 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1496 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1497 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1498 filename_over
, buf1
, quiet
);
1504 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1508 qprintf(quiet
, "Images are identical.\n");
1518 qemu_progress_end();
1523 enum ImgConvertBlockStatus
{
1529 #define MAX_COROUTINES 16
1531 typedef struct ImgConvertState
{
1533 int64_t *src_sectors
;
1535 int64_t total_sectors
;
1536 int64_t allocated_sectors
;
1537 int64_t allocated_done
;
1540 enum ImgConvertBlockStatus status
;
1541 int64_t sector_next_status
;
1542 BlockBackend
*target
;
1545 bool target_has_backing
;
1548 size_t cluster_sectors
;
1550 long num_coroutines
;
1551 int running_coroutines
;
1552 Coroutine
*co
[MAX_COROUTINES
];
1553 int64_t wait_sector_num
[MAX_COROUTINES
];
1558 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1559 int *src_cur
, int64_t *src_cur_offset
)
1562 *src_cur_offset
= 0;
1563 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1564 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1566 assert(*src_cur
< s
->src_num
);
1570 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1572 int64_t src_cur_offset
;
1573 int ret
, n
, src_cur
;
1575 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1577 assert(s
->total_sectors
> sector_num
);
1578 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1580 if (s
->sector_next_status
<= sector_num
) {
1581 int64_t count
= n
* BDRV_SECTOR_SIZE
;
1583 if (s
->target_has_backing
) {
1585 ret
= bdrv_block_status(blk_bs(s
->src
[src_cur
]),
1586 (sector_num
- src_cur_offset
) *
1588 count
, &count
, NULL
, NULL
);
1590 ret
= bdrv_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1591 (sector_num
- src_cur_offset
) *
1593 count
, &count
, NULL
, NULL
);
1598 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1600 if (ret
& BDRV_BLOCK_ZERO
) {
1601 s
->status
= BLK_ZERO
;
1602 } else if (ret
& BDRV_BLOCK_DATA
) {
1603 s
->status
= BLK_DATA
;
1605 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1608 s
->sector_next_status
= sector_num
+ n
;
1611 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1612 if (s
->status
== BLK_DATA
) {
1613 n
= MIN(n
, s
->buf_sectors
);
1616 /* We need to write complete clusters for compressed images, so if an
1617 * unallocated area is shorter than that, we must consider the whole
1618 * cluster allocated. */
1619 if (s
->compressed
) {
1620 if (n
< s
->cluster_sectors
) {
1621 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1622 s
->status
= BLK_DATA
;
1624 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1631 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1632 int nb_sectors
, uint8_t *buf
)
1638 assert(nb_sectors
<= s
->buf_sectors
);
1639 while (nb_sectors
> 0) {
1642 int64_t bs_sectors
, src_cur_offset
;
1644 /* In the case of compression with multiple source files, we can get a
1645 * nb_sectors that spreads into the next part. So we must be able to
1646 * read across multiple BDSes for one convert_read() call. */
1647 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1648 blk
= s
->src
[src_cur
];
1649 bs_sectors
= s
->src_sectors
[src_cur
];
1651 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1653 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1654 qemu_iovec_init_external(&qiov
, &iov
, 1);
1656 ret
= blk_co_preadv(
1657 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1658 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1665 buf
+= n
* BDRV_SECTOR_SIZE
;
1672 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1673 int nb_sectors
, uint8_t *buf
,
1674 enum ImgConvertBlockStatus status
)
1680 while (nb_sectors
> 0) {
1682 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1685 case BLK_BACKING_FILE
:
1686 /* If we have a backing file, leave clusters unallocated that are
1687 * unallocated in the source image, so that the backing file is
1688 * visible at the respective offset. */
1689 assert(s
->target_has_backing
);
1693 /* If we're told to keep the target fully allocated (-S 0) or there
1694 * is real non-zero data, we must write it. Otherwise we can treat
1695 * it as zero sectors.
1696 * Compressed clusters need to be written as a whole, so in that
1697 * case we can only save the write if the buffer is completely
1699 if (!s
->min_sparse
||
1701 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
)) ||
1703 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1706 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1707 qemu_iovec_init_external(&qiov
, &iov
, 1);
1709 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1710 n
<< BDRV_SECTOR_BITS
, &qiov
, flags
);
1719 if (s
->has_zero_init
) {
1720 assert(!s
->target_has_backing
);
1723 ret
= blk_co_pwrite_zeroes(s
->target
,
1724 sector_num
<< BDRV_SECTOR_BITS
,
1725 n
<< BDRV_SECTOR_BITS
, 0);
1734 buf
+= n
* BDRV_SECTOR_SIZE
;
1740 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1742 ImgConvertState
*s
= opaque
;
1743 uint8_t *buf
= NULL
;
1747 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1748 if (s
->co
[i
] == qemu_coroutine_self()) {
1755 s
->running_coroutines
++;
1756 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1761 enum ImgConvertBlockStatus status
;
1763 qemu_co_mutex_lock(&s
->lock
);
1764 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1765 qemu_co_mutex_unlock(&s
->lock
);
1768 n
= convert_iteration_sectors(s
, s
->sector_num
);
1770 qemu_co_mutex_unlock(&s
->lock
);
1774 /* save current sector and allocation status to local variables */
1775 sector_num
= s
->sector_num
;
1777 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1778 n
= MIN(n
, s
->buf_sectors
);
1780 /* increment global sector counter so that other coroutines can
1781 * already continue reading beyond this request */
1783 qemu_co_mutex_unlock(&s
->lock
);
1785 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1786 s
->allocated_done
+= n
;
1787 qemu_progress_print(100.0 * s
->allocated_done
/
1788 s
->allocated_sectors
, 0);
1791 if (status
== BLK_DATA
) {
1792 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1794 error_report("error while reading sector %" PRId64
1795 ": %s", sector_num
, strerror(-ret
));
1798 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1800 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1803 if (s
->wr_in_order
) {
1804 /* keep writes in order */
1805 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
1806 s
->wait_sector_num
[index
] = sector_num
;
1807 qemu_coroutine_yield();
1809 s
->wait_sector_num
[index
] = -1;
1812 if (s
->ret
== -EINPROGRESS
) {
1813 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1815 error_report("error while writing sector %" PRId64
1816 ": %s", sector_num
, strerror(-ret
));
1821 if (s
->wr_in_order
) {
1822 /* reenter the coroutine that might have waited
1823 * for this write to complete */
1824 s
->wr_offs
= sector_num
+ n
;
1825 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1826 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1828 * A -> B -> A cannot occur because A has
1829 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1830 * B will never enter A during this time window.
1832 qemu_coroutine_enter(s
->co
[i
]);
1840 s
->co
[index
] = NULL
;
1841 s
->running_coroutines
--;
1842 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1843 /* the convert job finished successfully */
1848 static int convert_do_copy(ImgConvertState
*s
)
1851 int64_t sector_num
= 0;
1853 /* Check whether we have zero initialisation or can get it efficiently */
1854 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1855 ? bdrv_has_zero_init(blk_bs(s
->target
))
1858 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1859 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1861 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1863 s
->has_zero_init
= true;
1867 /* Allocate buffer for copied data. For compressed images, only one cluster
1868 * can be copied at a time. */
1869 if (s
->compressed
) {
1870 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1871 error_report("invalid cluster size");
1874 s
->buf_sectors
= s
->cluster_sectors
;
1877 while (sector_num
< s
->total_sectors
) {
1878 n
= convert_iteration_sectors(s
, sector_num
);
1882 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1884 s
->allocated_sectors
+= n
;
1890 s
->sector_next_status
= 0;
1891 s
->ret
= -EINPROGRESS
;
1893 qemu_co_mutex_init(&s
->lock
);
1894 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1895 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1896 s
->wait_sector_num
[i
] = -1;
1897 qemu_coroutine_enter(s
->co
[i
]);
1900 while (s
->running_coroutines
) {
1901 main_loop_wait(false);
1904 if (s
->compressed
&& !s
->ret
) {
1905 /* signal EOF to align */
1906 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1915 static int img_convert(int argc
, char **argv
)
1917 int c
, bs_i
, flags
, src_flags
= 0;
1918 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
1919 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
1920 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
;
1921 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
1922 BlockDriverInfo bdi
;
1923 BlockDriverState
*out_bs
;
1924 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
1925 QemuOptsList
*create_opts
= NULL
;
1926 char *options
= NULL
;
1927 Error
*local_err
= NULL
;
1928 bool writethrough
, src_writethrough
, quiet
= false, image_opts
= false,
1929 skip_create
= false, progress
= false, tgt_image_opts
= false;
1930 int64_t ret
= -EINVAL
;
1931 bool force_share
= false;
1933 ImgConvertState s
= (ImgConvertState
) {
1934 /* Need at least 4k of zeros for sparse detection */
1936 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
1937 .wr_in_order
= true,
1938 .num_coroutines
= 8,
1942 static const struct option long_options
[] = {
1943 {"help", no_argument
, 0, 'h'},
1944 {"object", required_argument
, 0, OPTION_OBJECT
},
1945 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1946 {"force-share", no_argument
, 0, 'U'},
1947 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
1950 c
= getopt_long(argc
, argv
, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1951 long_options
, NULL
);
1957 missing_argument(argv
[optind
- 1]);
1960 unrecognized_option(argv
[optind
- 1]);
1972 out_baseimg
= optarg
;
1975 s
.compressed
= true;
1978 if (!is_valid_option_list(optarg
)) {
1979 error_report("Invalid option list: %s", optarg
);
1983 options
= g_strdup(optarg
);
1985 char *old_options
= options
;
1986 options
= g_strdup_printf("%s,%s", options
, optarg
);
1987 g_free(old_options
);
1991 snapshot_name
= optarg
;
1994 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1995 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
1998 error_report("Failed in parsing snapshot param '%s'",
2003 snapshot_name
= optarg
;
2010 sval
= cvtnum(optarg
);
2012 error_report("Invalid minimum zero buffer size for sparse output specified");
2016 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2035 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2036 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2037 error_report("Invalid number of coroutines. Allowed number of"
2038 " coroutines is between 1 and %d", MAX_COROUTINES
);
2043 s
.wr_in_order
= false;
2048 case OPTION_OBJECT
: {
2049 QemuOpts
*object_opts
;
2050 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2057 case OPTION_IMAGE_OPTS
:
2060 case OPTION_TARGET_IMAGE_OPTS
:
2061 tgt_image_opts
= true;
2066 if (!out_fmt
&& !tgt_image_opts
) {
2070 if (qemu_opts_foreach(&qemu_object_opts
,
2071 user_creatable_add_opts_foreach
,
2076 if (!s
.wr_in_order
&& s
.compressed
) {
2077 error_report("Out of order write and compress are mutually exclusive");
2081 if (tgt_image_opts
&& !skip_create
) {
2082 error_report("--target-image-opts requires use of -n flag");
2086 s
.src_num
= argc
- optind
- 1;
2087 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2089 if (options
&& has_help_option(options
)) {
2091 ret
= print_block_option_help(out_filename
, out_fmt
);
2094 error_report("Option help requires a format be specified");
2099 if (s
.src_num
< 1) {
2100 error_report("Must specify image file name");
2105 /* ret is still -EINVAL until here */
2106 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2108 error_report("Invalid source cache option: %s", src_cache
);
2112 /* Initialize before goto out */
2116 qemu_progress_init(progress
, 1.0);
2117 qemu_progress_print(0, 100);
2119 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2120 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2122 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2123 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2124 fmt
, src_flags
, src_writethrough
, quiet
,
2130 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2131 if (s
.src_sectors
[bs_i
] < 0) {
2132 error_report("Could not get size of %s: %s",
2133 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2137 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2141 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2142 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2143 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2145 } else if (snapshot_name
!= NULL
) {
2146 if (s
.src_num
> 1) {
2147 error_report("No support for concatenating multiple snapshot");
2152 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2156 error_reportf_err(local_err
, "Failed to load snapshot: ");
2162 /* Find driver and parse its options */
2163 drv
= bdrv_find_format(out_fmt
);
2165 error_report("Unknown file format '%s'", out_fmt
);
2170 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2172 error_report_err(local_err
);
2177 if (!drv
->create_opts
) {
2178 error_report("Format driver '%s' does not support image creation",
2184 if (!proto_drv
->create_opts
) {
2185 error_report("Protocol driver '%s' does not support image creation",
2186 proto_drv
->format_name
);
2191 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2192 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2194 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2196 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2198 error_report_err(local_err
);
2204 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, s
.total_sectors
* 512,
2206 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2212 /* Get backing file name if -o backing_file was used */
2213 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2214 if (out_baseimg_param
) {
2215 out_baseimg
= out_baseimg_param
;
2217 s
.target_has_backing
= (bool) out_baseimg
;
2219 if (s
.src_num
> 1 && out_baseimg
) {
2220 error_report("Having a backing file for the target makes no sense when "
2221 "concatenating multiple input images");
2226 /* Check if compression is supported */
2229 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2230 const char *encryptfmt
=
2231 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2232 const char *preallocation
=
2233 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2235 if (drv
&& !drv
->bdrv_co_pwritev_compressed
) {
2236 error_report("Compression not supported for this file format");
2241 if (encryption
|| encryptfmt
) {
2242 error_report("Compression and encryption not supported at "
2249 && strcmp(preallocation
, "off"))
2251 error_report("Compression and preallocation not supported at "
2259 /* Create the new image */
2260 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2262 error_reportf_err(local_err
, "%s: error while converting %s: ",
2263 out_filename
, out_fmt
);
2268 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2269 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2271 error_report("Invalid cache option: %s", cache
);
2276 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2277 flags
, writethrough
, quiet
, false);
2279 /* TODO ultimately we should allow --target-image-opts
2280 * to be used even when -n is not given.
2281 * That has to wait for bdrv_create to be improved
2282 * to allow filenames in option syntax
2284 s
.target
= img_open_new_file(out_filename
, opts
, out_fmt
,
2285 flags
, writethrough
, quiet
, false);
2291 out_bs
= blk_bs(s
.target
);
2293 if (s
.compressed
&& !out_bs
->drv
->bdrv_co_pwritev_compressed
) {
2294 error_report("Compression not supported for this file format");
2299 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2300 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2302 s
.buf_sectors
= MIN(32768,
2304 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2305 out_bs
->bl
.pdiscard_alignment
>>
2306 BDRV_SECTOR_BITS
)));
2309 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2310 if (output_sectors
< 0) {
2311 error_report("unable to get output image length: %s",
2312 strerror(-output_sectors
));
2315 } else if (output_sectors
< s
.total_sectors
) {
2316 error_report("output file is smaller than input file");
2322 ret
= bdrv_get_info(out_bs
, &bdi
);
2325 error_report("could not get block driver info");
2329 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2330 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2333 ret
= convert_do_copy(&s
);
2336 qemu_progress_print(100, 0);
2338 qemu_progress_end();
2339 qemu_opts_del(opts
);
2340 qemu_opts_free(create_opts
);
2341 qemu_opts_del(sn_opts
);
2342 blk_unref(s
.target
);
2344 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2345 blk_unref(s
.src
[bs_i
]);
2349 g_free(s
.src_sectors
);
2357 static void dump_snapshots(BlockDriverState
*bs
)
2359 QEMUSnapshotInfo
*sn_tab
, *sn
;
2362 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2365 printf("Snapshot list:\n");
2366 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2368 for(i
= 0; i
< nb_sns
; i
++) {
2370 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2376 static void dump_json_image_info_list(ImageInfoList
*list
)
2380 Visitor
*v
= qobject_output_visitor_new(&obj
);
2382 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2383 visit_complete(v
, &obj
);
2384 str
= qobject_to_json_pretty(obj
);
2385 assert(str
!= NULL
);
2386 printf("%s\n", qstring_get_str(str
));
2392 static void dump_json_image_info(ImageInfo
*info
)
2396 Visitor
*v
= qobject_output_visitor_new(&obj
);
2398 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2399 visit_complete(v
, &obj
);
2400 str
= qobject_to_json_pretty(obj
);
2401 assert(str
!= NULL
);
2402 printf("%s\n", qstring_get_str(str
));
2408 static void dump_human_image_info_list(ImageInfoList
*list
)
2410 ImageInfoList
*elem
;
2413 for (elem
= list
; elem
; elem
= elem
->next
) {
2419 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2423 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2425 return strcmp(a
, b
) == 0;
2429 * Open an image file chain and return an ImageInfoList
2431 * @filename: topmost image filename
2432 * @fmt: topmost image format (may be NULL to autodetect)
2433 * @chain: true - enumerate entire backing file chain
2434 * false - only topmost image file
2436 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2437 * image file. If there was an error a message will have been printed to
2440 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2441 const char *filename
,
2443 bool chain
, bool force_share
)
2445 ImageInfoList
*head
= NULL
;
2446 ImageInfoList
**last
= &head
;
2447 GHashTable
*filenames
;
2450 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2454 BlockDriverState
*bs
;
2456 ImageInfoList
*elem
;
2458 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2459 error_report("Backing file '%s' creates an infinite loop.",
2463 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2465 blk
= img_open(image_opts
, filename
, fmt
,
2466 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2473 bdrv_query_image_info(bs
, &info
, &err
);
2475 error_report_err(err
);
2480 elem
= g_new0(ImageInfoList
, 1);
2487 filename
= fmt
= NULL
;
2489 if (info
->has_full_backing_filename
) {
2490 filename
= info
->full_backing_filename
;
2491 } else if (info
->has_backing_filename
) {
2492 error_report("Could not determine absolute backing filename,"
2493 " but backing filename '%s' present",
2494 info
->backing_filename
);
2497 if (info
->has_backing_filename_format
) {
2498 fmt
= info
->backing_filename_format
;
2502 g_hash_table_destroy(filenames
);
2506 qapi_free_ImageInfoList(head
);
2507 g_hash_table_destroy(filenames
);
2511 static int img_info(int argc
, char **argv
)
2514 OutputFormat output_format
= OFORMAT_HUMAN
;
2516 const char *filename
, *fmt
, *output
;
2517 ImageInfoList
*list
;
2518 bool image_opts
= false;
2519 bool force_share
= false;
2524 int option_index
= 0;
2525 static const struct option long_options
[] = {
2526 {"help", no_argument
, 0, 'h'},
2527 {"format", required_argument
, 0, 'f'},
2528 {"output", required_argument
, 0, OPTION_OUTPUT
},
2529 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2530 {"object", required_argument
, 0, OPTION_OBJECT
},
2531 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2532 {"force-share", no_argument
, 0, 'U'},
2535 c
= getopt_long(argc
, argv
, ":f:hU",
2536 long_options
, &option_index
);
2542 missing_argument(argv
[optind
- 1]);
2545 unrecognized_option(argv
[optind
- 1]);
2559 case OPTION_BACKING_CHAIN
:
2562 case OPTION_OBJECT
: {
2564 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2570 case OPTION_IMAGE_OPTS
:
2575 if (optind
!= argc
- 1) {
2576 error_exit("Expecting one image file name");
2578 filename
= argv
[optind
++];
2580 if (output
&& !strcmp(output
, "json")) {
2581 output_format
= OFORMAT_JSON
;
2582 } else if (output
&& !strcmp(output
, "human")) {
2583 output_format
= OFORMAT_HUMAN
;
2584 } else if (output
) {
2585 error_report("--output must be used with human or json as argument.");
2589 if (qemu_opts_foreach(&qemu_object_opts
,
2590 user_creatable_add_opts_foreach
,
2595 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
2601 switch (output_format
) {
2603 dump_human_image_info_list(list
);
2607 dump_json_image_info_list(list
);
2609 dump_json_image_info(list
->value
);
2614 qapi_free_ImageInfoList(list
);
2618 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2621 switch (output_format
) {
2623 if (e
->data
&& !e
->has_offset
) {
2624 error_report("File contains external, encrypted or compressed clusters.");
2627 if (e
->data
&& !e
->zero
) {
2628 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2629 e
->start
, e
->length
,
2630 e
->has_offset
? e
->offset
: 0,
2631 e
->has_filename
? e
->filename
: "");
2633 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2634 * Modify the flags here to allow more coalescing.
2636 if (next
&& (!next
->data
|| next
->zero
)) {
2642 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2643 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2644 (e
->start
== 0 ? "[" : ",\n"),
2645 e
->start
, e
->length
, e
->depth
,
2646 e
->zero
? "true" : "false",
2647 e
->data
? "true" : "false");
2648 if (e
->has_offset
) {
2649 printf(", \"offset\": %"PRId64
"", e
->offset
);
2660 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
2661 int64_t bytes
, MapEntry
*e
)
2665 BlockDriverState
*file
;
2669 /* As an optimization, we could cache the current range of unallocated
2670 * clusters in each file of the chain, and avoid querying the same
2676 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
2681 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2684 bs
= backing_bs(bs
);
2693 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2698 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2699 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2701 .has_offset
= has_offset
,
2703 .has_filename
= file
&& has_offset
,
2704 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2710 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2712 if (curr
->length
== 0) {
2715 if (curr
->zero
!= next
->zero
||
2716 curr
->data
!= next
->data
||
2717 curr
->depth
!= next
->depth
||
2718 curr
->has_filename
!= next
->has_filename
||
2719 curr
->has_offset
!= next
->has_offset
) {
2722 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2725 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2731 static int img_map(int argc
, char **argv
)
2734 OutputFormat output_format
= OFORMAT_HUMAN
;
2736 BlockDriverState
*bs
;
2737 const char *filename
, *fmt
, *output
;
2739 MapEntry curr
= { .length
= 0 }, next
;
2741 bool image_opts
= false;
2742 bool force_share
= false;
2747 int option_index
= 0;
2748 static const struct option long_options
[] = {
2749 {"help", no_argument
, 0, 'h'},
2750 {"format", required_argument
, 0, 'f'},
2751 {"output", required_argument
, 0, OPTION_OUTPUT
},
2752 {"object", required_argument
, 0, OPTION_OBJECT
},
2753 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2754 {"force-share", no_argument
, 0, 'U'},
2757 c
= getopt_long(argc
, argv
, ":f:hU",
2758 long_options
, &option_index
);
2764 missing_argument(argv
[optind
- 1]);
2767 unrecognized_option(argv
[optind
- 1]);
2781 case OPTION_OBJECT
: {
2783 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2789 case OPTION_IMAGE_OPTS
:
2794 if (optind
!= argc
- 1) {
2795 error_exit("Expecting one image file name");
2797 filename
= argv
[optind
];
2799 if (output
&& !strcmp(output
, "json")) {
2800 output_format
= OFORMAT_JSON
;
2801 } else if (output
&& !strcmp(output
, "human")) {
2802 output_format
= OFORMAT_HUMAN
;
2803 } else if (output
) {
2804 error_report("--output must be used with human or json as argument.");
2808 if (qemu_opts_foreach(&qemu_object_opts
,
2809 user_creatable_add_opts_foreach
,
2814 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
2820 if (output_format
== OFORMAT_HUMAN
) {
2821 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2824 length
= blk_getlength(blk
);
2825 while (curr
.start
+ curr
.length
< length
) {
2826 int64_t offset
= curr
.start
+ curr
.length
;
2829 /* Probe up to 1 GiB at a time. */
2830 n
= QEMU_ALIGN_DOWN(MIN(1 << 30, length
- offset
), BDRV_SECTOR_SIZE
);
2831 ret
= get_block_status(bs
, offset
, n
, &next
);
2834 error_report("Could not read file metadata: %s", strerror(-ret
));
2838 if (entry_mergeable(&curr
, &next
)) {
2839 curr
.length
+= next
.length
;
2843 if (curr
.length
> 0) {
2844 dump_map_entry(output_format
, &curr
, &next
);
2849 dump_map_entry(output_format
, &curr
, NULL
);
2856 #define SNAPSHOT_LIST 1
2857 #define SNAPSHOT_CREATE 2
2858 #define SNAPSHOT_APPLY 3
2859 #define SNAPSHOT_DELETE 4
2861 static int img_snapshot(int argc
, char **argv
)
2864 BlockDriverState
*bs
;
2865 QEMUSnapshotInfo sn
;
2866 char *filename
, *snapshot_name
= NULL
;
2867 int c
, ret
= 0, bdrv_oflags
;
2872 bool image_opts
= false;
2873 bool force_share
= false;
2875 bdrv_oflags
= BDRV_O_RDWR
;
2876 /* Parse commandline parameters */
2878 static const struct option long_options
[] = {
2879 {"help", no_argument
, 0, 'h'},
2880 {"object", required_argument
, 0, OPTION_OBJECT
},
2881 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2882 {"force-share", no_argument
, 0, 'U'},
2885 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
2886 long_options
, NULL
);
2892 missing_argument(argv
[optind
- 1]);
2895 unrecognized_option(argv
[optind
- 1]);
2902 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2905 action
= SNAPSHOT_LIST
;
2906 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2910 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2913 action
= SNAPSHOT_APPLY
;
2914 snapshot_name
= optarg
;
2918 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2921 action
= SNAPSHOT_CREATE
;
2922 snapshot_name
= optarg
;
2926 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2929 action
= SNAPSHOT_DELETE
;
2930 snapshot_name
= optarg
;
2938 case OPTION_OBJECT
: {
2940 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2946 case OPTION_IMAGE_OPTS
:
2952 if (optind
!= argc
- 1) {
2953 error_exit("Expecting one image file name");
2955 filename
= argv
[optind
++];
2957 if (qemu_opts_foreach(&qemu_object_opts
,
2958 user_creatable_add_opts_foreach
,
2963 /* Open the image */
2964 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
2971 /* Perform the requested action */
2977 case SNAPSHOT_CREATE
:
2978 memset(&sn
, 0, sizeof(sn
));
2979 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2981 qemu_gettimeofday(&tv
);
2982 sn
.date_sec
= tv
.tv_sec
;
2983 sn
.date_nsec
= tv
.tv_usec
* 1000;
2985 ret
= bdrv_snapshot_create(bs
, &sn
);
2987 error_report("Could not create snapshot '%s': %d (%s)",
2988 snapshot_name
, ret
, strerror(-ret
));
2992 case SNAPSHOT_APPLY
:
2993 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
2995 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3000 case SNAPSHOT_DELETE
:
3001 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3003 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3018 static int img_rebase(int argc
, char **argv
)
3020 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3021 uint8_t *buf_old
= NULL
;
3022 uint8_t *buf_new
= NULL
;
3023 BlockDriverState
*bs
= NULL
;
3025 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3026 int c
, flags
, src_flags
, ret
;
3027 bool writethrough
, src_writethrough
;
3029 bool force_share
= false;
3032 Error
*local_err
= NULL
;
3033 bool image_opts
= false;
3035 /* Parse commandline parameters */
3037 cache
= BDRV_DEFAULT_CACHE
;
3038 src_cache
= BDRV_DEFAULT_CACHE
;
3042 static const struct option long_options
[] = {
3043 {"help", no_argument
, 0, 'h'},
3044 {"object", required_argument
, 0, OPTION_OBJECT
},
3045 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3046 {"force-share", no_argument
, 0, 'U'},
3049 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3050 long_options
, NULL
);
3056 missing_argument(argv
[optind
- 1]);
3059 unrecognized_option(argv
[optind
- 1]);
3068 out_basefmt
= optarg
;
3071 out_baseimg
= optarg
;
3088 case OPTION_OBJECT
: {
3090 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3096 case OPTION_IMAGE_OPTS
:
3109 if (optind
!= argc
- 1) {
3110 error_exit("Expecting one image file name");
3112 if (!unsafe
&& !out_baseimg
) {
3113 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3115 filename
= argv
[optind
++];
3117 if (qemu_opts_foreach(&qemu_object_opts
,
3118 user_creatable_add_opts_foreach
,
3123 qemu_progress_init(progress
, 2.0);
3124 qemu_progress_print(0, 100);
3126 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3127 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3129 error_report("Invalid cache option: %s", cache
);
3134 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3136 error_report("Invalid source cache option: %s", src_cache
);
3140 /* The source files are opened read-only, don't care about WCE */
3141 assert((src_flags
& BDRV_O_RDWR
) == 0);
3142 (void) src_writethrough
;
3147 * Ignore the old backing file for unsafe rebase in case we want to correct
3148 * the reference to a renamed or moved backing file.
3150 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3158 if (out_basefmt
!= NULL
) {
3159 if (bdrv_find_format(out_basefmt
) == NULL
) {
3160 error_report("Invalid format name: '%s'", out_basefmt
);
3166 /* For safe rebasing we need to compare old and new backing file */
3168 char backing_name
[PATH_MAX
];
3169 QDict
*options
= NULL
;
3171 if (bs
->backing_format
[0] != '\0') {
3172 options
= qdict_new();
3173 qdict_put_str(options
, "driver", bs
->backing_format
);
3178 options
= qdict_new();
3180 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3182 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3183 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3184 options
, src_flags
, &local_err
);
3185 if (!blk_old_backing
) {
3186 error_reportf_err(local_err
,
3187 "Could not open old backing file '%s': ",
3193 if (out_baseimg
[0]) {
3194 options
= qdict_new();
3196 qdict_put_str(options
, "driver", out_basefmt
);
3199 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3202 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3203 options
, src_flags
, &local_err
);
3204 if (!blk_new_backing
) {
3205 error_reportf_err(local_err
,
3206 "Could not open new backing file '%s': ",
3215 * Check each unallocated cluster in the COW file. If it is unallocated,
3216 * accesses go to the backing file. We must therefore compare this cluster
3217 * in the old and new backing file, and if they differ we need to copy it
3218 * from the old backing file into the COW file.
3220 * If qemu-img crashes during this step, no harm is done. The content of
3221 * the image is the same as the original one at any time.
3225 int64_t old_backing_size
;
3226 int64_t new_backing_size
= 0;
3229 float local_progress
= 0;
3231 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3232 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3234 size
= blk_getlength(blk
);
3236 error_report("Could not get size of '%s': %s",
3237 filename
, strerror(-size
));
3241 old_backing_size
= blk_getlength(blk_old_backing
);
3242 if (old_backing_size
< 0) {
3243 char backing_name
[PATH_MAX
];
3245 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3246 error_report("Could not get size of '%s': %s",
3247 backing_name
, strerror(-old_backing_size
));
3251 if (blk_new_backing
) {
3252 new_backing_size
= blk_getlength(blk_new_backing
);
3253 if (new_backing_size
< 0) {
3254 error_report("Could not get size of '%s': %s",
3255 out_baseimg
, strerror(-new_backing_size
));
3262 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3265 for (offset
= 0; offset
< size
; offset
+= n
) {
3266 /* How many bytes can we handle with the next read? */
3267 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3269 /* If the cluster is allocated, we don't need to take action */
3270 ret
= bdrv_is_allocated(bs
, offset
, n
, &n
);
3272 error_report("error while reading image metadata: %s",
3281 * Read old and new backing file and take into consideration that
3282 * backing files may be smaller than the COW image.
3284 if (offset
>= old_backing_size
) {
3285 memset(buf_old
, 0, n
);
3287 if (offset
+ n
> old_backing_size
) {
3288 n
= old_backing_size
- offset
;
3291 ret
= blk_pread(blk_old_backing
, offset
, buf_old
, n
);
3293 error_report("error while reading from old backing file");
3298 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3299 memset(buf_new
, 0, n
);
3301 if (offset
+ n
> new_backing_size
) {
3302 n
= new_backing_size
- offset
;
3305 ret
= blk_pread(blk_new_backing
, offset
, buf_new
, n
);
3307 error_report("error while reading from new backing file");
3312 /* If they differ, we need to write to the COW file */
3313 uint64_t written
= 0;
3315 while (written
< n
) {
3318 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3319 n
- written
, &pnum
))
3321 ret
= blk_pwrite(blk
, offset
+ written
,
3322 buf_old
+ written
, pnum
, 0);
3324 error_report("Error while writing to COW image: %s",
3332 qemu_progress_print(local_progress
, 100);
3337 * Change the backing file. All clusters that are different from the old
3338 * backing file are overwritten in the COW file now, so the visible content
3339 * doesn't change when we switch the backing file.
3341 if (out_baseimg
&& *out_baseimg
) {
3342 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3344 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3347 if (ret
== -ENOSPC
) {
3348 error_report("Could not change the backing file to '%s': No "
3349 "space left in the file header", out_baseimg
);
3350 } else if (ret
< 0) {
3351 error_report("Could not change the backing file to '%s': %s",
3352 out_baseimg
, strerror(-ret
));
3355 qemu_progress_print(100, 0);
3357 * TODO At this point it is possible to check if any clusters that are
3358 * allocated in the COW file are the same in the backing file. If so, they
3359 * could be dropped from the COW file. Don't do this before switching the
3360 * backing file, in case of a crash this would lead to corruption.
3363 qemu_progress_end();
3366 blk_unref(blk_old_backing
);
3367 blk_unref(blk_new_backing
);
3369 qemu_vfree(buf_old
);
3370 qemu_vfree(buf_new
);
3379 static int img_resize(int argc
, char **argv
)
3382 int c
, ret
, relative
;
3383 const char *filename
, *fmt
, *size
;
3384 int64_t n
, total_size
, current_size
;
3386 BlockBackend
*blk
= NULL
;
3387 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3390 static QemuOptsList resize_options
= {
3391 .name
= "resize_options",
3392 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3395 .name
= BLOCK_OPT_SIZE
,
3396 .type
= QEMU_OPT_SIZE
,
3397 .help
= "Virtual disk size"
3403 bool image_opts
= false;
3404 bool shrink
= false;
3406 /* Remove size from argv manually so that negative numbers are not treated
3407 * as options by getopt. */
3409 error_exit("Not enough arguments");
3413 size
= argv
[--argc
];
3415 /* Parse getopt arguments */
3418 static const struct option long_options
[] = {
3419 {"help", no_argument
, 0, 'h'},
3420 {"object", required_argument
, 0, OPTION_OBJECT
},
3421 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3422 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3423 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3426 c
= getopt_long(argc
, argv
, ":f:hq",
3427 long_options
, NULL
);
3433 missing_argument(argv
[optind
- 1]);
3436 unrecognized_option(argv
[optind
- 1]);
3447 case OPTION_OBJECT
: {
3449 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3455 case OPTION_IMAGE_OPTS
:
3458 case OPTION_PREALLOCATION
:
3459 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
3460 PREALLOC_MODE__MAX
, NULL
);
3461 if (prealloc
== PREALLOC_MODE__MAX
) {
3462 error_report("Invalid preallocation mode '%s'", optarg
);
3471 if (optind
!= argc
- 1) {
3472 error_exit("Expecting image file name and size");
3474 filename
= argv
[optind
++];
3476 if (qemu_opts_foreach(&qemu_object_opts
,
3477 user_creatable_add_opts_foreach
,
3482 /* Choose grow, shrink, or absolute resize mode */
3498 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3499 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3501 error_report_err(err
);
3503 qemu_opts_del(param
);
3506 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3507 qemu_opts_del(param
);
3509 blk
= img_open(image_opts
, filename
, fmt
,
3510 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
3517 current_size
= blk_getlength(blk
);
3518 if (current_size
< 0) {
3519 error_report("Failed to inquire current image length: %s",
3520 strerror(-current_size
));
3526 total_size
= current_size
+ n
* relative
;
3530 if (total_size
<= 0) {
3531 error_report("New image size must be positive");
3536 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
3537 error_report("Preallocation can only be used for growing images");
3542 if (total_size
< current_size
&& !shrink
) {
3543 warn_report("Shrinking an image will delete all data beyond the "
3544 "shrunken image's end. Before performing such an "
3545 "operation, make sure there is no important data there.");
3547 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk
)), "raw") != 0) {
3549 "Use the --shrink option to perform a shrink operation.");
3553 warn_report("Using the --shrink option will suppress this message. "
3554 "Note that future versions of qemu-img may refuse to "
3555 "shrink images without this option.");
3559 ret
= blk_truncate(blk
, total_size
, prealloc
, &err
);
3561 qprintf(quiet
, "Image resized.\n");
3563 error_report_err(err
);
3573 static void amend_status_cb(BlockDriverState
*bs
,
3574 int64_t offset
, int64_t total_work_size
,
3577 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3580 static int img_amend(int argc
, char **argv
)
3584 char *options
= NULL
;
3585 QemuOptsList
*create_opts
= NULL
;
3586 QemuOpts
*opts
= NULL
;
3587 const char *fmt
= NULL
, *filename
, *cache
;
3590 bool quiet
= false, progress
= false;
3591 BlockBackend
*blk
= NULL
;
3592 BlockDriverState
*bs
= NULL
;
3593 bool image_opts
= false;
3595 cache
= BDRV_DEFAULT_CACHE
;
3597 static const struct option long_options
[] = {
3598 {"help", no_argument
, 0, 'h'},
3599 {"object", required_argument
, 0, OPTION_OBJECT
},
3600 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3603 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3604 long_options
, NULL
);
3611 missing_argument(argv
[optind
- 1]);
3614 unrecognized_option(argv
[optind
- 1]);
3620 if (!is_valid_option_list(optarg
)) {
3621 error_report("Invalid option list: %s", optarg
);
3623 goto out_no_progress
;
3626 options
= g_strdup(optarg
);
3628 char *old_options
= options
;
3629 options
= g_strdup_printf("%s,%s", options
, optarg
);
3630 g_free(old_options
);
3646 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3650 goto out_no_progress
;
3653 case OPTION_IMAGE_OPTS
:
3660 error_exit("Must specify options (-o)");
3663 if (qemu_opts_foreach(&qemu_object_opts
,
3664 user_creatable_add_opts_foreach
,
3667 goto out_no_progress
;
3673 qemu_progress_init(progress
, 1.0);
3675 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3676 if (fmt
&& has_help_option(options
)) {
3677 /* If a format is explicitly specified (and possibly no filename is
3678 * given), print option help here */
3679 ret
= print_block_option_help(filename
, fmt
);
3683 if (optind
!= argc
- 1) {
3684 error_report("Expecting one image file name");
3689 flags
= BDRV_O_RDWR
;
3690 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3692 error_report("Invalid cache option: %s", cache
);
3696 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3704 fmt
= bs
->drv
->format_name
;
3706 if (has_help_option(options
)) {
3707 /* If the format was auto-detected, print option help here */
3708 ret
= print_block_option_help(filename
, fmt
);
3712 if (!bs
->drv
->create_opts
) {
3713 error_report("Format driver '%s' does not support any options to amend",
3719 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3720 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3721 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3723 error_report_err(err
);
3728 /* In case the driver does not call amend_status_cb() */
3729 qemu_progress_print(0.f
, 0);
3730 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3731 qemu_progress_print(100.f
, 0);
3733 error_report("Error while amending options: %s", strerror(-ret
));
3738 qemu_progress_end();
3742 qemu_opts_del(opts
);
3743 qemu_opts_free(create_opts
);
3752 typedef struct BenchData
{
3754 uint64_t image_size
;
3761 bool drain_on_flush
;
3770 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3773 error_report("Failed flush request: %s", strerror(-ret
));
3778 static void bench_cb(void *opaque
, int ret
)
3780 BenchData
*b
= opaque
;
3784 error_report("Failed request: %s", strerror(-ret
));
3789 /* Just finished a flush with drained queue: Start next requests */
3790 assert(b
->in_flight
== 0);
3791 b
->in_flush
= false;
3792 } else if (b
->in_flight
> 0) {
3793 int remaining
= b
->n
- b
->in_flight
;
3798 /* Time for flush? Drain queue if requested, then flush */
3799 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3800 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3801 BlockCompletionFunc
*cb
;
3803 if (b
->drain_on_flush
) {
3807 cb
= bench_undrained_flush_cb
;
3810 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3812 error_report("Failed to issue flush request");
3816 if (b
->drain_on_flush
) {
3822 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3823 int64_t offset
= b
->offset
;
3824 /* blk_aio_* might look for completed I/Os and kick bench_cb
3825 * again, so make sure this operation is counted by in_flight
3826 * and b->offset is ready for the next submission.
3829 b
->offset
+= b
->step
;
3830 b
->offset
%= b
->image_size
;
3832 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3834 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3837 error_report("Failed to issue request");
3843 static int img_bench(int argc
, char **argv
)
3846 const char *fmt
= NULL
, *filename
;
3848 bool image_opts
= false;
3849 bool is_write
= false;
3853 size_t bufsize
= 4096;
3856 int flush_interval
= 0;
3857 bool drain_on_flush
= true;
3859 BlockBackend
*blk
= NULL
;
3860 BenchData data
= {};
3862 bool writethrough
= false;
3863 struct timeval t1
, t2
;
3865 bool force_share
= false;
3869 static const struct option long_options
[] = {
3870 {"help", no_argument
, 0, 'h'},
3871 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3872 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3873 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3874 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3875 {"force-share", no_argument
, 0, 'U'},
3878 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:wU", long_options
, NULL
);
3885 missing_argument(argv
[optind
- 1]);
3888 unrecognized_option(argv
[optind
- 1]);
3897 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3898 error_report("Invalid request count specified");
3908 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3909 error_report("Invalid queue depth specified");
3919 flags
|= BDRV_O_NATIVE_AIO
;
3923 offset
= cvtnum(optarg
);
3925 error_report("Invalid offset specified");
3938 sval
= cvtnum(optarg
);
3939 if (sval
< 0 || sval
> INT_MAX
) {
3940 error_report("Invalid buffer size specified");
3951 sval
= cvtnum(optarg
);
3952 if (sval
< 0 || sval
> INT_MAX
) {
3953 error_report("Invalid step size specified");
3961 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3963 error_report("Invalid cache mode");
3969 flags
|= BDRV_O_RDWR
;
3975 case OPTION_PATTERN
:
3979 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3980 error_report("Invalid pattern byte specified");
3986 case OPTION_FLUSH_INTERVAL
:
3990 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3991 error_report("Invalid flush interval specified");
3994 flush_interval
= res
;
3997 case OPTION_NO_DRAIN
:
3998 drain_on_flush
= false;
4000 case OPTION_IMAGE_OPTS
:
4006 if (optind
!= argc
- 1) {
4007 error_exit("Expecting one image file name");
4009 filename
= argv
[argc
- 1];
4011 if (!is_write
&& flush_interval
) {
4012 error_report("--flush-interval is only available in write tests");
4016 if (flush_interval
&& flush_interval
< depth
) {
4017 error_report("Flush interval can't be smaller than depth");
4022 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4029 image_size
= blk_getlength(blk
);
4030 if (image_size
< 0) {
4035 data
= (BenchData
) {
4037 .image_size
= image_size
,
4039 .step
= step
?: bufsize
,
4044 .flush_interval
= flush_interval
,
4045 .drain_on_flush
= drain_on_flush
,
4047 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4048 "(starting at offset %" PRId64
", step size %d)\n",
4049 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4050 data
.offset
, data
.step
);
4051 if (flush_interval
) {
4052 printf("Sending flush every %d requests\n", flush_interval
);
4055 buf_size
= data
.nrreq
* data
.bufsize
;
4056 data
.buf
= blk_blockalign(blk
, buf_size
);
4057 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4059 blk_register_buf(blk
, data
.buf
, buf_size
);
4061 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4062 for (i
= 0; i
< data
.nrreq
; i
++) {
4063 qemu_iovec_init(&data
.qiov
[i
], 1);
4064 qemu_iovec_add(&data
.qiov
[i
],
4065 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4068 gettimeofday(&t1
, NULL
);
4071 while (data
.n
> 0) {
4072 main_loop_wait(false);
4074 gettimeofday(&t2
, NULL
);
4076 printf("Run completed in %3.3f seconds.\n",
4077 (t2
.tv_sec
- t1
.tv_sec
)
4078 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4082 blk_unregister_buf(blk
, data
.buf
);
4084 qemu_vfree(data
.buf
);
4105 int bsz
; /* Block size */
4113 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4117 static int img_dd_bs(const char *arg
,
4118 struct DdIo
*in
, struct DdIo
*out
,
4125 if (res
<= 0 || res
> INT_MAX
) {
4126 error_report("invalid number: '%s'", arg
);
4129 in
->bsz
= out
->bsz
= res
;
4134 static int img_dd_count(const char *arg
,
4135 struct DdIo
*in
, struct DdIo
*out
,
4138 dd
->count
= cvtnum(arg
);
4140 if (dd
->count
< 0) {
4141 error_report("invalid number: '%s'", arg
);
4148 static int img_dd_if(const char *arg
,
4149 struct DdIo
*in
, struct DdIo
*out
,
4152 in
->filename
= g_strdup(arg
);
4157 static int img_dd_of(const char *arg
,
4158 struct DdIo
*in
, struct DdIo
*out
,
4161 out
->filename
= g_strdup(arg
);
4166 static int img_dd_skip(const char *arg
,
4167 struct DdIo
*in
, struct DdIo
*out
,
4170 in
->offset
= cvtnum(arg
);
4172 if (in
->offset
< 0) {
4173 error_report("invalid number: '%s'", arg
);
4180 static int img_dd(int argc
, char **argv
)
4185 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4186 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4187 QemuOpts
*opts
= NULL
;
4188 QemuOptsList
*create_opts
= NULL
;
4189 Error
*local_err
= NULL
;
4190 bool image_opts
= false;
4192 const char *out_fmt
= "raw";
4193 const char *fmt
= NULL
;
4195 int64_t block_count
= 0, out_pos
, in_pos
;
4196 bool force_share
= false;
4197 struct DdInfo dd
= {
4202 .bsz
= 512, /* Block size is by default 512 bytes */
4214 const struct DdOpts options
[] = {
4215 { "bs", img_dd_bs
, C_BS
},
4216 { "count", img_dd_count
, C_COUNT
},
4217 { "if", img_dd_if
, C_IF
},
4218 { "of", img_dd_of
, C_OF
},
4219 { "skip", img_dd_skip
, C_SKIP
},
4222 const struct option long_options
[] = {
4223 { "help", no_argument
, 0, 'h'},
4224 { "object", required_argument
, 0, OPTION_OBJECT
},
4225 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4226 { "force-share", no_argument
, 0, 'U'},
4230 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
4242 missing_argument(argv
[optind
- 1]);
4245 unrecognized_option(argv
[optind
- 1]);
4254 if (!qemu_opts_parse_noisily(&qemu_object_opts
, optarg
, true)) {
4259 case OPTION_IMAGE_OPTS
:
4265 for (i
= optind
; i
< argc
; i
++) {
4267 arg
= g_strdup(argv
[i
]);
4269 tmp
= strchr(arg
, '=');
4271 error_report("unrecognized operand %s", arg
);
4278 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4279 if (!strcmp(arg
, options
[j
].name
)) {
4283 if (options
[j
].name
== NULL
) {
4284 error_report("unrecognized operand %s", arg
);
4289 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4293 dd
.flags
|= options
[j
].flag
;
4298 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4299 error_report("Must specify both input and output files");
4304 if (qemu_opts_foreach(&qemu_object_opts
,
4305 user_creatable_add_opts_foreach
,
4311 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
4319 drv
= bdrv_find_format(out_fmt
);
4321 error_report("Unknown file format");
4325 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4328 error_report_err(local_err
);
4332 if (!drv
->create_opts
) {
4333 error_report("Format driver '%s' does not support image creation",
4338 if (!proto_drv
->create_opts
) {
4339 error_report("Protocol driver '%s' does not support image creation",
4340 proto_drv
->format_name
);
4344 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4345 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4347 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4349 size
= blk_getlength(blk1
);
4351 error_report("Failed to get size for '%s'", in
.filename
);
4356 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4357 dd
.count
* in
.bsz
< size
) {
4358 size
= dd
.count
* in
.bsz
;
4361 /* Overflow means the specified offset is beyond input image's size */
4362 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4363 size
< in
.bsz
* in
.offset
)) {
4364 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4366 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4367 size
- in
.bsz
* in
.offset
, &error_abort
);
4370 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4372 error_reportf_err(local_err
,
4373 "%s: error while creating output image: ",
4379 /* TODO, we can't honour --image-opts for the target,
4380 * since it needs to be given in a format compatible
4381 * with the bdrv_create() call above which does not
4382 * support image-opts style.
4384 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
4385 false, false, false);
4392 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4393 size
< in
.offset
* in
.bsz
)) {
4394 /* We give a warning if the skip option is bigger than the input
4395 * size and create an empty output disk image (i.e. like dd(1)).
4397 error_report("%s: cannot skip to specified offset", in
.filename
);
4400 in_pos
= in
.offset
* in
.bsz
;
4403 in
.buf
= g_new(uint8_t, in
.bsz
);
4405 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4406 int in_ret
, out_ret
;
4408 if (in_pos
+ in
.bsz
> size
) {
4409 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4411 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4414 error_report("error while reading from input image file: %s",
4421 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4424 error_report("error while writing to output image file: %s",
4425 strerror(-out_ret
));
4434 qemu_opts_del(opts
);
4435 qemu_opts_free(create_opts
);
4438 g_free(in
.filename
);
4439 g_free(out
.filename
);
4449 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
4453 Visitor
*v
= qobject_output_visitor_new(&obj
);
4455 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
4456 visit_complete(v
, &obj
);
4457 str
= qobject_to_json_pretty(obj
);
4458 assert(str
!= NULL
);
4459 printf("%s\n", qstring_get_str(str
));
4465 static int img_measure(int argc
, char **argv
)
4467 static const struct option long_options
[] = {
4468 {"help", no_argument
, 0, 'h'},
4469 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4470 {"object", required_argument
, 0, OPTION_OBJECT
},
4471 {"output", required_argument
, 0, OPTION_OUTPUT
},
4472 {"size", required_argument
, 0, OPTION_SIZE
},
4473 {"force-share", no_argument
, 0, 'U'},
4476 OutputFormat output_format
= OFORMAT_HUMAN
;
4477 BlockBackend
*in_blk
= NULL
;
4479 const char *filename
= NULL
;
4480 const char *fmt
= NULL
;
4481 const char *out_fmt
= "raw";
4482 char *options
= NULL
;
4483 char *snapshot_name
= NULL
;
4484 bool force_share
= false;
4485 QemuOpts
*opts
= NULL
;
4486 QemuOpts
*object_opts
= NULL
;
4487 QemuOpts
*sn_opts
= NULL
;
4488 QemuOptsList
*create_opts
= NULL
;
4489 bool image_opts
= false;
4490 uint64_t img_size
= UINT64_MAX
;
4491 BlockMeasureInfo
*info
= NULL
;
4492 Error
*local_err
= NULL
;
4496 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
4497 long_options
, NULL
)) != -1) {
4510 if (!is_valid_option_list(optarg
)) {
4511 error_report("Invalid option list: %s", optarg
);
4515 options
= g_strdup(optarg
);
4517 char *old_options
= options
;
4518 options
= g_strdup_printf("%s,%s", options
, optarg
);
4519 g_free(old_options
);
4523 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
4524 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
4527 error_report("Failed in parsing snapshot param '%s'",
4532 snapshot_name
= optarg
;
4539 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
4545 case OPTION_IMAGE_OPTS
:
4549 if (!strcmp(optarg
, "json")) {
4550 output_format
= OFORMAT_JSON
;
4551 } else if (!strcmp(optarg
, "human")) {
4552 output_format
= OFORMAT_HUMAN
;
4554 error_report("--output must be used with human or json "
4563 sval
= cvtnum(optarg
);
4565 if (sval
== -ERANGE
) {
4566 error_report("Image size must be less than 8 EiB!");
4568 error_report("Invalid image size specified! You may use "
4569 "k, M, G, T, P or E suffixes for ");
4570 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4571 "petabytes and exabytes.");
4575 img_size
= (uint64_t)sval
;
4581 if (qemu_opts_foreach(&qemu_object_opts
,
4582 user_creatable_add_opts_foreach
,
4587 if (argc
- optind
> 1) {
4588 error_report("At most one filename argument is allowed.");
4590 } else if (argc
- optind
== 1) {
4591 filename
= argv
[optind
];
4595 (object_opts
|| image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
4596 error_report("--object, --image-opts, -f, and -l "
4597 "require a filename argument.");
4600 if (filename
&& img_size
!= UINT64_MAX
) {
4601 error_report("--size N cannot be used together with a filename.");
4604 if (!filename
&& img_size
== UINT64_MAX
) {
4605 error_report("Either --size N or one filename must be specified.");
4610 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
4611 false, false, force_share
);
4617 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
4618 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
4619 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
4621 } else if (snapshot_name
!= NULL
) {
4622 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
4623 snapshot_name
, &local_err
);
4626 error_reportf_err(local_err
, "Failed to load snapshot: ");
4631 drv
= bdrv_find_format(out_fmt
);
4633 error_report("Unknown file format '%s'", out_fmt
);
4636 if (!drv
->create_opts
) {
4637 error_report("Format driver '%s' does not support image creation",
4642 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4643 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
4644 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4646 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
4648 error_report_err(local_err
);
4649 error_report("Invalid options for file format '%s'", out_fmt
);
4653 if (img_size
!= UINT64_MAX
) {
4654 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
4657 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
4659 error_report_err(local_err
);
4663 if (output_format
== OFORMAT_HUMAN
) {
4664 printf("required size: %" PRIu64
"\n", info
->required
);
4665 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
4667 dump_json_block_measure_info(info
);
4673 qapi_free_BlockMeasureInfo(info
);
4674 qemu_opts_del(object_opts
);
4675 qemu_opts_del(opts
);
4676 qemu_opts_del(sn_opts
);
4677 qemu_opts_free(create_opts
);
4683 static const img_cmd_t img_cmds
[] = {
4684 #define DEF(option, callback, arg_string) \
4685 { option, callback },
4686 #include "qemu-img-cmds.h"
4692 int main(int argc
, char **argv
)
4694 const img_cmd_t
*cmd
;
4695 const char *cmdname
;
4696 Error
*local_error
= NULL
;
4697 char *trace_file
= NULL
;
4699 static const struct option long_options
[] = {
4700 {"help", no_argument
, 0, 'h'},
4701 {"version", no_argument
, 0, 'V'},
4702 {"trace", required_argument
, NULL
, 'T'},
4707 signal(SIGPIPE
, SIG_IGN
);
4710 module_call_init(MODULE_INIT_TRACE
);
4711 error_set_progname(argv
[0]);
4712 qemu_init_exec_dir(argv
[0]);
4714 if (qemu_init_main_loop(&local_error
)) {
4715 error_report_err(local_error
);
4719 qcrypto_init(&error_fatal
);
4721 module_call_init(MODULE_INIT_QOM
);
4724 error_exit("Not enough arguments");
4727 qemu_add_opts(&qemu_object_opts
);
4728 qemu_add_opts(&qemu_source_opts
);
4729 qemu_add_opts(&qemu_trace_opts
);
4731 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4734 missing_argument(argv
[optind
- 1]);
4737 unrecognized_option(argv
[optind
- 1]);
4743 printf(QEMU_IMG_VERSION
);
4747 trace_file
= trace_opt_parse(optarg
);
4752 cmdname
= argv
[optind
];
4754 /* reset getopt_long scanning */
4762 if (!trace_init_backends()) {
4765 trace_init_file(trace_file
);
4766 qemu_set_log(LOG_TRACE
);
4768 /* find the command */
4769 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4770 if (!strcmp(cmdname
, cmd
->name
)) {
4771 return cmd
->handler(argc
, argv
);
4776 error_exit("Command not found: %s", cmdname
);