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 /* Please keep in synch with qemu-img.texi */
92 static void QEMU_NORETURN
help(void)
94 const char *help_msg
=
96 "usage: qemu-img [standard options] command [command options]\n"
97 "QEMU disk image utility\n"
99 " '-h', '--help' display this help and exit\n"
100 " '-V', '--version' output version information and exit\n"
101 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
102 " specify tracing options\n"
105 #define DEF(option, callback, arg_string) \
107 #include "qemu-img-cmds.h"
111 "Command parameters:\n"
112 " 'filename' is a disk image filename\n"
113 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
114 " manual page for a description of the object properties. The most common\n"
115 " object type is a 'secret', which is used to supply passwords and/or\n"
116 " encryption keys.\n"
117 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
118 " 'cache' is the cache mode used to write the output disk image, the valid\n"
119 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
120 " 'directsync' and 'unsafe' (default for convert)\n"
121 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
122 " options are the same as for the 'cache' option\n"
123 " 'size' is the disk image size in bytes. Optional suffixes\n"
124 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
125 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
126 " supported. 'b' is ignored.\n"
127 " 'output_filename' is the destination disk image filename\n"
128 " 'output_fmt' is the destination format\n"
129 " 'options' is a comma separated list of format specific options in a\n"
130 " name=value format. Use -o ? for an overview of the options supported by the\n"
132 " 'snapshot_param' is param used for internal snapshot, format\n"
133 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
135 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
137 " '-c' indicates that target image must be compressed (qcow format only)\n"
138 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
139 " match exactly. The image doesn't need a working backing file before\n"
140 " rebasing in this case (useful for renaming the backing file)\n"
141 " '-h' with or without a command shows this help and lists the supported formats\n"
142 " '-p' show progress of command (only certain commands)\n"
143 " '-q' use Quiet mode - do not print any output (except errors)\n"
144 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
145 " contain only zeros for qemu-img to create a sparse image during\n"
146 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
147 " unallocated or zero sectors, and the destination image will always be\n"
149 " '--output' takes the format in which the output must be done (human or json)\n"
150 " '-n' skips the target volume creation (useful if the volume is created\n"
151 " prior to running qemu-img)\n"
153 "Parameters to check subcommand:\n"
154 " '-r' tries to repair any inconsistencies that are found during the check.\n"
155 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
156 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
157 " hiding corruption that has already occurred.\n"
159 "Parameters to convert subcommand:\n"
160 " '-m' specifies how many coroutines work in parallel during the convert\n"
161 " process (defaults to 8)\n"
162 " '-W' allow to write to the target out of order rather than sequential\n"
164 "Parameters to snapshot subcommand:\n"
165 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
166 " '-a' applies a snapshot (revert disk to saved state)\n"
167 " '-c' creates a snapshot\n"
168 " '-d' deletes a snapshot\n"
169 " '-l' lists all snapshots in the given image\n"
171 "Parameters to compare subcommand:\n"
172 " '-f' first image format\n"
173 " '-F' second image format\n"
174 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
176 "Parameters to dd subcommand:\n"
177 " 'bs=BYTES' read and write up to BYTES bytes at a time "
179 " 'count=N' copy only N input blocks\n"
180 " 'if=FILE' read from FILE\n"
181 " 'of=FILE' write to FILE\n"
182 " 'skip=N' skip N bs-sized blocks at the start of input\n";
184 printf("%s\nSupported formats:", help_msg
);
185 bdrv_iterate_format(format_print
, NULL
);
190 static QemuOptsList qemu_object_opts
= {
192 .implied_opt_name
= "qom-type",
193 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
199 static QemuOptsList qemu_source_opts
= {
201 .implied_opt_name
= "file",
202 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
208 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
214 ret
= vprintf(fmt
, args
);
221 static int print_block_option_help(const char *filename
, const char *fmt
)
223 BlockDriver
*drv
, *proto_drv
;
224 QemuOptsList
*create_opts
= NULL
;
225 Error
*local_err
= NULL
;
227 /* Find driver and parse its options */
228 drv
= bdrv_find_format(fmt
);
230 error_report("Unknown file format '%s'", fmt
);
234 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
236 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
238 error_report_err(local_err
);
239 qemu_opts_free(create_opts
);
242 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
245 qemu_opts_print_help(create_opts
);
246 qemu_opts_free(create_opts
);
251 static int img_open_password(BlockBackend
*blk
, const char *filename
,
252 int flags
, bool quiet
)
254 BlockDriverState
*bs
;
258 if (bdrv_is_encrypted(bs
) && bdrv_key_required(bs
) &&
259 !(flags
& BDRV_O_NO_IO
)) {
260 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
261 if (qemu_read_password(password
, sizeof(password
)) < 0) {
262 error_report("No password given");
265 if (bdrv_set_key(bs
, password
) < 0) {
266 error_report("invalid password");
274 static BlockBackend
*img_open_opts(const char *optstr
,
275 QemuOpts
*opts
, int flags
, bool writethrough
,
279 Error
*local_err
= NULL
;
281 options
= qemu_opts_to_qdict(opts
, NULL
);
282 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
284 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
287 blk_set_enable_write_cache(blk
, !writethrough
);
289 if (img_open_password(blk
, optstr
, flags
, quiet
) < 0) {
296 static BlockBackend
*img_open_file(const char *filename
,
297 const char *fmt
, int flags
,
298 bool writethrough
, bool quiet
)
301 Error
*local_err
= NULL
;
302 QDict
*options
= NULL
;
305 options
= qdict_new();
306 qdict_put(options
, "driver", qstring_from_str(fmt
));
309 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
311 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
314 blk_set_enable_write_cache(blk
, !writethrough
);
316 if (img_open_password(blk
, filename
, flags
, quiet
) < 0) {
324 static BlockBackend
*img_open(bool image_opts
,
325 const char *filename
,
326 const char *fmt
, int flags
, bool writethrough
,
333 error_report("--image-opts and --format are mutually exclusive");
336 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
341 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
);
343 blk
= img_open_file(filename
, fmt
, flags
, writethrough
, quiet
);
349 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
350 const char *base_filename
,
351 const char *base_fmt
)
356 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
358 error_report("Backing file not supported for file format '%s'",
365 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
367 error_report("Backing file format not supported for file "
376 static int64_t cvtnum(const char *s
)
381 err
= qemu_strtosz(s
, NULL
, &value
);
385 if (value
> INT64_MAX
) {
391 static int img_create(int argc
, char **argv
)
394 uint64_t img_size
= -1;
395 const char *fmt
= "raw";
396 const char *base_fmt
= NULL
;
397 const char *filename
;
398 const char *base_filename
= NULL
;
399 char *options
= NULL
;
400 Error
*local_err
= NULL
;
404 static const struct option long_options
[] = {
405 {"help", no_argument
, 0, 'h'},
406 {"object", required_argument
, 0, OPTION_OBJECT
},
409 c
= getopt_long(argc
, argv
, "F:b:f:he6o:q",
423 base_filename
= optarg
;
429 error_report("option -e is deprecated, please use \'-o "
430 "encryption\' instead!");
433 error_report("option -6 is deprecated, please use \'-o "
434 "compat6\' instead!");
437 if (!is_valid_option_list(optarg
)) {
438 error_report("Invalid option list: %s", optarg
);
442 options
= g_strdup(optarg
);
444 char *old_options
= options
;
445 options
= g_strdup_printf("%s,%s", options
, optarg
);
452 case OPTION_OBJECT
: {
454 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
463 /* Get the filename */
464 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
465 if (options
&& has_help_option(options
)) {
467 return print_block_option_help(filename
, fmt
);
470 if (optind
>= argc
) {
471 error_exit("Expecting image file name");
475 if (qemu_opts_foreach(&qemu_object_opts
,
476 user_creatable_add_opts_foreach
,
481 /* Get image size, if specified */
485 sval
= cvtnum(argv
[optind
++]);
487 if (sval
== -ERANGE
) {
488 error_report("Image size must be less than 8 EiB!");
490 error_report("Invalid image size specified! You may use k, M, "
491 "G, T, P or E suffixes for ");
492 error_report("kilobytes, megabytes, gigabytes, terabytes, "
493 "petabytes and exabytes.");
497 img_size
= (uint64_t)sval
;
499 if (optind
!= argc
) {
500 error_exit("Unexpected argument: %s", argv
[optind
]);
503 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
504 options
, img_size
, 0, &local_err
, quiet
);
506 error_reportf_err(local_err
, "%s: ", filename
);
518 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
522 Visitor
*v
= qobject_output_visitor_new(&obj
);
524 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
525 visit_complete(v
, &obj
);
526 str
= qobject_to_json_pretty(obj
);
528 qprintf(quiet
, "%s\n", qstring_get_str(str
));
534 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
536 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
537 qprintf(quiet
, "No errors were found on the image.\n");
539 if (check
->corruptions
) {
540 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
541 "Data may be corrupted, or further writes to the image "
548 "\n%" PRId64
" leaked clusters were found on the image.\n"
549 "This means waste of disk space, but no harm to data.\n",
553 if (check
->check_errors
) {
556 " internal errors have occurred during the check.\n",
557 check
->check_errors
);
561 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
562 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
563 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
564 check
->allocated_clusters
, check
->total_clusters
,
565 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
566 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
567 check
->compressed_clusters
* 100.0 /
568 check
->allocated_clusters
);
571 if (check
->image_end_offset
) {
573 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
577 static int collect_image_check(BlockDriverState
*bs
,
579 const char *filename
,
584 BdrvCheckResult result
;
586 ret
= bdrv_check(bs
, &result
, fix
);
591 check
->filename
= g_strdup(filename
);
592 check
->format
= g_strdup(bdrv_get_format_name(bs
));
593 check
->check_errors
= result
.check_errors
;
594 check
->corruptions
= result
.corruptions
;
595 check
->has_corruptions
= result
.corruptions
!= 0;
596 check
->leaks
= result
.leaks
;
597 check
->has_leaks
= result
.leaks
!= 0;
598 check
->corruptions_fixed
= result
.corruptions_fixed
;
599 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
600 check
->leaks_fixed
= result
.leaks_fixed
;
601 check
->has_leaks_fixed
= result
.leaks
!= 0;
602 check
->image_end_offset
= result
.image_end_offset
;
603 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
604 check
->total_clusters
= result
.bfi
.total_clusters
;
605 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
606 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
607 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
608 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
609 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
610 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
611 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
617 * Checks an image for consistency. Exit codes:
619 * 0 - Check completed, image is good
620 * 1 - Check not completed because of internal errors
621 * 2 - Check completed, image is corrupted
622 * 3 - Check completed, image has leaked clusters, but is good otherwise
623 * 63 - Checks are not supported by the image format
625 static int img_check(int argc
, char **argv
)
628 OutputFormat output_format
= OFORMAT_HUMAN
;
629 const char *filename
, *fmt
, *output
, *cache
;
631 BlockDriverState
*bs
;
633 int flags
= BDRV_O_CHECK
;
637 bool image_opts
= false;
641 cache
= BDRV_DEFAULT_CACHE
;
644 int option_index
= 0;
645 static const struct option long_options
[] = {
646 {"help", no_argument
, 0, 'h'},
647 {"format", required_argument
, 0, 'f'},
648 {"repair", required_argument
, 0, 'r'},
649 {"output", required_argument
, 0, OPTION_OUTPUT
},
650 {"object", required_argument
, 0, OPTION_OBJECT
},
651 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
654 c
= getopt_long(argc
, argv
, "hf:r:T:q",
655 long_options
, &option_index
);
668 flags
|= BDRV_O_RDWR
;
670 if (!strcmp(optarg
, "leaks")) {
671 fix
= BDRV_FIX_LEAKS
;
672 } else if (!strcmp(optarg
, "all")) {
673 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
675 error_exit("Unknown option value for -r "
676 "(expecting 'leaks' or 'all'): %s", optarg
);
688 case OPTION_OBJECT
: {
690 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
696 case OPTION_IMAGE_OPTS
:
701 if (optind
!= argc
- 1) {
702 error_exit("Expecting one image file name");
704 filename
= argv
[optind
++];
706 if (output
&& !strcmp(output
, "json")) {
707 output_format
= OFORMAT_JSON
;
708 } else if (output
&& !strcmp(output
, "human")) {
709 output_format
= OFORMAT_HUMAN
;
711 error_report("--output must be used with human or json as argument.");
715 if (qemu_opts_foreach(&qemu_object_opts
,
716 user_creatable_add_opts_foreach
,
721 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
723 error_report("Invalid source cache option: %s", cache
);
727 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
733 check
= g_new0(ImageCheck
, 1);
734 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
736 if (ret
== -ENOTSUP
) {
737 error_report("This image format does not support checks");
742 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
743 int corruptions_fixed
, leaks_fixed
;
745 leaks_fixed
= check
->leaks_fixed
;
746 corruptions_fixed
= check
->corruptions_fixed
;
748 if (output_format
== OFORMAT_HUMAN
) {
750 "The following inconsistencies were found and repaired:\n\n"
751 " %" PRId64
" leaked clusters\n"
752 " %" PRId64
" corruptions\n\n"
753 "Double checking the fixed image now...\n",
755 check
->corruptions_fixed
);
758 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
760 check
->leaks_fixed
= leaks_fixed
;
761 check
->corruptions_fixed
= corruptions_fixed
;
765 switch (output_format
) {
767 dump_human_image_check(check
, quiet
);
770 dump_json_image_check(check
, quiet
);
775 if (ret
|| check
->check_errors
) {
777 error_report("Check failed: %s", strerror(-ret
));
779 error_report("Check failed");
785 if (check
->corruptions
) {
787 } else if (check
->leaks
) {
794 qapi_free_ImageCheck(check
);
799 typedef struct CommonBlockJobCBInfo
{
800 BlockDriverState
*bs
;
802 } CommonBlockJobCBInfo
;
804 static void common_block_job_cb(void *opaque
, int ret
)
806 CommonBlockJobCBInfo
*cbi
= opaque
;
809 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
813 static void run_block_job(BlockJob
*job
, Error
**errp
)
815 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
817 /* FIXME In error cases, the job simply goes away and we access a dangling
819 aio_context_acquire(aio_context
);
821 aio_poll(aio_context
, true);
822 qemu_progress_print(job
->len
?
823 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
824 } while (!job
->ready
);
826 block_job_complete_sync(job
, errp
);
827 aio_context_release(aio_context
);
829 /* A block job may finish instantaneously without publishing any progress,
830 * so just signal completion here */
831 qemu_progress_print(100.f
, 0);
834 static int img_commit(int argc
, char **argv
)
837 const char *filename
, *fmt
, *cache
, *base
;
839 BlockDriverState
*bs
, *base_bs
;
841 bool progress
= false, quiet
= false, drop
= false;
843 Error
*local_err
= NULL
;
844 CommonBlockJobCBInfo cbi
;
845 bool image_opts
= false;
846 AioContext
*aio_context
;
849 cache
= BDRV_DEFAULT_CACHE
;
852 static const struct option long_options
[] = {
853 {"help", no_argument
, 0, 'h'},
854 {"object", required_argument
, 0, OPTION_OBJECT
},
855 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
858 c
= getopt_long(argc
, argv
, "f:ht:b:dpq",
888 case OPTION_OBJECT
: {
890 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
896 case OPTION_IMAGE_OPTS
:
902 /* Progress is not shown in Quiet mode */
907 if (optind
!= argc
- 1) {
908 error_exit("Expecting one image file name");
910 filename
= argv
[optind
++];
912 if (qemu_opts_foreach(&qemu_object_opts
,
913 user_creatable_add_opts_foreach
,
918 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
919 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
921 error_report("Invalid cache option: %s", cache
);
925 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
931 qemu_progress_init(progress
, 1.f
);
932 qemu_progress_print(0.f
, 100);
935 base_bs
= bdrv_find_backing_image(bs
, base
);
937 error_setg(&local_err
,
938 "Did not find '%s' in the backing chain of '%s'",
943 /* This is different from QMP, which by default uses the deepest file in
944 * the backing chain (i.e., the very base); however, the traditional
945 * behavior of qemu-img commit is using the immediate backing file. */
946 base_bs
= backing_bs(bs
);
948 error_setg(&local_err
, "Image does not have a backing file");
953 cbi
= (CommonBlockJobCBInfo
){
958 aio_context
= bdrv_get_aio_context(bs
);
959 aio_context_acquire(aio_context
);
960 commit_active_start("commit", bs
, base_bs
, BLOCK_JOB_DEFAULT
, 0,
961 BLOCKDEV_ON_ERROR_REPORT
, common_block_job_cb
, &cbi
,
963 aio_context_release(aio_context
);
968 /* When the block job completes, the BlockBackend reference will point to
969 * the old backing file. In order to avoid that the top image is already
970 * deleted, so we can still empty it afterwards, increment the reference
971 * counter here preemptively. */
976 job
= block_job_get("commit");
977 run_block_job(job
, &local_err
);
982 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
983 ret
= bs
->drv
->bdrv_make_empty(bs
);
985 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
1002 error_report_err(local_err
);
1006 qprintf(quiet
, "Image committed.\n");
1011 * Returns true iff the first sector pointed to by 'buf' contains at least
1014 * 'pnum' is set to the number of sectors (including and immediately following
1015 * the first one) that are known to be in the same allocated/unallocated state.
1017 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
1026 is_zero
= buffer_is_zero(buf
, 512);
1027 for(i
= 1; i
< n
; i
++) {
1029 if (is_zero
!= buffer_is_zero(buf
, 512)) {
1038 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1039 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1040 * breaking up write requests for only small sparse areas.
1042 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1046 int num_checked
, num_used
;
1052 ret
= is_allocated_sectors(buf
, n
, pnum
);
1058 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1060 num_checked
= num_used
;
1063 ret
= is_allocated_sectors(buf
, n
, pnum
);
1065 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1067 num_checked
+= *pnum
;
1069 num_used
= num_checked
;
1070 } else if (*pnum
>= min
) {
1080 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1081 * buffers matches, non-zero otherwise.
1083 * pnum is set to the number of sectors (including and immediately following
1084 * the first one) that are known to have the same comparison result
1086 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1097 res
= !!memcmp(buf1
, buf2
, 512);
1098 for(i
= 1; i
< n
; i
++) {
1102 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1111 #define IO_BUF_SIZE (2 * 1024 * 1024)
1113 static int64_t sectors_to_bytes(int64_t sectors
)
1115 return sectors
<< BDRV_SECTOR_BITS
;
1118 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1120 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1124 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1126 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1127 * data and negative value on error.
1129 * @param blk: BlockBackend for the image
1130 * @param sect_num: Number of first sector to check
1131 * @param sect_count: Number of sectors to check
1132 * @param filename: Name of disk file we are checking (logging purpose)
1133 * @param buffer: Allocated buffer for storing read data
1134 * @param quiet: Flag for quiet mode
1136 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1137 int sect_count
, const char *filename
,
1138 uint8_t *buffer
, bool quiet
)
1141 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1142 sect_count
<< BDRV_SECTOR_BITS
);
1144 error_report("Error while reading offset %" PRId64
" of %s: %s",
1145 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1148 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1149 if (ret
|| pnum
!= sect_count
) {
1150 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1151 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1159 * Compares two images. Exit codes:
1161 * 0 - Images are identical
1163 * >1 - Error occurred
1165 static int img_compare(int argc
, char **argv
)
1167 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1168 BlockBackend
*blk1
, *blk2
;
1169 BlockDriverState
*bs1
, *bs2
;
1170 int64_t total_sectors1
, total_sectors2
;
1171 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1173 int allocated1
, allocated2
;
1174 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1175 bool progress
= false, quiet
= false, strict
= false;
1178 int64_t total_sectors
;
1179 int64_t sector_num
= 0;
1182 uint64_t progress_base
;
1183 bool image_opts
= false;
1185 cache
= BDRV_DEFAULT_CACHE
;
1187 static const struct option long_options
[] = {
1188 {"help", no_argument
, 0, 'h'},
1189 {"object", required_argument
, 0, OPTION_OBJECT
},
1190 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1193 c
= getopt_long(argc
, argv
, "hf:F:T:pqs",
1194 long_options
, NULL
);
1221 case OPTION_OBJECT
: {
1223 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1230 case OPTION_IMAGE_OPTS
:
1236 /* Progress is not shown in Quiet mode */
1242 if (optind
!= argc
- 2) {
1243 error_exit("Expecting two image file names");
1245 filename1
= argv
[optind
++];
1246 filename2
= argv
[optind
++];
1248 if (qemu_opts_foreach(&qemu_object_opts
,
1249 user_creatable_add_opts_foreach
,
1255 /* Initialize before goto out */
1256 qemu_progress_init(progress
, 2.0);
1259 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1261 error_report("Invalid source cache option: %s", cache
);
1266 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
);
1272 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
);
1280 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1281 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1282 total_sectors1
= blk_nb_sectors(blk1
);
1283 if (total_sectors1
< 0) {
1284 error_report("Can't get size of %s: %s",
1285 filename1
, strerror(-total_sectors1
));
1289 total_sectors2
= blk_nb_sectors(blk2
);
1290 if (total_sectors2
< 0) {
1291 error_report("Can't get size of %s: %s",
1292 filename2
, strerror(-total_sectors2
));
1296 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1297 progress_base
= MAX(total_sectors1
, total_sectors2
);
1299 qemu_progress_print(0, 100);
1301 if (strict
&& total_sectors1
!= total_sectors2
) {
1303 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1308 int64_t status1
, status2
;
1309 BlockDriverState
*file
;
1311 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1312 if (nb_sectors
<= 0) {
1315 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1316 total_sectors1
- sector_num
,
1320 error_report("Sector allocation test failed for %s", filename1
);
1323 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1325 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1326 total_sectors2
- sector_num
,
1330 error_report("Sector allocation test failed for %s", filename2
);
1333 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1335 nb_sectors
= MIN(nb_sectors
, pnum1
);
1338 nb_sectors
= MIN(nb_sectors
, pnum2
);
1342 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1343 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1345 qprintf(quiet
, "Strict mode: Offset %" PRId64
1346 " block status mismatch!\n",
1347 sectors_to_bytes(sector_num
));
1351 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1352 nb_sectors
= MIN(pnum1
, pnum2
);
1353 } else if (allocated1
== allocated2
) {
1355 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1356 nb_sectors
<< BDRV_SECTOR_BITS
);
1358 error_report("Error while reading offset %" PRId64
" of %s:"
1359 " %s", sectors_to_bytes(sector_num
), filename1
,
1364 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1365 nb_sectors
<< BDRV_SECTOR_BITS
);
1367 error_report("Error while reading offset %" PRId64
1368 " of %s: %s", sectors_to_bytes(sector_num
),
1369 filename2
, strerror(-ret
));
1373 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1374 if (ret
|| pnum
!= nb_sectors
) {
1375 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1377 ret
? sector_num
: sector_num
+ pnum
));
1385 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1386 filename1
, buf1
, quiet
);
1388 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1389 filename2
, buf1
, quiet
);
1393 error_report("Error while reading offset %" PRId64
": %s",
1394 sectors_to_bytes(sector_num
), strerror(-ret
));
1400 sector_num
+= nb_sectors
;
1401 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1404 if (total_sectors1
!= total_sectors2
) {
1405 BlockBackend
*blk_over
;
1406 int64_t total_sectors_over
;
1407 const char *filename_over
;
1409 qprintf(quiet
, "Warning: Image size mismatch!\n");
1410 if (total_sectors1
> total_sectors2
) {
1411 total_sectors_over
= total_sectors1
;
1413 filename_over
= filename1
;
1415 total_sectors_over
= total_sectors2
;
1417 filename_over
= filename2
;
1421 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1422 if (nb_sectors
<= 0) {
1425 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
, sector_num
,
1429 error_report("Sector allocation test failed for %s",
1436 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1437 filename_over
, buf1
, quiet
);
1440 error_report("Error while reading offset %" PRId64
1441 " of %s: %s", sectors_to_bytes(sector_num
),
1442 filename_over
, strerror(-ret
));
1448 sector_num
+= nb_sectors
;
1449 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1453 qprintf(quiet
, "Images are identical.\n");
1463 qemu_progress_end();
1468 enum ImgConvertBlockStatus
{
1474 #define MAX_COROUTINES 16
1476 typedef struct ImgConvertState
{
1478 int64_t *src_sectors
;
1480 int64_t total_sectors
;
1481 int64_t allocated_sectors
;
1482 int64_t allocated_done
;
1485 enum ImgConvertBlockStatus status
;
1486 int64_t sector_next_status
;
1487 BlockBackend
*target
;
1490 bool target_has_backing
;
1493 size_t cluster_sectors
;
1496 int running_coroutines
;
1497 Coroutine
*co
[MAX_COROUTINES
];
1498 int64_t wait_sector_num
[MAX_COROUTINES
];
1503 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1504 int *src_cur
, int64_t *src_cur_offset
)
1507 *src_cur_offset
= 0;
1508 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1509 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1511 assert(*src_cur
< s
->src_num
);
1515 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1517 int64_t ret
, src_cur_offset
;
1520 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1522 assert(s
->total_sectors
> sector_num
);
1523 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1525 if (s
->sector_next_status
<= sector_num
) {
1526 BlockDriverState
*file
;
1527 ret
= bdrv_get_block_status(blk_bs(s
->src
[src_cur
]),
1528 sector_num
- src_cur_offset
,
1534 if (ret
& BDRV_BLOCK_ZERO
) {
1535 s
->status
= BLK_ZERO
;
1536 } else if (ret
& BDRV_BLOCK_DATA
) {
1537 s
->status
= BLK_DATA
;
1538 } else if (!s
->target_has_backing
) {
1539 /* Without a target backing file we must copy over the contents of
1540 * the backing file as well. */
1541 /* Check block status of the backing file chain to avoid
1542 * needlessly reading zeroes and limiting the iteration to the
1544 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[src_cur
]), NULL
,
1545 sector_num
- src_cur_offset
,
1551 if (ret
& BDRV_BLOCK_ZERO
) {
1552 s
->status
= BLK_ZERO
;
1554 s
->status
= BLK_DATA
;
1557 s
->status
= BLK_BACKING_FILE
;
1560 s
->sector_next_status
= sector_num
+ n
;
1563 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1564 if (s
->status
== BLK_DATA
) {
1565 n
= MIN(n
, s
->buf_sectors
);
1568 /* We need to write complete clusters for compressed images, so if an
1569 * unallocated area is shorter than that, we must consider the whole
1570 * cluster allocated. */
1571 if (s
->compressed
) {
1572 if (n
< s
->cluster_sectors
) {
1573 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1574 s
->status
= BLK_DATA
;
1576 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1583 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1584 int nb_sectors
, uint8_t *buf
)
1590 assert(nb_sectors
<= s
->buf_sectors
);
1591 while (nb_sectors
> 0) {
1594 int64_t bs_sectors
, src_cur_offset
;
1596 /* In the case of compression with multiple source files, we can get a
1597 * nb_sectors that spreads into the next part. So we must be able to
1598 * read across multiple BDSes for one convert_read() call. */
1599 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1600 blk
= s
->src
[src_cur
];
1601 bs_sectors
= s
->src_sectors
[src_cur
];
1603 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1605 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1606 qemu_iovec_init_external(&qiov
, &iov
, 1);
1608 ret
= blk_co_preadv(
1609 blk
, (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
,
1610 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1617 buf
+= n
* BDRV_SECTOR_SIZE
;
1624 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1625 int nb_sectors
, uint8_t *buf
,
1626 enum ImgConvertBlockStatus status
)
1632 while (nb_sectors
> 0) {
1635 case BLK_BACKING_FILE
:
1636 /* If we have a backing file, leave clusters unallocated that are
1637 * unallocated in the source image, so that the backing file is
1638 * visible at the respective offset. */
1639 assert(s
->target_has_backing
);
1643 /* We must always write compressed clusters as a whole, so don't
1644 * try to find zeroed parts in the buffer. We can only save the
1645 * write if the buffer is completely zeroed and we're allowed to
1646 * keep the target sparse. */
1647 if (s
->compressed
) {
1648 if (s
->has_zero_init
&& s
->min_sparse
&&
1649 buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
))
1651 assert(!s
->target_has_backing
);
1656 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1657 qemu_iovec_init_external(&qiov
, &iov
, 1);
1659 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1660 n
<< BDRV_SECTOR_BITS
, &qiov
,
1661 BDRV_REQ_WRITE_COMPRESSED
);
1668 /* If there is real non-zero data or we're told to keep the target
1669 * fully allocated (-S 0), we must write it. Otherwise we can treat
1670 * it as zero sectors. */
1671 if (!s
->min_sparse
||
1672 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
))
1675 iov
.iov_len
= n
<< BDRV_SECTOR_BITS
;
1676 qemu_iovec_init_external(&qiov
, &iov
, 1);
1678 ret
= blk_co_pwritev(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1679 n
<< BDRV_SECTOR_BITS
, &qiov
, 0);
1688 if (s
->has_zero_init
) {
1691 ret
= blk_co_pwrite_zeroes(s
->target
,
1692 sector_num
<< BDRV_SECTOR_BITS
,
1693 n
<< BDRV_SECTOR_BITS
, 0);
1702 buf
+= n
* BDRV_SECTOR_SIZE
;
1708 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1710 ImgConvertState
*s
= opaque
;
1711 uint8_t *buf
= NULL
;
1715 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1716 if (s
->co
[i
] == qemu_coroutine_self()) {
1723 s
->running_coroutines
++;
1724 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1729 enum ImgConvertBlockStatus status
;
1731 qemu_co_mutex_lock(&s
->lock
);
1732 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1733 qemu_co_mutex_unlock(&s
->lock
);
1736 n
= convert_iteration_sectors(s
, s
->sector_num
);
1738 qemu_co_mutex_unlock(&s
->lock
);
1742 /* save current sector and allocation status to local variables */
1743 sector_num
= s
->sector_num
;
1745 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1746 n
= MIN(n
, s
->buf_sectors
);
1748 /* increment global sector counter so that other coroutines can
1749 * already continue reading beyond this request */
1751 qemu_co_mutex_unlock(&s
->lock
);
1753 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
1754 s
->allocated_done
+= n
;
1755 qemu_progress_print(100.0 * s
->allocated_done
/
1756 s
->allocated_sectors
, 0);
1759 if (status
== BLK_DATA
) {
1760 ret
= convert_co_read(s
, sector_num
, n
, buf
);
1762 error_report("error while reading sector %" PRId64
1763 ": %s", sector_num
, strerror(-ret
));
1767 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
1769 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
1772 if (s
->wr_in_order
) {
1773 /* keep writes in order */
1774 while (s
->wr_offs
!= sector_num
) {
1775 if (s
->ret
!= -EINPROGRESS
) {
1778 s
->wait_sector_num
[index
] = sector_num
;
1779 qemu_coroutine_yield();
1781 s
->wait_sector_num
[index
] = -1;
1784 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
1786 error_report("error while writing sector %" PRId64
1787 ": %s", sector_num
, strerror(-ret
));
1792 if (s
->wr_in_order
) {
1793 /* reenter the coroutine that might have waited
1794 * for this write to complete */
1795 s
->wr_offs
= sector_num
+ n
;
1796 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1797 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
1799 * A -> B -> A cannot occur because A has
1800 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1801 * B will never enter A during this time window.
1803 qemu_coroutine_enter(s
->co
[i
]);
1812 s
->co
[index
] = NULL
;
1813 s
->running_coroutines
--;
1814 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
1815 /* the convert job finished successfully */
1820 static int convert_do_copy(ImgConvertState
*s
)
1823 int64_t sector_num
= 0;
1825 /* Check whether we have zero initialisation or can get it efficiently */
1826 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1827 ? bdrv_has_zero_init(blk_bs(s
->target
))
1830 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1831 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1833 ret
= blk_make_zero(s
->target
, BDRV_REQ_MAY_UNMAP
);
1835 s
->has_zero_init
= true;
1839 /* Allocate buffer for copied data. For compressed images, only one cluster
1840 * can be copied at a time. */
1841 if (s
->compressed
) {
1842 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1843 error_report("invalid cluster size");
1846 s
->buf_sectors
= s
->cluster_sectors
;
1849 while (sector_num
< s
->total_sectors
) {
1850 n
= convert_iteration_sectors(s
, sector_num
);
1854 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1856 s
->allocated_sectors
+= n
;
1862 s
->sector_next_status
= 0;
1863 s
->ret
= -EINPROGRESS
;
1865 qemu_co_mutex_init(&s
->lock
);
1866 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1867 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
1868 s
->wait_sector_num
[i
] = -1;
1869 qemu_coroutine_enter(s
->co
[i
]);
1872 while (s
->ret
== -EINPROGRESS
) {
1873 main_loop_wait(false);
1876 if (s
->compressed
&& !s
->ret
) {
1877 /* signal EOF to align */
1878 ret
= blk_pwrite_compressed(s
->target
, 0, NULL
, 0);
1887 static int img_convert(int argc
, char **argv
)
1889 int c
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1891 int progress
= 0, flags
, src_flags
;
1892 bool writethrough
, src_writethrough
;
1893 const char *fmt
, *out_fmt
, *cache
, *src_cache
, *out_baseimg
, *out_filename
;
1894 BlockDriver
*drv
, *proto_drv
;
1895 BlockBackend
**blk
= NULL
, *out_blk
= NULL
;
1896 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1897 int64_t total_sectors
;
1898 int64_t *bs_sectors
= NULL
;
1899 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1900 BlockDriverInfo bdi
;
1901 QemuOpts
*opts
= NULL
;
1902 QemuOptsList
*create_opts
= NULL
;
1903 const char *out_baseimg_param
;
1904 char *options
= NULL
;
1905 const char *snapshot_name
= NULL
;
1906 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1908 Error
*local_err
= NULL
;
1909 QemuOpts
*sn_opts
= NULL
;
1910 ImgConvertState state
;
1911 bool image_opts
= false;
1912 bool wr_in_order
= true;
1913 long num_coroutines
= 8;
1918 src_cache
= BDRV_DEFAULT_CACHE
;
1923 static const struct option long_options
[] = {
1924 {"help", no_argument
, 0, 'h'},
1925 {"object", required_argument
, 0, OPTION_OBJECT
},
1926 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1929 c
= getopt_long(argc
, argv
, "hf:O:B:ce6o:s:l:S:pt:T:qnm:W",
1930 long_options
, NULL
);
1946 out_baseimg
= optarg
;
1952 error_report("option -e is deprecated, please use \'-o "
1953 "encryption\' instead!");
1957 error_report("option -6 is deprecated, please use \'-o "
1958 "compat6\' instead!");
1962 if (!is_valid_option_list(optarg
)) {
1963 error_report("Invalid option list: %s", optarg
);
1968 options
= g_strdup(optarg
);
1970 char *old_options
= options
;
1971 options
= g_strdup_printf("%s,%s", options
, optarg
);
1972 g_free(old_options
);
1976 snapshot_name
= optarg
;
1979 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1980 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
1983 error_report("Failed in parsing snapshot param '%s'",
1989 snapshot_name
= optarg
;
1996 sval
= cvtnum(optarg
);
1998 error_report("Invalid minimum zero buffer size for sparse output specified");
2003 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2022 if (qemu_strtol(optarg
, NULL
, 0, &num_coroutines
) ||
2023 num_coroutines
< 1 || num_coroutines
> MAX_COROUTINES
) {
2024 error_report("Invalid number of coroutines. Allowed number of"
2025 " coroutines is between 1 and %d", MAX_COROUTINES
);
2031 wr_in_order
= false;
2034 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2040 case OPTION_IMAGE_OPTS
:
2046 if (qemu_opts_foreach(&qemu_object_opts
,
2047 user_creatable_add_opts_foreach
,
2052 if (!wr_in_order
&& compress
) {
2053 error_report("Out of order write and compress are mutually exclusive");
2058 /* Initialize before goto out */
2062 qemu_progress_init(progress
, 1.0);
2064 bs_n
= argc
- optind
- 1;
2065 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
2067 if (options
&& has_help_option(options
)) {
2068 ret
= print_block_option_help(out_filename
, out_fmt
);
2073 error_exit("Must specify image file name");
2077 if (bs_n
> 1 && out_baseimg
) {
2078 error_report("-B makes no sense when concatenating multiple input "
2085 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2087 error_report("Invalid source cache option: %s", src_cache
);
2091 qemu_progress_print(0, 100);
2093 blk
= g_new0(BlockBackend
*, bs_n
);
2094 bs
= g_new0(BlockDriverState
*, bs_n
);
2095 bs_sectors
= g_new(int64_t, bs_n
);
2098 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2099 blk
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2100 fmt
, src_flags
, src_writethrough
, quiet
);
2105 bs
[bs_i
] = blk_bs(blk
[bs_i
]);
2106 bs_sectors
[bs_i
] = blk_nb_sectors(blk
[bs_i
]);
2107 if (bs_sectors
[bs_i
] < 0) {
2108 error_report("Could not get size of %s: %s",
2109 argv
[optind
+ bs_i
], strerror(-bs_sectors
[bs_i
]));
2113 total_sectors
+= bs_sectors
[bs_i
];
2117 bdrv_snapshot_load_tmp(bs
[0],
2118 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2119 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2121 } else if (snapshot_name
!= NULL
) {
2123 error_report("No support for concatenating multiple snapshot");
2128 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
2131 error_reportf_err(local_err
, "Failed to load snapshot: ");
2136 /* Find driver and parse its options */
2137 drv
= bdrv_find_format(out_fmt
);
2139 error_report("Unknown file format '%s'", out_fmt
);
2144 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2146 error_report_err(local_err
);
2152 if (!drv
->create_opts
) {
2153 error_report("Format driver '%s' does not support image creation",
2159 if (!proto_drv
->create_opts
) {
2160 error_report("Protocol driver '%s' does not support image creation",
2161 proto_drv
->format_name
);
2166 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2167 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2169 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2171 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
2173 error_report_err(local_err
);
2179 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_sectors
* 512,
2181 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2187 /* Get backing file name if -o backing_file was used */
2188 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2189 if (out_baseimg_param
) {
2190 out_baseimg
= out_baseimg_param
;
2193 /* Check if compression is supported */
2196 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2197 const char *preallocation
=
2198 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2200 if (!drv
->bdrv_co_pwritev_compressed
) {
2201 error_report("Compression not supported for this file format");
2207 error_report("Compression and encryption not supported at "
2214 && strcmp(preallocation
, "off"))
2216 error_report("Compression and preallocation not supported at "
2224 /* Create the new image */
2225 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2227 error_reportf_err(local_err
, "%s: error while converting %s: ",
2228 out_filename
, out_fmt
);
2233 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2234 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2236 error_report("Invalid cache option: %s", cache
);
2240 /* XXX we should allow --image-opts to trigger use of
2241 * img_open() here, but then we have trouble with
2242 * the bdrv_create() call which takes different params.
2243 * Not critical right now, so fix can wait...
2245 out_blk
= img_open_file(out_filename
, out_fmt
, flags
, writethrough
, quiet
);
2250 out_bs
= blk_bs(out_blk
);
2252 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2253 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2255 bufsectors
= MIN(32768,
2257 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2258 out_bs
->bl
.pdiscard_alignment
>>
2259 BDRV_SECTOR_BITS
)));
2262 int64_t output_sectors
= blk_nb_sectors(out_blk
);
2263 if (output_sectors
< 0) {
2264 error_report("unable to get output image length: %s",
2265 strerror(-output_sectors
));
2268 } else if (output_sectors
< total_sectors
) {
2269 error_report("output file is smaller than input file");
2275 cluster_sectors
= 0;
2276 ret
= bdrv_get_info(out_bs
, &bdi
);
2279 error_report("could not get block driver info");
2283 compress
= compress
|| bdi
.needs_compressed_writes
;
2284 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2287 state
= (ImgConvertState
) {
2289 .src_sectors
= bs_sectors
,
2291 .total_sectors
= total_sectors
,
2293 .compressed
= compress
,
2294 .target_has_backing
= (bool) out_baseimg
,
2295 .min_sparse
= min_sparse
,
2296 .cluster_sectors
= cluster_sectors
,
2297 .buf_sectors
= bufsectors
,
2298 .wr_in_order
= wr_in_order
,
2299 .num_coroutines
= num_coroutines
,
2301 ret
= convert_do_copy(&state
);
2305 qemu_progress_print(100, 0);
2307 qemu_progress_end();
2308 qemu_opts_del(opts
);
2309 qemu_opts_free(create_opts
);
2310 qemu_opts_del(sn_opts
);
2314 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2315 blk_unref(blk
[bs_i
]);
2330 static void dump_snapshots(BlockDriverState
*bs
)
2332 QEMUSnapshotInfo
*sn_tab
, *sn
;
2335 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2338 printf("Snapshot list:\n");
2339 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2341 for(i
= 0; i
< nb_sns
; i
++) {
2343 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2349 static void dump_json_image_info_list(ImageInfoList
*list
)
2353 Visitor
*v
= qobject_output_visitor_new(&obj
);
2355 visit_type_ImageInfoList(v
, NULL
, &list
, &error_abort
);
2356 visit_complete(v
, &obj
);
2357 str
= qobject_to_json_pretty(obj
);
2358 assert(str
!= NULL
);
2359 printf("%s\n", qstring_get_str(str
));
2360 qobject_decref(obj
);
2365 static void dump_json_image_info(ImageInfo
*info
)
2369 Visitor
*v
= qobject_output_visitor_new(&obj
);
2371 visit_type_ImageInfo(v
, NULL
, &info
, &error_abort
);
2372 visit_complete(v
, &obj
);
2373 str
= qobject_to_json_pretty(obj
);
2374 assert(str
!= NULL
);
2375 printf("%s\n", qstring_get_str(str
));
2376 qobject_decref(obj
);
2381 static void dump_human_image_info_list(ImageInfoList
*list
)
2383 ImageInfoList
*elem
;
2386 for (elem
= list
; elem
; elem
= elem
->next
) {
2392 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2396 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2398 return strcmp(a
, b
) == 0;
2402 * Open an image file chain and return an ImageInfoList
2404 * @filename: topmost image filename
2405 * @fmt: topmost image format (may be NULL to autodetect)
2406 * @chain: true - enumerate entire backing file chain
2407 * false - only topmost image file
2409 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2410 * image file. If there was an error a message will have been printed to
2413 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2414 const char *filename
,
2418 ImageInfoList
*head
= NULL
;
2419 ImageInfoList
**last
= &head
;
2420 GHashTable
*filenames
;
2423 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2427 BlockDriverState
*bs
;
2429 ImageInfoList
*elem
;
2431 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2432 error_report("Backing file '%s' creates an infinite loop.",
2436 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2438 blk
= img_open(image_opts
, filename
, fmt
,
2439 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false);
2445 bdrv_query_image_info(bs
, &info
, &err
);
2447 error_report_err(err
);
2452 elem
= g_new0(ImageInfoList
, 1);
2459 filename
= fmt
= NULL
;
2461 if (info
->has_full_backing_filename
) {
2462 filename
= info
->full_backing_filename
;
2463 } else if (info
->has_backing_filename
) {
2464 error_report("Could not determine absolute backing filename,"
2465 " but backing filename '%s' present",
2466 info
->backing_filename
);
2469 if (info
->has_backing_filename_format
) {
2470 fmt
= info
->backing_filename_format
;
2474 g_hash_table_destroy(filenames
);
2478 qapi_free_ImageInfoList(head
);
2479 g_hash_table_destroy(filenames
);
2483 static int img_info(int argc
, char **argv
)
2486 OutputFormat output_format
= OFORMAT_HUMAN
;
2488 const char *filename
, *fmt
, *output
;
2489 ImageInfoList
*list
;
2490 bool image_opts
= false;
2495 int option_index
= 0;
2496 static const struct option long_options
[] = {
2497 {"help", no_argument
, 0, 'h'},
2498 {"format", required_argument
, 0, 'f'},
2499 {"output", required_argument
, 0, OPTION_OUTPUT
},
2500 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2501 {"object", required_argument
, 0, OPTION_OBJECT
},
2502 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2505 c
= getopt_long(argc
, argv
, "f:h",
2506 long_options
, &option_index
);
2521 case OPTION_BACKING_CHAIN
:
2524 case OPTION_OBJECT
: {
2526 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2532 case OPTION_IMAGE_OPTS
:
2537 if (optind
!= argc
- 1) {
2538 error_exit("Expecting one image file name");
2540 filename
= argv
[optind
++];
2542 if (output
&& !strcmp(output
, "json")) {
2543 output_format
= OFORMAT_JSON
;
2544 } else if (output
&& !strcmp(output
, "human")) {
2545 output_format
= OFORMAT_HUMAN
;
2546 } else if (output
) {
2547 error_report("--output must be used with human or json as argument.");
2551 if (qemu_opts_foreach(&qemu_object_opts
,
2552 user_creatable_add_opts_foreach
,
2557 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
);
2562 switch (output_format
) {
2564 dump_human_image_info_list(list
);
2568 dump_json_image_info_list(list
);
2570 dump_json_image_info(list
->value
);
2575 qapi_free_ImageInfoList(list
);
2579 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2582 switch (output_format
) {
2584 if (e
->data
&& !e
->has_offset
) {
2585 error_report("File contains external, encrypted or compressed clusters.");
2588 if (e
->data
&& !e
->zero
) {
2589 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2590 e
->start
, e
->length
,
2591 e
->has_offset
? e
->offset
: 0,
2592 e
->has_filename
? e
->filename
: "");
2594 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2595 * Modify the flags here to allow more coalescing.
2597 if (next
&& (!next
->data
|| next
->zero
)) {
2603 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2604 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2605 (e
->start
== 0 ? "[" : ",\n"),
2606 e
->start
, e
->length
, e
->depth
,
2607 e
->zero
? "true" : "false",
2608 e
->data
? "true" : "false");
2609 if (e
->has_offset
) {
2610 printf(", \"offset\": %"PRId64
"", e
->offset
);
2621 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2622 int nb_sectors
, MapEntry
*e
)
2626 BlockDriverState
*file
;
2629 /* As an optimization, we could cache the current range of unallocated
2630 * clusters in each file of the chain, and avoid querying the same
2636 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2642 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2645 bs
= backing_bs(bs
);
2654 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2657 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2658 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2659 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2660 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2661 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2662 .has_offset
= has_offset
,
2664 .has_filename
= file
&& has_offset
,
2665 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2671 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2673 if (curr
->length
== 0) {
2676 if (curr
->zero
!= next
->zero
||
2677 curr
->data
!= next
->data
||
2678 curr
->depth
!= next
->depth
||
2679 curr
->has_filename
!= next
->has_filename
||
2680 curr
->has_offset
!= next
->has_offset
) {
2683 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2686 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2692 static int img_map(int argc
, char **argv
)
2695 OutputFormat output_format
= OFORMAT_HUMAN
;
2697 BlockDriverState
*bs
;
2698 const char *filename
, *fmt
, *output
;
2700 MapEntry curr
= { .length
= 0 }, next
;
2702 bool image_opts
= false;
2707 int option_index
= 0;
2708 static const struct option long_options
[] = {
2709 {"help", no_argument
, 0, 'h'},
2710 {"format", required_argument
, 0, 'f'},
2711 {"output", required_argument
, 0, OPTION_OUTPUT
},
2712 {"object", required_argument
, 0, OPTION_OBJECT
},
2713 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2716 c
= getopt_long(argc
, argv
, "f:h",
2717 long_options
, &option_index
);
2732 case OPTION_OBJECT
: {
2734 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2740 case OPTION_IMAGE_OPTS
:
2745 if (optind
!= argc
- 1) {
2746 error_exit("Expecting one image file name");
2748 filename
= argv
[optind
];
2750 if (output
&& !strcmp(output
, "json")) {
2751 output_format
= OFORMAT_JSON
;
2752 } else if (output
&& !strcmp(output
, "human")) {
2753 output_format
= OFORMAT_HUMAN
;
2754 } else if (output
) {
2755 error_report("--output must be used with human or json as argument.");
2759 if (qemu_opts_foreach(&qemu_object_opts
,
2760 user_creatable_add_opts_foreach
,
2765 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false);
2771 if (output_format
== OFORMAT_HUMAN
) {
2772 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2775 length
= blk_getlength(blk
);
2776 while (curr
.start
+ curr
.length
< length
) {
2777 int64_t nsectors_left
;
2781 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2783 /* Probe up to 1 GiB at a time. */
2784 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2785 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2786 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2789 error_report("Could not read file metadata: %s", strerror(-ret
));
2793 if (entry_mergeable(&curr
, &next
)) {
2794 curr
.length
+= next
.length
;
2798 if (curr
.length
> 0) {
2799 dump_map_entry(output_format
, &curr
, &next
);
2804 dump_map_entry(output_format
, &curr
, NULL
);
2811 #define SNAPSHOT_LIST 1
2812 #define SNAPSHOT_CREATE 2
2813 #define SNAPSHOT_APPLY 3
2814 #define SNAPSHOT_DELETE 4
2816 static int img_snapshot(int argc
, char **argv
)
2819 BlockDriverState
*bs
;
2820 QEMUSnapshotInfo sn
;
2821 char *filename
, *snapshot_name
= NULL
;
2822 int c
, ret
= 0, bdrv_oflags
;
2827 bool image_opts
= false;
2829 bdrv_oflags
= BDRV_O_RDWR
;
2830 /* Parse commandline parameters */
2832 static const struct option long_options
[] = {
2833 {"help", no_argument
, 0, 'h'},
2834 {"object", required_argument
, 0, OPTION_OBJECT
},
2835 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2838 c
= getopt_long(argc
, argv
, "la:c:d:hq",
2839 long_options
, NULL
);
2850 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2853 action
= SNAPSHOT_LIST
;
2854 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2858 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2861 action
= SNAPSHOT_APPLY
;
2862 snapshot_name
= optarg
;
2866 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2869 action
= SNAPSHOT_CREATE
;
2870 snapshot_name
= optarg
;
2874 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2877 action
= SNAPSHOT_DELETE
;
2878 snapshot_name
= optarg
;
2883 case OPTION_OBJECT
: {
2885 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2891 case OPTION_IMAGE_OPTS
:
2897 if (optind
!= argc
- 1) {
2898 error_exit("Expecting one image file name");
2900 filename
= argv
[optind
++];
2902 if (qemu_opts_foreach(&qemu_object_opts
,
2903 user_creatable_add_opts_foreach
,
2908 /* Open the image */
2909 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
);
2915 /* Perform the requested action */
2921 case SNAPSHOT_CREATE
:
2922 memset(&sn
, 0, sizeof(sn
));
2923 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2925 qemu_gettimeofday(&tv
);
2926 sn
.date_sec
= tv
.tv_sec
;
2927 sn
.date_nsec
= tv
.tv_usec
* 1000;
2929 ret
= bdrv_snapshot_create(bs
, &sn
);
2931 error_report("Could not create snapshot '%s': %d (%s)",
2932 snapshot_name
, ret
, strerror(-ret
));
2936 case SNAPSHOT_APPLY
:
2937 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2939 error_report("Could not apply snapshot '%s': %d (%s)",
2940 snapshot_name
, ret
, strerror(-ret
));
2944 case SNAPSHOT_DELETE
:
2945 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2947 error_reportf_err(err
, "Could not delete snapshot '%s': ",
2962 static int img_rebase(int argc
, char **argv
)
2964 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
2965 uint8_t *buf_old
= NULL
;
2966 uint8_t *buf_new
= NULL
;
2967 BlockDriverState
*bs
= NULL
;
2969 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
2970 int c
, flags
, src_flags
, ret
;
2971 bool writethrough
, src_writethrough
;
2975 Error
*local_err
= NULL
;
2976 bool image_opts
= false;
2978 /* Parse commandline parameters */
2980 cache
= BDRV_DEFAULT_CACHE
;
2981 src_cache
= BDRV_DEFAULT_CACHE
;
2985 static const struct option long_options
[] = {
2986 {"help", no_argument
, 0, 'h'},
2987 {"object", required_argument
, 0, OPTION_OBJECT
},
2988 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2991 c
= getopt_long(argc
, argv
, "hf:F:b:upt:T:q",
2992 long_options
, NULL
);
3005 out_basefmt
= optarg
;
3008 out_baseimg
= optarg
;
3025 case OPTION_OBJECT
: {
3027 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3033 case OPTION_IMAGE_OPTS
:
3043 if (optind
!= argc
- 1) {
3044 error_exit("Expecting one image file name");
3046 if (!unsafe
&& !out_baseimg
) {
3047 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3049 filename
= argv
[optind
++];
3051 if (qemu_opts_foreach(&qemu_object_opts
,
3052 user_creatable_add_opts_foreach
,
3057 qemu_progress_init(progress
, 2.0);
3058 qemu_progress_print(0, 100);
3060 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3061 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3063 error_report("Invalid cache option: %s", cache
);
3068 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3070 error_report("Invalid source cache option: %s", src_cache
);
3074 /* The source files are opened read-only, don't care about WCE */
3075 assert((src_flags
& BDRV_O_RDWR
) == 0);
3076 (void) src_writethrough
;
3081 * Ignore the old backing file for unsafe rebase in case we want to correct
3082 * the reference to a renamed or moved backing file.
3084 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3091 if (out_basefmt
!= NULL
) {
3092 if (bdrv_find_format(out_basefmt
) == NULL
) {
3093 error_report("Invalid format name: '%s'", out_basefmt
);
3099 /* For safe rebasing we need to compare old and new backing file */
3101 char backing_name
[PATH_MAX
];
3102 QDict
*options
= NULL
;
3104 if (bs
->backing_format
[0] != '\0') {
3105 options
= qdict_new();
3106 qdict_put(options
, "driver", qstring_from_str(bs
->backing_format
));
3109 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3110 blk_old_backing
= blk_new_open(backing_name
, NULL
,
3111 options
, src_flags
, &local_err
);
3112 if (!blk_old_backing
) {
3113 error_reportf_err(local_err
,
3114 "Could not open old backing file '%s': ",
3120 if (out_baseimg
[0]) {
3122 options
= qdict_new();
3123 qdict_put(options
, "driver", qstring_from_str(out_basefmt
));
3128 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
3129 options
, src_flags
, &local_err
);
3130 if (!blk_new_backing
) {
3131 error_reportf_err(local_err
,
3132 "Could not open new backing file '%s': ",
3141 * Check each unallocated cluster in the COW file. If it is unallocated,
3142 * accesses go to the backing file. We must therefore compare this cluster
3143 * in the old and new backing file, and if they differ we need to copy it
3144 * from the old backing file into the COW file.
3146 * If qemu-img crashes during this step, no harm is done. The content of
3147 * the image is the same as the original one at any time.
3150 int64_t num_sectors
;
3151 int64_t old_backing_num_sectors
;
3152 int64_t new_backing_num_sectors
= 0;
3155 float local_progress
= 0;
3157 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3158 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3160 num_sectors
= blk_nb_sectors(blk
);
3161 if (num_sectors
< 0) {
3162 error_report("Could not get size of '%s': %s",
3163 filename
, strerror(-num_sectors
));
3167 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
3168 if (old_backing_num_sectors
< 0) {
3169 char backing_name
[PATH_MAX
];
3171 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
3172 error_report("Could not get size of '%s': %s",
3173 backing_name
, strerror(-old_backing_num_sectors
));
3177 if (blk_new_backing
) {
3178 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3179 if (new_backing_num_sectors
< 0) {
3180 error_report("Could not get size of '%s': %s",
3181 out_baseimg
, strerror(-new_backing_num_sectors
));
3187 if (num_sectors
!= 0) {
3188 local_progress
= (float)100 /
3189 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3192 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3194 /* How many sectors can we handle with the next read? */
3195 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3196 n
= (IO_BUF_SIZE
/ 512);
3198 n
= num_sectors
- sector
;
3201 /* If the cluster is allocated, we don't need to take action */
3202 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
3204 error_report("error while reading image metadata: %s",
3213 * Read old and new backing file and take into consideration that
3214 * backing files may be smaller than the COW image.
3216 if (sector
>= old_backing_num_sectors
) {
3217 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3219 if (sector
+ n
> old_backing_num_sectors
) {
3220 n
= old_backing_num_sectors
- sector
;
3223 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3224 buf_old
, n
<< BDRV_SECTOR_BITS
);
3226 error_report("error while reading from old backing file");
3231 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3232 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3234 if (sector
+ n
> new_backing_num_sectors
) {
3235 n
= new_backing_num_sectors
- sector
;
3238 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3239 buf_new
, n
<< BDRV_SECTOR_BITS
);
3241 error_report("error while reading from new backing file");
3246 /* If they differ, we need to write to the COW file */
3247 uint64_t written
= 0;
3249 while (written
< n
) {
3252 if (compare_sectors(buf_old
+ written
* 512,
3253 buf_new
+ written
* 512, n
- written
, &pnum
))
3255 ret
= blk_pwrite(blk
,
3256 (sector
+ written
) << BDRV_SECTOR_BITS
,
3257 buf_old
+ written
* 512,
3258 pnum
<< BDRV_SECTOR_BITS
, 0);
3260 error_report("Error while writing to COW image: %s",
3268 qemu_progress_print(local_progress
, 100);
3273 * Change the backing file. All clusters that are different from the old
3274 * backing file are overwritten in the COW file now, so the visible content
3275 * doesn't change when we switch the backing file.
3277 if (out_baseimg
&& *out_baseimg
) {
3278 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3280 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3283 if (ret
== -ENOSPC
) {
3284 error_report("Could not change the backing file to '%s': No "
3285 "space left in the file header", out_baseimg
);
3286 } else if (ret
< 0) {
3287 error_report("Could not change the backing file to '%s': %s",
3288 out_baseimg
, strerror(-ret
));
3291 qemu_progress_print(100, 0);
3293 * TODO At this point it is possible to check if any clusters that are
3294 * allocated in the COW file are the same in the backing file. If so, they
3295 * could be dropped from the COW file. Don't do this before switching the
3296 * backing file, in case of a crash this would lead to corruption.
3299 qemu_progress_end();
3302 blk_unref(blk_old_backing
);
3303 blk_unref(blk_new_backing
);
3305 qemu_vfree(buf_old
);
3306 qemu_vfree(buf_new
);
3315 static int img_resize(int argc
, char **argv
)
3318 int c
, ret
, relative
;
3319 const char *filename
, *fmt
, *size
;
3320 int64_t n
, total_size
;
3322 BlockBackend
*blk
= NULL
;
3325 static QemuOptsList resize_options
= {
3326 .name
= "resize_options",
3327 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3330 .name
= BLOCK_OPT_SIZE
,
3331 .type
= QEMU_OPT_SIZE
,
3332 .help
= "Virtual disk size"
3338 bool image_opts
= false;
3340 /* Remove size from argv manually so that negative numbers are not treated
3341 * as options by getopt. */
3343 error_exit("Not enough arguments");
3347 size
= argv
[--argc
];
3349 /* Parse getopt arguments */
3352 static const struct option long_options
[] = {
3353 {"help", no_argument
, 0, 'h'},
3354 {"object", required_argument
, 0, OPTION_OBJECT
},
3355 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3358 c
= getopt_long(argc
, argv
, "f:hq",
3359 long_options
, NULL
);
3374 case OPTION_OBJECT
: {
3376 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3382 case OPTION_IMAGE_OPTS
:
3387 if (optind
!= argc
- 1) {
3388 error_exit("Expecting one image file name");
3390 filename
= argv
[optind
++];
3392 if (qemu_opts_foreach(&qemu_object_opts
,
3393 user_creatable_add_opts_foreach
,
3398 /* Choose grow, shrink, or absolute resize mode */
3414 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3415 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3417 error_report_err(err
);
3419 qemu_opts_del(param
);
3422 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3423 qemu_opts_del(param
);
3425 blk
= img_open(image_opts
, filename
, fmt
,
3426 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
);
3433 total_size
= blk_getlength(blk
) + n
* relative
;
3437 if (total_size
<= 0) {
3438 error_report("New image size must be positive");
3443 ret
= blk_truncate(blk
, total_size
);
3446 qprintf(quiet
, "Image resized.\n");
3449 error_report("This image does not support resize");
3452 error_report("Image is read-only");
3455 error_report("Error resizing image: %s", strerror(-ret
));
3466 static void amend_status_cb(BlockDriverState
*bs
,
3467 int64_t offset
, int64_t total_work_size
,
3470 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3473 static int img_amend(int argc
, char **argv
)
3477 char *options
= NULL
;
3478 QemuOptsList
*create_opts
= NULL
;
3479 QemuOpts
*opts
= NULL
;
3480 const char *fmt
= NULL
, *filename
, *cache
;
3483 bool quiet
= false, progress
= false;
3484 BlockBackend
*blk
= NULL
;
3485 BlockDriverState
*bs
= NULL
;
3486 bool image_opts
= false;
3488 cache
= BDRV_DEFAULT_CACHE
;
3490 static const struct option long_options
[] = {
3491 {"help", no_argument
, 0, 'h'},
3492 {"object", required_argument
, 0, OPTION_OBJECT
},
3493 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3496 c
= getopt_long(argc
, argv
, "ho:f:t:pq",
3497 long_options
, NULL
);
3508 if (!is_valid_option_list(optarg
)) {
3509 error_report("Invalid option list: %s", optarg
);
3511 goto out_no_progress
;
3514 options
= g_strdup(optarg
);
3516 char *old_options
= options
;
3517 options
= g_strdup_printf("%s,%s", options
, optarg
);
3518 g_free(old_options
);
3534 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3538 goto out_no_progress
;
3541 case OPTION_IMAGE_OPTS
:
3548 error_exit("Must specify options (-o)");
3551 if (qemu_opts_foreach(&qemu_object_opts
,
3552 user_creatable_add_opts_foreach
,
3555 goto out_no_progress
;
3561 qemu_progress_init(progress
, 1.0);
3563 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3564 if (fmt
&& has_help_option(options
)) {
3565 /* If a format is explicitly specified (and possibly no filename is
3566 * given), print option help here */
3567 ret
= print_block_option_help(filename
, fmt
);
3571 if (optind
!= argc
- 1) {
3572 error_report("Expecting one image file name");
3577 flags
= BDRV_O_RDWR
;
3578 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3580 error_report("Invalid cache option: %s", cache
);
3584 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3591 fmt
= bs
->drv
->format_name
;
3593 if (has_help_option(options
)) {
3594 /* If the format was auto-detected, print option help here */
3595 ret
= print_block_option_help(filename
, fmt
);
3599 if (!bs
->drv
->create_opts
) {
3600 error_report("Format driver '%s' does not support any options to amend",
3606 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3607 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3608 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3610 error_report_err(err
);
3615 /* In case the driver does not call amend_status_cb() */
3616 qemu_progress_print(0.f
, 0);
3617 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3618 qemu_progress_print(100.f
, 0);
3620 error_report("Error while amending options: %s", strerror(-ret
));
3625 qemu_progress_end();
3629 qemu_opts_del(opts
);
3630 qemu_opts_free(create_opts
);
3639 typedef struct BenchData
{
3641 uint64_t image_size
;
3648 bool drain_on_flush
;
3657 static void bench_undrained_flush_cb(void *opaque
, int ret
)
3660 error_report("Failed flush request: %s", strerror(-ret
));
3665 static void bench_cb(void *opaque
, int ret
)
3667 BenchData
*b
= opaque
;
3671 error_report("Failed request: %s", strerror(-ret
));
3676 /* Just finished a flush with drained queue: Start next requests */
3677 assert(b
->in_flight
== 0);
3678 b
->in_flush
= false;
3679 } else if (b
->in_flight
> 0) {
3680 int remaining
= b
->n
- b
->in_flight
;
3685 /* Time for flush? Drain queue if requested, then flush */
3686 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
3687 if (!b
->in_flight
|| !b
->drain_on_flush
) {
3688 BlockCompletionFunc
*cb
;
3690 if (b
->drain_on_flush
) {
3694 cb
= bench_undrained_flush_cb
;
3697 acb
= blk_aio_flush(b
->blk
, cb
, b
);
3699 error_report("Failed to issue flush request");
3703 if (b
->drain_on_flush
) {
3709 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
3710 int64_t offset
= b
->offset
;
3711 /* blk_aio_* might look for completed I/Os and kick bench_cb
3712 * again, so make sure this operation is counted by in_flight
3713 * and b->offset is ready for the next submission.
3716 b
->offset
+= b
->step
;
3717 b
->offset
%= b
->image_size
;
3719 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3721 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
3724 error_report("Failed to issue request");
3730 static int img_bench(int argc
, char **argv
)
3733 const char *fmt
= NULL
, *filename
;
3735 bool image_opts
= false;
3736 bool is_write
= false;
3740 size_t bufsize
= 4096;
3743 int flush_interval
= 0;
3744 bool drain_on_flush
= true;
3746 BlockBackend
*blk
= NULL
;
3747 BenchData data
= {};
3749 bool writethrough
= false;
3750 struct timeval t1
, t2
;
3754 static const struct option long_options
[] = {
3755 {"help", no_argument
, 0, 'h'},
3756 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
3757 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3758 {"pattern", required_argument
, 0, OPTION_PATTERN
},
3759 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
3762 c
= getopt_long(argc
, argv
, "hc:d:f:no:qs:S:t:w", long_options
, NULL
);
3776 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3777 error_report("Invalid request count specified");
3787 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3788 error_report("Invalid queue depth specified");
3798 flags
|= BDRV_O_NATIVE_AIO
;
3802 offset
= cvtnum(optarg
);
3804 error_report("Invalid offset specified");
3817 sval
= cvtnum(optarg
);
3818 if (sval
< 0 || sval
> INT_MAX
) {
3819 error_report("Invalid buffer size specified");
3830 sval
= cvtnum(optarg
);
3831 if (sval
< 0 || sval
> INT_MAX
) {
3832 error_report("Invalid step size specified");
3840 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
3842 error_report("Invalid cache mode");
3848 flags
|= BDRV_O_RDWR
;
3851 case OPTION_PATTERN
:
3855 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
3856 error_report("Invalid pattern byte specified");
3862 case OPTION_FLUSH_INTERVAL
:
3866 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
3867 error_report("Invalid flush interval specified");
3870 flush_interval
= res
;
3873 case OPTION_NO_DRAIN
:
3874 drain_on_flush
= false;
3876 case OPTION_IMAGE_OPTS
:
3882 if (optind
!= argc
- 1) {
3883 error_exit("Expecting one image file name");
3885 filename
= argv
[argc
- 1];
3887 if (!is_write
&& flush_interval
) {
3888 error_report("--flush-interval is only available in write tests");
3892 if (flush_interval
&& flush_interval
< depth
) {
3893 error_report("Flush interval can't be smaller than depth");
3898 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3904 image_size
= blk_getlength(blk
);
3905 if (image_size
< 0) {
3910 data
= (BenchData
) {
3912 .image_size
= image_size
,
3914 .step
= step
?: bufsize
,
3919 .flush_interval
= flush_interval
,
3920 .drain_on_flush
= drain_on_flush
,
3922 printf("Sending %d %s requests, %d bytes each, %d in parallel "
3923 "(starting at offset %" PRId64
", step size %d)\n",
3924 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
3925 data
.offset
, data
.step
);
3926 if (flush_interval
) {
3927 printf("Sending flush every %d requests\n", flush_interval
);
3930 data
.buf
= blk_blockalign(blk
, data
.nrreq
* data
.bufsize
);
3931 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
3933 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
3934 for (i
= 0; i
< data
.nrreq
; i
++) {
3935 qemu_iovec_init(&data
.qiov
[i
], 1);
3936 qemu_iovec_add(&data
.qiov
[i
],
3937 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
3940 gettimeofday(&t1
, NULL
);
3943 while (data
.n
> 0) {
3944 main_loop_wait(false);
3946 gettimeofday(&t2
, NULL
);
3948 printf("Run completed in %3.3f seconds.\n",
3949 (t2
.tv_sec
- t1
.tv_sec
)
3950 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
3953 qemu_vfree(data
.buf
);
3974 int bsz
; /* Block size */
3982 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
3986 static int img_dd_bs(const char *arg
,
3987 struct DdIo
*in
, struct DdIo
*out
,
3994 if (res
<= 0 || res
> INT_MAX
) {
3995 error_report("invalid number: '%s'", arg
);
3998 in
->bsz
= out
->bsz
= res
;
4003 static int img_dd_count(const char *arg
,
4004 struct DdIo
*in
, struct DdIo
*out
,
4007 dd
->count
= cvtnum(arg
);
4009 if (dd
->count
< 0) {
4010 error_report("invalid number: '%s'", arg
);
4017 static int img_dd_if(const char *arg
,
4018 struct DdIo
*in
, struct DdIo
*out
,
4021 in
->filename
= g_strdup(arg
);
4026 static int img_dd_of(const char *arg
,
4027 struct DdIo
*in
, struct DdIo
*out
,
4030 out
->filename
= g_strdup(arg
);
4035 static int img_dd_skip(const char *arg
,
4036 struct DdIo
*in
, struct DdIo
*out
,
4039 in
->offset
= cvtnum(arg
);
4041 if (in
->offset
< 0) {
4042 error_report("invalid number: '%s'", arg
);
4049 static int img_dd(int argc
, char **argv
)
4054 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4055 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4056 QemuOpts
*opts
= NULL
;
4057 QemuOptsList
*create_opts
= NULL
;
4058 Error
*local_err
= NULL
;
4059 bool image_opts
= false;
4061 const char *out_fmt
= "raw";
4062 const char *fmt
= NULL
;
4064 int64_t block_count
= 0, out_pos
, in_pos
;
4065 struct DdInfo dd
= {
4070 .bsz
= 512, /* Block size is by default 512 bytes */
4082 const struct DdOpts options
[] = {
4083 { "bs", img_dd_bs
, C_BS
},
4084 { "count", img_dd_count
, C_COUNT
},
4085 { "if", img_dd_if
, C_IF
},
4086 { "of", img_dd_of
, C_OF
},
4087 { "skip", img_dd_skip
, C_SKIP
},
4090 const struct option long_options
[] = {
4091 { "help", no_argument
, 0, 'h'},
4092 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4096 while ((c
= getopt_long(argc
, argv
, "hf:O:", long_options
, NULL
))) {
4108 error_report("Try 'qemu-img --help' for more information.");
4114 case OPTION_IMAGE_OPTS
:
4120 for (i
= optind
; i
< argc
; i
++) {
4122 arg
= g_strdup(argv
[i
]);
4124 tmp
= strchr(arg
, '=');
4126 error_report("unrecognized operand %s", arg
);
4133 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
4134 if (!strcmp(arg
, options
[j
].name
)) {
4138 if (options
[j
].name
== NULL
) {
4139 error_report("unrecognized operand %s", arg
);
4144 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
4148 dd
.flags
|= options
[j
].flag
;
4153 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
4154 error_report("Must specify both input and output files");
4158 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false);
4165 drv
= bdrv_find_format(out_fmt
);
4167 error_report("Unknown file format");
4171 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
4174 error_report_err(local_err
);
4178 if (!drv
->create_opts
) {
4179 error_report("Format driver '%s' does not support image creation",
4184 if (!proto_drv
->create_opts
) {
4185 error_report("Protocol driver '%s' does not support image creation",
4186 proto_drv
->format_name
);
4190 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
4191 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
4193 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
4195 size
= blk_getlength(blk1
);
4197 error_report("Failed to get size for '%s'", in
.filename
);
4202 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
4203 dd
.count
* in
.bsz
< size
) {
4204 size
= dd
.count
* in
.bsz
;
4207 /* Overflow means the specified offset is beyond input image's size */
4208 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4209 size
< in
.bsz
* in
.offset
)) {
4210 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
4212 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
4213 size
- in
.bsz
* in
.offset
, &error_abort
);
4216 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
4218 error_reportf_err(local_err
,
4219 "%s: error while creating output image: ",
4225 blk2
= img_open(image_opts
, out
.filename
, out_fmt
, BDRV_O_RDWR
,
4233 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
4234 size
< in
.offset
* in
.bsz
)) {
4235 /* We give a warning if the skip option is bigger than the input
4236 * size and create an empty output disk image (i.e. like dd(1)).
4238 error_report("%s: cannot skip to specified offset", in
.filename
);
4241 in_pos
= in
.offset
* in
.bsz
;
4244 in
.buf
= g_new(uint8_t, in
.bsz
);
4246 for (out_pos
= 0; in_pos
< size
; block_count
++) {
4247 int in_ret
, out_ret
;
4249 if (in_pos
+ in
.bsz
> size
) {
4250 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, size
- in_pos
);
4252 in_ret
= blk_pread(blk1
, in_pos
, in
.buf
, in
.bsz
);
4255 error_report("error while reading from input image file: %s",
4262 out_ret
= blk_pwrite(blk2
, out_pos
, in
.buf
, in_ret
, 0);
4265 error_report("error while writing to output image file: %s",
4266 strerror(-out_ret
));
4275 qemu_opts_del(opts
);
4276 qemu_opts_free(create_opts
);
4279 g_free(in
.filename
);
4280 g_free(out
.filename
);
4291 static const img_cmd_t img_cmds
[] = {
4292 #define DEF(option, callback, arg_string) \
4293 { option, callback },
4294 #include "qemu-img-cmds.h"
4300 int main(int argc
, char **argv
)
4302 const img_cmd_t
*cmd
;
4303 const char *cmdname
;
4304 Error
*local_error
= NULL
;
4305 char *trace_file
= NULL
;
4307 static const struct option long_options
[] = {
4308 {"help", no_argument
, 0, 'h'},
4309 {"version", no_argument
, 0, 'V'},
4310 {"trace", required_argument
, NULL
, 'T'},
4315 signal(SIGPIPE
, SIG_IGN
);
4318 module_call_init(MODULE_INIT_TRACE
);
4319 error_set_progname(argv
[0]);
4320 qemu_init_exec_dir(argv
[0]);
4322 if (qemu_init_main_loop(&local_error
)) {
4323 error_report_err(local_error
);
4327 qcrypto_init(&error_fatal
);
4329 module_call_init(MODULE_INIT_QOM
);
4332 error_exit("Not enough arguments");
4335 qemu_add_opts(&qemu_object_opts
);
4336 qemu_add_opts(&qemu_source_opts
);
4337 qemu_add_opts(&qemu_trace_opts
);
4339 while ((c
= getopt_long(argc
, argv
, "+hVT:", long_options
, NULL
)) != -1) {
4345 printf(QEMU_IMG_VERSION
);
4349 trace_file
= trace_opt_parse(optarg
);
4354 cmdname
= argv
[optind
];
4356 /* reset getopt_long scanning */
4364 if (!trace_init_backends()) {
4367 trace_init_file(trace_file
);
4368 qemu_set_log(LOG_TRACE
);
4370 /* find the command */
4371 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
4372 if (!strcmp(cmdname
, cmd
->name
)) {
4373 return cmd
->handler(argc
, argv
);
4378 error_exit("Command not found: %s", cmdname
);