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/qmp-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"
35 #include "qom/object_interfaces.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/block-backend.h"
38 #include "block/block_int.h"
39 #include "block/blockjob.h"
40 #include "block/qapi.h"
41 #include "crypto/init.h"
44 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
45 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
47 typedef struct img_cmd_t
{
49 int (*handler
)(int argc
, char **argv
);
54 OPTION_BACKING_CHAIN
= 257,
56 OPTION_IMAGE_OPTS
= 259,
59 typedef enum OutputFormat
{
64 /* Default to cache=writeback as data integrity is not important for qemu-img */
65 #define BDRV_DEFAULT_CACHE "writeback"
67 static void format_print(void *opaque
, const char *name
)
72 static void QEMU_NORETURN
GCC_FMT_ATTR(1, 2) error_exit(const char *fmt
, ...)
76 error_printf("qemu-img: ");
79 error_vprintf(fmt
, ap
);
82 error_printf("\nTry 'qemu-img --help' for more information\n");
86 /* Please keep in synch with qemu-img.texi */
87 static void QEMU_NORETURN
help(void)
89 const char *help_msg
=
91 "usage: qemu-img command [command options]\n"
92 "QEMU disk image utility\n"
95 #define DEF(option, callback, arg_string) \
97 #include "qemu-img-cmds.h"
101 "Command parameters:\n"
102 " 'filename' is a disk image filename\n"
103 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
104 " manual page for a description of the object properties. The most common\n"
105 " object type is a 'secret', which is used to supply passwords and/or\n"
106 " encryption keys.\n"
107 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
108 " 'cache' is the cache mode used to write the output disk image, the valid\n"
109 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
110 " 'directsync' and 'unsafe' (default for convert)\n"
111 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
112 " options are the same as for the 'cache' option\n"
113 " 'size' is the disk image size in bytes. Optional suffixes\n"
114 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
115 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
116 " supported. 'b' is ignored.\n"
117 " 'output_filename' is the destination disk image filename\n"
118 " 'output_fmt' is the destination format\n"
119 " 'options' is a comma separated list of format specific options in a\n"
120 " name=value format. Use -o ? for an overview of the options supported by the\n"
122 " 'snapshot_param' is param used for internal snapshot, format\n"
123 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
125 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
127 " '-c' indicates that target image must be compressed (qcow format only)\n"
128 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
129 " match exactly. The image doesn't need a working backing file before\n"
130 " rebasing in this case (useful for renaming the backing file)\n"
131 " '-h' with or without a command shows this help and lists the supported formats\n"
132 " '-p' show progress of command (only certain commands)\n"
133 " '-q' use Quiet mode - do not print any output (except errors)\n"
134 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
135 " contain only zeros for qemu-img to create a sparse image during\n"
136 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
137 " unallocated or zero sectors, and the destination image will always be\n"
139 " '--output' takes the format in which the output must be done (human or json)\n"
140 " '-n' skips the target volume creation (useful if the volume is created\n"
141 " prior to running qemu-img)\n"
143 "Parameters to check subcommand:\n"
144 " '-r' tries to repair any inconsistencies that are found during the check.\n"
145 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
146 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
147 " hiding corruption that has already occurred.\n"
149 "Parameters to snapshot subcommand:\n"
150 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
151 " '-a' applies a snapshot (revert disk to saved state)\n"
152 " '-c' creates a snapshot\n"
153 " '-d' deletes a snapshot\n"
154 " '-l' lists all snapshots in the given image\n"
156 "Parameters to compare subcommand:\n"
157 " '-f' first image format\n"
158 " '-F' second image format\n"
159 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
161 printf("%s\nSupported formats:", help_msg
);
162 bdrv_iterate_format(format_print
, NULL
);
167 static QemuOptsList qemu_object_opts
= {
169 .implied_opt_name
= "qom-type",
170 .head
= QTAILQ_HEAD_INITIALIZER(qemu_object_opts
.head
),
176 static QemuOptsList qemu_source_opts
= {
178 .implied_opt_name
= "file",
179 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
185 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
191 ret
= vprintf(fmt
, args
);
198 static int print_block_option_help(const char *filename
, const char *fmt
)
200 BlockDriver
*drv
, *proto_drv
;
201 QemuOptsList
*create_opts
= NULL
;
202 Error
*local_err
= NULL
;
204 /* Find driver and parse its options */
205 drv
= bdrv_find_format(fmt
);
207 error_report("Unknown file format '%s'", fmt
);
211 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
213 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
215 error_report_err(local_err
);
216 qemu_opts_free(create_opts
);
219 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
222 qemu_opts_print_help(create_opts
);
223 qemu_opts_free(create_opts
);
228 static int img_open_password(BlockBackend
*blk
, const char *filename
,
229 int flags
, bool quiet
)
231 BlockDriverState
*bs
;
235 if (bdrv_is_encrypted(bs
) && bdrv_key_required(bs
) &&
236 !(flags
& BDRV_O_NO_IO
)) {
237 qprintf(quiet
, "Disk image '%s' is encrypted.\n", filename
);
238 if (qemu_read_password(password
, sizeof(password
)) < 0) {
239 error_report("No password given");
242 if (bdrv_set_key(bs
, password
) < 0) {
243 error_report("invalid password");
251 static BlockBackend
*img_open_opts(const char *optstr
,
252 QemuOpts
*opts
, int flags
, bool writethrough
,
256 Error
*local_err
= NULL
;
258 options
= qemu_opts_to_qdict(opts
, NULL
);
259 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
261 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
264 blk_set_enable_write_cache(blk
, !writethrough
);
266 if (img_open_password(blk
, optstr
, flags
, quiet
) < 0) {
273 static BlockBackend
*img_open_file(const char *filename
,
274 const char *fmt
, int flags
,
275 bool writethrough
, bool quiet
)
278 Error
*local_err
= NULL
;
279 QDict
*options
= NULL
;
282 options
= qdict_new();
283 qdict_put(options
, "driver", qstring_from_str(fmt
));
286 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
288 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
291 blk_set_enable_write_cache(blk
, !writethrough
);
293 if (img_open_password(blk
, filename
, flags
, quiet
) < 0) {
301 static BlockBackend
*img_open(bool image_opts
,
302 const char *filename
,
303 const char *fmt
, int flags
, bool writethrough
,
310 error_report("--image-opts and --format are mutually exclusive");
313 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
318 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
);
320 blk
= img_open_file(filename
, fmt
, flags
, writethrough
, quiet
);
326 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
327 const char *base_filename
,
328 const char *base_fmt
)
333 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
, &err
);
335 error_report("Backing file not supported for file format '%s'",
342 qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, &err
);
344 error_report("Backing file format not supported for file "
353 static int img_create(int argc
, char **argv
)
356 uint64_t img_size
= -1;
357 const char *fmt
= "raw";
358 const char *base_fmt
= NULL
;
359 const char *filename
;
360 const char *base_filename
= NULL
;
361 char *options
= NULL
;
362 Error
*local_err
= NULL
;
366 static const struct option long_options
[] = {
367 {"help", no_argument
, 0, 'h'},
368 {"object", required_argument
, 0, OPTION_OBJECT
},
371 c
= getopt_long(argc
, argv
, "F:b:f:he6o:q",
385 base_filename
= optarg
;
391 error_report("option -e is deprecated, please use \'-o "
392 "encryption\' instead!");
395 error_report("option -6 is deprecated, please use \'-o "
396 "compat6\' instead!");
399 if (!is_valid_option_list(optarg
)) {
400 error_report("Invalid option list: %s", optarg
);
404 options
= g_strdup(optarg
);
406 char *old_options
= options
;
407 options
= g_strdup_printf("%s,%s", options
, optarg
);
414 case OPTION_OBJECT
: {
416 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
425 /* Get the filename */
426 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
427 if (options
&& has_help_option(options
)) {
429 return print_block_option_help(filename
, fmt
);
432 if (optind
>= argc
) {
433 error_exit("Expecting image file name");
437 if (qemu_opts_foreach(&qemu_object_opts
,
438 user_creatable_add_opts_foreach
,
443 /* Get image size, if specified */
447 sval
= qemu_strtosz_suffix(argv
[optind
++], &end
,
448 QEMU_STRTOSZ_DEFSUFFIX_B
);
449 if (sval
< 0 || *end
) {
450 if (sval
== -ERANGE
) {
451 error_report("Image size must be less than 8 EiB!");
453 error_report("Invalid image size specified! You may use k, M, "
454 "G, T, P or E suffixes for ");
455 error_report("kilobytes, megabytes, gigabytes, terabytes, "
456 "petabytes and exabytes.");
460 img_size
= (uint64_t)sval
;
462 if (optind
!= argc
) {
463 error_exit("Unexpected argument: %s", argv
[optind
]);
466 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
467 options
, img_size
, 0, &local_err
, quiet
);
469 error_reportf_err(local_err
, "%s: ", filename
);
481 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
483 Error
*local_err
= NULL
;
485 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
487 visit_type_ImageCheck(qmp_output_get_visitor(ov
), NULL
, &check
,
489 obj
= qmp_output_get_qobject(ov
);
490 str
= qobject_to_json_pretty(obj
);
492 qprintf(quiet
, "%s\n", qstring_get_str(str
));
494 qmp_output_visitor_cleanup(ov
);
498 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
500 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
501 qprintf(quiet
, "No errors were found on the image.\n");
503 if (check
->corruptions
) {
504 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
505 "Data may be corrupted, or further writes to the image "
512 "\n%" PRId64
" leaked clusters were found on the image.\n"
513 "This means waste of disk space, but no harm to data.\n",
517 if (check
->check_errors
) {
520 " internal errors have occurred during the check.\n",
521 check
->check_errors
);
525 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
526 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
527 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
528 check
->allocated_clusters
, check
->total_clusters
,
529 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
530 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
531 check
->compressed_clusters
* 100.0 /
532 check
->allocated_clusters
);
535 if (check
->image_end_offset
) {
537 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
541 static int collect_image_check(BlockDriverState
*bs
,
543 const char *filename
,
548 BdrvCheckResult result
;
550 ret
= bdrv_check(bs
, &result
, fix
);
555 check
->filename
= g_strdup(filename
);
556 check
->format
= g_strdup(bdrv_get_format_name(bs
));
557 check
->check_errors
= result
.check_errors
;
558 check
->corruptions
= result
.corruptions
;
559 check
->has_corruptions
= result
.corruptions
!= 0;
560 check
->leaks
= result
.leaks
;
561 check
->has_leaks
= result
.leaks
!= 0;
562 check
->corruptions_fixed
= result
.corruptions_fixed
;
563 check
->has_corruptions_fixed
= result
.corruptions
!= 0;
564 check
->leaks_fixed
= result
.leaks_fixed
;
565 check
->has_leaks_fixed
= result
.leaks
!= 0;
566 check
->image_end_offset
= result
.image_end_offset
;
567 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
568 check
->total_clusters
= result
.bfi
.total_clusters
;
569 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
570 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
571 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
572 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
573 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
574 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
575 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
581 * Checks an image for consistency. Exit codes:
583 * 0 - Check completed, image is good
584 * 1 - Check not completed because of internal errors
585 * 2 - Check completed, image is corrupted
586 * 3 - Check completed, image has leaked clusters, but is good otherwise
587 * 63 - Checks are not supported by the image format
589 static int img_check(int argc
, char **argv
)
592 OutputFormat output_format
= OFORMAT_HUMAN
;
593 const char *filename
, *fmt
, *output
, *cache
;
595 BlockDriverState
*bs
;
597 int flags
= BDRV_O_CHECK
;
601 bool image_opts
= false;
605 cache
= BDRV_DEFAULT_CACHE
;
608 int option_index
= 0;
609 static const struct option long_options
[] = {
610 {"help", no_argument
, 0, 'h'},
611 {"format", required_argument
, 0, 'f'},
612 {"repair", required_argument
, 0, 'r'},
613 {"output", required_argument
, 0, OPTION_OUTPUT
},
614 {"object", required_argument
, 0, OPTION_OBJECT
},
615 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
618 c
= getopt_long(argc
, argv
, "hf:r:T:q",
619 long_options
, &option_index
);
632 flags
|= BDRV_O_RDWR
;
634 if (!strcmp(optarg
, "leaks")) {
635 fix
= BDRV_FIX_LEAKS
;
636 } else if (!strcmp(optarg
, "all")) {
637 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
639 error_exit("Unknown option value for -r "
640 "(expecting 'leaks' or 'all'): %s", optarg
);
652 case OPTION_OBJECT
: {
654 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
660 case OPTION_IMAGE_OPTS
:
665 if (optind
!= argc
- 1) {
666 error_exit("Expecting one image file name");
668 filename
= argv
[optind
++];
670 if (output
&& !strcmp(output
, "json")) {
671 output_format
= OFORMAT_JSON
;
672 } else if (output
&& !strcmp(output
, "human")) {
673 output_format
= OFORMAT_HUMAN
;
675 error_report("--output must be used with human or json as argument.");
679 if (qemu_opts_foreach(&qemu_object_opts
,
680 user_creatable_add_opts_foreach
,
685 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
687 error_report("Invalid source cache option: %s", cache
);
691 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
697 check
= g_new0(ImageCheck
, 1);
698 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
700 if (ret
== -ENOTSUP
) {
701 error_report("This image format does not support checks");
706 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
707 int corruptions_fixed
, leaks_fixed
;
709 leaks_fixed
= check
->leaks_fixed
;
710 corruptions_fixed
= check
->corruptions_fixed
;
712 if (output_format
== OFORMAT_HUMAN
) {
714 "The following inconsistencies were found and repaired:\n\n"
715 " %" PRId64
" leaked clusters\n"
716 " %" PRId64
" corruptions\n\n"
717 "Double checking the fixed image now...\n",
719 check
->corruptions_fixed
);
722 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
724 check
->leaks_fixed
= leaks_fixed
;
725 check
->corruptions_fixed
= corruptions_fixed
;
729 switch (output_format
) {
731 dump_human_image_check(check
, quiet
);
734 dump_json_image_check(check
, quiet
);
739 if (ret
|| check
->check_errors
) {
741 error_report("Check failed: %s", strerror(-ret
));
743 error_report("Check failed");
749 if (check
->corruptions
) {
751 } else if (check
->leaks
) {
758 qapi_free_ImageCheck(check
);
763 typedef struct CommonBlockJobCBInfo
{
764 BlockDriverState
*bs
;
766 } CommonBlockJobCBInfo
;
768 static void common_block_job_cb(void *opaque
, int ret
)
770 CommonBlockJobCBInfo
*cbi
= opaque
;
773 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
777 static void run_block_job(BlockJob
*job
, Error
**errp
)
779 AioContext
*aio_context
= blk_get_aio_context(job
->blk
);
782 aio_poll(aio_context
, true);
783 qemu_progress_print(job
->len
?
784 ((float)job
->offset
/ job
->len
* 100.f
) : 0.0f
, 0);
785 } while (!job
->ready
);
787 block_job_complete_sync(job
, errp
);
789 /* A block job may finish instantaneously without publishing any progress,
790 * so just signal completion here */
791 qemu_progress_print(100.f
, 0);
794 static int img_commit(int argc
, char **argv
)
797 const char *filename
, *fmt
, *cache
, *base
;
799 BlockDriverState
*bs
, *base_bs
;
800 bool progress
= false, quiet
= false, drop
= false;
802 Error
*local_err
= NULL
;
803 CommonBlockJobCBInfo cbi
;
804 bool image_opts
= false;
807 cache
= BDRV_DEFAULT_CACHE
;
810 static const struct option long_options
[] = {
811 {"help", no_argument
, 0, 'h'},
812 {"object", required_argument
, 0, OPTION_OBJECT
},
813 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
816 c
= getopt_long(argc
, argv
, "f:ht:b:dpq",
846 case OPTION_OBJECT
: {
848 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
854 case OPTION_IMAGE_OPTS
:
860 /* Progress is not shown in Quiet mode */
865 if (optind
!= argc
- 1) {
866 error_exit("Expecting one image file name");
868 filename
= argv
[optind
++];
870 if (qemu_opts_foreach(&qemu_object_opts
,
871 user_creatable_add_opts_foreach
,
876 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
877 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
879 error_report("Invalid cache option: %s", cache
);
883 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
889 qemu_progress_init(progress
, 1.f
);
890 qemu_progress_print(0.f
, 100);
893 base_bs
= bdrv_find_backing_image(bs
, base
);
895 error_setg(&local_err
, QERR_BASE_NOT_FOUND
, base
);
899 /* This is different from QMP, which by default uses the deepest file in
900 * the backing chain (i.e., the very base); however, the traditional
901 * behavior of qemu-img commit is using the immediate backing file. */
902 base_bs
= backing_bs(bs
);
904 error_setg(&local_err
, "Image does not have a backing file");
909 cbi
= (CommonBlockJobCBInfo
){
914 commit_active_start(bs
, base_bs
, 0, BLOCKDEV_ON_ERROR_REPORT
,
915 common_block_job_cb
, &cbi
, &local_err
);
920 /* When the block job completes, the BlockBackend reference will point to
921 * the old backing file. In order to avoid that the top image is already
922 * deleted, so we can still empty it afterwards, increment the reference
923 * counter here preemptively. */
928 run_block_job(bs
->job
, &local_err
);
933 if (!drop
&& bs
->drv
->bdrv_make_empty
) {
934 ret
= bs
->drv
->bdrv_make_empty(bs
);
936 error_setg_errno(&local_err
, -ret
, "Could not empty %s",
953 error_report_err(local_err
);
957 qprintf(quiet
, "Image committed.\n");
962 * Returns true iff the first sector pointed to by 'buf' contains at least
965 * 'pnum' is set to the number of sectors (including and immediately following
966 * the first one) that are known to be in the same allocated/unallocated state.
968 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
)
977 is_zero
= buffer_is_zero(buf
, 512);
978 for(i
= 1; i
< n
; i
++) {
980 if (is_zero
!= buffer_is_zero(buf
, 512)) {
989 * Like is_allocated_sectors, but if the buffer starts with a used sector,
990 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
991 * breaking up write requests for only small sparse areas.
993 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
997 int num_checked
, num_used
;
1003 ret
= is_allocated_sectors(buf
, n
, pnum
);
1009 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1011 num_checked
= num_used
;
1014 ret
= is_allocated_sectors(buf
, n
, pnum
);
1016 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1018 num_checked
+= *pnum
;
1020 num_used
= num_checked
;
1021 } else if (*pnum
>= min
) {
1031 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1032 * buffers matches, non-zero otherwise.
1034 * pnum is set to the number of sectors (including and immediately following
1035 * the first one) that are known to have the same comparison result
1037 static int compare_sectors(const uint8_t *buf1
, const uint8_t *buf2
, int n
,
1048 res
= !!memcmp(buf1
, buf2
, 512);
1049 for(i
= 1; i
< n
; i
++) {
1053 if (!!memcmp(buf1
, buf2
, 512) != res
) {
1062 #define IO_BUF_SIZE (2 * 1024 * 1024)
1064 static int64_t sectors_to_bytes(int64_t sectors
)
1066 return sectors
<< BDRV_SECTOR_BITS
;
1069 static int64_t sectors_to_process(int64_t total
, int64_t from
)
1071 return MIN(total
- from
, IO_BUF_SIZE
>> BDRV_SECTOR_BITS
);
1075 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1077 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1078 * data and negative value on error.
1080 * @param blk: BlockBackend for the image
1081 * @param sect_num: Number of first sector to check
1082 * @param sect_count: Number of sectors to check
1083 * @param filename: Name of disk file we are checking (logging purpose)
1084 * @param buffer: Allocated buffer for storing read data
1085 * @param quiet: Flag for quiet mode
1087 static int check_empty_sectors(BlockBackend
*blk
, int64_t sect_num
,
1088 int sect_count
, const char *filename
,
1089 uint8_t *buffer
, bool quiet
)
1092 ret
= blk_pread(blk
, sect_num
<< BDRV_SECTOR_BITS
, buffer
,
1093 sect_count
<< BDRV_SECTOR_BITS
);
1095 error_report("Error while reading offset %" PRId64
" of %s: %s",
1096 sectors_to_bytes(sect_num
), filename
, strerror(-ret
));
1099 ret
= is_allocated_sectors(buffer
, sect_count
, &pnum
);
1100 if (ret
|| pnum
!= sect_count
) {
1101 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1102 sectors_to_bytes(ret
? sect_num
: sect_num
+ pnum
));
1110 * Compares two images. Exit codes:
1112 * 0 - Images are identical
1114 * >1 - Error occurred
1116 static int img_compare(int argc
, char **argv
)
1118 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1119 BlockBackend
*blk1
, *blk2
;
1120 BlockDriverState
*bs1
, *bs2
;
1121 int64_t total_sectors1
, total_sectors2
;
1122 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1124 int allocated1
, allocated2
;
1125 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1126 bool progress
= false, quiet
= false, strict
= false;
1129 int64_t total_sectors
;
1130 int64_t sector_num
= 0;
1133 uint64_t progress_base
;
1134 bool image_opts
= false;
1136 cache
= BDRV_DEFAULT_CACHE
;
1138 static const struct option long_options
[] = {
1139 {"help", no_argument
, 0, 'h'},
1140 {"object", required_argument
, 0, OPTION_OBJECT
},
1141 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1144 c
= getopt_long(argc
, argv
, "hf:F:T:pqs",
1145 long_options
, NULL
);
1172 case OPTION_OBJECT
: {
1174 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1181 case OPTION_IMAGE_OPTS
:
1187 /* Progress is not shown in Quiet mode */
1193 if (optind
!= argc
- 2) {
1194 error_exit("Expecting two image file names");
1196 filename1
= argv
[optind
++];
1197 filename2
= argv
[optind
++];
1199 if (qemu_opts_foreach(&qemu_object_opts
,
1200 user_creatable_add_opts_foreach
,
1206 /* Initialize before goto out */
1207 qemu_progress_init(progress
, 2.0);
1210 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1212 error_report("Invalid source cache option: %s", cache
);
1217 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
);
1223 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
);
1231 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1232 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1233 total_sectors1
= blk_nb_sectors(blk1
);
1234 if (total_sectors1
< 0) {
1235 error_report("Can't get size of %s: %s",
1236 filename1
, strerror(-total_sectors1
));
1240 total_sectors2
= blk_nb_sectors(blk2
);
1241 if (total_sectors2
< 0) {
1242 error_report("Can't get size of %s: %s",
1243 filename2
, strerror(-total_sectors2
));
1247 total_sectors
= MIN(total_sectors1
, total_sectors2
);
1248 progress_base
= MAX(total_sectors1
, total_sectors2
);
1250 qemu_progress_print(0, 100);
1252 if (strict
&& total_sectors1
!= total_sectors2
) {
1254 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1259 int64_t status1
, status2
;
1260 BlockDriverState
*file
;
1262 nb_sectors
= sectors_to_process(total_sectors
, sector_num
);
1263 if (nb_sectors
<= 0) {
1266 status1
= bdrv_get_block_status_above(bs1
, NULL
, sector_num
,
1267 total_sectors1
- sector_num
,
1271 error_report("Sector allocation test failed for %s", filename1
);
1274 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1276 status2
= bdrv_get_block_status_above(bs2
, NULL
, sector_num
,
1277 total_sectors2
- sector_num
,
1281 error_report("Sector allocation test failed for %s", filename2
);
1284 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1286 nb_sectors
= MIN(nb_sectors
, pnum1
);
1289 nb_sectors
= MIN(nb_sectors
, pnum2
);
1293 if ((status1
& ~BDRV_BLOCK_OFFSET_MASK
) !=
1294 (status2
& ~BDRV_BLOCK_OFFSET_MASK
)) {
1296 qprintf(quiet
, "Strict mode: Offset %" PRId64
1297 " block status mismatch!\n",
1298 sectors_to_bytes(sector_num
));
1302 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1303 nb_sectors
= MIN(pnum1
, pnum2
);
1304 } else if (allocated1
== allocated2
) {
1306 ret
= blk_pread(blk1
, sector_num
<< BDRV_SECTOR_BITS
, buf1
,
1307 nb_sectors
<< BDRV_SECTOR_BITS
);
1309 error_report("Error while reading offset %" PRId64
" of %s:"
1310 " %s", sectors_to_bytes(sector_num
), filename1
,
1315 ret
= blk_pread(blk2
, sector_num
<< BDRV_SECTOR_BITS
, buf2
,
1316 nb_sectors
<< BDRV_SECTOR_BITS
);
1318 error_report("Error while reading offset %" PRId64
1319 " of %s: %s", sectors_to_bytes(sector_num
),
1320 filename2
, strerror(-ret
));
1324 ret
= compare_sectors(buf1
, buf2
, nb_sectors
, &pnum
);
1325 if (ret
|| pnum
!= nb_sectors
) {
1326 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1328 ret
? sector_num
: sector_num
+ pnum
));
1336 ret
= check_empty_sectors(blk1
, sector_num
, nb_sectors
,
1337 filename1
, buf1
, quiet
);
1339 ret
= check_empty_sectors(blk2
, sector_num
, nb_sectors
,
1340 filename2
, buf1
, quiet
);
1344 error_report("Error while reading offset %" PRId64
": %s",
1345 sectors_to_bytes(sector_num
), strerror(-ret
));
1351 sector_num
+= nb_sectors
;
1352 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1355 if (total_sectors1
!= total_sectors2
) {
1356 BlockBackend
*blk_over
;
1357 int64_t total_sectors_over
;
1358 const char *filename_over
;
1360 qprintf(quiet
, "Warning: Image size mismatch!\n");
1361 if (total_sectors1
> total_sectors2
) {
1362 total_sectors_over
= total_sectors1
;
1364 filename_over
= filename1
;
1366 total_sectors_over
= total_sectors2
;
1368 filename_over
= filename2
;
1372 nb_sectors
= sectors_to_process(total_sectors_over
, sector_num
);
1373 if (nb_sectors
<= 0) {
1376 ret
= bdrv_is_allocated_above(blk_bs(blk_over
), NULL
, sector_num
,
1380 error_report("Sector allocation test failed for %s",
1387 ret
= check_empty_sectors(blk_over
, sector_num
, nb_sectors
,
1388 filename_over
, buf1
, quiet
);
1391 error_report("Error while reading offset %" PRId64
1392 " of %s: %s", sectors_to_bytes(sector_num
),
1393 filename_over
, strerror(-ret
));
1399 sector_num
+= nb_sectors
;
1400 qemu_progress_print(((float) nb_sectors
/ progress_base
)*100, 100);
1404 qprintf(quiet
, "Images are identical.\n");
1414 qemu_progress_end();
1419 enum ImgConvertBlockStatus
{
1425 typedef struct ImgConvertState
{
1427 int64_t *src_sectors
;
1428 int src_cur
, src_num
;
1429 int64_t src_cur_offset
;
1430 int64_t total_sectors
;
1431 int64_t allocated_sectors
;
1432 enum ImgConvertBlockStatus status
;
1433 int64_t sector_next_status
;
1434 BlockBackend
*target
;
1437 bool target_has_backing
;
1439 size_t cluster_sectors
;
1443 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
)
1445 assert(sector_num
>= s
->src_cur_offset
);
1446 while (sector_num
- s
->src_cur_offset
>= s
->src_sectors
[s
->src_cur
]) {
1447 s
->src_cur_offset
+= s
->src_sectors
[s
->src_cur
];
1449 assert(s
->src_cur
< s
->src_num
);
1453 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1458 convert_select_part(s
, sector_num
);
1460 assert(s
->total_sectors
> sector_num
);
1461 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1463 if (s
->sector_next_status
<= sector_num
) {
1464 BlockDriverState
*file
;
1465 ret
= bdrv_get_block_status(blk_bs(s
->src
[s
->src_cur
]),
1466 sector_num
- s
->src_cur_offset
,
1472 if (ret
& BDRV_BLOCK_ZERO
) {
1473 s
->status
= BLK_ZERO
;
1474 } else if (ret
& BDRV_BLOCK_DATA
) {
1475 s
->status
= BLK_DATA
;
1476 } else if (!s
->target_has_backing
) {
1477 /* Without a target backing file we must copy over the contents of
1478 * the backing file as well. */
1479 /* Check block status of the backing file chain to avoid
1480 * needlessly reading zeroes and limiting the iteration to the
1482 ret
= bdrv_get_block_status_above(blk_bs(s
->src
[s
->src_cur
]), NULL
,
1483 sector_num
- s
->src_cur_offset
,
1489 if (ret
& BDRV_BLOCK_ZERO
) {
1490 s
->status
= BLK_ZERO
;
1492 s
->status
= BLK_DATA
;
1495 s
->status
= BLK_BACKING_FILE
;
1498 s
->sector_next_status
= sector_num
+ n
;
1501 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1502 if (s
->status
== BLK_DATA
) {
1503 n
= MIN(n
, s
->buf_sectors
);
1506 /* We need to write complete clusters for compressed images, so if an
1507 * unallocated area is shorter than that, we must consider the whole
1508 * cluster allocated. */
1509 if (s
->compressed
) {
1510 if (n
< s
->cluster_sectors
) {
1511 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1512 s
->status
= BLK_DATA
;
1514 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1521 static int convert_read(ImgConvertState
*s
, int64_t sector_num
, int nb_sectors
,
1527 assert(nb_sectors
<= s
->buf_sectors
);
1528 while (nb_sectors
> 0) {
1532 /* In the case of compression with multiple source files, we can get a
1533 * nb_sectors that spreads into the next part. So we must be able to
1534 * read across multiple BDSes for one convert_read() call. */
1535 convert_select_part(s
, sector_num
);
1536 blk
= s
->src
[s
->src_cur
];
1537 bs_sectors
= s
->src_sectors
[s
->src_cur
];
1539 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- s
->src_cur_offset
));
1540 ret
= blk_pread(blk
,
1541 (sector_num
- s
->src_cur_offset
) << BDRV_SECTOR_BITS
,
1542 buf
, n
<< BDRV_SECTOR_BITS
);
1549 buf
+= n
* BDRV_SECTOR_SIZE
;
1555 static int convert_write(ImgConvertState
*s
, int64_t sector_num
, int nb_sectors
,
1560 while (nb_sectors
> 0) {
1563 switch (s
->status
) {
1564 case BLK_BACKING_FILE
:
1565 /* If we have a backing file, leave clusters unallocated that are
1566 * unallocated in the source image, so that the backing file is
1567 * visible at the respective offset. */
1568 assert(s
->target_has_backing
);
1572 /* We must always write compressed clusters as a whole, so don't
1573 * try to find zeroed parts in the buffer. We can only save the
1574 * write if the buffer is completely zeroed and we're allowed to
1575 * keep the target sparse. */
1576 if (s
->compressed
) {
1577 if (s
->has_zero_init
&& s
->min_sparse
&&
1578 buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
))
1580 assert(!s
->target_has_backing
);
1584 ret
= blk_write_compressed(s
->target
, sector_num
, buf
, n
);
1591 /* If there is real non-zero data or we're told to keep the target
1592 * fully allocated (-S 0), we must write it. Otherwise we can treat
1593 * it as zero sectors. */
1594 if (!s
->min_sparse
||
1595 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
))
1597 ret
= blk_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1598 buf
, n
<< BDRV_SECTOR_BITS
, 0);
1607 if (s
->has_zero_init
) {
1610 ret
= blk_pwrite_zeroes(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1611 n
<< BDRV_SECTOR_BITS
, 0);
1620 buf
+= n
* BDRV_SECTOR_SIZE
;
1626 static int convert_do_copy(ImgConvertState
*s
)
1628 uint8_t *buf
= NULL
;
1629 int64_t sector_num
, allocated_done
;
1633 /* Check whether we have zero initialisation or can get it efficiently */
1634 s
->has_zero_init
= s
->min_sparse
&& !s
->target_has_backing
1635 ? bdrv_has_zero_init(blk_bs(s
->target
))
1638 if (!s
->has_zero_init
&& !s
->target_has_backing
&&
1639 bdrv_can_write_zeroes_with_unmap(blk_bs(s
->target
)))
1641 ret
= bdrv_make_zero(blk_bs(s
->target
), BDRV_REQ_MAY_UNMAP
);
1643 s
->has_zero_init
= true;
1647 /* Allocate buffer for copied data. For compressed images, only one cluster
1648 * can be copied at a time. */
1649 if (s
->compressed
) {
1650 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
1651 error_report("invalid cluster size");
1655 s
->buf_sectors
= s
->cluster_sectors
;
1657 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1659 /* Calculate allocated sectors for progress */
1660 s
->allocated_sectors
= 0;
1662 while (sector_num
< s
->total_sectors
) {
1663 n
= convert_iteration_sectors(s
, sector_num
);
1668 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1670 s
->allocated_sectors
+= n
;
1677 s
->src_cur_offset
= 0;
1678 s
->sector_next_status
= 0;
1683 while (sector_num
< s
->total_sectors
) {
1684 n
= convert_iteration_sectors(s
, sector_num
);
1689 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
1691 allocated_done
+= n
;
1692 qemu_progress_print(100.0 * allocated_done
/ s
->allocated_sectors
,
1696 if (s
->status
== BLK_DATA
) {
1697 ret
= convert_read(s
, sector_num
, n
, buf
);
1699 error_report("error while reading sector %" PRId64
1700 ": %s", sector_num
, strerror(-ret
));
1703 } else if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
1704 n
= MIN(n
, s
->buf_sectors
);
1705 memset(buf
, 0, n
* BDRV_SECTOR_SIZE
);
1706 s
->status
= BLK_DATA
;
1709 ret
= convert_write(s
, sector_num
, n
, buf
);
1711 error_report("error while writing sector %" PRId64
1712 ": %s", sector_num
, strerror(-ret
));
1719 if (s
->compressed
) {
1720 /* signal EOF to align */
1721 ret
= blk_write_compressed(s
->target
, 0, NULL
, 0);
1733 static int img_convert(int argc
, char **argv
)
1735 int c
, bs_n
, bs_i
, compress
, cluster_sectors
, skip_create
;
1737 int progress
= 0, flags
, src_flags
;
1738 bool writethrough
, src_writethrough
;
1739 const char *fmt
, *out_fmt
, *cache
, *src_cache
, *out_baseimg
, *out_filename
;
1740 BlockDriver
*drv
, *proto_drv
;
1741 BlockBackend
**blk
= NULL
, *out_blk
= NULL
;
1742 BlockDriverState
**bs
= NULL
, *out_bs
= NULL
;
1743 int64_t total_sectors
;
1744 int64_t *bs_sectors
= NULL
;
1745 size_t bufsectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
;
1746 BlockDriverInfo bdi
;
1747 QemuOpts
*opts
= NULL
;
1748 QemuOptsList
*create_opts
= NULL
;
1749 const char *out_baseimg_param
;
1750 char *options
= NULL
;
1751 const char *snapshot_name
= NULL
;
1752 int min_sparse
= 8; /* Need at least 4k of zeros for sparse detection */
1754 Error
*local_err
= NULL
;
1755 QemuOpts
*sn_opts
= NULL
;
1756 ImgConvertState state
;
1757 bool image_opts
= false;
1762 src_cache
= BDRV_DEFAULT_CACHE
;
1767 static const struct option long_options
[] = {
1768 {"help", no_argument
, 0, 'h'},
1769 {"object", required_argument
, 0, OPTION_OBJECT
},
1770 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1773 c
= getopt_long(argc
, argv
, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1774 long_options
, NULL
);
1790 out_baseimg
= optarg
;
1796 error_report("option -e is deprecated, please use \'-o "
1797 "encryption\' instead!");
1801 error_report("option -6 is deprecated, please use \'-o "
1802 "compat6\' instead!");
1806 if (!is_valid_option_list(optarg
)) {
1807 error_report("Invalid option list: %s", optarg
);
1812 options
= g_strdup(optarg
);
1814 char *old_options
= options
;
1815 options
= g_strdup_printf("%s,%s", options
, optarg
);
1816 g_free(old_options
);
1820 snapshot_name
= optarg
;
1823 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
1824 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
1827 error_report("Failed in parsing snapshot param '%s'",
1833 snapshot_name
= optarg
;
1840 sval
= qemu_strtosz_suffix(optarg
, &end
, QEMU_STRTOSZ_DEFSUFFIX_B
);
1841 if (sval
< 0 || *end
) {
1842 error_report("Invalid minimum zero buffer size for sparse output specified");
1847 min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
1866 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
1872 case OPTION_IMAGE_OPTS
:
1878 if (qemu_opts_foreach(&qemu_object_opts
,
1879 user_creatable_add_opts_foreach
,
1884 /* Initialize before goto out */
1888 qemu_progress_init(progress
, 1.0);
1890 bs_n
= argc
- optind
- 1;
1891 out_filename
= bs_n
>= 1 ? argv
[argc
- 1] : NULL
;
1893 if (options
&& has_help_option(options
)) {
1894 ret
= print_block_option_help(out_filename
, out_fmt
);
1899 error_exit("Must specify image file name");
1903 if (bs_n
> 1 && out_baseimg
) {
1904 error_report("-B makes no sense when concatenating multiple input "
1911 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
1913 error_report("Invalid source cache option: %s", src_cache
);
1917 qemu_progress_print(0, 100);
1919 blk
= g_new0(BlockBackend
*, bs_n
);
1920 bs
= g_new0(BlockDriverState
*, bs_n
);
1921 bs_sectors
= g_new(int64_t, bs_n
);
1924 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
1925 blk
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
1926 fmt
, src_flags
, src_writethrough
, quiet
);
1931 bs
[bs_i
] = blk_bs(blk
[bs_i
]);
1932 bs_sectors
[bs_i
] = blk_nb_sectors(blk
[bs_i
]);
1933 if (bs_sectors
[bs_i
] < 0) {
1934 error_report("Could not get size of %s: %s",
1935 argv
[optind
+ bs_i
], strerror(-bs_sectors
[bs_i
]));
1939 total_sectors
+= bs_sectors
[bs_i
];
1943 ret
= bdrv_snapshot_load_tmp(bs
[0],
1944 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1945 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1947 } else if (snapshot_name
!= NULL
) {
1949 error_report("No support for concatenating multiple snapshot");
1954 bdrv_snapshot_load_tmp_by_id_or_name(bs
[0], snapshot_name
, &local_err
);
1957 error_reportf_err(local_err
, "Failed to load snapshot: ");
1962 /* Find driver and parse its options */
1963 drv
= bdrv_find_format(out_fmt
);
1965 error_report("Unknown file format '%s'", out_fmt
);
1970 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
1972 error_report_err(local_err
);
1978 if (!drv
->create_opts
) {
1979 error_report("Format driver '%s' does not support image creation",
1985 if (!proto_drv
->create_opts
) {
1986 error_report("Protocol driver '%s' does not support image creation",
1987 proto_drv
->format_name
);
1992 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
1993 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
1995 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
1997 qemu_opts_do_parse(opts
, options
, NULL
, &local_err
);
1999 error_report_err(local_err
);
2005 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, total_sectors
* 512,
2007 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, NULL
);
2013 /* Get backing file name if -o backing_file was used */
2014 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2015 if (out_baseimg_param
) {
2016 out_baseimg
= out_baseimg_param
;
2019 /* Check if compression is supported */
2022 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2023 const char *preallocation
=
2024 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2026 if (!drv
->bdrv_write_compressed
) {
2027 error_report("Compression not supported for this file format");
2033 error_report("Compression and encryption not supported at "
2040 && strcmp(preallocation
, "off"))
2042 error_report("Compression and preallocation not supported at "
2050 /* Create the new image */
2051 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2053 error_reportf_err(local_err
, "%s: error while converting %s: ",
2054 out_filename
, out_fmt
);
2059 flags
= min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2060 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2062 error_report("Invalid cache option: %s", cache
);
2066 /* XXX we should allow --image-opts to trigger use of
2067 * img_open() here, but then we have trouble with
2068 * the bdrv_create() call which takes different params.
2069 * Not critical right now, so fix can wait...
2071 out_blk
= img_open_file(out_filename
, out_fmt
, flags
, writethrough
, quiet
);
2076 out_bs
= blk_bs(out_blk
);
2078 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2079 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2081 bufsectors
= MIN(32768,
2082 MAX(bufsectors
, MAX(out_bs
->bl
.opt_transfer_length
,
2083 out_bs
->bl
.discard_alignment
))
2087 int64_t output_sectors
= blk_nb_sectors(out_blk
);
2088 if (output_sectors
< 0) {
2089 error_report("unable to get output image length: %s",
2090 strerror(-output_sectors
));
2093 } else if (output_sectors
< total_sectors
) {
2094 error_report("output file is smaller than input file");
2100 cluster_sectors
= 0;
2101 ret
= bdrv_get_info(out_bs
, &bdi
);
2104 error_report("could not get block driver info");
2108 compress
= compress
|| bdi
.needs_compressed_writes
;
2109 cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2112 state
= (ImgConvertState
) {
2114 .src_sectors
= bs_sectors
,
2116 .total_sectors
= total_sectors
,
2118 .compressed
= compress
,
2119 .target_has_backing
= (bool) out_baseimg
,
2120 .min_sparse
= min_sparse
,
2121 .cluster_sectors
= cluster_sectors
,
2122 .buf_sectors
= bufsectors
,
2124 ret
= convert_do_copy(&state
);
2128 qemu_progress_print(100, 0);
2130 qemu_progress_end();
2131 qemu_opts_del(opts
);
2132 qemu_opts_free(create_opts
);
2133 qemu_opts_del(sn_opts
);
2137 for (bs_i
= 0; bs_i
< bs_n
; bs_i
++) {
2138 blk_unref(blk
[bs_i
]);
2153 static void dump_snapshots(BlockDriverState
*bs
)
2155 QEMUSnapshotInfo
*sn_tab
, *sn
;
2158 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2161 printf("Snapshot list:\n");
2162 bdrv_snapshot_dump(fprintf
, stdout
, NULL
);
2164 for(i
= 0; i
< nb_sns
; i
++) {
2166 bdrv_snapshot_dump(fprintf
, stdout
, sn
);
2172 static void dump_json_image_info_list(ImageInfoList
*list
)
2174 Error
*local_err
= NULL
;
2176 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
2178 visit_type_ImageInfoList(qmp_output_get_visitor(ov
), NULL
, &list
,
2180 obj
= qmp_output_get_qobject(ov
);
2181 str
= qobject_to_json_pretty(obj
);
2182 assert(str
!= NULL
);
2183 printf("%s\n", qstring_get_str(str
));
2184 qobject_decref(obj
);
2185 qmp_output_visitor_cleanup(ov
);
2189 static void dump_json_image_info(ImageInfo
*info
)
2191 Error
*local_err
= NULL
;
2193 QmpOutputVisitor
*ov
= qmp_output_visitor_new();
2195 visit_type_ImageInfo(qmp_output_get_visitor(ov
), NULL
, &info
, &local_err
);
2196 obj
= qmp_output_get_qobject(ov
);
2197 str
= qobject_to_json_pretty(obj
);
2198 assert(str
!= NULL
);
2199 printf("%s\n", qstring_get_str(str
));
2200 qobject_decref(obj
);
2201 qmp_output_visitor_cleanup(ov
);
2205 static void dump_human_image_info_list(ImageInfoList
*list
)
2207 ImageInfoList
*elem
;
2210 for (elem
= list
; elem
; elem
= elem
->next
) {
2216 bdrv_image_info_dump(fprintf
, stdout
, elem
->value
);
2220 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2222 return strcmp(a
, b
) == 0;
2226 * Open an image file chain and return an ImageInfoList
2228 * @filename: topmost image filename
2229 * @fmt: topmost image format (may be NULL to autodetect)
2230 * @chain: true - enumerate entire backing file chain
2231 * false - only topmost image file
2233 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2234 * image file. If there was an error a message will have been printed to
2237 static ImageInfoList
*collect_image_info_list(bool image_opts
,
2238 const char *filename
,
2242 ImageInfoList
*head
= NULL
;
2243 ImageInfoList
**last
= &head
;
2244 GHashTable
*filenames
;
2247 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2251 BlockDriverState
*bs
;
2253 ImageInfoList
*elem
;
2255 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2256 error_report("Backing file '%s' creates an infinite loop.",
2260 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2262 blk
= img_open(image_opts
, filename
, fmt
,
2263 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false);
2269 bdrv_query_image_info(bs
, &info
, &err
);
2271 error_report_err(err
);
2276 elem
= g_new0(ImageInfoList
, 1);
2283 filename
= fmt
= NULL
;
2285 if (info
->has_full_backing_filename
) {
2286 filename
= info
->full_backing_filename
;
2287 } else if (info
->has_backing_filename
) {
2288 error_report("Could not determine absolute backing filename,"
2289 " but backing filename '%s' present",
2290 info
->backing_filename
);
2293 if (info
->has_backing_filename_format
) {
2294 fmt
= info
->backing_filename_format
;
2298 g_hash_table_destroy(filenames
);
2302 qapi_free_ImageInfoList(head
);
2303 g_hash_table_destroy(filenames
);
2307 static int img_info(int argc
, char **argv
)
2310 OutputFormat output_format
= OFORMAT_HUMAN
;
2312 const char *filename
, *fmt
, *output
;
2313 ImageInfoList
*list
;
2314 bool image_opts
= false;
2319 int option_index
= 0;
2320 static const struct option long_options
[] = {
2321 {"help", no_argument
, 0, 'h'},
2322 {"format", required_argument
, 0, 'f'},
2323 {"output", required_argument
, 0, OPTION_OUTPUT
},
2324 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
2325 {"object", required_argument
, 0, OPTION_OBJECT
},
2326 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2329 c
= getopt_long(argc
, argv
, "f:h",
2330 long_options
, &option_index
);
2345 case OPTION_BACKING_CHAIN
:
2348 case OPTION_OBJECT
: {
2350 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2356 case OPTION_IMAGE_OPTS
:
2361 if (optind
!= argc
- 1) {
2362 error_exit("Expecting one image file name");
2364 filename
= argv
[optind
++];
2366 if (output
&& !strcmp(output
, "json")) {
2367 output_format
= OFORMAT_JSON
;
2368 } else if (output
&& !strcmp(output
, "human")) {
2369 output_format
= OFORMAT_HUMAN
;
2370 } else if (output
) {
2371 error_report("--output must be used with human or json as argument.");
2375 if (qemu_opts_foreach(&qemu_object_opts
,
2376 user_creatable_add_opts_foreach
,
2381 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
);
2386 switch (output_format
) {
2388 dump_human_image_info_list(list
);
2392 dump_json_image_info_list(list
);
2394 dump_json_image_info(list
->value
);
2399 qapi_free_ImageInfoList(list
);
2403 static void dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
2406 switch (output_format
) {
2408 if (e
->data
&& !e
->has_offset
) {
2409 error_report("File contains external, encrypted or compressed clusters.");
2412 if (e
->data
&& !e
->zero
) {
2413 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
2414 e
->start
, e
->length
,
2415 e
->has_offset
? e
->offset
: 0,
2416 e
->has_filename
? e
->filename
: "");
2418 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2419 * Modify the flags here to allow more coalescing.
2421 if (next
&& (!next
->data
|| next
->zero
)) {
2427 printf("%s{ \"start\": %"PRId64
", \"length\": %"PRId64
","
2428 " \"depth\": %"PRId64
", \"zero\": %s, \"data\": %s",
2429 (e
->start
== 0 ? "[" : ",\n"),
2430 e
->start
, e
->length
, e
->depth
,
2431 e
->zero
? "true" : "false",
2432 e
->data
? "true" : "false");
2433 if (e
->has_offset
) {
2434 printf(", \"offset\": %"PRId64
"", e
->offset
);
2445 static int get_block_status(BlockDriverState
*bs
, int64_t sector_num
,
2446 int nb_sectors
, MapEntry
*e
)
2450 BlockDriverState
*file
;
2453 /* As an optimization, we could cache the current range of unallocated
2454 * clusters in each file of the chain, and avoid querying the same
2460 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &nb_sectors
,
2466 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
2469 bs
= backing_bs(bs
);
2478 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
2481 .start
= sector_num
* BDRV_SECTOR_SIZE
,
2482 .length
= nb_sectors
* BDRV_SECTOR_SIZE
,
2483 .data
= !!(ret
& BDRV_BLOCK_DATA
),
2484 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
2485 .offset
= ret
& BDRV_BLOCK_OFFSET_MASK
,
2486 .has_offset
= has_offset
,
2488 .has_filename
= file
&& has_offset
,
2489 .filename
= file
&& has_offset
? file
->filename
: NULL
,
2495 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
2497 if (curr
->length
== 0) {
2500 if (curr
->zero
!= next
->zero
||
2501 curr
->data
!= next
->data
||
2502 curr
->depth
!= next
->depth
||
2503 curr
->has_filename
!= next
->has_filename
||
2504 curr
->has_offset
!= next
->has_offset
) {
2507 if (curr
->has_filename
&& strcmp(curr
->filename
, next
->filename
)) {
2510 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
2516 static int img_map(int argc
, char **argv
)
2519 OutputFormat output_format
= OFORMAT_HUMAN
;
2521 BlockDriverState
*bs
;
2522 const char *filename
, *fmt
, *output
;
2524 MapEntry curr
= { .length
= 0 }, next
;
2526 bool image_opts
= false;
2531 int option_index
= 0;
2532 static const struct option long_options
[] = {
2533 {"help", no_argument
, 0, 'h'},
2534 {"format", required_argument
, 0, 'f'},
2535 {"output", required_argument
, 0, OPTION_OUTPUT
},
2536 {"object", required_argument
, 0, OPTION_OBJECT
},
2537 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2540 c
= getopt_long(argc
, argv
, "f:h",
2541 long_options
, &option_index
);
2556 case OPTION_OBJECT
: {
2558 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2564 case OPTION_IMAGE_OPTS
:
2569 if (optind
!= argc
- 1) {
2570 error_exit("Expecting one image file name");
2572 filename
= argv
[optind
];
2574 if (output
&& !strcmp(output
, "json")) {
2575 output_format
= OFORMAT_JSON
;
2576 } else if (output
&& !strcmp(output
, "human")) {
2577 output_format
= OFORMAT_HUMAN
;
2578 } else if (output
) {
2579 error_report("--output must be used with human or json as argument.");
2583 if (qemu_opts_foreach(&qemu_object_opts
,
2584 user_creatable_add_opts_foreach
,
2589 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false);
2595 if (output_format
== OFORMAT_HUMAN
) {
2596 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2599 length
= blk_getlength(blk
);
2600 while (curr
.start
+ curr
.length
< length
) {
2601 int64_t nsectors_left
;
2605 sector_num
= (curr
.start
+ curr
.length
) >> BDRV_SECTOR_BITS
;
2607 /* Probe up to 1 GiB at a time. */
2608 nsectors_left
= DIV_ROUND_UP(length
, BDRV_SECTOR_SIZE
) - sector_num
;
2609 n
= MIN(1 << (30 - BDRV_SECTOR_BITS
), nsectors_left
);
2610 ret
= get_block_status(bs
, sector_num
, n
, &next
);
2613 error_report("Could not read file metadata: %s", strerror(-ret
));
2617 if (entry_mergeable(&curr
, &next
)) {
2618 curr
.length
+= next
.length
;
2622 if (curr
.length
> 0) {
2623 dump_map_entry(output_format
, &curr
, &next
);
2628 dump_map_entry(output_format
, &curr
, NULL
);
2635 #define SNAPSHOT_LIST 1
2636 #define SNAPSHOT_CREATE 2
2637 #define SNAPSHOT_APPLY 3
2638 #define SNAPSHOT_DELETE 4
2640 static int img_snapshot(int argc
, char **argv
)
2643 BlockDriverState
*bs
;
2644 QEMUSnapshotInfo sn
;
2645 char *filename
, *snapshot_name
= NULL
;
2646 int c
, ret
= 0, bdrv_oflags
;
2651 bool image_opts
= false;
2653 bdrv_oflags
= BDRV_O_RDWR
;
2654 /* Parse commandline parameters */
2656 static const struct option long_options
[] = {
2657 {"help", no_argument
, 0, 'h'},
2658 {"object", required_argument
, 0, OPTION_OBJECT
},
2659 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2662 c
= getopt_long(argc
, argv
, "la:c:d:hq",
2663 long_options
, NULL
);
2674 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2677 action
= SNAPSHOT_LIST
;
2678 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
2682 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2685 action
= SNAPSHOT_APPLY
;
2686 snapshot_name
= optarg
;
2690 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2693 action
= SNAPSHOT_CREATE
;
2694 snapshot_name
= optarg
;
2698 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2701 action
= SNAPSHOT_DELETE
;
2702 snapshot_name
= optarg
;
2707 case OPTION_OBJECT
: {
2709 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2715 case OPTION_IMAGE_OPTS
:
2721 if (optind
!= argc
- 1) {
2722 error_exit("Expecting one image file name");
2724 filename
= argv
[optind
++];
2726 if (qemu_opts_foreach(&qemu_object_opts
,
2727 user_creatable_add_opts_foreach
,
2732 /* Open the image */
2733 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
);
2739 /* Perform the requested action */
2745 case SNAPSHOT_CREATE
:
2746 memset(&sn
, 0, sizeof(sn
));
2747 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
2749 qemu_gettimeofday(&tv
);
2750 sn
.date_sec
= tv
.tv_sec
;
2751 sn
.date_nsec
= tv
.tv_usec
* 1000;
2753 ret
= bdrv_snapshot_create(bs
, &sn
);
2755 error_report("Could not create snapshot '%s': %d (%s)",
2756 snapshot_name
, ret
, strerror(-ret
));
2760 case SNAPSHOT_APPLY
:
2761 ret
= bdrv_snapshot_goto(bs
, snapshot_name
);
2763 error_report("Could not apply snapshot '%s': %d (%s)",
2764 snapshot_name
, ret
, strerror(-ret
));
2768 case SNAPSHOT_DELETE
:
2769 bdrv_snapshot_delete_by_id_or_name(bs
, snapshot_name
, &err
);
2771 error_reportf_err(err
, "Could not delete snapshot '%s': ",
2786 static int img_rebase(int argc
, char **argv
)
2788 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
2789 uint8_t *buf_old
= NULL
;
2790 uint8_t *buf_new
= NULL
;
2791 BlockDriverState
*bs
= NULL
;
2793 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
2794 int c
, flags
, src_flags
, ret
;
2795 bool writethrough
, src_writethrough
;
2799 Error
*local_err
= NULL
;
2800 bool image_opts
= false;
2802 /* Parse commandline parameters */
2804 cache
= BDRV_DEFAULT_CACHE
;
2805 src_cache
= BDRV_DEFAULT_CACHE
;
2809 static const struct option long_options
[] = {
2810 {"help", no_argument
, 0, 'h'},
2811 {"object", required_argument
, 0, OPTION_OBJECT
},
2812 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2815 c
= getopt_long(argc
, argv
, "hf:F:b:upt:T:q",
2816 long_options
, NULL
);
2829 out_basefmt
= optarg
;
2832 out_baseimg
= optarg
;
2849 case OPTION_OBJECT
: {
2851 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
2857 case OPTION_IMAGE_OPTS
:
2867 if (optind
!= argc
- 1) {
2868 error_exit("Expecting one image file name");
2870 if (!unsafe
&& !out_baseimg
) {
2871 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2873 filename
= argv
[optind
++];
2875 if (qemu_opts_foreach(&qemu_object_opts
,
2876 user_creatable_add_opts_foreach
,
2881 qemu_progress_init(progress
, 2.0);
2882 qemu_progress_print(0, 100);
2884 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
2885 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2887 error_report("Invalid cache option: %s", cache
);
2892 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2894 error_report("Invalid source cache option: %s", src_cache
);
2898 /* The source files are opened read-only, don't care about WCE */
2899 assert((src_flags
& BDRV_O_RDWR
) == 0);
2900 (void) src_writethrough
;
2905 * Ignore the old backing file for unsafe rebase in case we want to correct
2906 * the reference to a renamed or moved backing file.
2908 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
2915 if (out_basefmt
!= NULL
) {
2916 if (bdrv_find_format(out_basefmt
) == NULL
) {
2917 error_report("Invalid format name: '%s'", out_basefmt
);
2923 /* For safe rebasing we need to compare old and new backing file */
2925 char backing_name
[PATH_MAX
];
2926 QDict
*options
= NULL
;
2928 if (bs
->backing_format
[0] != '\0') {
2929 options
= qdict_new();
2930 qdict_put(options
, "driver", qstring_from_str(bs
->backing_format
));
2933 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2934 blk_old_backing
= blk_new_open(backing_name
, NULL
,
2935 options
, src_flags
, &local_err
);
2936 if (!blk_old_backing
) {
2937 error_reportf_err(local_err
,
2938 "Could not open old backing file '%s': ",
2943 if (out_baseimg
[0]) {
2945 options
= qdict_new();
2946 qdict_put(options
, "driver", qstring_from_str(out_basefmt
));
2951 blk_new_backing
= blk_new_open(out_baseimg
, NULL
,
2952 options
, src_flags
, &local_err
);
2953 if (!blk_new_backing
) {
2954 error_reportf_err(local_err
,
2955 "Could not open new backing file '%s': ",
2963 * Check each unallocated cluster in the COW file. If it is unallocated,
2964 * accesses go to the backing file. We must therefore compare this cluster
2965 * in the old and new backing file, and if they differ we need to copy it
2966 * from the old backing file into the COW file.
2968 * If qemu-img crashes during this step, no harm is done. The content of
2969 * the image is the same as the original one at any time.
2972 int64_t num_sectors
;
2973 int64_t old_backing_num_sectors
;
2974 int64_t new_backing_num_sectors
= 0;
2977 float local_progress
= 0;
2979 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
2980 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
2982 num_sectors
= blk_nb_sectors(blk
);
2983 if (num_sectors
< 0) {
2984 error_report("Could not get size of '%s': %s",
2985 filename
, strerror(-num_sectors
));
2989 old_backing_num_sectors
= blk_nb_sectors(blk_old_backing
);
2990 if (old_backing_num_sectors
< 0) {
2991 char backing_name
[PATH_MAX
];
2993 bdrv_get_backing_filename(bs
, backing_name
, sizeof(backing_name
));
2994 error_report("Could not get size of '%s': %s",
2995 backing_name
, strerror(-old_backing_num_sectors
));
2999 if (blk_new_backing
) {
3000 new_backing_num_sectors
= blk_nb_sectors(blk_new_backing
);
3001 if (new_backing_num_sectors
< 0) {
3002 error_report("Could not get size of '%s': %s",
3003 out_baseimg
, strerror(-new_backing_num_sectors
));
3009 if (num_sectors
!= 0) {
3010 local_progress
= (float)100 /
3011 (num_sectors
/ MIN(num_sectors
, IO_BUF_SIZE
/ 512));
3014 for (sector
= 0; sector
< num_sectors
; sector
+= n
) {
3016 /* How many sectors can we handle with the next read? */
3017 if (sector
+ (IO_BUF_SIZE
/ 512) <= num_sectors
) {
3018 n
= (IO_BUF_SIZE
/ 512);
3020 n
= num_sectors
- sector
;
3023 /* If the cluster is allocated, we don't need to take action */
3024 ret
= bdrv_is_allocated(bs
, sector
, n
, &n
);
3026 error_report("error while reading image metadata: %s",
3035 * Read old and new backing file and take into consideration that
3036 * backing files may be smaller than the COW image.
3038 if (sector
>= old_backing_num_sectors
) {
3039 memset(buf_old
, 0, n
* BDRV_SECTOR_SIZE
);
3041 if (sector
+ n
> old_backing_num_sectors
) {
3042 n
= old_backing_num_sectors
- sector
;
3045 ret
= blk_pread(blk_old_backing
, sector
<< BDRV_SECTOR_BITS
,
3046 buf_old
, n
<< BDRV_SECTOR_BITS
);
3048 error_report("error while reading from old backing file");
3053 if (sector
>= new_backing_num_sectors
|| !blk_new_backing
) {
3054 memset(buf_new
, 0, n
* BDRV_SECTOR_SIZE
);
3056 if (sector
+ n
> new_backing_num_sectors
) {
3057 n
= new_backing_num_sectors
- sector
;
3060 ret
= blk_pread(blk_new_backing
, sector
<< BDRV_SECTOR_BITS
,
3061 buf_new
, n
<< BDRV_SECTOR_BITS
);
3063 error_report("error while reading from new backing file");
3068 /* If they differ, we need to write to the COW file */
3069 uint64_t written
= 0;
3071 while (written
< n
) {
3074 if (compare_sectors(buf_old
+ written
* 512,
3075 buf_new
+ written
* 512, n
- written
, &pnum
))
3077 ret
= blk_pwrite(blk
,
3078 (sector
+ written
) << BDRV_SECTOR_BITS
,
3079 buf_old
+ written
* 512,
3080 pnum
<< BDRV_SECTOR_BITS
, 0);
3082 error_report("Error while writing to COW image: %s",
3090 qemu_progress_print(local_progress
, 100);
3095 * Change the backing file. All clusters that are different from the old
3096 * backing file are overwritten in the COW file now, so the visible content
3097 * doesn't change when we switch the backing file.
3099 if (out_baseimg
&& *out_baseimg
) {
3100 ret
= bdrv_change_backing_file(bs
, out_baseimg
, out_basefmt
);
3102 ret
= bdrv_change_backing_file(bs
, NULL
, NULL
);
3105 if (ret
== -ENOSPC
) {
3106 error_report("Could not change the backing file to '%s': No "
3107 "space left in the file header", out_baseimg
);
3108 } else if (ret
< 0) {
3109 error_report("Could not change the backing file to '%s': %s",
3110 out_baseimg
, strerror(-ret
));
3113 qemu_progress_print(100, 0);
3115 * TODO At this point it is possible to check if any clusters that are
3116 * allocated in the COW file are the same in the backing file. If so, they
3117 * could be dropped from the COW file. Don't do this before switching the
3118 * backing file, in case of a crash this would lead to corruption.
3121 qemu_progress_end();
3124 blk_unref(blk_old_backing
);
3125 blk_unref(blk_new_backing
);
3127 qemu_vfree(buf_old
);
3128 qemu_vfree(buf_new
);
3137 static int img_resize(int argc
, char **argv
)
3140 int c
, ret
, relative
;
3141 const char *filename
, *fmt
, *size
;
3142 int64_t n
, total_size
;
3144 BlockBackend
*blk
= NULL
;
3147 static QemuOptsList resize_options
= {
3148 .name
= "resize_options",
3149 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3152 .name
= BLOCK_OPT_SIZE
,
3153 .type
= QEMU_OPT_SIZE
,
3154 .help
= "Virtual disk size"
3160 bool image_opts
= false;
3162 /* Remove size from argv manually so that negative numbers are not treated
3163 * as options by getopt. */
3165 error_exit("Not enough arguments");
3169 size
= argv
[--argc
];
3171 /* Parse getopt arguments */
3174 static const struct option long_options
[] = {
3175 {"help", no_argument
, 0, 'h'},
3176 {"object", required_argument
, 0, OPTION_OBJECT
},
3177 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3180 c
= getopt_long(argc
, argv
, "f:hq",
3181 long_options
, NULL
);
3196 case OPTION_OBJECT
: {
3198 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3204 case OPTION_IMAGE_OPTS
:
3209 if (optind
!= argc
- 1) {
3210 error_exit("Expecting one image file name");
3212 filename
= argv
[optind
++];
3214 if (qemu_opts_foreach(&qemu_object_opts
,
3215 user_creatable_add_opts_foreach
,
3220 /* Choose grow, shrink, or absolute resize mode */
3236 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
3237 qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
);
3239 error_report_err(err
);
3241 qemu_opts_del(param
);
3244 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
3245 qemu_opts_del(param
);
3247 blk
= img_open(image_opts
, filename
, fmt
,
3248 BDRV_O_RDWR
, false, quiet
);
3255 total_size
= blk_getlength(blk
) + n
* relative
;
3259 if (total_size
<= 0) {
3260 error_report("New image size must be positive");
3265 ret
= blk_truncate(blk
, total_size
);
3268 qprintf(quiet
, "Image resized.\n");
3271 error_report("This image does not support resize");
3274 error_report("Image is read-only");
3277 error_report("Error resizing image (%d)", -ret
);
3288 static void amend_status_cb(BlockDriverState
*bs
,
3289 int64_t offset
, int64_t total_work_size
,
3292 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
3295 static int img_amend(int argc
, char **argv
)
3299 char *options
= NULL
;
3300 QemuOptsList
*create_opts
= NULL
;
3301 QemuOpts
*opts
= NULL
;
3302 const char *fmt
= NULL
, *filename
, *cache
;
3305 bool quiet
= false, progress
= false;
3306 BlockBackend
*blk
= NULL
;
3307 BlockDriverState
*bs
= NULL
;
3308 bool image_opts
= false;
3310 cache
= BDRV_DEFAULT_CACHE
;
3312 static const struct option long_options
[] = {
3313 {"help", no_argument
, 0, 'h'},
3314 {"object", required_argument
, 0, OPTION_OBJECT
},
3315 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3318 c
= getopt_long(argc
, argv
, "ho:f:t:pq",
3319 long_options
, NULL
);
3330 if (!is_valid_option_list(optarg
)) {
3331 error_report("Invalid option list: %s", optarg
);
3333 goto out_no_progress
;
3336 options
= g_strdup(optarg
);
3338 char *old_options
= options
;
3339 options
= g_strdup_printf("%s,%s", options
, optarg
);
3340 g_free(old_options
);
3356 opts
= qemu_opts_parse_noisily(&qemu_object_opts
,
3360 goto out_no_progress
;
3363 case OPTION_IMAGE_OPTS
:
3370 error_exit("Must specify options (-o)");
3373 if (qemu_opts_foreach(&qemu_object_opts
,
3374 user_creatable_add_opts_foreach
,
3377 goto out_no_progress
;
3383 qemu_progress_init(progress
, 1.0);
3385 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
3386 if (fmt
&& has_help_option(options
)) {
3387 /* If a format is explicitly specified (and possibly no filename is
3388 * given), print option help here */
3389 ret
= print_block_option_help(filename
, fmt
);
3393 if (optind
!= argc
- 1) {
3394 error_report("Expecting one image file name");
3399 flags
= BDRV_O_RDWR
;
3400 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3402 error_report("Invalid cache option: %s", cache
);
3406 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
);
3413 fmt
= bs
->drv
->format_name
;
3415 if (has_help_option(options
)) {
3416 /* If the format was auto-detected, print option help here */
3417 ret
= print_block_option_help(filename
, fmt
);
3421 if (!bs
->drv
->create_opts
) {
3422 error_report("Format driver '%s' does not support any options to amend",
3428 create_opts
= qemu_opts_append(create_opts
, bs
->drv
->create_opts
);
3429 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
3431 qemu_opts_do_parse(opts
, options
, NULL
, &err
);
3433 error_report_err(err
);
3439 /* In case the driver does not call amend_status_cb() */
3440 qemu_progress_print(0.f
, 0);
3441 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
);
3442 qemu_progress_print(100.f
, 0);
3444 error_report("Error while amending options: %s", strerror(-ret
));
3449 qemu_progress_end();
3453 qemu_opts_del(opts
);
3454 qemu_opts_free(create_opts
);
3463 static const img_cmd_t img_cmds
[] = {
3464 #define DEF(option, callback, arg_string) \
3465 { option, callback },
3466 #include "qemu-img-cmds.h"
3472 int main(int argc
, char **argv
)
3474 const img_cmd_t
*cmd
;
3475 const char *cmdname
;
3476 Error
*local_error
= NULL
;
3478 static const struct option long_options
[] = {
3479 {"help", no_argument
, 0, 'h'},
3480 {"version", no_argument
, 0, 'v'},
3485 signal(SIGPIPE
, SIG_IGN
);
3488 error_set_progname(argv
[0]);
3489 qemu_init_exec_dir(argv
[0]);
3491 if (qemu_init_main_loop(&local_error
)) {
3492 error_report_err(local_error
);
3496 qcrypto_init(&error_fatal
);
3498 module_call_init(MODULE_INIT_QOM
);
3501 error_exit("Not enough arguments");
3505 qemu_add_opts(&qemu_object_opts
);
3506 qemu_add_opts(&qemu_source_opts
);
3508 /* find the command */
3509 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
3510 if (!strcmp(cmdname
, cmd
->name
)) {
3511 return cmd
->handler(argc
- 1, argv
+ 1);
3515 c
= getopt_long(argc
, argv
, "h", long_options
, NULL
);
3521 printf(QEMU_IMG_VERSION
);
3526 error_exit("Command not found: %s", cmdname
);