2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi-visit.h"
28 #include "qapi/qobject-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qemu/cutils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
36 #include "qom/object_interfaces.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/block-backend.h"
39 #include "block/block_int.h"
40 #include "block/blockjob.h"
41 #include "block/qapi.h"
42 #include "crypto/init.h"
43 #include "trace/control.h"
46 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
47 "\n" QEMU_COPYRIGHT "\n"
49 typedef struct img_cmd_t
{
51 int (*handler
)(int argc
, char **argv
);
56 OPTION_BACKING_CHAIN
= 257,
58 OPTION_IMAGE_OPTS
= 259,
60 OPTION_FLUSH_INTERVAL
= 261,
61 OPTION_NO_DRAIN
= 262,
64 typedef enum OutputFormat
{
69 /* Default to cache=writeback as data integrity is not important for qemu-img */
70 #define BDRV_DEFAULT_CACHE "writeback"
72 static void format_print(void *opaque
, const char *name
)
77 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
81 error_printf("qemu-img: ");
84 error_vprintf(fmt
, ap
);
87 error_printf("\nTry 'qemu-img --help' for more information\n");
91 static void QEMU_NORETURN
missing_argument(const char *option
)
93 error_exit("missing argument for option '%s'", option
);
96 static void QEMU_NORETURN
unrecognized_option(const char *option
)
98 error_exit("unrecognized option '%s'", option
);
101 /* Please keep in synch with qemu-img.texi */
102 static void QEMU_NORETURN
help(void)
104 const char *help_msg
=
106 "usage: qemu-img [standard options] command [command options]\n"
107 "QEMU disk image utility\n"
109 " '-h', '--help' display this help and exit\n"
110 " '-V', '--version' output version information and exit\n"
111 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
112 " specify tracing options\n"
115 #define DEF(option, callback, arg_string) \
117 #include "qemu-img-cmds.h"
121 "Command parameters:\n"
122 " 'filename' is a disk image filename\n"
123 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
124 " manual page for a description of the object properties. The most common\n"
125 " object type is a 'secret', which is used to supply passwords and/or\n"
126 " encryption keys.\n"
127 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
128 " 'cache' is the cache mode used to write the output disk image, the valid\n"
129 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
130 " 'directsync' and 'unsafe' (default for convert)\n"
131 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
132 " options are the same as for the 'cache' option\n"
133 " 'size' is the disk image size in bytes. Optional suffixes\n"
134 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
135 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
136 " supported. 'b' is ignored.\n"
137 " 'output_filename' is the destination disk image filename\n"
138 " 'output_fmt' is the destination format\n"
139 " 'options' is a comma separated list of format specific options in a\n"
140 " name=value format. Use -o ? for an overview of the options supported by the\n"
142 " 'snapshot_param' is param used for internal snapshot, format\n"
143 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
145 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
147 " '-c' indicates that target image must be compressed (qcow format only)\n"
148 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
149 " match exactly. The image doesn't need a working backing file before\n"
150 " rebasing in this case (useful for renaming the backing file)\n"
151 " '-h' with or without a command shows this help and lists the supported formats\n"
152 " '-p' show progress of command (only certain commands)\n"
153 " '-q' use Quiet mode - do not print any output (except errors)\n"
154 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
155 " contain only zeros for qemu-img to create a sparse image during\n"
156 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
157 " unallocated or zero sectors, and the destination image will always be\n"
159 " '--output' takes the format in which the output must be done (human or json)\n"
160 " '-n' skips the target volume creation (useful if the volume is created\n"
161 " prior to running qemu-img)\n"
163 "Parameters to check subcommand:\n"
164 " '-r' tries to repair any inconsistencies that are found during the check.\n"
165 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
166 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
167 " hiding corruption that has already occurred.\n"
169 "Parameters to convert subcommand:\n"
170 " '-m' specifies how many coroutines work in parallel during the convert\n"
171 " process (defaults to 8)\n"
172 " '-W' allow to write to the target out of order rather than sequential\n"
174 "Parameters to snapshot subcommand:\n"
175 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
176 " '-a' applies a snapshot (revert disk to saved state)\n"
177 " '-c' creates a snapshot\n"
178 " '-d' deletes a snapshot\n"
179 " '-l' lists all snapshots in the given image\n"
181 "Parameters to compare subcommand:\n"
182 " '-f' first image format\n"
183 " '-F' second image format\n"
184 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
186 "Parameters to dd subcommand:\n"
187 " 'bs=BYTES' read and write up to BYTES bytes at a time "
189 " 'count=N' copy only N input blocks\n"
190 " 'if=FILE' read from FILE\n"
191 " 'of=FILE' write to FILE\n"
192 " 'skip=N' skip N bs-sized blocks at the start of input\n";
194 printf("%s\nSupported formats:", help_msg
);
195 bdrv_iterate_format(format_print
, NULL
);
200 static QemuOptsList qemu_object_opts
= {
202 .implied_opt_name
= "qom-type",
203 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
209 static QemuOptsList qemu_source_opts
= {
211 .implied_opt_name
= "file",
212 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
218 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
224 ret
= vprintf(fmt
, args
);
231 static int print_block_option_help(const char *filename
, const char *fmt
)
233 BlockDriver
*drv
, *proto_drv
;
234 QemuOptsList
*create_opts
= NULL
;
235 Error
*local_err
= NULL
;
237 /* Find driver and parse its options */
238 drv
= bdrv_find_format(fmt
);
240 error_report("Unknown file format '%s'", fmt
);
244 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
246 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
248 error_report_err(local_err
);
249 qemu_opts_free(create_opts
);
252 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
255 qemu_opts_print_help(create_opts
);
256 qemu_opts_free(create_opts
);
261 static int img_open_password(BlockBackend
*blk
, const char *filename
,
262 int flags
, bool quiet
)
264 BlockDriverState
*bs
;
268 if (bdrv_is_encrypted(bs
) && bdrv_key_required(bs
) &&
269 !(flags
& BDRV_O_NO_IO
)) {
270 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
271 if (qemu_read_password(password
, sizeof(password
)) < 0) {
272 error_report("No password given");
275 if (bdrv_set_key(bs
, password
) < 0) {
276 error_report("invalid password");
284 static BlockBackend
*img_open_opts(const char *optstr
,
285 QemuOpts
*opts
, int flags
, bool writethrough
,
289 Error
*local_err
= NULL
;
291 options
= qemu_opts_to_qdict(opts
, NULL
);
292 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
294 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
297 blk_set_enable_write_cache(blk
, !writethrough
);
299 if (img_open_password(blk
, optstr
, flags
, quiet
) < 0) {
306 static BlockBackend
*img_open_file(const char *filename
,
307 const char *fmt
, int flags
,
308 bool writethrough
, bool quiet
)
311 Error
*local_err
= NULL
;
312 QDict
*options
= NULL
;
315 options
= qdict_new();
316 qdict_put_str(options
, "driver", fmt
);
319 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
321 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
324 blk_set_enable_write_cache(blk
, !writethrough
);
326 if (img_open_password(blk
, filename
, flags
, quiet
) < 0) {
334 static BlockBackend
*img_open(bool image_opts
,
335 const char *filename
,
336 const char *fmt
, int flags
, bool writethrough
,
343 error_report("--image-opts and --format are mutually exclusive");
346 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
351 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
);
353 blk
= img_open_file(filename
, fmt
, flags
, writethrough
, quiet
);
359 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
360 const char *base_filename
,
361 const char *base_fmt
)
366 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
368 error_report("Backing file not supported for file format '%s'",
375 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
377 error_report("Backing file format not supported for file "
386 static int64_t cvtnum(const char *s
)
391 err
= qemu_strtosz(s
, NULL
, &value
);
395 if (value
> INT64_MAX
) {
401 static int img_create(int argc
, char **argv
)
404 uint64_t img_size
= -1;
405 const char *fmt
= "raw";
406 const char *base_fmt
= NULL
;
407 const char *filename
;
408 const char *base_filename
= NULL
;
409 char *options
= NULL
;
410 Error
*local_err
= NULL
;
414 static const struct option long_options
[] = {
415 {"help", no_argument
, 0, 'h'},
416 {"object", required_argument
, 0, OPTION_OBJECT
},
419 c
= getopt_long(argc
, argv
, ":F:b:f:he6o:q",
426 missing_argument(argv
[optind
- 1]);
429 unrecognized_option(argv
[optind
- 1]);
438 base_filename
= optarg
;
444 error_report("option -e is deprecated, please use \'-o "
445 "encryption\' instead!");
448 error_report("option -6 is deprecated, please use \'-o "
449 "compat6\' instead!");
452 if (!is_valid_option_list(optarg
)) {
453 error_report("Invalid option list: %s", optarg
);
457 options
= g_strdup(optarg
);
459 char *old_options
= options
;
460 options
= g_strdup_printf("%s,%s", options
, optarg
);
467 case OPTION_OBJECT
: {
469 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
478 /* Get the filename */
479 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
480 if (options
&& has_help_option(options
)) {
482 return print_block_option_help(filename
, fmt
);
485 if (optind
>= argc
) {
486 error_exit("Expecting image file name");
490 if (qemu_opts_foreach(&qemu_object_opts
,
491 user_creatable_add_opts_foreach
,
496 /* Get image size, if specified */
500 sval
= cvtnum(argv
[optind
++]);
502 if (sval
== -ERANGE
) {
503 error_report("Image size must be less than 8 EiB!");
505 error_report("Invalid image size specified! You may use k, M, "
506 "G, T, P or E suffixes for ");
507 error_report("kilobytes, megabytes, gigabytes, terabytes, "
508 "petabytes and exabytes.");
512 img_size
= (uint64_t)sval
;
514 if (optind
!= argc
) {
515 error_exit("Unexpected argument: %s", argv
[optind
]);
518 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
519 options
, img_size
, 0, &local_err
, quiet
);
521 error_reportf_err(local_err
, "%s: ", filename
);
533 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
537 Visitor
*v
= qobject_output_visitor_new(&obj
);
539 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
540 visit_complete(v
, &obj
);
541 str
= qobject_to_json_pretty(obj
);
543 qprintf(quiet
, "%s\n", qstring_get_str(str
));
549 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
551 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
552 qprintf(quiet
, "No errors were found on the image.\n");
554 if (check
->corruptions
) {
555 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
556 "Data may be corrupted, or further writes to the image "
563 "\n%" PRId64
" leaked clusters were found on the image.\n"
564 "This means waste of disk space, but no harm to data.\n",
568 if (check
->check_errors
) {
571 " internal errors have occurred during the check.\n",
572 check
->check_errors
);
576 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
577 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
578 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
579 check
->allocated_clusters
, check
->total_clusters
,
580 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
581 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
582 check
->compressed_clusters
* 100.0 /
583 check
->allocated_clusters
);
586 if (check
->image_end_offset
) {
588 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
592 static int collect_image_check(BlockDriverState
*bs
,
594 const char *filename
,
599 BdrvCheckResult result
;
601 ret
= bdrv_check(bs
, &result
, fix
);
606 check
->filename
= g_strdup(filename
);
607 check
->format
= g_strdup(bdrv_get_format_name(bs
));
608 check
->check_errors
= result
.check_errors
;
609 check
->corruptions
= result
.corruptions
;
610 check
->has_corruptions
= result
.corruptions
!= 0;
611 check
->leaks
= result
.leaks
;
612 check
->has_leaks
= result
.leaks
!= 0;
613 check
->corruptions_fixed
= result
.corruptions_fixed
;
614 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
615 check
->leaks_fixed
= result
.leaks_fixed
;
616 check
->has_leaks_fixed
= result
.leaks
!= 0;
617 check
->image_end_offset
= result
.image_end_offset
;
618 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
619 check
->total_clusters
= result
.bfi
.total_clusters
;
620 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
621 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
622 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
623 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
624 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
625 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
626 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
632 * Checks an image for consistency. Exit codes:
634 * 0 - Check completed, image is good
635 * 1 - Check not completed because of internal errors
636 * 2 - Check completed, image is corrupted
637 * 3 - Check completed, image has leaked clusters, but is good otherwise
638 * 63 - Checks are not supported by the image format
640 static int img_check(int argc
, char **argv
)
643 OutputFormat output_format
= OFORMAT_HUMAN
;
644 const char *filename
, *fmt
, *output
, *cache
;
646 BlockDriverState
*bs
;
648 int flags
= BDRV_O_CHECK
;
652 bool image_opts
= false;
656 cache
= BDRV_DEFAULT_CACHE
;
659 int option_index
= 0;
660 static const struct option long_options
[] = {
661 {"help", no_argument
, 0, 'h'},
662 {"format", required_argument
, 0, 'f'},
663 {"repair", required_argument
, 0, 'r'},
664 {"output", required_argument
, 0, OPTION_OUTPUT
},
665 {"object", required_argument
, 0, OPTION_OBJECT
},
666 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
669 c
= getopt_long(argc
, argv
, ":hf:r:T:q",
670 long_options
, &option_index
);
676 missing_argument(argv
[optind
- 1]);
679 unrecognized_option(argv
[optind
- 1]);
688 flags
|= BDRV_O_RDWR
;
690 if (!strcmp(optarg
, "leaks")) {
691 fix
= BDRV_FIX_LEAKS
;
692 } else if (!strcmp(optarg
, "all")) {
693 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
695 error_exit("Unknown option value for -r "
696 "(expecting 'leaks' or 'all'): %s", optarg
);
708 case OPTION_OBJECT
: {
710 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
716 case OPTION_IMAGE_OPTS
:
721 if (optind
!= argc
- 1) {
722 error_exit("Expecting one image file name");
724 filename
= argv
[optind
++];
726 if (output
&& !strcmp(output
, "json")) {
727 output_format
= OFORMAT_JSON
;
728 } else if (output
&& !strcmp(output
, "human")) {
729 output_format
= OFORMAT_HUMAN
;
731 error_report("--output must be used with human or json as argument.");
735 if (qemu_opts_foreach(&qemu_object_opts
,
736 user_creatable_add_opts_foreach
,
741 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
743 error_report("Invalid source cache option: %s", cache
);
747 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
753 check
= g_new0(ImageCheck
, 1);
754 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
756 if (ret
== -ENOTSUP
) {
757 error_report("This image format does not support checks");
762 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
763 int corruptions_fixed
, leaks_fixed
;
765 leaks_fixed
= check
->leaks_fixed
;
766 corruptions_fixed
= check
->corruptions_fixed
;
768 if (output_format
== OFORMAT_HUMAN
) {
770 "The following inconsistencies were found and repaired:\n\n"
771 " %" PRId64
" leaked clusters\n"
772 " %" PRId64
" corruptions\n\n"
773 "Double checking the fixed image now...\n",
775 check
->corruptions_fixed
);
778 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
780 check
->leaks_fixed
= leaks_fixed
;
781 check
->corruptions_fixed
= corruptions_fixed
;
785 switch (output_format
) {
787 dump_human_image_check(check
, quiet
);
790 dump_json_image_check(check
, quiet
);
795 if (ret
|| check
->check_errors
) {
797 error_report("Check failed: %s", strerror(-ret
));
799 error_report("Check failed");
805 if (check
->corruptions
) {
807 } else if (check
->leaks
) {
814 qapi_free_ImageCheck(check
);
819 typedef struct CommonBlockJobCBInfo
{
820 BlockDriverState
*bs
;
822 } CommonBlockJobCBInfo
;
824 static void common_block_job_cb(void *opaque
, int ret
)
826 CommonBlockJobCBInfo
*cbi
= opaque
;
829 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
833 static void run_block_job(BlockJob
*job
, Error
**errp
)
835 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
837 /* FIXME In error cases, the job simply goes away and we access a dangling
839 aio_context_acquire(aio_context
);
841 aio_poll(aio_context
, true);
842 qemu_progress_print(job
->len
?
843 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
844 } while (!job
->ready
);
846 block_job_complete_sync(job
, errp
);
847 aio_context_release(aio_context
);
849 /* A block job may finish instantaneously without publishing any progress,
850 * so just signal completion here */
851 qemu_progress_print(100.f
, 0);
854 static int img_commit(int argc
, char **argv
)
857 const char *filename
, *fmt
, *cache
, *base
;
859 BlockDriverState
*bs
, *base_bs
;
861 bool progress
= false, quiet
= false, drop
= false;
863 Error
*local_err
= NULL
;
864 CommonBlockJobCBInfo cbi
;
865 bool image_opts
= false;
866 AioContext
*aio_context
;
869 cache
= BDRV_DEFAULT_CACHE
;
872 static const struct option long_options
[] = {
873 {"help", no_argument
, 0, 'h'},
874 {"object", required_argument
, 0, OPTION_OBJECT
},
875 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
878 c
= getopt_long(argc
, argv
, ":f:ht:b:dpq",
885 missing_argument(argv
[optind
- 1]);
888 unrecognized_option(argv
[optind
- 1]);
913 case OPTION_OBJECT
: {
915 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
921 case OPTION_IMAGE_OPTS
:
927 /* Progress is not shown in Quiet mode */
932 if (optind
!= argc
- 1) {
933 error_exit("Expecting one image file name");
935 filename
= argv
[optind
++];
937 if (qemu_opts_foreach(&qemu_object_opts
,
938 user_creatable_add_opts_foreach
,
943 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
944 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
946 error_report("Invalid cache option: %s", cache
);
950 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
956 qemu_progress_init(progress
, 1.f
);
957 qemu_progress_print(0.f
, 100);
960 base_bs
= bdrv_find_backing_image(bs
, base
);
962 error_setg(&local_err
,
963 "Did not find '%s' in the backing chain of '%s'",
968 /* This is different from QMP, which by default uses the deepest file in
969 * the backing chain (i.e., the very base); however, the traditional
970 * behavior of qemu-img commit is using the immediate backing file. */
971 base_bs
= backing_bs(bs
);
973 error_setg(&local_err
, "Image does not have a backing file");
978 cbi
= (CommonBlockJobCBInfo
){
983 aio_context
= bdrv_get_aio_context(bs
);
984 aio_context_acquire(aio_context
);
985 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
986 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
987 &cbi
, &local_err
, false);
988 aio_context_release(aio_context
);
993 /* When the block job completes, the BlockBackend reference will point to
994 * the old backing file. In order to avoid that the top image is already
995 * deleted, so we can still empty it afterwards, increment the reference
996 * counter here preemptively. */
1001 job
= block_job_get("commit");
1002 run_block_job(job
, &local_err
);
1007 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
1008 ret
= bs
->drv
->bdrv_make_empty(bs
);
1010 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1022 qemu_progress_end();
1027 error_report_err(local_err
);
1031 qprintf(quiet
, "Image committed.\n");
1036 * Returns true iff the first sector pointed to by 'buf' contains at least
1039 * 'pnum' is set to the number of sectors (including and immediately following
1040 * the first one) that are known to be in the same allocated/unallocated state.
1042 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1051 is_zero
= buffer_is_zero(buf
, 512);
1052 for(i
= 1; i
< n
; i
++) {
1054 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1063 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1064 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1065 * breaking up write requests for only small sparse areas.
1067 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1071 int num_checked
, num_used
;
1077 ret
= is_allocated_sectors(buf
, n
, pnum
);
1083 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1085 num_checked
= num_used
;
1088 ret
= is_allocated_sectors(buf
, n
, pnum
);
1090 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1092 num_checked
+= *pnum
;
1094 num_used
= num_checked
;
1095 } else if (*pnum
>= min
) {
1105 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1106 * buffers matches, non-zero otherwise.
1108 * pnum is set to the number of sectors (including and immediately following
1109 * the first one) that are known to have the same comparison result
1111 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1122 res
= !!memcmp(buf1
, buf2
, 512);
1123 for(i
= 1; i
< n
; i
++) {
1127 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1136 #define IO_BUF_SIZE (2 * 1024 * 1024)
1138 static int64_t sectors_to_bytes(int64_t sectors
)
1140 return sectors
<< BDRV_SECTOR_BITS
;
1143 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1145 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1149 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1151 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1152 * data and negative value on error.
1154 * @param blk: BlockBackend for the image
1155 * @param sect_num: Number of first sector to check
1156 * @param sect_count: Number of sectors to check
1157 * @param filename: Name of disk file we are checking (logging purpose)
1158 * @param buffer: Allocated buffer for storing read data
1159 * @param quiet: Flag for quiet mode
1161 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1162 int sect_count
, const char *filename
,
1163 uint8_t *buffer
, bool quiet
)
1166 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1167 sect_count
<< BDRV_SECTOR_BITS
);
1169 error_report("Error while reading offset %" PRId64
" of %s: %s",
1170 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1173 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1174 if (ret
|| pnum
!= sect_count
) {
1175 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1176 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1184 * Compares two images. Exit codes:
1186 * 0 - Images are identical
1188 * >1 - Error occurred
1190 static int img_compare(int argc
, char **argv
)
1192 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1193 BlockBackend
*blk1
, *blk2
;
1194 BlockDriverState
*bs1
, *bs2
;
1195 int64_t total_sectors1
, total_sectors2
;
1196 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1198 int allocated1
, allocated2
;
1199 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1200 bool progress
= false, quiet
= false, strict
= false;
1203 int64_t total_sectors
;
1204 int64_t sector_num
= 0;
1207 uint64_t progress_base
;
1208 bool image_opts
= false;
1210 cache
= BDRV_DEFAULT_CACHE
;
1212 static const struct option long_options
[] = {
1213 {"help", no_argument
, 0, 'h'},
1214 {"object", required_argument
, 0, OPTION_OBJECT
},
1215 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1218 c
= getopt_long(argc
, argv
, ":hf:F:T:pqs",
1219 long_options
, NULL
);
1225 missing_argument(argv
[optind
- 1]);
1228 unrecognized_option(argv
[optind
- 1]);
1251 case OPTION_OBJECT
: {
1253 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1260 case OPTION_IMAGE_OPTS
:
1266 /* Progress is not shown in Quiet mode */
1272 if (optind
!= argc
- 2) {
1273 error_exit("Expecting two image file names");
1275 filename1
= argv
[optind
++];
1276 filename2
= argv
[optind
++];
1278 if (qemu_opts_foreach(&qemu_object_opts
,
1279 user_creatable_add_opts_foreach
,
1285 /* Initialize before goto out */
1286 qemu_progress_init(progress
, 2.0);
1289 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1291 error_report("Invalid source cache option: %s", cache
);
1296 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
);
1302 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
);
1310 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1311 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1312 total_sectors1
= blk_nb_sectors(blk1
);
1313 if (total_sectors1
< 0) {
1314 error_report("Can't get size of %s: %s",
1315 filename1
, strerror(-total_sectors1
));
1319 total_sectors2
= blk_nb_sectors(blk2
);
1320 if (total_sectors2
< 0) {
1321 error_report("Can't get size of %s: %s",
1322 filename2
, strerror(-total_sectors2
));
1326 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1327 progress_base
= MAX(total_sectors1
, total_sectors2
);
1329 qemu_progress_print(0, 100);
1331 if (strict
&& total_sectors1
!= total_sectors2
) {
1333 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1338 int64_t status1
, status2
;
1339 BlockDriverState
*file
;
1341 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1342 if (nb_sectors
<= 0) {
1345 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1346 total_sectors1
- sector_num
,
1350 error_report("Sector allocation test failed for %s", filename1
);
1353 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1355 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1356 total_sectors2
- sector_num
,
1360 error_report("Sector allocation test failed for %s", filename2
);
1363 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1365 nb_sectors
= MIN(nb_sectors
, pnum1
);
1368 nb_sectors
= MIN(nb_sectors
, pnum2
);
1372 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1373 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1375 qprintf(quiet
, "Strict mode: Offset %" PRId64
1376 " block status mismatch!\n",
1377 sectors_to_bytes(sector_num
));
1381 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1382 nb_sectors
= MIN(pnum1
, pnum2
);
1383 } else if (allocated1
== allocated2
) {
1385 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1386 nb_sectors
<< BDRV_SECTOR_BITS
);
1388 error_report("Error while reading offset %" PRId64
" of %s:"
1389 " %s", sectors_to_bytes(sector_num
), filename1
,
1394 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1395 nb_sectors
<< BDRV_SECTOR_BITS
);
1397 error_report("Error while reading offset %" PRId64
1398 " of %s: %s", sectors_to_bytes(sector_num
),
1399 filename2
, strerror(-ret
));
1403 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1404 if (ret
|| pnum
!= nb_sectors
) {
1405 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1407 ret
? sector_num
: sector_num
+ pnum
));
1415 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1416 filename1
, buf1
, quiet
);
1418 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1419 filename2
, buf1
, quiet
);
1423 error_report("Error while reading offset %" PRId64
": %s",
1424 sectors_to_bytes(sector_num
), strerror(-ret
));
1430 sector_num
+= nb_sectors
;
1431 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1434 if (total_sectors1
!= total_sectors2
) {
1435 BlockBackend
*blk_over
;
1436 int64_t total_sectors_over
;
1437 const char *filename_over
;
1439 qprintf(quiet
, "Warning: Image size mismatch!\n");
1440 if (total_sectors1
> total_sectors2
) {
1441 total_sectors_over
= total_sectors1
;
1443 filename_over
= filename1
;
1445 total_sectors_over
= total_sectors2
;
1447 filename_over
= filename2
;
1451 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1452 if (nb_sectors
<= 0) {
1455 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
, sector_num
,
1459 error_report("Sector allocation test failed for %s",
1466 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1467 filename_over
, buf1
, quiet
);
1470 error_report("Error while reading offset %" PRId64
1471 " of %s: %s", sectors_to_bytes(sector_num
),
1472 filename_over
, strerror(-ret
));
1478 sector_num
+= nb_sectors
;
1479 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1483 qprintf(quiet
, "Images are identical.\n");
1493 qemu_progress_end();
1498 enum ImgConvertBlockStatus
{
1504 #define MAX_COROUTINES 16
1506 typedef struct ImgConvertState
{
1508 int64_t *src_sectors
;
1510 int64_t total_sectors
;
1511 int64_t allocated_sectors
;
1512 int64_t allocated_done
;
1515 enum ImgConvertBlockStatus status
;
1516 int64_t sector_next_status
;
1517 BlockBackend
*target
;
1520 bool target_has_backing
;
1523 size_t cluster_sectors
;
1526 int running_coroutines
;
1527 Coroutine
*co
[MAX_COROUTINES
];
1528 int64_t wait_sector_num
[MAX_COROUTINES
];
1533 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1534 int *src_cur
, int64_t *src_cur_offset
)
1537 *src_cur_offset
= 0;
1538 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1539 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1541 assert(*src_cur
< s
->src_num
);
1545 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1547 int64_t ret
, src_cur_offset
;
1550 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1552 assert(s
->total_sectors
> sector_num
);
1553 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1555 if (s
->sector_next_status
<= sector_num
) {
1556 BlockDriverState
*file
;
1557 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1558 sector_num
- src_cur_offset
,
1564 if (ret
& BDRV_BLOCK_ZERO
) {
1565 s
->status
= BLK_ZERO
;
1566 } else if (ret
& BDRV_BLOCK_DATA
) {
1567 s
->status
= BLK_DATA
;
1568 } else if (!s
->target_has_backing
) {
1569 /* Without a target backing file we must copy over the contents of
1570 * the backing file as well. */
1571 /* Check block status of the backing file chain to avoid
1572 * needlessly reading zeroes and limiting the iteration to the
1574 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1575 sector_num
- src_cur_offset
,
1581 if (ret
& BDRV_BLOCK_ZERO
) {
1582 s
->status
= BLK_ZERO
;
1584 s
->status
= BLK_DATA
;
1587 s
->status
= BLK_BACKING_FILE
;
1590 s
->sector_next_status
= sector_num
+ n
;
1593 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1594 if (s
->status
== BLK_DATA
) {
1595 n
= MIN(n
, s
->buf_sectors
);
1598 /* We need to write complete clusters for compressed images, so if an
1599 * unallocated area is shorter than that, we must consider the whole
1600 * cluster allocated. */
1601 if (s
->compressed
) {
1602 if (n
< s
->cluster_sectors
) {
1603 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1604 s
->status
= BLK_DATA
;
1606 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1613 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1614 int nb_sectors
, uint8_t *buf
)
1620 assert(nb_sectors
<= s
->buf_sectors
);
1621 while (nb_sectors
> 0) {
1624 int64_t bs_sectors
, src_cur_offset
;
1626 /* In the case of compression with multiple source files, we can get a
1627 * nb_sectors that spreads into the next part. So we must be able to
1628 * read across multiple BDSes for one convert_read() call. */
1629 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1630 blk
= s
->src
[src_cur
];
1631 bs_sectors
= s
->src_sectors
[src_cur
];
1633 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1635 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1636 qemu_iovec_init_external(&qiov
, &iov
, 1);
1638 ret
= blk_co_preadv(
1639 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1640 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1647 buf
+= n
* BDRV_SECTOR_SIZE
;
1654 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1655 int nb_sectors
, uint8_t *buf
,
1656 enum ImgConvertBlockStatus status
)
1662 while (nb_sectors
> 0) {
1665 case BLK_BACKING_FILE
:
1666 /* If we have a backing file, leave clusters unallocated that are
1667 * unallocated in the source image, so that the backing file is
1668 * visible at the respective offset. */
1669 assert(s
->target_has_backing
);
1673 /* We must always write compressed clusters as a whole, so don't
1674 * try to find zeroed parts in the buffer. We can only save the
1675 * write if the buffer is completely zeroed and we're allowed to
1676 * keep the target sparse. */
1677 if (s
->compressed
) {
1678 if (s
->has_zero_init
&& s
->min_sparse
&&
1679 buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
))
1681 assert(!s
->target_has_backing
);
1686 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1687 qemu_iovec_init_external(&qiov
, &iov
, 1);
1689 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1690 n
<< BDRV_SECTOR_BITS
, &qiov
,
1691 BDRV_REQ_WRITE_COMPRESSED
);
1698 /* If there is real non-zero data or we're told to keep the target
1699 * fully allocated (-S 0), we must write it. Otherwise we can treat
1700 * it as zero sectors. */
1701 if (!s
->min_sparse
||
1702 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
))
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
, 0);
1718 if (s
->has_zero_init
) {
1721 ret
= blk_co_pwrite_zeroes(s
->target
,
1722 sector_num
<< BDRV_SECTOR_BITS
,
1723 n
<< BDRV_SECTOR_BITS
, 0);
1732 buf
+= n
* BDRV_SECTOR_SIZE
;
1738 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1740 ImgConvertState
*s
= opaque
;
1741 uint8_t *buf
= NULL
;
1745 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1746 if (s
->co
[i
] == qemu_coroutine_self()) {
1753 s
->running_coroutines
++;
1754 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1759 enum ImgConvertBlockStatus status
;
1761 qemu_co_mutex_lock(&s
->lock
);
1762 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1763 qemu_co_mutex_unlock(&s
->lock
);
1766 n
= convert_iteration_sectors(s
, s
->sector_num
);
1768 qemu_co_mutex_unlock(&s
->lock
);
1772 /* save current sector and allocation status to local variables */
1773 sector_num
= s
->sector_num
;
1775 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1776 n
= MIN(n
, s
->buf_sectors
);
1778 /* increment global sector counter so that other coroutines can
1779 * already continue reading beyond this request */
1781 qemu_co_mutex_unlock(&s
->lock
);
1783 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1784 s
->allocated_done
+= n
;
1785 qemu_progress_print(100.0 * s
->allocated_done
/
1786 s
->allocated_sectors
, 0);
1789 if (status
== BLK_DATA
) {
1790 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1792 error_report("error while reading sector %" PRId64
1793 ": %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
) {
1805 if (s
->ret
!= -EINPROGRESS
) {
1808 s
->wait_sector_num
[index
] = sector_num
;
1809 qemu_coroutine_yield();
1811 s
->wait_sector_num
[index
] = -1;
1814 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1816 error_report("error while writing sector %" PRId64
1817 ": %s", sector_num
, strerror(-ret
));
1822 if (s
->wr_in_order
) {
1823 /* reenter the coroutine that might have waited
1824 * for this write to complete */
1825 s
->wr_offs
= sector_num
+ n
;
1826 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1827 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1829 * A -> B -> A cannot occur because A has
1830 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1831 * B will never enter A during this time window.
1833 qemu_coroutine_enter(s
->co
[i
]);
1842 s
->co
[index
] = NULL
;
1843 s
->running_coroutines
--;
1844 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1845 /* the convert job finished successfully */
1850 static int convert_do_copy(ImgConvertState
*s
)
1853 int64_t sector_num
= 0;
1855 /* Check whether we have zero initialisation or can get it efficiently */
1856 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1857 ? bdrv_has_zero_init(blk_bs(s
->target
))
1860 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1861 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1863 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1865 s
->has_zero_init
= true;
1869 /* Allocate buffer for copied data. For compressed images, only one cluster
1870 * can be copied at a time. */
1871 if (s
->compressed
) {
1872 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1873 error_report("invalid cluster size");
1876 s
->buf_sectors
= s
->cluster_sectors
;
1879 while (sector_num
< s
->total_sectors
) {
1880 n
= convert_iteration_sectors(s
, sector_num
);
1884 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1886 s
->allocated_sectors
+= n
;
1892 s
->sector_next_status
= 0;
1893 s
->ret
= -EINPROGRESS
;
1895 qemu_co_mutex_init(&s
->lock
);
1896 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1897 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1898 s
->wait_sector_num
[i
] = -1;
1899 qemu_coroutine_enter(s
->co
[i
]);
1902 while (s
->ret
== -EINPROGRESS
) {
1903 main_loop_wait(false);
1906 if (s
->compressed
&& !s
->ret
) {
1907 /* signal EOF to align */
1908 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1917 static int img_convert(int argc
, char **argv
)
1919 int c
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1921 int progress
= 0, flags
, src_flags
;
1922 bool writethrough
, src_writethrough
;
1923 const char *fmt
, *out_fmt
, *cache
, *src_cache
, *out_baseimg
, *out_filename
;
1924 BlockDriver
*drv
, *proto_drv
;
1925 BlockBackend
**blk
= NULL
, *out_blk
= NULL
;
1926 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1927 int64_t total_sectors
;
1928 int64_t *bs_sectors
= NULL
;
1929 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1930 BlockDriverInfo bdi
;
1931 QemuOpts
*opts
= NULL
;
1932 QemuOptsList
*create_opts
= NULL
;
1933 const char *out_baseimg_param
;
1934 char *options
= NULL
;
1935 const char *snapshot_name
= NULL
;
1936 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1938 Error
*local_err
= NULL
;
1939 QemuOpts
*sn_opts
= NULL
;
1940 ImgConvertState state
;
1941 bool image_opts
= false;
1942 bool wr_in_order
= true;
1943 long num_coroutines
= 8;
1948 src_cache
= BDRV_DEFAULT_CACHE
;
1953 static const struct option long_options
[] = {
1954 {"help", no_argument
, 0, 'h'},
1955 {"object", required_argument
, 0, OPTION_OBJECT
},
1956 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1959 c
= getopt_long(argc
, argv
, ":hf:O:B:ce6o:s:l:S:pt:T:qnm:W",
1960 long_options
, NULL
);
1966 missing_argument(argv
[optind
- 1]);
1969 unrecognized_option(argv
[optind
- 1]);
1981 out_baseimg
= optarg
;
1987 error_report("option -e is deprecated, please use \'-o "
1988 "encryption\' instead!");
1992 error_report("option -6 is deprecated, please use \'-o "
1993 "compat6\' instead!");
1997 if (!is_valid_option_list(optarg
)) {
1998 error_report("Invalid option list: %s", optarg
);
2003 options
= g_strdup(optarg
);
2005 char *old_options
= options
;
2006 options
= g_strdup_printf("%s,%s", options
, optarg
);
2007 g_free(old_options
);
2011 snapshot_name
= optarg
;
2014 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2015 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2018 error_report("Failed in parsing snapshot param '%s'",
2024 snapshot_name
= optarg
;
2031 sval
= cvtnum(optarg
);
2033 error_report("Invalid minimum zero buffer size for sparse output specified");
2038 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2057 if (qemu_strtol(optarg
, NULL
, 0, &num_coroutines
) ||
2058 num_coroutines
< 1 || num_coroutines
> MAX_COROUTINES
) {
2059 error_report("Invalid number of coroutines. Allowed number of"
2060 " coroutines is between 1 and %d", MAX_COROUTINES
);
2066 wr_in_order
= false;
2068 case OPTION_OBJECT
: {
2069 QemuOpts
*object_opts
;
2070 object_opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2078 case OPTION_IMAGE_OPTS
:
2084 if (qemu_opts_foreach(&qemu_object_opts
,
2085 user_creatable_add_opts_foreach
,
2091 if (!wr_in_order
&& compress
) {
2092 error_report("Out of order write and compress are mutually exclusive");
2097 /* Initialize before goto out */
2101 qemu_progress_init(progress
, 1.0);
2103 bs_n
= argc
- optind
- 1;
2104 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
2106 if (options
&& has_help_option(options
)) {
2107 ret
= print_block_option_help(out_filename
, out_fmt
);
2112 error_exit("Must specify image file name");
2117 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2119 error_report("Invalid source cache option: %s", src_cache
);
2123 qemu_progress_print(0, 100);
2125 blk
= g_new0(BlockBackend
*, bs_n
);
2126 bs
= g_new0(BlockDriverState
*, bs_n
);
2127 bs_sectors
= g_new(int64_t, bs_n
);
2130 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2131 blk
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2132 fmt
, src_flags
, src_writethrough
, quiet
);
2137 bs
[bs_i
] = blk_bs(blk
[bs_i
]);
2138 bs_sectors
[bs_i
] = blk_nb_sectors(blk
[bs_i
]);
2139 if (bs_sectors
[bs_i
] < 0) {
2140 error_report("Could not get size of %s: %s",
2141 argv
[optind
+ bs_i
], strerror(-bs_sectors
[bs_i
]));
2145 total_sectors
+= bs_sectors
[bs_i
];
2149 bdrv_snapshot_load_tmp(bs
[0],
2150 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2151 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2153 } else if (snapshot_name
!= NULL
) {
2155 error_report("No support for concatenating multiple snapshot");
2160 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
2163 error_reportf_err(local_err
, "Failed to load snapshot: ");
2168 /* Find driver and parse its options */
2169 drv
= bdrv_find_format(out_fmt
);
2171 error_report("Unknown file format '%s'", out_fmt
);
2176 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2178 error_report_err(local_err
);
2184 if (!drv
->create_opts
) {
2185 error_report("Format driver '%s' does not support image creation",
2191 if (!proto_drv
->create_opts
) {
2192 error_report("Protocol driver '%s' does not support image creation",
2193 proto_drv
->format_name
);
2198 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2199 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2201 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2203 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2205 error_report_err(local_err
);
2211 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_sectors
* 512,
2213 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2219 /* Get backing file name if -o backing_file was used */
2220 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2221 if (out_baseimg_param
) {
2222 out_baseimg
= out_baseimg_param
;
2225 if (bs_n
> 1 && out_baseimg
) {
2226 error_report("Having a backing file for the target makes no sense when "
2227 "concatenating multiple input images");
2232 /* Check if compression is supported */
2235 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2236 const char *preallocation
=
2237 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2239 if (!drv
->bdrv_co_pwritev_compressed
) {
2240 error_report("Compression not supported for this file format");
2246 error_report("Compression and encryption not supported at "
2253 && strcmp(preallocation
, "off"))
2255 error_report("Compression and preallocation not supported at "
2263 /* Create the new image */
2264 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2266 error_reportf_err(local_err
, "%s: error while converting %s: ",
2267 out_filename
, out_fmt
);
2272 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2273 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2275 error_report("Invalid cache option: %s", cache
);
2279 /* XXX we should allow --image-opts to trigger use of
2280 * img_open() here, but then we have trouble with
2281 * the bdrv_create() call which takes different params.
2282 * Not critical right now, so fix can wait...
2284 out_blk
= img_open_file(out_filename
, out_fmt
, flags
, writethrough
, quiet
);
2289 out_bs
= blk_bs(out_blk
);
2291 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2292 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2294 bufsectors
= MIN(32768,
2296 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2297 out_bs
->bl
.pdiscard_alignment
>>
2298 BDRV_SECTOR_BITS
)));
2301 int64_t output_sectors
= blk_nb_sectors(out_blk
);
2302 if (output_sectors
< 0) {
2303 error_report("unable to get output image length: %s",
2304 strerror(-output_sectors
));
2307 } else if (output_sectors
< total_sectors
) {
2308 error_report("output file is smaller than input file");
2314 cluster_sectors
= 0;
2315 ret
= bdrv_get_info(out_bs
, &bdi
);
2318 error_report("could not get block driver info");
2322 compress
= compress
|| bdi
.needs_compressed_writes
;
2323 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2326 state
= (ImgConvertState
) {
2328 .src_sectors
= bs_sectors
,
2330 .total_sectors
= total_sectors
,
2332 .compressed
= compress
,
2333 .target_has_backing
= (bool) out_baseimg
,
2334 .min_sparse
= min_sparse
,
2335 .cluster_sectors
= cluster_sectors
,
2336 .buf_sectors
= bufsectors
,
2337 .wr_in_order
= wr_in_order
,
2338 .num_coroutines
= num_coroutines
,
2340 ret
= convert_do_copy(&state
);
2344 qemu_progress_print(100, 0);
2346 qemu_progress_end();
2347 qemu_opts_del(opts
);
2348 qemu_opts_free(create_opts
);
2349 qemu_opts_del(sn_opts
);
2353 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2354 blk_unref(blk
[bs_i
]);
2369 static void dump_snapshots(BlockDriverState
*bs
)
2371 QEMUSnapshotInfo
*sn_tab
, *sn
;
2374 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2377 printf("Snapshot list:\n");
2378 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2380 for(i
= 0; i
< nb_sns
; i
++) {
2382 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2388 static void dump_json_image_info_list(ImageInfoList
*list
)
2392 Visitor
*v
= qobject_output_visitor_new(&obj
);
2394 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2395 visit_complete(v
, &obj
);
2396 str
= qobject_to_json_pretty(obj
);
2397 assert(str
!= NULL
);
2398 printf("%s\n", qstring_get_str(str
));
2399 qobject_decref(obj
);
2404 static void dump_json_image_info(ImageInfo
*info
)
2408 Visitor
*v
= qobject_output_visitor_new(&obj
);
2410 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2411 visit_complete(v
, &obj
);
2412 str
= qobject_to_json_pretty(obj
);
2413 assert(str
!= NULL
);
2414 printf("%s\n", qstring_get_str(str
));
2415 qobject_decref(obj
);
2420 static void dump_human_image_info_list(ImageInfoList
*list
)
2422 ImageInfoList
*elem
;
2425 for (elem
= list
; elem
; elem
= elem
->next
) {
2431 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2435 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2437 return strcmp(a
, b
) == 0;
2441 * Open an image file chain and return an ImageInfoList
2443 * @filename: topmost image filename
2444 * @fmt: topmost image format (may be NULL to autodetect)
2445 * @chain: true - enumerate entire backing file chain
2446 * false - only topmost image file
2448 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2449 * image file. If there was an error a message will have been printed to
2452 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2453 const char *filename
,
2457 ImageInfoList
*head
= NULL
;
2458 ImageInfoList
**last
= &head
;
2459 GHashTable
*filenames
;
2462 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2466 BlockDriverState
*bs
;
2468 ImageInfoList
*elem
;
2470 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2471 error_report("Backing file '%s' creates an infinite loop.",
2475 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2477 blk
= img_open(image_opts
, filename
, fmt
,
2478 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false);
2484 bdrv_query_image_info(bs
, &info
, &err
);
2486 error_report_err(err
);
2491 elem
= g_new0(ImageInfoList
, 1);
2498 filename
= fmt
= NULL
;
2500 if (info
->has_full_backing_filename
) {
2501 filename
= info
->full_backing_filename
;
2502 } else if (info
->has_backing_filename
) {
2503 error_report("Could not determine absolute backing filename,"
2504 " but backing filename '%s' present",
2505 info
->backing_filename
);
2508 if (info
->has_backing_filename_format
) {
2509 fmt
= info
->backing_filename_format
;
2513 g_hash_table_destroy(filenames
);
2517 qapi_free_ImageInfoList(head
);
2518 g_hash_table_destroy(filenames
);
2522 static int img_info(int argc
, char **argv
)
2525 OutputFormat output_format
= OFORMAT_HUMAN
;
2527 const char *filename
, *fmt
, *output
;
2528 ImageInfoList
*list
;
2529 bool image_opts
= false;
2534 int option_index
= 0;
2535 static const struct option long_options
[] = {
2536 {"help", no_argument
, 0, 'h'},
2537 {"format", required_argument
, 0, 'f'},
2538 {"output", required_argument
, 0, OPTION_OUTPUT
},
2539 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2540 {"object", required_argument
, 0, OPTION_OBJECT
},
2541 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2544 c
= getopt_long(argc
, argv
, ":f:h",
2545 long_options
, &option_index
);
2551 missing_argument(argv
[optind
- 1]);
2554 unrecognized_option(argv
[optind
- 1]);
2565 case OPTION_BACKING_CHAIN
:
2568 case OPTION_OBJECT
: {
2570 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2576 case OPTION_IMAGE_OPTS
:
2581 if (optind
!= argc
- 1) {
2582 error_exit("Expecting one image file name");
2584 filename
= argv
[optind
++];
2586 if (output
&& !strcmp(output
, "json")) {
2587 output_format
= OFORMAT_JSON
;
2588 } else if (output
&& !strcmp(output
, "human")) {
2589 output_format
= OFORMAT_HUMAN
;
2590 } else if (output
) {
2591 error_report("--output must be used with human or json as argument.");
2595 if (qemu_opts_foreach(&qemu_object_opts
,
2596 user_creatable_add_opts_foreach
,
2601 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
);
2606 switch (output_format
) {
2608 dump_human_image_info_list(list
);
2612 dump_json_image_info_list(list
);
2614 dump_json_image_info(list
->value
);
2619 qapi_free_ImageInfoList(list
);
2623 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2626 switch (output_format
) {
2628 if (e
->data
&& !e
->has_offset
) {
2629 error_report("File contains external, encrypted or compressed clusters.");
2632 if (e
->data
&& !e
->zero
) {
2633 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2634 e
->start
, e
->length
,
2635 e
->has_offset
? e
->offset
: 0,
2636 e
->has_filename
? e
->filename
: "");
2638 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2639 * Modify the flags here to allow more coalescing.
2641 if (next
&& (!next
->data
|| next
->zero
)) {
2647 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2648 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2649 (e
->start
== 0 ? "[" : ",\n"),
2650 e
->start
, e
->length
, e
->depth
,
2651 e
->zero
? "true" : "false",
2652 e
->data
? "true" : "false");
2653 if (e
->has_offset
) {
2654 printf(", \"offset\": %"PRId64
"", e
->offset
);
2665 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2666 int nb_sectors
, MapEntry
*e
)
2670 BlockDriverState
*file
;
2673 /* As an optimization, we could cache the current range of unallocated
2674 * clusters in each file of the chain, and avoid querying the same
2680 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2686 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2689 bs
= backing_bs(bs
);
2698 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2701 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2702 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2703 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2704 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2705 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2706 .has_offset
= has_offset
,
2708 .has_filename
= file
&& has_offset
,
2709 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2715 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2717 if (curr
->length
== 0) {
2720 if (curr
->zero
!= next
->zero
||
2721 curr
->data
!= next
->data
||
2722 curr
->depth
!= next
->depth
||
2723 curr
->has_filename
!= next
->has_filename
||
2724 curr
->has_offset
!= next
->has_offset
) {
2727 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2730 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2736 static int img_map(int argc
, char **argv
)
2739 OutputFormat output_format
= OFORMAT_HUMAN
;
2741 BlockDriverState
*bs
;
2742 const char *filename
, *fmt
, *output
;
2744 MapEntry curr
= { .length
= 0 }, next
;
2746 bool image_opts
= false;
2751 int option_index
= 0;
2752 static const struct option long_options
[] = {
2753 {"help", no_argument
, 0, 'h'},
2754 {"format", required_argument
, 0, 'f'},
2755 {"output", required_argument
, 0, OPTION_OUTPUT
},
2756 {"object", required_argument
, 0, OPTION_OBJECT
},
2757 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2760 c
= getopt_long(argc
, argv
, ":f:h",
2761 long_options
, &option_index
);
2767 missing_argument(argv
[optind
- 1]);
2770 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);
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 nsectors_left
;
2830 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2832 /* Probe up to 1 GiB at a time. */
2833 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2834 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2835 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2838 error_report("Could not read file metadata: %s", strerror(-ret
));
2842 if (entry_mergeable(&curr
, &next
)) {
2843 curr
.length
+= next
.length
;
2847 if (curr
.length
> 0) {
2848 dump_map_entry(output_format
, &curr
, &next
);
2853 dump_map_entry(output_format
, &curr
, NULL
);
2860 #define SNAPSHOT_LIST 1
2861 #define SNAPSHOT_CREATE 2
2862 #define SNAPSHOT_APPLY 3
2863 #define SNAPSHOT_DELETE 4
2865 static int img_snapshot(int argc
, char **argv
)
2868 BlockDriverState
*bs
;
2869 QEMUSnapshotInfo sn
;
2870 char *filename
, *snapshot_name
= NULL
;
2871 int c
, ret
= 0, bdrv_oflags
;
2876 bool image_opts
= false;
2878 bdrv_oflags
= BDRV_O_RDWR
;
2879 /* Parse commandline parameters */
2881 static const struct option long_options
[] = {
2882 {"help", no_argument
, 0, 'h'},
2883 {"object", required_argument
, 0, OPTION_OBJECT
},
2884 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2887 c
= getopt_long(argc
, argv
, ":la:c:d:hq",
2888 long_options
, NULL
);
2894 missing_argument(argv
[optind
- 1]);
2897 unrecognized_option(argv
[optind
- 1]);
2904 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2907 action
= SNAPSHOT_LIST
;
2908 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2912 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2915 action
= SNAPSHOT_APPLY
;
2916 snapshot_name
= optarg
;
2920 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2923 action
= SNAPSHOT_CREATE
;
2924 snapshot_name
= optarg
;
2928 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2931 action
= SNAPSHOT_DELETE
;
2932 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
);
2969 /* Perform the requested action */
2975 case SNAPSHOT_CREATE
:
2976 memset(&sn
, 0, sizeof(sn
));
2977 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2979 qemu_gettimeofday(&tv
);
2980 sn
.date_sec
= tv
.tv_sec
;
2981 sn
.date_nsec
= tv
.tv_usec
* 1000;
2983 ret
= bdrv_snapshot_create(bs
, &sn
);
2985 error_report("Could not create snapshot '%s': %d (%s)",
2986 snapshot_name
, ret
, strerror(-ret
));
2990 case SNAPSHOT_APPLY
:
2991 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2993 error_report("Could not apply snapshot '%s': %d (%s)",
2994 snapshot_name
, ret
, strerror(-ret
));
2998 case SNAPSHOT_DELETE
:
2999 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
3001 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3016 static int img_rebase(int argc
, char **argv
)
3018 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3019 uint8_t *buf_old
= NULL
;
3020 uint8_t *buf_new
= NULL
;
3021 BlockDriverState
*bs
= NULL
;
3023 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3024 int c
, flags
, src_flags
, ret
;
3025 bool writethrough
, src_writethrough
;
3029 Error
*local_err
= NULL
;
3030 bool image_opts
= false;
3032 /* Parse commandline parameters */
3034 cache
= BDRV_DEFAULT_CACHE
;
3035 src_cache
= BDRV_DEFAULT_CACHE
;
3039 static const struct option long_options
[] = {
3040 {"help", no_argument
, 0, 'h'},
3041 {"object", required_argument
, 0, OPTION_OBJECT
},
3042 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3045 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:q",
3046 long_options
, NULL
);
3052 missing_argument(argv
[optind
- 1]);
3055 unrecognized_option(argv
[optind
- 1]);
3064 out_basefmt
= optarg
;
3067 out_baseimg
= optarg
;
3084 case OPTION_OBJECT
: {
3086 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3092 case OPTION_IMAGE_OPTS
:
3102 if (optind
!= argc
- 1) {
3103 error_exit("Expecting one image file name");
3105 if (!unsafe
&& !out_baseimg
) {
3106 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3108 filename
= argv
[optind
++];
3110 if (qemu_opts_foreach(&qemu_object_opts
,
3111 user_creatable_add_opts_foreach
,
3116 qemu_progress_init(progress
, 2.0);
3117 qemu_progress_print(0, 100);
3119 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3120 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3122 error_report("Invalid cache option: %s", cache
);
3127 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3129 error_report("Invalid source cache option: %s", src_cache
);
3133 /* The source files are opened read-only, don't care about WCE */
3134 assert((src_flags
& BDRV_O_RDWR
) == 0);
3135 (void) src_writethrough
;
3140 * Ignore the old backing file for unsafe rebase in case we want to correct
3141 * the reference to a renamed or moved backing file.
3143 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3150 if (out_basefmt
!= NULL
) {
3151 if (bdrv_find_format(out_basefmt
) == NULL
) {
3152 error_report("Invalid format name: '%s'", out_basefmt
);
3158 /* For safe rebasing we need to compare old and new backing file */
3160 char backing_name
[PATH_MAX
];
3161 QDict
*options
= NULL
;
3163 if (bs
->backing_format
[0] != '\0') {
3164 options
= qdict_new();
3165 qdict_put_str(options
, "driver", bs
->backing_format
);
3168 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3169 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3170 options
, src_flags
, &local_err
);
3171 if (!blk_old_backing
) {
3172 error_reportf_err(local_err
,
3173 "Could not open old backing file '%s': ",
3179 if (out_baseimg
[0]) {
3181 options
= qdict_new();
3182 qdict_put_str(options
, "driver", out_basefmt
);
3187 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3188 options
, src_flags
, &local_err
);
3189 if (!blk_new_backing
) {
3190 error_reportf_err(local_err
,
3191 "Could not open new backing file '%s': ",
3200 * Check each unallocated cluster in the COW file. If it is unallocated,
3201 * accesses go to the backing file. We must therefore compare this cluster
3202 * in the old and new backing file, and if they differ we need to copy it
3203 * from the old backing file into the COW file.
3205 * If qemu-img crashes during this step, no harm is done. The content of
3206 * the image is the same as the original one at any time.
3209 int64_t num_sectors
;
3210 int64_t old_backing_num_sectors
;
3211 int64_t new_backing_num_sectors
= 0;
3214 float local_progress
= 0;
3216 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3217 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3219 num_sectors
= blk_nb_sectors(blk
);
3220 if (num_sectors
< 0) {
3221 error_report("Could not get size of '%s': %s",
3222 filename
, strerror(-num_sectors
));
3226 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
3227 if (old_backing_num_sectors
< 0) {
3228 char backing_name
[PATH_MAX
];
3230 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3231 error_report("Could not get size of '%s': %s",
3232 backing_name
, strerror(-old_backing_num_sectors
));
3236 if (blk_new_backing
) {
3237 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3238 if (new_backing_num_sectors
< 0) {
3239 error_report("Could not get size of '%s': %s",
3240 out_baseimg
, strerror(-new_backing_num_sectors
));
3246 if (num_sectors
!= 0) {
3247 local_progress
= (float)100 /
3248 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3251 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3253 /* How many sectors can we handle with the next read? */
3254 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3255 n
= (IO_BUF_SIZE
/ 512);
3257 n
= num_sectors
- sector
;
3260 /* If the cluster is allocated, we don't need to take action */
3261 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
3263 error_report("error while reading image metadata: %s",
3272 * Read old and new backing file and take into consideration that
3273 * backing files may be smaller than the COW image.
3275 if (sector
>= old_backing_num_sectors
) {
3276 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3278 if (sector
+ n
> old_backing_num_sectors
) {
3279 n
= old_backing_num_sectors
- sector
;
3282 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3283 buf_old
, n
<< BDRV_SECTOR_BITS
);
3285 error_report("error while reading from old backing file");
3290 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3291 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3293 if (sector
+ n
> new_backing_num_sectors
) {
3294 n
= new_backing_num_sectors
- sector
;
3297 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3298 buf_new
, n
<< BDRV_SECTOR_BITS
);
3300 error_report("error while reading from new backing file");
3305 /* If they differ, we need to write to the COW file */
3306 uint64_t written
= 0;
3308 while (written
< n
) {
3311 if (compare_sectors(buf_old
+ written
* 512,
3312 buf_new
+ written
* 512, n
- written
, &pnum
))
3314 ret
= blk_pwrite(blk
,
3315 (sector
+ written
) << BDRV_SECTOR_BITS
,
3316 buf_old
+ written
* 512,
3317 pnum
<< BDRV_SECTOR_BITS
, 0);
3319 error_report("Error while writing to COW image: %s",
3327 qemu_progress_print(local_progress
, 100);
3332 * Change the backing file. All clusters that are different from the old
3333 * backing file are overwritten in the COW file now, so the visible content
3334 * doesn't change when we switch the backing file.
3336 if (out_baseimg
&& *out_baseimg
) {
3337 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3339 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3342 if (ret
== -ENOSPC
) {
3343 error_report("Could not change the backing file to '%s': No "
3344 "space left in the file header", out_baseimg
);
3345 } else if (ret
< 0) {
3346 error_report("Could not change the backing file to '%s': %s",
3347 out_baseimg
, strerror(-ret
));
3350 qemu_progress_print(100, 0);
3352 * TODO At this point it is possible to check if any clusters that are
3353 * allocated in the COW file are the same in the backing file. If so, they
3354 * could be dropped from the COW file. Don't do this before switching the
3355 * backing file, in case of a crash this would lead to corruption.
3358 qemu_progress_end();
3361 blk_unref(blk_old_backing
);
3362 blk_unref(blk_new_backing
);
3364 qemu_vfree(buf_old
);
3365 qemu_vfree(buf_new
);
3374 static int img_resize(int argc
, char **argv
)
3377 int c
, ret
, relative
;
3378 const char *filename
, *fmt
, *size
;
3379 int64_t n
, total_size
;
3381 BlockBackend
*blk
= NULL
;
3384 static QemuOptsList resize_options
= {
3385 .name
= "resize_options",
3386 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3389 .name
= BLOCK_OPT_SIZE
,
3390 .type
= QEMU_OPT_SIZE
,
3391 .help
= "Virtual disk size"
3397 bool image_opts
= false;
3399 /* Remove size from argv manually so that negative numbers are not treated
3400 * as options by getopt. */
3402 error_exit("Not enough arguments");
3406 size
= argv
[--argc
];
3408 /* Parse getopt arguments */
3411 static const struct option long_options
[] = {
3412 {"help", no_argument
, 0, 'h'},
3413 {"object", required_argument
, 0, OPTION_OBJECT
},
3414 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3417 c
= getopt_long(argc
, argv
, ":f:hq",
3418 long_options
, NULL
);
3424 missing_argument(argv
[optind
- 1]);
3427 unrecognized_option(argv
[optind
- 1]);
3438 case OPTION_OBJECT
: {
3440 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3446 case OPTION_IMAGE_OPTS
:
3451 if (optind
!= argc
- 1) {
3452 error_exit("Expecting one image file name");
3454 filename
= argv
[optind
++];
3456 if (qemu_opts_foreach(&qemu_object_opts
,
3457 user_creatable_add_opts_foreach
,
3462 /* Choose grow, shrink, or absolute resize mode */
3478 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3479 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3481 error_report_err(err
);
3483 qemu_opts_del(param
);
3486 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3487 qemu_opts_del(param
);
3489 blk
= img_open(image_opts
, filename
, fmt
,
3490 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
);
3497 total_size
= blk_getlength(blk
) + n
* relative
;
3501 if (total_size
<= 0) {
3502 error_report("New image size must be positive");
3507 ret
= blk_truncate(blk
, total_size
);
3510 qprintf(quiet
, "Image resized.\n");
3513 error_report("This image does not support resize");
3516 error_report("Image is read-only");
3519 error_report("Error resizing image: %s", strerror(-ret
));
3530 static void amend_status_cb(BlockDriverState
*bs
,
3531 int64_t offset
, int64_t total_work_size
,
3534 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3537 static int img_amend(int argc
, char **argv
)
3541 char *options
= NULL
;
3542 QemuOptsList
*create_opts
= NULL
;
3543 QemuOpts
*opts
= NULL
;
3544 const char *fmt
= NULL
, *filename
, *cache
;
3547 bool quiet
= false, progress
= false;
3548 BlockBackend
*blk
= NULL
;
3549 BlockDriverState
*bs
= NULL
;
3550 bool image_opts
= false;
3552 cache
= BDRV_DEFAULT_CACHE
;
3554 static const struct option long_options
[] = {
3555 {"help", no_argument
, 0, 'h'},
3556 {"object", required_argument
, 0, OPTION_OBJECT
},
3557 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3560 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
3561 long_options
, NULL
);
3568 missing_argument(argv
[optind
- 1]);
3571 unrecognized_option(argv
[optind
- 1]);
3577 if (!is_valid_option_list(optarg
)) {
3578 error_report("Invalid option list: %s", optarg
);
3580 goto out_no_progress
;
3583 options
= g_strdup(optarg
);
3585 char *old_options
= options
;
3586 options
= g_strdup_printf("%s,%s", options
, optarg
);
3587 g_free(old_options
);
3603 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3607 goto out_no_progress
;
3610 case OPTION_IMAGE_OPTS
:
3617 error_exit("Must specify options (-o)");
3620 if (qemu_opts_foreach(&qemu_object_opts
,
3621 user_creatable_add_opts_foreach
,
3624 goto out_no_progress
;
3630 qemu_progress_init(progress
, 1.0);
3632 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3633 if (fmt
&& has_help_option(options
)) {
3634 /* If a format is explicitly specified (and possibly no filename is
3635 * given), print option help here */
3636 ret
= print_block_option_help(filename
, fmt
);
3640 if (optind
!= argc
- 1) {
3641 error_report("Expecting one image file name");
3646 flags
= BDRV_O_RDWR
;
3647 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3649 error_report("Invalid cache option: %s", cache
);
3653 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3660 fmt
= bs
->drv
->format_name
;
3662 if (has_help_option(options
)) {
3663 /* If the format was auto-detected, print option help here */
3664 ret
= print_block_option_help(filename
, fmt
);
3668 if (!bs
->drv
->create_opts
) {
3669 error_report("Format driver '%s' does not support any options to amend",
3675 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3676 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3677 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3679 error_report_err(err
);
3684 /* In case the driver does not call amend_status_cb() */
3685 qemu_progress_print(0.f
, 0);
3686 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3687 qemu_progress_print(100.f
, 0);
3689 error_report("Error while amending options: %s", strerror(-ret
));
3694 qemu_progress_end();
3698 qemu_opts_del(opts
);
3699 qemu_opts_free(create_opts
);
3708 typedef struct BenchData
{
3710 uint64_t image_size
;
3717 bool drain_on_flush
;
3726 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3729 error_report("Failed flush request: %s", strerror(-ret
));
3734 static void bench_cb(void *opaque
, int ret
)
3736 BenchData
*b
= opaque
;
3740 error_report("Failed request: %s", strerror(-ret
));
3745 /* Just finished a flush with drained queue: Start next requests */
3746 assert(b
->in_flight
== 0);
3747 b
->in_flush
= false;
3748 } else if (b
->in_flight
> 0) {
3749 int remaining
= b
->n
- b
->in_flight
;
3754 /* Time for flush? Drain queue if requested, then flush */
3755 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3756 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3757 BlockCompletionFunc
*cb
;
3759 if (b
->drain_on_flush
) {
3763 cb
= bench_undrained_flush_cb
;
3766 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3768 error_report("Failed to issue flush request");
3772 if (b
->drain_on_flush
) {
3778 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3779 int64_t offset
= b
->offset
;
3780 /* blk_aio_* might look for completed I/Os and kick bench_cb
3781 * again, so make sure this operation is counted by in_flight
3782 * and b->offset is ready for the next submission.
3785 b
->offset
+= b
->step
;
3786 b
->offset
%= b
->image_size
;
3788 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3790 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3793 error_report("Failed to issue request");
3799 static int img_bench(int argc
, char **argv
)
3802 const char *fmt
= NULL
, *filename
;
3804 bool image_opts
= false;
3805 bool is_write
= false;
3809 size_t bufsize
= 4096;
3812 int flush_interval
= 0;
3813 bool drain_on_flush
= true;
3815 BlockBackend
*blk
= NULL
;
3816 BenchData data
= {};
3818 bool writethrough
= false;
3819 struct timeval t1
, t2
;
3823 static const struct option long_options
[] = {
3824 {"help", no_argument
, 0, 'h'},
3825 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3826 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3827 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3828 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3831 c
= getopt_long(argc
, argv
, ":hc:d:f:no:qs:S:t:w", long_options
, NULL
);
3838 missing_argument(argv
[optind
- 1]);
3841 unrecognized_option(argv
[optind
- 1]);
3850 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3851 error_report("Invalid request count specified");
3861 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3862 error_report("Invalid queue depth specified");
3872 flags
|= BDRV_O_NATIVE_AIO
;
3876 offset
= cvtnum(optarg
);
3878 error_report("Invalid offset specified");
3891 sval
= cvtnum(optarg
);
3892 if (sval
< 0 || sval
> INT_MAX
) {
3893 error_report("Invalid buffer size specified");
3904 sval
= cvtnum(optarg
);
3905 if (sval
< 0 || sval
> INT_MAX
) {
3906 error_report("Invalid step size specified");
3914 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3916 error_report("Invalid cache mode");
3922 flags
|= BDRV_O_RDWR
;
3925 case OPTION_PATTERN
:
3929 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3930 error_report("Invalid pattern byte specified");
3936 case OPTION_FLUSH_INTERVAL
:
3940 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3941 error_report("Invalid flush interval specified");
3944 flush_interval
= res
;
3947 case OPTION_NO_DRAIN
:
3948 drain_on_flush
= false;
3950 case OPTION_IMAGE_OPTS
:
3956 if (optind
!= argc
- 1) {
3957 error_exit("Expecting one image file name");
3959 filename
= argv
[argc
- 1];
3961 if (!is_write
&& flush_interval
) {
3962 error_report("--flush-interval is only available in write tests");
3966 if (flush_interval
&& flush_interval
< depth
) {
3967 error_report("Flush interval can't be smaller than depth");
3972 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3978 image_size
= blk_getlength(blk
);
3979 if (image_size
< 0) {
3984 data
= (BenchData
) {
3986 .image_size
= image_size
,
3988 .step
= step
?: bufsize
,
3993 .flush_interval
= flush_interval
,
3994 .drain_on_flush
= drain_on_flush
,
3996 printf("Sending %d %s requests, %d bytes each, %d in parallel "
3997 "(starting at offset %" PRId64
", step size %d)\n",
3998 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
3999 data
.offset
, data
.step
);
4000 if (flush_interval
) {
4001 printf("Sending flush every %d requests\n", flush_interval
);
4004 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
4005 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4007 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4008 for (i
= 0; i
< data
.nrreq
; i
++) {
4009 qemu_iovec_init(&data
.qiov
[i
], 1);
4010 qemu_iovec_add(&data
.qiov
[i
],
4011 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4014 gettimeofday(&t1
, NULL
);
4017 while (data
.n
> 0) {
4018 main_loop_wait(false);
4020 gettimeofday(&t2
, NULL
);
4022 printf("Run completed in %3.3f seconds.\n",
4023 (t2
.tv_sec
- t1
.tv_sec
)
4024 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4027 qemu_vfree(data
.buf
);
4048 int bsz
; /* Block size */
4056 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4060 static int img_dd_bs(const char *arg
,
4061 struct DdIo
*in
, struct DdIo
*out
,
4068 if (res
<= 0 || res
> INT_MAX
) {
4069 error_report("invalid number: '%s'", arg
);
4072 in
->bsz
= out
->bsz
= res
;
4077 static int img_dd_count(const char *arg
,
4078 struct DdIo
*in
, struct DdIo
*out
,
4081 dd
->count
= cvtnum(arg
);
4083 if (dd
->count
< 0) {
4084 error_report("invalid number: '%s'", arg
);
4091 static int img_dd_if(const char *arg
,
4092 struct DdIo
*in
, struct DdIo
*out
,
4095 in
->filename
= g_strdup(arg
);
4100 static int img_dd_of(const char *arg
,
4101 struct DdIo
*in
, struct DdIo
*out
,
4104 out
->filename
= g_strdup(arg
);
4109 static int img_dd_skip(const char *arg
,
4110 struct DdIo
*in
, struct DdIo
*out
,
4113 in
->offset
= cvtnum(arg
);
4115 if (in
->offset
< 0) {
4116 error_report("invalid number: '%s'", arg
);
4123 static int img_dd(int argc
, char **argv
)
4128 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4129 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4130 QemuOpts
*opts
= NULL
;
4131 QemuOptsList
*create_opts
= NULL
;
4132 Error
*local_err
= NULL
;
4133 bool image_opts
= false;
4135 const char *out_fmt
= "raw";
4136 const char *fmt
= NULL
;
4138 int64_t block_count
= 0, out_pos
, in_pos
;
4139 struct DdInfo dd
= {
4144 .bsz
= 512, /* Block size is by default 512 bytes */
4156 const struct DdOpts options
[] = {
4157 { "bs", img_dd_bs
, C_BS
},
4158 { "count", img_dd_count
, C_COUNT
},
4159 { "if", img_dd_if
, C_IF
},
4160 { "of", img_dd_of
, C_OF
},
4161 { "skip", img_dd_skip
, C_SKIP
},
4164 const struct option long_options
[] = {
4165 { "help", no_argument
, 0, 'h'},
4166 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4170 while ((c
= getopt_long(argc
, argv
, ":hf:O:", long_options
, NULL
))) {
4182 missing_argument(argv
[optind
- 1]);
4185 unrecognized_option(argv
[optind
- 1]);
4190 case OPTION_IMAGE_OPTS
:
4196 for (i
= optind
; i
< argc
; i
++) {
4198 arg
= g_strdup(argv
[i
]);
4200 tmp
= strchr(arg
, '=');
4202 error_report("unrecognized operand %s", arg
);
4209 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4210 if (!strcmp(arg
, options
[j
].name
)) {
4214 if (options
[j
].name
== NULL
) {
4215 error_report("unrecognized operand %s", arg
);
4220 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4224 dd
.flags
|= options
[j
].flag
;
4229 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4230 error_report("Must specify both input and output files");
4234 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false);
4241 drv
= bdrv_find_format(out_fmt
);
4243 error_report("Unknown file format");
4247 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4250 error_report_err(local_err
);
4254 if (!drv
->create_opts
) {
4255 error_report("Format driver '%s' does not support image creation",
4260 if (!proto_drv
->create_opts
) {
4261 error_report("Protocol driver '%s' does not support image creation",
4262 proto_drv
->format_name
);
4266 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4267 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4269 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4271 size
= blk_getlength(blk1
);
4273 error_report("Failed to get size for '%s'", in
.filename
);
4278 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4279 dd
.count
* in
.bsz
< size
) {
4280 size
= dd
.count
* in
.bsz
;
4283 /* Overflow means the specified offset is beyond input image's size */
4284 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4285 size
< in
.bsz
* in
.offset
)) {
4286 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4288 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4289 size
- in
.bsz
* in
.offset
, &error_abort
);
4292 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4294 error_reportf_err(local_err
,
4295 "%s: error while creating output image: ",
4301 blk2
= img_open(image_opts
, out
.filename
, out_fmt
, BDRV_O_RDWR
,
4309 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4310 size
< in
.offset
* in
.bsz
)) {
4311 /* We give a warning if the skip option is bigger than the input
4312 * size and create an empty output disk image (i.e. like dd(1)).
4314 error_report("%s: cannot skip to specified offset", in
.filename
);
4317 in_pos
= in
.offset
* in
.bsz
;
4320 in
.buf
= g_new(uint8_t, in
.bsz
);
4322 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4323 int in_ret
, out_ret
;
4325 if (in_pos
+ in
.bsz
> size
) {
4326 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4328 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4331 error_report("error while reading from input image file: %s",
4338 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4341 error_report("error while writing to output image file: %s",
4342 strerror(-out_ret
));
4351 qemu_opts_del(opts
);
4352 qemu_opts_free(create_opts
);
4355 g_free(in
.filename
);
4356 g_free(out
.filename
);
4367 static const img_cmd_t img_cmds
[] = {
4368 #define DEF(option, callback, arg_string) \
4369 { option, callback },
4370 #include "qemu-img-cmds.h"
4376 int main(int argc
, char **argv
)
4378 const img_cmd_t
*cmd
;
4379 const char *cmdname
;
4380 Error
*local_error
= NULL
;
4381 char *trace_file
= NULL
;
4383 static const struct option long_options
[] = {
4384 {"help", no_argument
, 0, 'h'},
4385 {"version", no_argument
, 0, 'V'},
4386 {"trace", required_argument
, NULL
, 'T'},
4391 signal(SIGPIPE
, SIG_IGN
);
4394 module_call_init(MODULE_INIT_TRACE
);
4395 error_set_progname(argv
[0]);
4396 qemu_init_exec_dir(argv
[0]);
4398 if (qemu_init_main_loop(&local_error
)) {
4399 error_report_err(local_error
);
4403 qcrypto_init(&error_fatal
);
4405 module_call_init(MODULE_INIT_QOM
);
4408 error_exit("Not enough arguments");
4411 qemu_add_opts(&qemu_object_opts
);
4412 qemu_add_opts(&qemu_source_opts
);
4413 qemu_add_opts(&qemu_trace_opts
);
4415 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
4418 missing_argument(argv
[optind
- 1]);
4421 unrecognized_option(argv
[optind
- 1]);
4427 printf(QEMU_IMG_VERSION
);
4431 trace_file
= trace_opt_parse(optarg
);
4436 cmdname
= argv
[optind
];
4438 /* reset getopt_long scanning */
4446 if (!trace_init_backends()) {
4449 trace_init_file(trace_file
);
4450 qemu_set_log(LOG_TRACE
);
4452 /* find the command */
4453 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4454 if (!strcmp(cmdname
, cmd
->name
)) {
4455 return cmd
->handler(argc
, argv
);
4460 error_exit("Command not found: %s", cmdname
);