2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
28 #include "qemu/help-texts.h"
29 #include "qemu/qemu-progress.h"
30 #include "qemu-version.h"
31 #include "qapi/error.h"
32 #include "qapi/qapi-commands-block-core.h"
33 #include "qapi/qapi-visit-block-core.h"
34 #include "qapi/qobject-output-visitor.h"
35 #include "qapi/qmp/qjson.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/sockets.h"
45 #include "qemu/units.h"
46 #include "qemu/memalign.h"
47 #include "qom/object_interfaces.h"
48 #include "sysemu/block-backend.h"
49 #include "block/block_int.h"
50 #include "block/blockjob.h"
51 #include "block/dirty-bitmap.h"
52 #include "block/qapi.h"
53 #include "crypto/init.h"
54 #include "trace/control.h"
55 #include "qemu/throttle.h"
56 #include "block/throttle-groups.h"
58 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
59 "\n" QEMU_COPYRIGHT "\n"
61 typedef struct img_cmd_t
{
63 int (*handler
)(int argc
, char **argv
);
68 OPTION_BACKING_CHAIN
= 257,
70 OPTION_IMAGE_OPTS
= 259,
72 OPTION_FLUSH_INTERVAL
= 261,
73 OPTION_NO_DRAIN
= 262,
74 OPTION_TARGET_IMAGE_OPTS
= 263,
76 OPTION_PREALLOCATION
= 265,
79 OPTION_TARGET_IS_ZERO
= 268,
88 OPTION_SKIP_BROKEN
= 277,
91 typedef enum OutputFormat
{
96 /* Default to cache=writeback as data integrity is not important for qemu-img */
97 #define BDRV_DEFAULT_CACHE "writeback"
99 static void format_print(void *opaque
, const char *name
)
104 static G_NORETURN
G_GNUC_PRINTF(1, 2)
105 void error_exit(const char *fmt
, ...)
110 error_vreport(fmt
, ap
);
113 error_printf("Try 'qemu-img --help' for more information\n");
118 void missing_argument(const char *option
)
120 error_exit("missing argument for option '%s'", option
);
124 void unrecognized_option(const char *option
)
126 error_exit("unrecognized option '%s'", option
);
129 /* Please keep in synch with docs/tools/qemu-img.rst */
133 const char *help_msg
=
135 "usage: qemu-img [standard options] command [command options]\n"
136 "QEMU disk image utility\n"
138 " '-h', '--help' display this help and exit\n"
139 " '-V', '--version' output version information and exit\n"
140 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
141 " specify tracing options\n"
144 #define DEF(option, callback, arg_string) \
146 #include "qemu-img-cmds.h"
149 "Command parameters:\n"
150 " 'filename' is a disk image filename\n"
151 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
152 " manual page for a description of the object properties. The most common\n"
153 " object type is a 'secret', which is used to supply passwords and/or\n"
154 " encryption keys.\n"
155 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
156 " 'cache' is the cache mode used to write the output disk image, the valid\n"
157 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
158 " 'directsync' and 'unsafe' (default for convert)\n"
159 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
160 " options are the same as for the 'cache' option\n"
161 " 'size' is the disk image size in bytes. Optional suffixes\n"
162 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
163 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
164 " supported. 'b' is ignored.\n"
165 " 'output_filename' is the destination disk image filename\n"
166 " 'output_fmt' is the destination format\n"
167 " 'options' is a comma separated list of format specific options in a\n"
168 " name=value format. Use -o help for an overview of the options supported by\n"
170 " 'snapshot_param' is param used for internal snapshot, format\n"
171 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
173 " '-c' indicates that target image must be compressed (qcow format only)\n"
174 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
175 " new backing file match exactly. The image doesn't need a working\n"
176 " backing file before rebasing in this case (useful for renaming the\n"
177 " backing file). For image creation, allow creating without attempting\n"
178 " to open the backing file.\n"
179 " '-h' with or without a command shows this help and lists the supported formats\n"
180 " '-p' show progress of command (only certain commands)\n"
181 " '-q' use Quiet mode - do not print any output (except errors)\n"
182 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
183 " contain only zeros for qemu-img to create a sparse image during\n"
184 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
185 " unallocated or zero sectors, and the destination image will always be\n"
187 " '--output' takes the format in which the output must be done (human or json)\n"
188 " '-n' skips the target volume creation (useful if the volume is created\n"
189 " prior to running qemu-img)\n"
191 "Parameters to bitmap subcommand:\n"
192 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
193 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
194 " or '--merge source'\n"
195 " '-g granularity' sets the granularity for '--add' actions\n"
196 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
197 " bitmaps from an alternative file\n"
199 "Parameters to check subcommand:\n"
200 " '-r' tries to repair any inconsistencies that are found during the check.\n"
201 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
202 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
203 " hiding corruption that has already occurred.\n"
205 "Parameters to convert subcommand:\n"
206 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
207 " '-m' specifies how many coroutines work in parallel during the convert\n"
208 " process (defaults to 8)\n"
209 " '-W' allow to write to the target out of order rather than sequential\n"
211 "Parameters to snapshot subcommand:\n"
212 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
213 " '-a' applies a snapshot (revert disk to saved state)\n"
214 " '-c' creates a snapshot\n"
215 " '-d' deletes a snapshot\n"
216 " '-l' lists all snapshots in the given image\n"
218 "Parameters to compare subcommand:\n"
219 " '-f' first image format\n"
220 " '-F' second image format\n"
221 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
223 "Parameters to dd subcommand:\n"
224 " 'bs=BYTES' read and write up to BYTES bytes at a time "
226 " 'count=N' copy only N input blocks\n"
227 " 'if=FILE' read from FILE\n"
228 " 'of=FILE' write to FILE\n"
229 " 'skip=N' skip N bs-sized blocks at the start of input\n";
231 printf("%s\nSupported formats:", help_msg
);
232 bdrv_iterate_format(format_print
, NULL
, false);
233 printf("\n\n" QEMU_HELP_BOTTOM
"\n");
238 * Is @list safe for accumulate_options()?
239 * It is when multiple of them can be joined together separated by ','.
240 * To make that work, @list must not start with ',' (or else a
241 * separating ',' preceding it gets escaped), and it must not end with
242 * an odd number of ',' (or else a separating ',' following it gets
243 * escaped), or be empty (or else a separating ',' preceding it can
244 * escape a separating ',' following it).
247 static bool is_valid_option_list(const char *list
)
249 size_t len
= strlen(list
);
252 if (!list
[0] || list
[0] == ',') {
256 for (i
= len
; i
> 0 && list
[i
- 1] == ','; i
--) {
265 static int accumulate_options(char **options
, char *list
)
269 if (!is_valid_option_list(list
)) {
270 error_report("Invalid option list: %s", list
);
275 *options
= g_strdup(list
);
277 new_options
= g_strdup_printf("%s,%s", *options
, list
);
279 *options
= new_options
;
284 static QemuOptsList qemu_source_opts
= {
286 .implied_opt_name
= "file",
287 .head
= QTAILQ_HEAD_INITIALIZER(qemu_source_opts
.head
),
293 static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet
, const char *fmt
, ...)
299 ret
= vprintf(fmt
, args
);
306 static int print_block_option_help(const char *filename
, const char *fmt
)
308 BlockDriver
*drv
, *proto_drv
;
309 QemuOptsList
*create_opts
= NULL
;
310 Error
*local_err
= NULL
;
312 /* Find driver and parse its options */
313 drv
= bdrv_find_format(fmt
);
315 error_report("Unknown file format '%s'", fmt
);
319 if (!drv
->create_opts
) {
320 error_report("Format driver '%s' does not support image creation", fmt
);
324 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
326 proto_drv
= bdrv_find_protocol(filename
, true, &local_err
);
328 error_report_err(local_err
);
329 qemu_opts_free(create_opts
);
332 if (!proto_drv
->create_opts
) {
333 error_report("Protocol driver '%s' does not support image creation",
334 proto_drv
->format_name
);
335 qemu_opts_free(create_opts
);
338 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
342 printf("Supported options:\n");
344 printf("Supported %s options:\n", fmt
);
346 qemu_opts_print_help(create_opts
, false);
347 qemu_opts_free(create_opts
);
351 "The protocol level may support further options.\n"
352 "Specify the target filename to include those options.\n");
359 static BlockBackend
*img_open_opts(const char *optstr
,
360 QemuOpts
*opts
, int flags
, bool writethrough
,
361 bool quiet
, bool force_share
)
364 Error
*local_err
= NULL
;
366 options
= qemu_opts_to_qdict(opts
, NULL
);
368 if (qdict_haskey(options
, BDRV_OPT_FORCE_SHARE
)
369 && strcmp(qdict_get_str(options
, BDRV_OPT_FORCE_SHARE
), "on")) {
370 error_report("--force-share/-U conflicts with image options");
371 qobject_unref(options
);
374 qdict_put_str(options
, BDRV_OPT_FORCE_SHARE
, "on");
376 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
378 error_reportf_err(local_err
, "Could not open '%s': ", optstr
);
381 blk_set_enable_write_cache(blk
, !writethrough
);
386 static BlockBackend
*img_open_file(const char *filename
,
388 const char *fmt
, int flags
,
389 bool writethrough
, bool quiet
,
393 Error
*local_err
= NULL
;
396 options
= qdict_new();
399 qdict_put_str(options
, "driver", fmt
);
403 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
405 blk
= blk_new_open(filename
, NULL
, options
, flags
, &local_err
);
407 error_reportf_err(local_err
, "Could not open '%s': ", filename
);
410 blk_set_enable_write_cache(blk
, !writethrough
);
416 static int img_add_key_secrets(void *opaque
,
417 const char *name
, const char *value
,
420 QDict
*options
= opaque
;
422 if (g_str_has_suffix(name
, "key-secret")) {
423 qdict_put_str(options
, name
, value
);
430 static BlockBackend
*img_open(bool image_opts
,
431 const char *filename
,
432 const char *fmt
, int flags
, bool writethrough
,
433 bool quiet
, bool force_share
)
439 error_report("--image-opts and --format are mutually exclusive");
442 opts
= qemu_opts_parse_noisily(qemu_find_opts("source"),
447 blk
= img_open_opts(filename
, opts
, flags
, writethrough
, quiet
,
450 blk
= img_open_file(filename
, NULL
, fmt
, flags
, writethrough
, quiet
,
455 blk_set_force_allow_inactivate(blk
);
462 static int add_old_style_options(const char *fmt
, QemuOpts
*opts
,
463 const char *base_filename
,
464 const char *base_fmt
)
467 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FILE
, base_filename
,
469 error_report("Backing file not supported for file format '%s'",
475 if (!qemu_opt_set(opts
, BLOCK_OPT_BACKING_FMT
, base_fmt
, NULL
)) {
476 error_report("Backing file format not supported for file "
484 static int64_t cvtnum_full(const char *name
, const char *value
, int64_t min
,
490 err
= qemu_strtosz(value
, NULL
, &res
);
491 if (err
< 0 && err
!= -ERANGE
) {
492 error_report("Invalid %s specified. You may use "
493 "k, M, G, T, P or E suffixes for", name
);
494 error_report("kilobytes, megabytes, gigabytes, terabytes, "
495 "petabytes and exabytes.");
498 if (err
== -ERANGE
|| res
> max
|| res
< min
) {
499 error_report("Invalid %s specified. Must be between %" PRId64
500 " and %" PRId64
".", name
, min
, max
);
506 static int64_t cvtnum(const char *name
, const char *value
)
508 return cvtnum_full(name
, value
, 0, INT64_MAX
);
511 static int img_create(int argc
, char **argv
)
514 uint64_t img_size
= -1;
515 const char *fmt
= "raw";
516 const char *base_fmt
= NULL
;
517 const char *filename
;
518 const char *base_filename
= NULL
;
519 char *options
= NULL
;
520 Error
*local_err
= NULL
;
525 static const struct option long_options
[] = {
526 {"help", no_argument
, 0, 'h'},
527 {"object", required_argument
, 0, OPTION_OBJECT
},
530 c
= getopt_long(argc
, argv
, ":F:b:f:ho:qu",
537 missing_argument(argv
[optind
- 1]);
540 unrecognized_option(argv
[optind
- 1]);
549 base_filename
= optarg
;
555 if (accumulate_options(&options
, optarg
) < 0) {
563 flags
|= BDRV_O_NO_BACKING
;
566 user_creatable_process_cmdline(optarg
);
571 /* Get the filename */
572 filename
= (optind
< argc
) ? argv
[optind
] : NULL
;
573 if (options
&& has_help_option(options
)) {
575 return print_block_option_help(filename
, fmt
);
578 if (optind
>= argc
) {
579 error_exit("Expecting image file name");
583 /* Get image size, if specified */
587 sval
= cvtnum("image size", argv
[optind
++]);
591 img_size
= (uint64_t)sval
;
593 if (optind
!= argc
) {
594 error_exit("Unexpected argument: %s", argv
[optind
]);
597 bdrv_img_create(filename
, fmt
, base_filename
, base_fmt
,
598 options
, img_size
, flags
, quiet
, &local_err
);
600 error_reportf_err(local_err
, "%s: ", filename
);
612 static void dump_json_image_check(ImageCheck
*check
, bool quiet
)
616 Visitor
*v
= qobject_output_visitor_new(&obj
);
618 visit_type_ImageCheck(v
, NULL
, &check
, &error_abort
);
619 visit_complete(v
, &obj
);
620 str
= qobject_to_json_pretty(obj
, true);
622 qprintf(quiet
, "%s\n", str
->str
);
625 g_string_free(str
, true);
628 static void dump_human_image_check(ImageCheck
*check
, bool quiet
)
630 if (!(check
->corruptions
|| check
->leaks
|| check
->check_errors
)) {
631 qprintf(quiet
, "No errors were found on the image.\n");
633 if (check
->corruptions
) {
634 qprintf(quiet
, "\n%" PRId64
" errors were found on the image.\n"
635 "Data may be corrupted, or further writes to the image "
642 "\n%" PRId64
" leaked clusters were found on the image.\n"
643 "This means waste of disk space, but no harm to data.\n",
647 if (check
->check_errors
) {
650 " internal errors have occurred during the check.\n",
651 check
->check_errors
);
655 if (check
->total_clusters
!= 0 && check
->allocated_clusters
!= 0) {
656 qprintf(quiet
, "%" PRId64
"/%" PRId64
" = %0.2f%% allocated, "
657 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
658 check
->allocated_clusters
, check
->total_clusters
,
659 check
->allocated_clusters
* 100.0 / check
->total_clusters
,
660 check
->fragmented_clusters
* 100.0 / check
->allocated_clusters
,
661 check
->compressed_clusters
* 100.0 /
662 check
->allocated_clusters
);
665 if (check
->image_end_offset
) {
667 "Image end offset: %" PRId64
"\n", check
->image_end_offset
);
671 static int collect_image_check(BlockDriverState
*bs
,
673 const char *filename
,
678 BdrvCheckResult result
;
680 ret
= bdrv_check(bs
, &result
, fix
);
685 check
->filename
= g_strdup(filename
);
686 check
->format
= g_strdup(bdrv_get_format_name(bs
));
687 check
->check_errors
= result
.check_errors
;
688 check
->corruptions
= result
.corruptions
;
689 check
->has_corruptions
= result
.corruptions
!= 0;
690 check
->leaks
= result
.leaks
;
691 check
->has_leaks
= result
.leaks
!= 0;
692 check
->corruptions_fixed
= result
.corruptions_fixed
;
693 check
->has_corruptions_fixed
= result
.corruptions_fixed
!= 0;
694 check
->leaks_fixed
= result
.leaks_fixed
;
695 check
->has_leaks_fixed
= result
.leaks_fixed
!= 0;
696 check
->image_end_offset
= result
.image_end_offset
;
697 check
->has_image_end_offset
= result
.image_end_offset
!= 0;
698 check
->total_clusters
= result
.bfi
.total_clusters
;
699 check
->has_total_clusters
= result
.bfi
.total_clusters
!= 0;
700 check
->allocated_clusters
= result
.bfi
.allocated_clusters
;
701 check
->has_allocated_clusters
= result
.bfi
.allocated_clusters
!= 0;
702 check
->fragmented_clusters
= result
.bfi
.fragmented_clusters
;
703 check
->has_fragmented_clusters
= result
.bfi
.fragmented_clusters
!= 0;
704 check
->compressed_clusters
= result
.bfi
.compressed_clusters
;
705 check
->has_compressed_clusters
= result
.bfi
.compressed_clusters
!= 0;
711 * Checks an image for consistency. Exit codes:
713 * 0 - Check completed, image is good
714 * 1 - Check not completed because of internal errors
715 * 2 - Check completed, image is corrupted
716 * 3 - Check completed, image has leaked clusters, but is good otherwise
717 * 63 - Checks are not supported by the image format
719 static int img_check(int argc
, char **argv
)
722 OutputFormat output_format
= OFORMAT_HUMAN
;
723 const char *filename
, *fmt
, *output
, *cache
;
725 BlockDriverState
*bs
;
727 int flags
= BDRV_O_CHECK
;
731 bool image_opts
= false;
732 bool force_share
= false;
736 cache
= BDRV_DEFAULT_CACHE
;
739 int option_index
= 0;
740 static const struct option long_options
[] = {
741 {"help", no_argument
, 0, 'h'},
742 {"format", required_argument
, 0, 'f'},
743 {"repair", required_argument
, 0, 'r'},
744 {"output", required_argument
, 0, OPTION_OUTPUT
},
745 {"object", required_argument
, 0, OPTION_OBJECT
},
746 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
747 {"force-share", no_argument
, 0, 'U'},
750 c
= getopt_long(argc
, argv
, ":hf:r:T:qU",
751 long_options
, &option_index
);
757 missing_argument(argv
[optind
- 1]);
760 unrecognized_option(argv
[optind
- 1]);
769 flags
|= BDRV_O_RDWR
;
771 if (!strcmp(optarg
, "leaks")) {
772 fix
= BDRV_FIX_LEAKS
;
773 } else if (!strcmp(optarg
, "all")) {
774 fix
= BDRV_FIX_LEAKS
| BDRV_FIX_ERRORS
;
776 error_exit("Unknown option value for -r "
777 "(expecting 'leaks' or 'all'): %s", optarg
);
793 user_creatable_process_cmdline(optarg
);
795 case OPTION_IMAGE_OPTS
:
800 if (optind
!= argc
- 1) {
801 error_exit("Expecting one image file name");
803 filename
= argv
[optind
++];
805 if (output
&& !strcmp(output
, "json")) {
806 output_format
= OFORMAT_JSON
;
807 } else if (output
&& !strcmp(output
, "human")) {
808 output_format
= OFORMAT_HUMAN
;
810 error_report("--output must be used with human or json as argument.");
814 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
816 error_report("Invalid source cache option: %s", cache
);
820 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
827 check
= g_new0(ImageCheck
, 1);
828 ret
= collect_image_check(bs
, check
, filename
, fmt
, fix
);
830 if (ret
== -ENOTSUP
) {
831 error_report("This image format does not support checks");
836 if (check
->corruptions_fixed
|| check
->leaks_fixed
) {
837 int corruptions_fixed
, leaks_fixed
;
838 bool has_leaks_fixed
, has_corruptions_fixed
;
840 leaks_fixed
= check
->leaks_fixed
;
841 has_leaks_fixed
= check
->has_leaks_fixed
;
842 corruptions_fixed
= check
->corruptions_fixed
;
843 has_corruptions_fixed
= check
->has_corruptions_fixed
;
845 if (output_format
== OFORMAT_HUMAN
) {
847 "The following inconsistencies were found and repaired:\n\n"
848 " %" PRId64
" leaked clusters\n"
849 " %" PRId64
" corruptions\n\n"
850 "Double checking the fixed image now...\n",
852 check
->corruptions_fixed
);
855 qapi_free_ImageCheck(check
);
856 check
= g_new0(ImageCheck
, 1);
857 ret
= collect_image_check(bs
, check
, filename
, fmt
, 0);
859 check
->leaks_fixed
= leaks_fixed
;
860 check
->has_leaks_fixed
= has_leaks_fixed
;
861 check
->corruptions_fixed
= corruptions_fixed
;
862 check
->has_corruptions_fixed
= has_corruptions_fixed
;
866 switch (output_format
) {
868 dump_human_image_check(check
, quiet
);
871 dump_json_image_check(check
, quiet
);
876 if (ret
|| check
->check_errors
) {
878 error_report("Check failed: %s", strerror(-ret
));
880 error_report("Check failed");
886 if (check
->corruptions
) {
888 } else if (check
->leaks
) {
895 qapi_free_ImageCheck(check
);
900 typedef struct CommonBlockJobCBInfo
{
901 BlockDriverState
*bs
;
903 } CommonBlockJobCBInfo
;
905 static void common_block_job_cb(void *opaque
, int ret
)
907 CommonBlockJobCBInfo
*cbi
= opaque
;
910 error_setg_errno(cbi
->errp
, -ret
, "Block job failed");
914 static void run_block_job(BlockJob
*job
, Error
**errp
)
916 uint64_t progress_current
, progress_total
;
917 AioContext
*aio_context
= block_job_get_aio_context(job
);
921 job_ref_locked(&job
->job
);
923 float progress
= 0.0f
;
925 aio_poll(aio_context
, true);
927 progress_get_snapshot(&job
->job
.progress
, &progress_current
,
929 if (progress_total
) {
930 progress
= (float)progress_current
/ progress_total
* 100.f
;
932 qemu_progress_print(progress
, 0);
934 } while (!job_is_ready_locked(&job
->job
) &&
935 !job_is_completed_locked(&job
->job
));
937 if (!job_is_completed_locked(&job
->job
)) {
938 ret
= job_complete_sync_locked(&job
->job
, errp
);
942 job_unref_locked(&job
->job
);
945 /* publish completion progress only when success */
947 qemu_progress_print(100.f
, 0);
951 static int img_commit(int argc
, char **argv
)
954 const char *filename
, *fmt
, *cache
, *base
;
956 BlockDriverState
*bs
, *base_bs
;
958 bool progress
= false, quiet
= false, drop
= false;
960 Error
*local_err
= NULL
;
961 CommonBlockJobCBInfo cbi
;
962 bool image_opts
= false;
963 AioContext
*aio_context
;
964 int64_t rate_limit
= 0;
967 cache
= BDRV_DEFAULT_CACHE
;
970 static const struct option long_options
[] = {
971 {"help", no_argument
, 0, 'h'},
972 {"object", required_argument
, 0, OPTION_OBJECT
},
973 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
976 c
= getopt_long(argc
, argv
, ":f:ht:b:dpqr:",
983 missing_argument(argv
[optind
- 1]);
986 unrecognized_option(argv
[optind
- 1]);
1012 rate_limit
= cvtnum("rate limit", optarg
);
1013 if (rate_limit
< 0) {
1018 user_creatable_process_cmdline(optarg
);
1020 case OPTION_IMAGE_OPTS
:
1026 /* Progress is not shown in Quiet mode */
1031 if (optind
!= argc
- 1) {
1032 error_exit("Expecting one image file name");
1034 filename
= argv
[optind
++];
1036 flags
= BDRV_O_RDWR
| BDRV_O_UNMAP
;
1037 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1039 error_report("Invalid cache option: %s", cache
);
1043 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
1050 qemu_progress_init(progress
, 1.f
);
1051 qemu_progress_print(0.f
, 100);
1053 bdrv_graph_rdlock_main_loop();
1055 base_bs
= bdrv_find_backing_image(bs
, base
);
1057 error_setg(&local_err
,
1058 "Did not find '%s' in the backing chain of '%s'",
1060 bdrv_graph_rdunlock_main_loop();
1064 /* This is different from QMP, which by default uses the deepest file in
1065 * the backing chain (i.e., the very base); however, the traditional
1066 * behavior of qemu-img commit is using the immediate backing file. */
1067 base_bs
= bdrv_backing_chain_next(bs
);
1069 error_setg(&local_err
, "Image does not have a backing file");
1070 bdrv_graph_rdunlock_main_loop();
1074 bdrv_graph_rdunlock_main_loop();
1076 cbi
= (CommonBlockJobCBInfo
){
1081 aio_context
= bdrv_get_aio_context(bs
);
1082 aio_context_acquire(aio_context
);
1083 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1084 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1085 &cbi
, false, &local_err
);
1086 aio_context_release(aio_context
);
1091 /* When the block job completes, the BlockBackend reference will point to
1092 * the old backing file. In order to avoid that the top image is already
1093 * deleted, so we can still empty it afterwards, increment the reference
1094 * counter here preemptively. */
1099 job
= block_job_get("commit");
1101 run_block_job(job
, &local_err
);
1107 BlockBackend
*old_backing_blk
;
1109 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1111 if (!old_backing_blk
) {
1114 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1115 blk_unref(old_backing_blk
);
1116 if (ret
== -ENOTSUP
) {
1117 error_free(local_err
);
1119 } else if (ret
< 0) {
1130 qemu_progress_end();
1133 * Manually inactivate the image first because this way we can know whether
1134 * an error occurred. blk_unref() doesn't tell us about failures.
1136 ret
= bdrv_inactivate_all();
1137 if (ret
< 0 && !local_err
) {
1138 error_setg_errno(&local_err
, -ret
, "Error while closing the image");
1143 error_report_err(local_err
);
1147 qprintf(quiet
, "Image committed.\n");
1152 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1153 * of the first sector boundary within buf where the sector contains a
1154 * non-zero byte. This function is robust to a buffer that is not
1157 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1160 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1162 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1163 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1167 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1174 * Returns true iff the first sector pointed to by 'buf' contains at least
1177 * 'pnum' is set to the number of sectors (including and immediately following
1178 * the first one) that are known to be in the same allocated/unallocated state.
1179 * The function will try to align the end offset to alignment boundaries so
1180 * that the request will at least end aligned and consecutive requests will
1181 * also start at an aligned offset.
1183 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1184 int64_t sector_num
, int alignment
)
1193 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1194 for(i
= 1; i
< n
; i
++) {
1195 buf
+= BDRV_SECTOR_SIZE
;
1196 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1203 * The whole buf is the same.
1204 * No reason to split it into chunks, so return now.
1210 tail
= (sector_num
+ i
) & (alignment
- 1);
1212 if (is_zero
&& i
<= tail
) {
1214 * For sure next sector after i is data, and it will rewrite this
1215 * tail anyway due to RMW. So, let's just write data now.
1220 /* If possible, align up end offset of allocated areas. */
1221 i
+= alignment
- tail
;
1225 * For sure next sector after i is data, and it will rewrite this
1226 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1237 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1238 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1239 * breaking up write requests for only small sparse areas.
1241 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1242 int min
, int64_t sector_num
, int alignment
)
1245 int num_checked
, num_used
;
1251 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1257 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1259 sector_num
+= *pnum
;
1260 num_checked
= num_used
;
1263 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1265 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1267 sector_num
+= *pnum
;
1268 num_checked
+= *pnum
;
1270 num_used
= num_checked
;
1271 } else if (*pnum
>= min
) {
1281 * Compares two buffers chunk by chunk, where @chsize is the chunk size.
1282 * If @chsize is 0, default chunk size of BDRV_SECTOR_SIZE is used.
1283 * Returns 0 if the first chunk of each buffer matches, non-zero otherwise.
1285 * @pnum is set to the size of the buffer prefix aligned to @chsize that
1286 * has the same matching status as the first chunk.
1288 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1289 int64_t bytes
, uint64_t chsize
, int64_t *pnum
)
1297 chsize
= BDRV_SECTOR_SIZE
;
1299 i
= MIN(bytes
, chsize
);
1301 res
= !!memcmp(buf1
, buf2
, i
);
1303 int64_t len
= MIN(bytes
- i
, chsize
);
1305 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1315 #define IO_BUF_SIZE (2 * MiB)
1318 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1320 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1321 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1322 * failure), and 4 on error (the exit status for read errors), after emitting
1325 * @param blk: BlockBackend for the image
1326 * @param offset: Starting offset to check
1327 * @param bytes: Number of bytes to check
1328 * @param filename: Name of disk file we are checking (logging purpose)
1329 * @param buffer: Allocated buffer for storing read data
1330 * @param quiet: Flag for quiet mode
1332 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1333 int64_t bytes
, const char *filename
,
1334 uint8_t *buffer
, bool quiet
)
1339 ret
= blk_pread(blk
, offset
, bytes
, buffer
, 0);
1341 error_report("Error while reading offset %" PRId64
" of %s: %s",
1342 offset
, filename
, strerror(-ret
));
1345 idx
= find_nonzero(buffer
, bytes
);
1347 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1356 * Compares two images. Exit codes:
1358 * 0 - Images are identical or the requested help was printed
1360 * >1 - Error occurred
1362 static int img_compare(int argc
, char **argv
)
1364 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1365 BlockBackend
*blk1
, *blk2
;
1366 BlockDriverState
*bs1
, *bs2
;
1367 int64_t total_size1
, total_size2
;
1368 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1369 int64_t pnum1
, pnum2
;
1370 int allocated1
, allocated2
;
1371 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1372 bool progress
= false, quiet
= false, strict
= false;
1379 uint64_t progress_base
;
1380 bool image_opts
= false;
1381 bool force_share
= false;
1383 cache
= BDRV_DEFAULT_CACHE
;
1385 static const struct option long_options
[] = {
1386 {"help", no_argument
, 0, 'h'},
1387 {"object", required_argument
, 0, OPTION_OBJECT
},
1388 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1389 {"force-share", no_argument
, 0, 'U'},
1392 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1393 long_options
, NULL
);
1399 missing_argument(argv
[optind
- 1]);
1402 unrecognized_option(argv
[optind
- 1]);
1430 Error
*local_err
= NULL
;
1432 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1434 error_report_err(local_err
);
1437 /* Help was printed */
1443 case OPTION_IMAGE_OPTS
:
1449 /* Progress is not shown in Quiet mode */
1455 if (optind
!= argc
- 2) {
1456 error_exit("Expecting two image file names");
1458 filename1
= argv
[optind
++];
1459 filename2
= argv
[optind
++];
1461 /* Initialize before goto out */
1462 qemu_progress_init(progress
, 2.0);
1465 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1467 error_report("Invalid source cache option: %s", cache
);
1472 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1479 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1488 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1489 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1490 total_size1
= blk_getlength(blk1
);
1491 if (total_size1
< 0) {
1492 error_report("Can't get size of %s: %s",
1493 filename1
, strerror(-total_size1
));
1497 total_size2
= blk_getlength(blk2
);
1498 if (total_size2
< 0) {
1499 error_report("Can't get size of %s: %s",
1500 filename2
, strerror(-total_size2
));
1504 total_size
= MIN(total_size1
, total_size2
);
1505 progress_base
= MAX(total_size1
, total_size2
);
1507 qemu_progress_print(0, 100);
1509 if (strict
&& total_size1
!= total_size2
) {
1511 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1515 while (offset
< total_size
) {
1516 int status1
, status2
;
1518 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1519 total_size1
- offset
, &pnum1
, NULL
,
1523 error_report("Sector allocation test failed for %s", filename1
);
1526 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1528 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1529 total_size2
- offset
, &pnum2
, NULL
,
1533 error_report("Sector allocation test failed for %s", filename2
);
1536 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1538 assert(pnum1
&& pnum2
);
1539 chunk
= MIN(pnum1
, pnum2
);
1542 if (status1
!= status2
) {
1544 qprintf(quiet
, "Strict mode: Offset %" PRId64
1545 " block status mismatch!\n", offset
);
1549 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1551 } else if (allocated1
== allocated2
) {
1555 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1556 ret
= blk_pread(blk1
, offset
, chunk
, buf1
, 0);
1558 error_report("Error while reading offset %" PRId64
1560 offset
, filename1
, strerror(-ret
));
1564 ret
= blk_pread(blk2
, offset
, chunk
, buf2
, 0);
1566 error_report("Error while reading offset %" PRId64
1568 offset
, filename2
, strerror(-ret
));
1572 ret
= compare_buffers(buf1
, buf2
, chunk
, 0, &pnum
);
1573 if (ret
|| pnum
!= chunk
) {
1574 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1575 offset
+ (ret
? 0 : pnum
));
1581 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1583 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1584 filename1
, buf1
, quiet
);
1586 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1587 filename2
, buf1
, quiet
);
1594 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1597 if (total_size1
!= total_size2
) {
1598 BlockBackend
*blk_over
;
1599 const char *filename_over
;
1601 qprintf(quiet
, "Warning: Image size mismatch!\n");
1602 if (total_size1
> total_size2
) {
1604 filename_over
= filename1
;
1607 filename_over
= filename2
;
1610 while (offset
< progress_base
) {
1611 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1612 progress_base
- offset
, &chunk
,
1616 error_report("Sector allocation test failed for %s",
1621 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1622 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1623 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1624 filename_over
, buf1
, quiet
);
1630 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1634 qprintf(quiet
, "Images are identical.\n");
1644 qemu_progress_end();
1648 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1649 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1650 const char *src_node
, const char *src_name
,
1653 BlockDirtyBitmapOrStr
*merge_src
;
1654 BlockDirtyBitmapOrStrList
*list
= NULL
;
1656 merge_src
= g_new0(BlockDirtyBitmapOrStr
, 1);
1657 merge_src
->type
= QTYPE_QDICT
;
1658 merge_src
->u
.external
.node
= g_strdup(src_node
);
1659 merge_src
->u
.external
.name
= g_strdup(src_name
);
1660 QAPI_LIST_PREPEND(list
, merge_src
);
1661 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1662 qapi_free_BlockDirtyBitmapOrStrList(list
);
1665 enum ImgConvertBlockStatus
{
1671 #define MAX_COROUTINES 16
1672 #define CONVERT_THROTTLE_GROUP "img_convert"
1674 typedef struct ImgConvertState
{
1676 int64_t *src_sectors
;
1679 int64_t total_sectors
;
1680 int64_t allocated_sectors
;
1681 int64_t allocated_done
;
1684 enum ImgConvertBlockStatus status
;
1685 int64_t sector_next_status
;
1686 BlockBackend
*target
;
1690 bool target_has_backing
;
1691 int64_t target_backing_sectors
; /* negative if unknown */
1698 size_t cluster_sectors
;
1700 long num_coroutines
;
1701 int running_coroutines
;
1702 Coroutine
*co
[MAX_COROUTINES
];
1703 int64_t wait_sector_num
[MAX_COROUTINES
];
1708 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1709 int *src_cur
, int64_t *src_cur_offset
)
1712 *src_cur_offset
= 0;
1713 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1714 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1716 assert(*src_cur
< s
->src_num
);
1720 static int coroutine_mixed_fn GRAPH_RDLOCK
1721 convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1723 int64_t src_cur_offset
;
1724 int ret
, n
, src_cur
;
1725 bool post_backing_zero
= false;
1727 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1729 assert(s
->total_sectors
> sector_num
);
1730 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1732 if (s
->target_backing_sectors
>= 0) {
1733 if (sector_num
>= s
->target_backing_sectors
) {
1734 post_backing_zero
= true;
1735 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1736 /* Split requests around target_backing_sectors (because
1737 * starting from there, zeros are handled differently) */
1738 n
= s
->target_backing_sectors
- sector_num
;
1742 if (s
->sector_next_status
<= sector_num
) {
1743 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1746 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1747 BlockDriverState
*base
;
1749 if (s
->target_has_backing
) {
1750 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1756 count
= n
* BDRV_SECTOR_SIZE
;
1758 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1765 warn_report("error while reading block status at "
1766 "offset %" PRIu64
": %s", offset
,
1769 /* Just try to read the data, then */
1770 ret
= BDRV_BLOCK_DATA
;
1771 count
= BDRV_SECTOR_SIZE
;
1773 /* Retry on a shorter range */
1774 n
= DIV_ROUND_UP(n
, 4);
1777 error_report("error while reading block status at offset "
1778 "%" PRIu64
": %s", offset
, strerror(-ret
));
1784 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1787 * Avoid that s->sector_next_status becomes unaligned to the source
1788 * request alignment and/or cluster size to avoid unnecessary read
1791 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1796 if (ret
& BDRV_BLOCK_ZERO
) {
1797 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1798 } else if (ret
& BDRV_BLOCK_DATA
) {
1799 s
->status
= BLK_DATA
;
1801 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1804 s
->sector_next_status
= sector_num
+ n
;
1807 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1808 if (s
->status
== BLK_DATA
) {
1809 n
= MIN(n
, s
->buf_sectors
);
1812 /* We need to write complete clusters for compressed images, so if an
1813 * unallocated area is shorter than that, we must consider the whole
1814 * cluster allocated. */
1815 if (s
->compressed
) {
1816 if (n
< s
->cluster_sectors
) {
1817 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1818 s
->status
= BLK_DATA
;
1820 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1827 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1828 int nb_sectors
, uint8_t *buf
)
1830 uint64_t single_read_until
= 0;
1833 assert(nb_sectors
<= s
->buf_sectors
);
1834 while (nb_sectors
> 0) {
1837 int64_t bs_sectors
, src_cur_offset
;
1840 /* In the case of compression with multiple source files, we can get a
1841 * nb_sectors that spreads into the next part. So we must be able to
1842 * read across multiple BDSes for one convert_read() call. */
1843 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1844 blk
= s
->src
[src_cur
];
1845 bs_sectors
= s
->src_sectors
[src_cur
];
1847 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1849 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1850 if (single_read_until
> offset
) {
1854 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1858 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1862 warn_report("error while reading offset %" PRIu64
1863 ": %s", offset
, strerror(-ret
));
1865 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1874 buf
+= n
* BDRV_SECTOR_SIZE
;
1881 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1882 int nb_sectors
, uint8_t *buf
,
1883 enum ImgConvertBlockStatus status
)
1887 while (nb_sectors
> 0) {
1889 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1892 case BLK_BACKING_FILE
:
1893 /* If we have a backing file, leave clusters unallocated that are
1894 * unallocated in the source image, so that the backing file is
1895 * visible at the respective offset. */
1896 assert(s
->target_has_backing
);
1900 /* If we're told to keep the target fully allocated (-S 0) or there
1901 * is real non-zero data, we must write it. Otherwise we can treat
1902 * it as zero sectors.
1903 * Compressed clusters need to be written as a whole, so in that
1904 * case we can only save the write if the buffer is completely
1906 if (!s
->min_sparse
||
1908 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1909 sector_num
, s
->alignment
)) ||
1911 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1913 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1914 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1923 if (s
->has_zero_init
) {
1924 assert(!s
->target_has_backing
);
1927 ret
= blk_co_pwrite_zeroes(s
->target
,
1928 sector_num
<< BDRV_SECTOR_BITS
,
1929 n
<< BDRV_SECTOR_BITS
,
1930 BDRV_REQ_MAY_UNMAP
);
1939 buf
+= n
* BDRV_SECTOR_SIZE
;
1945 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1950 while (nb_sectors
> 0) {
1953 int64_t bs_sectors
, src_cur_offset
;
1956 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1957 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1958 blk
= s
->src
[src_cur
];
1959 bs_sectors
= s
->src_sectors
[src_cur
];
1961 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1963 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1964 sector_num
<< BDRV_SECTOR_BITS
,
1965 n
<< BDRV_SECTOR_BITS
, 0, 0);
1976 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1978 ImgConvertState
*s
= opaque
;
1979 uint8_t *buf
= NULL
;
1983 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1984 if (s
->co
[i
] == qemu_coroutine_self()) {
1991 s
->running_coroutines
++;
1992 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1997 enum ImgConvertBlockStatus status
;
2000 qemu_co_mutex_lock(&s
->lock
);
2001 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
2002 qemu_co_mutex_unlock(&s
->lock
);
2005 WITH_GRAPH_RDLOCK_GUARD() {
2006 n
= convert_iteration_sectors(s
, s
->sector_num
);
2009 qemu_co_mutex_unlock(&s
->lock
);
2013 /* save current sector and allocation status to local variables */
2014 sector_num
= s
->sector_num
;
2016 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
2017 n
= MIN(n
, s
->buf_sectors
);
2019 /* increment global sector counter so that other coroutines can
2020 * already continue reading beyond this request */
2022 qemu_co_mutex_unlock(&s
->lock
);
2024 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2025 s
->allocated_done
+= n
;
2026 qemu_progress_print(100.0 * s
->allocated_done
/
2027 s
->allocated_sectors
, 0);
2031 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2032 if (status
== BLK_DATA
&& !copy_range
) {
2033 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2035 error_report("error while reading at byte %lld: %s",
2036 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2039 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2041 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2044 if (s
->wr_in_order
) {
2045 /* keep writes in order */
2046 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2047 s
->wait_sector_num
[index
] = sector_num
;
2048 qemu_coroutine_yield();
2050 s
->wait_sector_num
[index
] = -1;
2053 if (s
->ret
== -EINPROGRESS
) {
2055 WITH_GRAPH_RDLOCK_GUARD() {
2056 ret
= convert_co_copy_range(s
, sector_num
, n
);
2059 s
->copy_range
= false;
2063 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2066 error_report("error while writing at byte %lld: %s",
2067 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2072 if (s
->wr_in_order
) {
2073 /* reenter the coroutine that might have waited
2074 * for this write to complete */
2075 s
->wr_offs
= sector_num
+ n
;
2076 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2077 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2079 * A -> B -> A cannot occur because A has
2080 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2081 * B will never enter A during this time window.
2083 qemu_coroutine_enter(s
->co
[i
]);
2091 s
->co
[index
] = NULL
;
2092 s
->running_coroutines
--;
2093 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2094 /* the convert job finished successfully */
2099 static int convert_do_copy(ImgConvertState
*s
)
2102 int64_t sector_num
= 0;
2104 /* Check whether we have zero initialisation or can get it efficiently */
2105 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2106 !s
->target_has_backing
) {
2107 bdrv_graph_rdlock_main_loop();
2108 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2109 bdrv_graph_rdunlock_main_loop();
2112 /* Allocate buffer for copied data. For compressed images, only one cluster
2113 * can be copied at a time. */
2114 if (s
->compressed
) {
2115 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2116 error_report("invalid cluster size");
2119 s
->buf_sectors
= s
->cluster_sectors
;
2122 while (sector_num
< s
->total_sectors
) {
2123 bdrv_graph_rdlock_main_loop();
2124 n
= convert_iteration_sectors(s
, sector_num
);
2125 bdrv_graph_rdunlock_main_loop();
2129 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2131 s
->allocated_sectors
+= n
;
2137 s
->sector_next_status
= 0;
2138 s
->ret
= -EINPROGRESS
;
2140 qemu_co_mutex_init(&s
->lock
);
2141 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2142 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2143 s
->wait_sector_num
[i
] = -1;
2144 qemu_coroutine_enter(s
->co
[i
]);
2147 while (s
->running_coroutines
) {
2148 main_loop_wait(false);
2151 if (s
->compressed
&& !s
->ret
) {
2152 /* signal EOF to align */
2153 ret
= blk_pwrite_compressed(s
->target
, 0, 0, NULL
);
2162 /* Check that bitmaps can be copied, or output an error */
2163 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2165 BdrvDirtyBitmap
*bm
;
2167 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2168 error_report("Source lacks bitmap support");
2171 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2172 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2175 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2176 error_report("Cannot copy inconsistent bitmap '%s'",
2177 bdrv_dirty_bitmap_name(bm
));
2178 error_printf("Try --skip-broken-bitmaps, or "
2179 "use 'qemu-img bitmap --remove' to delete it\n");
2186 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2189 BdrvDirtyBitmap
*bm
;
2192 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2195 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2198 name
= bdrv_dirty_bitmap_name(bm
);
2199 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2200 warn_report("Skipping inconsistent bitmap '%s'", name
);
2203 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2204 true, bdrv_dirty_bitmap_granularity(bm
),
2206 true, !bdrv_dirty_bitmap_enabled(bm
),
2209 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2213 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2216 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2217 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2225 #define MAX_BUF_SECTORS 32768
2227 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2231 throttle_config_init(&cfg
);
2232 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2234 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2235 blk_set_io_limits(blk
, &cfg
);
2238 static int img_convert(int argc
, char **argv
)
2240 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2241 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2242 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2243 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2244 *backing_fmt
= NULL
;
2245 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2246 BlockDriverInfo bdi
;
2247 BlockDriverState
*out_bs
;
2248 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2249 QemuOptsList
*create_opts
= NULL
;
2250 QDict
*open_opts
= NULL
;
2251 char *options
= NULL
;
2252 Error
*local_err
= NULL
;
2253 bool writethrough
, src_writethrough
, image_opts
= false,
2254 skip_create
= false, progress
= false, tgt_image_opts
= false;
2255 int64_t ret
= -EINVAL
;
2256 bool force_share
= false;
2257 bool explict_min_sparse
= false;
2258 bool bitmaps
= false;
2259 bool skip_broken
= false;
2260 int64_t rate_limit
= 0;
2262 ImgConvertState s
= (ImgConvertState
) {
2263 /* Need at least 4k of zeros for sparse detection */
2265 .copy_range
= false,
2266 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2267 .wr_in_order
= true,
2268 .num_coroutines
= 8,
2272 static const struct option long_options
[] = {
2273 {"help", no_argument
, 0, 'h'},
2274 {"object", required_argument
, 0, OPTION_OBJECT
},
2275 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2276 {"force-share", no_argument
, 0, 'U'},
2277 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2278 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2279 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2280 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2281 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2284 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2285 long_options
, NULL
);
2291 missing_argument(argv
[optind
- 1]);
2294 unrecognized_option(argv
[optind
- 1]);
2306 out_baseimg
= optarg
;
2309 s
.copy_range
= true;
2312 s
.compressed
= true;
2315 backing_fmt
= optarg
;
2318 if (accumulate_options(&options
, optarg
) < 0) {
2323 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2324 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2327 error_report("Failed in parsing snapshot param '%s'",
2332 snapshot_name
= optarg
;
2339 sval
= cvtnum("buffer size for sparse output", optarg
);
2342 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2343 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2344 error_report("Invalid buffer size for sparse output specified. "
2345 "Valid sizes are multiples of %llu up to %llu. Select "
2346 "0 to disable sparse detection (fully allocates output).",
2347 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2351 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2352 explict_min_sparse
= true;
2371 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2372 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2373 error_report("Invalid number of coroutines. Allowed number of"
2374 " coroutines is between 1 and %d", MAX_COROUTINES
);
2379 s
.wr_in_order
= false;
2385 rate_limit
= cvtnum("rate limit", optarg
);
2386 if (rate_limit
< 0) {
2391 user_creatable_process_cmdline(optarg
);
2393 case OPTION_IMAGE_OPTS
:
2396 case OPTION_SALVAGE
:
2399 case OPTION_TARGET_IMAGE_OPTS
:
2400 tgt_image_opts
= true;
2402 case OPTION_TARGET_IS_ZERO
:
2404 * The user asserting that the target is blank has the
2405 * same effect as the target driver supporting zero
2408 s
.has_zero_init
= true;
2410 case OPTION_BITMAPS
:
2413 case OPTION_SKIP_BROKEN
:
2419 if (!out_fmt
&& !tgt_image_opts
) {
2423 if (skip_broken
&& !bitmaps
) {
2424 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2428 if (s
.compressed
&& s
.copy_range
) {
2429 error_report("Cannot enable copy offloading when -c is used");
2433 if (explict_min_sparse
&& s
.copy_range
) {
2434 error_report("Cannot enable copy offloading when -S is used");
2438 if (s
.copy_range
&& s
.salvage
) {
2439 error_report("Cannot use copy offloading in salvaging mode");
2443 if (tgt_image_opts
&& !skip_create
) {
2444 error_report("--target-image-opts requires use of -n flag");
2448 if (skip_create
&& options
) {
2449 error_report("-o has no effect when skipping image creation");
2453 if (s
.has_zero_init
&& !skip_create
) {
2454 error_report("--target-is-zero requires use of -n flag");
2458 s
.src_num
= argc
- optind
- 1;
2459 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2461 if (options
&& has_help_option(options
)) {
2463 ret
= print_block_option_help(out_filename
, out_fmt
);
2466 error_report("Option help requires a format be specified");
2471 if (s
.src_num
< 1) {
2472 error_report("Must specify image file name");
2476 /* ret is still -EINVAL until here */
2477 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2479 error_report("Invalid source cache option: %s", src_cache
);
2483 /* Initialize before goto out */
2487 qemu_progress_init(progress
, 1.0);
2488 qemu_progress_print(0, 100);
2490 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2491 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2492 s
.src_alignment
= g_new(int, s
.src_num
);
2494 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2495 BlockDriverState
*src_bs
;
2496 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2497 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2503 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2504 if (s
.src_sectors
[bs_i
] < 0) {
2505 error_report("Could not get size of %s: %s",
2506 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2510 src_bs
= blk_bs(s
.src
[bs_i
]);
2511 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2513 if (!bdrv_get_info(src_bs
, &bdi
)) {
2514 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2515 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2517 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2521 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2522 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2523 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2525 } else if (snapshot_name
!= NULL
) {
2526 if (s
.src_num
> 1) {
2527 error_report("No support for concatenating multiple snapshot");
2532 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2536 error_reportf_err(local_err
, "Failed to load snapshot: ");
2542 /* Find driver and parse its options */
2543 drv
= bdrv_find_format(out_fmt
);
2545 error_report("Unknown file format '%s'", out_fmt
);
2550 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2552 error_report_err(local_err
);
2557 if (!drv
->create_opts
) {
2558 error_report("Format driver '%s' does not support image creation",
2564 if (!proto_drv
->create_opts
) {
2565 error_report("Protocol driver '%s' does not support image creation",
2566 proto_drv
->format_name
);
2571 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2572 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2574 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2576 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2577 error_report_err(local_err
);
2583 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2584 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2585 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2591 /* Get backing file name if -o backing_file was used */
2592 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2593 if (out_baseimg_param
) {
2594 out_baseimg
= out_baseimg_param
;
2596 s
.target_has_backing
= (bool) out_baseimg
;
2598 if (s
.has_zero_init
&& s
.target_has_backing
) {
2599 error_report("Cannot use --target-is-zero when the destination "
2600 "image has a backing file");
2604 if (s
.src_num
> 1 && out_baseimg
) {
2605 error_report("Having a backing file for the target makes no sense when "
2606 "concatenating multiple input images");
2611 if (out_baseimg_param
) {
2612 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2613 error_report("Use of backing file requires explicit "
2620 /* Check if compression is supported */
2623 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2624 const char *encryptfmt
=
2625 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2626 const char *preallocation
=
2627 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2629 if (drv
&& !block_driver_can_compress(drv
)) {
2630 error_report("Compression not supported for this file format");
2635 if (encryption
|| encryptfmt
) {
2636 error_report("Compression and encryption not supported at "
2643 && strcmp(preallocation
, "off"))
2645 error_report("Compression and preallocation not supported at "
2652 /* Determine if bitmaps need copying */
2654 if (s
.src_num
> 1) {
2655 error_report("Copying bitmaps only possible with single source");
2659 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2666 * The later open call will need any decryption secrets, and
2667 * bdrv_create() will purge "opts", so extract them now before
2671 open_opts
= qdict_new();
2672 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2674 /* Create the new image */
2675 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2677 error_reportf_err(local_err
, "%s: error while converting %s: ",
2678 out_filename
, out_fmt
);
2683 s
.target_is_new
= !skip_create
;
2685 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2686 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2688 error_report("Invalid cache option: %s", cache
);
2692 if (flags
& BDRV_O_NOCACHE
) {
2694 * If we open the target with O_DIRECT, it may be necessary to
2695 * extend its size to align to the physical sector size.
2697 flags
|= BDRV_O_RESIZE
;
2701 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2702 flags
, writethrough
, s
.quiet
, false);
2704 /* TODO ultimately we should allow --target-image-opts
2705 * to be used even when -n is not given.
2706 * That has to wait for bdrv_create to be improved
2707 * to allow filenames in option syntax
2709 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2710 flags
, writethrough
, s
.quiet
, false);
2711 open_opts
= NULL
; /* blk_new_open will have freed it */
2717 out_bs
= blk_bs(s
.target
);
2719 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2720 error_report("Format driver '%s' does not support bitmaps",
2721 out_bs
->drv
->format_name
);
2726 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2727 error_report("Compression not supported for this file format");
2732 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2733 * or discard_alignment of the out_bs is greater. Limit to
2734 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2735 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2737 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2738 out_bs
->bl
.pdiscard_alignment
>>
2739 BDRV_SECTOR_BITS
)));
2741 /* try to align the write requests to the destination to avoid unnecessary
2743 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2744 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2746 assert(is_power_of_2(s
.alignment
));
2749 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2750 if (output_sectors
< 0) {
2751 error_report("unable to get output image length: %s",
2752 strerror(-output_sectors
));
2755 } else if (output_sectors
< s
.total_sectors
) {
2756 error_report("output file is smaller than input file");
2762 if (s
.target_has_backing
&& s
.target_is_new
) {
2763 /* Errors are treated as "backing length unknown" (which means
2764 * s.target_backing_sectors has to be negative, which it will
2765 * be automatically). The backing file length is used only
2766 * for optimizations, so such a case is not fatal. */
2767 bdrv_graph_rdlock_main_loop();
2768 s
.target_backing_sectors
=
2769 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2770 bdrv_graph_rdunlock_main_loop();
2772 s
.target_backing_sectors
= -1;
2775 ret
= bdrv_get_info(out_bs
, &bdi
);
2778 error_report("could not get block driver info");
2782 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2783 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2787 set_rate_limit(s
.target
, rate_limit
);
2790 ret
= convert_do_copy(&s
);
2792 /* Now copy the bitmaps */
2793 if (bitmaps
&& ret
== 0) {
2794 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2799 qemu_progress_print(100, 0);
2801 qemu_progress_end();
2802 qemu_opts_del(opts
);
2803 qemu_opts_free(create_opts
);
2804 qobject_unref(open_opts
);
2805 blk_unref(s
.target
);
2807 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2808 blk_unref(s
.src
[bs_i
]);
2812 g_free(s
.src_sectors
);
2813 g_free(s
.src_alignment
);
2815 qemu_opts_del(sn_opts
);
2822 static void dump_snapshots(BlockDriverState
*bs
)
2824 QEMUSnapshotInfo
*sn_tab
, *sn
;
2827 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2830 printf("Snapshot list:\n");
2831 bdrv_snapshot_dump(NULL
);
2833 for(i
= 0; i
< nb_sns
; i
++) {
2835 bdrv_snapshot_dump(sn
);
2841 static void dump_json_block_graph_info_list(BlockGraphInfoList
*list
)
2845 Visitor
*v
= qobject_output_visitor_new(&obj
);
2847 visit_type_BlockGraphInfoList(v
, NULL
, &list
, &error_abort
);
2848 visit_complete(v
, &obj
);
2849 str
= qobject_to_json_pretty(obj
, true);
2850 assert(str
!= NULL
);
2851 printf("%s\n", str
->str
);
2854 g_string_free(str
, true);
2857 static void dump_json_block_graph_info(BlockGraphInfo
*info
)
2861 Visitor
*v
= qobject_output_visitor_new(&obj
);
2863 visit_type_BlockGraphInfo(v
, NULL
, &info
, &error_abort
);
2864 visit_complete(v
, &obj
);
2865 str
= qobject_to_json_pretty(obj
, true);
2866 assert(str
!= NULL
);
2867 printf("%s\n", str
->str
);
2870 g_string_free(str
, true);
2873 static void dump_human_image_info(BlockGraphInfo
*info
, int indentation
,
2876 BlockChildInfoList
*children_list
;
2878 bdrv_node_info_dump(qapi_BlockGraphInfo_base(info
), indentation
,
2879 info
->children
== NULL
);
2881 for (children_list
= info
->children
; children_list
;
2882 children_list
= children_list
->next
)
2884 BlockChildInfo
*child
= children_list
->value
;
2885 g_autofree
char *child_path
= NULL
;
2887 printf("%*sChild node '%s%s':\n",
2888 indentation
* 4, "", path
, child
->name
);
2889 child_path
= g_strdup_printf("%s%s/", path
, child
->name
);
2890 dump_human_image_info(child
->info
, indentation
+ 1, child_path
);
2894 static void dump_human_image_info_list(BlockGraphInfoList
*list
)
2896 BlockGraphInfoList
*elem
;
2899 for (elem
= list
; elem
; elem
= elem
->next
) {
2905 dump_human_image_info(elem
->value
, 0, "/");
2909 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2911 return strcmp(a
, b
) == 0;
2915 * Open an image file chain and return an BlockGraphInfoList
2917 * @filename: topmost image filename
2918 * @fmt: topmost image format (may be NULL to autodetect)
2919 * @chain: true - enumerate entire backing file chain
2920 * false - only topmost image file
2922 * Returns a list of BlockNodeInfo objects or NULL if there was an error
2923 * opening an image file. If there was an error a message will have been
2924 * printed to stderr.
2926 static BlockGraphInfoList
*collect_image_info_list(bool image_opts
,
2927 const char *filename
,
2929 bool chain
, bool force_share
)
2931 BlockGraphInfoList
*head
= NULL
;
2932 BlockGraphInfoList
**tail
= &head
;
2933 GHashTable
*filenames
;
2936 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2940 BlockDriverState
*bs
;
2941 BlockGraphInfo
*info
;
2943 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2944 error_report("Backing file '%s' creates an infinite loop.",
2948 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2950 blk
= img_open(image_opts
, filename
, fmt
,
2951 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2959 * Note that the returned BlockGraphInfo object will not have
2960 * information about this image's backing node, because we have opened
2961 * it with BDRV_O_NO_BACKING. Printing this object will therefore not
2962 * duplicate the backing chain information that we obtain by walking
2963 * the chain manually here.
2965 bdrv_graph_rdlock_main_loop();
2966 bdrv_query_block_graph_info(bs
, &info
, &err
);
2967 bdrv_graph_rdunlock_main_loop();
2970 error_report_err(err
);
2975 QAPI_LIST_APPEND(tail
, info
);
2979 /* Clear parameters that only apply to the topmost image */
2980 filename
= fmt
= NULL
;
2984 if (info
->full_backing_filename
) {
2985 filename
= info
->full_backing_filename
;
2986 } else if (info
->backing_filename
) {
2987 error_report("Could not determine absolute backing filename,"
2988 " but backing filename '%s' present",
2989 info
->backing_filename
);
2992 if (info
->backing_filename_format
) {
2993 fmt
= info
->backing_filename_format
;
2997 g_hash_table_destroy(filenames
);
3001 qapi_free_BlockGraphInfoList(head
);
3002 g_hash_table_destroy(filenames
);
3006 static int img_info(int argc
, char **argv
)
3009 OutputFormat output_format
= OFORMAT_HUMAN
;
3011 const char *filename
, *fmt
, *output
;
3012 BlockGraphInfoList
*list
;
3013 bool image_opts
= false;
3014 bool force_share
= false;
3019 int option_index
= 0;
3020 static const struct option long_options
[] = {
3021 {"help", no_argument
, 0, 'h'},
3022 {"format", required_argument
, 0, 'f'},
3023 {"output", required_argument
, 0, OPTION_OUTPUT
},
3024 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
3025 {"object", required_argument
, 0, OPTION_OBJECT
},
3026 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3027 {"force-share", no_argument
, 0, 'U'},
3030 c
= getopt_long(argc
, argv
, ":f:hU",
3031 long_options
, &option_index
);
3037 missing_argument(argv
[optind
- 1]);
3040 unrecognized_option(argv
[optind
- 1]);
3054 case OPTION_BACKING_CHAIN
:
3058 user_creatable_process_cmdline(optarg
);
3060 case OPTION_IMAGE_OPTS
:
3065 if (optind
!= argc
- 1) {
3066 error_exit("Expecting one image file name");
3068 filename
= argv
[optind
++];
3070 if (output
&& !strcmp(output
, "json")) {
3071 output_format
= OFORMAT_JSON
;
3072 } else if (output
&& !strcmp(output
, "human")) {
3073 output_format
= OFORMAT_HUMAN
;
3074 } else if (output
) {
3075 error_report("--output must be used with human or json as argument.");
3079 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3085 switch (output_format
) {
3087 dump_human_image_info_list(list
);
3091 dump_json_block_graph_info_list(list
);
3093 dump_json_block_graph_info(list
->value
);
3098 qapi_free_BlockGraphInfoList(list
);
3102 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3105 switch (output_format
) {
3107 if (e
->data
&& !e
->has_offset
) {
3108 error_report("File contains external, encrypted or compressed clusters.");
3111 if (e
->data
&& !e
->zero
) {
3112 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3113 e
->start
, e
->length
,
3114 e
->has_offset
? e
->offset
: 0,
3117 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3118 * Modify the flags here to allow more coalescing.
3120 if (next
&& (!next
->data
|| next
->zero
)) {
3126 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3127 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3128 " \"data\": %s, \"compressed\": %s",
3129 e
->start
, e
->length
, e
->depth
,
3130 e
->present
? "true" : "false",
3131 e
->zero
? "true" : "false",
3132 e
->data
? "true" : "false",
3133 e
->compressed
? "true" : "false");
3134 if (e
->has_offset
) {
3135 printf(", \"offset\": %"PRId64
"", e
->offset
);
3147 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3148 int64_t bytes
, MapEntry
*e
)
3152 BlockDriverState
*file
;
3155 char *filename
= NULL
;
3157 GLOBAL_STATE_CODE();
3158 GRAPH_RDLOCK_GUARD_MAINLOOP();
3160 /* As an optimization, we could cache the current range of unallocated
3161 * clusters in each file of the chain, and avoid querying the same
3167 bs
= bdrv_skip_filters(bs
);
3168 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3173 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3176 bs
= bdrv_cow_bs(bs
);
3185 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3187 if (file
&& has_offset
) {
3188 bdrv_refresh_filename(file
);
3189 filename
= file
->filename
;
3195 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3196 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3197 .compressed
= !!(ret
& BDRV_BLOCK_COMPRESSED
),
3199 .has_offset
= has_offset
,
3201 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3202 .filename
= filename
,
3208 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3210 if (curr
->length
== 0) {
3213 if (curr
->zero
!= next
->zero
||
3214 curr
->data
!= next
->data
||
3215 curr
->compressed
!= next
->compressed
||
3216 curr
->depth
!= next
->depth
||
3217 curr
->present
!= next
->present
||
3218 !curr
->filename
!= !next
->filename
||
3219 curr
->has_offset
!= next
->has_offset
) {
3222 if (curr
->filename
&& strcmp(curr
->filename
, next
->filename
)) {
3225 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3231 static int img_map(int argc
, char **argv
)
3234 OutputFormat output_format
= OFORMAT_HUMAN
;
3236 BlockDriverState
*bs
;
3237 const char *filename
, *fmt
, *output
;
3239 MapEntry curr
= { .length
= 0 }, next
;
3241 bool image_opts
= false;
3242 bool force_share
= false;
3243 int64_t start_offset
= 0;
3244 int64_t max_length
= -1;
3249 int option_index
= 0;
3250 static const struct option long_options
[] = {
3251 {"help", no_argument
, 0, 'h'},
3252 {"format", required_argument
, 0, 'f'},
3253 {"output", required_argument
, 0, OPTION_OUTPUT
},
3254 {"object", required_argument
, 0, OPTION_OBJECT
},
3255 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3256 {"force-share", no_argument
, 0, 'U'},
3257 {"start-offset", required_argument
, 0, 's'},
3258 {"max-length", required_argument
, 0, 'l'},
3261 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3262 long_options
, &option_index
);
3268 missing_argument(argv
[optind
- 1]);
3271 unrecognized_option(argv
[optind
- 1]);
3286 start_offset
= cvtnum("start offset", optarg
);
3287 if (start_offset
< 0) {
3292 max_length
= cvtnum("max length", optarg
);
3293 if (max_length
< 0) {
3298 user_creatable_process_cmdline(optarg
);
3300 case OPTION_IMAGE_OPTS
:
3305 if (optind
!= argc
- 1) {
3306 error_exit("Expecting one image file name");
3308 filename
= argv
[optind
];
3310 if (output
&& !strcmp(output
, "json")) {
3311 output_format
= OFORMAT_JSON
;
3312 } else if (output
&& !strcmp(output
, "human")) {
3313 output_format
= OFORMAT_HUMAN
;
3314 } else if (output
) {
3315 error_report("--output must be used with human or json as argument.");
3319 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3325 if (output_format
== OFORMAT_HUMAN
) {
3326 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3327 } else if (output_format
== OFORMAT_JSON
) {
3331 length
= blk_getlength(blk
);
3333 error_report("Failed to get size for '%s'", filename
);
3336 if (max_length
!= -1) {
3337 length
= MIN(start_offset
+ max_length
, length
);
3340 curr
.start
= start_offset
;
3341 while (curr
.start
+ curr
.length
< length
) {
3342 int64_t offset
= curr
.start
+ curr
.length
;
3343 int64_t n
= length
- offset
;
3345 ret
= get_block_status(bs
, offset
, n
, &next
);
3347 error_report("Could not read file metadata: %s", strerror(-ret
));
3351 if (entry_mergeable(&curr
, &next
)) {
3352 curr
.length
+= next
.length
;
3356 if (curr
.length
> 0) {
3357 ret
= dump_map_entry(output_format
, &curr
, &next
);
3365 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3366 if (output_format
== OFORMAT_JSON
) {
3375 #define SNAPSHOT_LIST 1
3376 #define SNAPSHOT_CREATE 2
3377 #define SNAPSHOT_APPLY 3
3378 #define SNAPSHOT_DELETE 4
3380 static int img_snapshot(int argc
, char **argv
)
3383 BlockDriverState
*bs
;
3384 QEMUSnapshotInfo sn
;
3385 char *filename
, *snapshot_name
= NULL
;
3386 int c
, ret
= 0, bdrv_oflags
;
3390 bool image_opts
= false;
3391 bool force_share
= false;
3394 bdrv_oflags
= BDRV_O_RDWR
;
3395 /* Parse commandline parameters */
3397 static const struct option long_options
[] = {
3398 {"help", no_argument
, 0, 'h'},
3399 {"object", required_argument
, 0, OPTION_OBJECT
},
3400 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3401 {"force-share", no_argument
, 0, 'U'},
3404 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3405 long_options
, NULL
);
3411 missing_argument(argv
[optind
- 1]);
3414 unrecognized_option(argv
[optind
- 1]);
3421 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3424 action
= SNAPSHOT_LIST
;
3425 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3429 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3432 action
= SNAPSHOT_APPLY
;
3433 snapshot_name
= optarg
;
3437 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3440 action
= SNAPSHOT_CREATE
;
3441 snapshot_name
= optarg
;
3445 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3448 action
= SNAPSHOT_DELETE
;
3449 snapshot_name
= optarg
;
3458 user_creatable_process_cmdline(optarg
);
3460 case OPTION_IMAGE_OPTS
:
3466 if (optind
!= argc
- 1) {
3467 error_exit("Expecting one image file name");
3469 filename
= argv
[optind
++];
3471 /* Open the image */
3472 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3479 /* Perform the requested action */
3485 case SNAPSHOT_CREATE
:
3486 memset(&sn
, 0, sizeof(sn
));
3487 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3489 rt
= g_get_real_time();
3490 sn
.date_sec
= rt
/ G_USEC_PER_SEC
;
3491 sn
.date_nsec
= (rt
% G_USEC_PER_SEC
) * 1000;
3493 bdrv_graph_rdlock_main_loop();
3494 ret
= bdrv_snapshot_create(bs
, &sn
);
3495 bdrv_graph_rdunlock_main_loop();
3498 error_report("Could not create snapshot '%s': %s",
3499 snapshot_name
, strerror(-ret
));
3503 case SNAPSHOT_APPLY
:
3504 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3506 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3511 case SNAPSHOT_DELETE
:
3512 bdrv_graph_rdlock_main_loop();
3513 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3515 error_report("Could not delete snapshot '%s': snapshot not "
3516 "found", snapshot_name
);
3519 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3521 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3526 bdrv_graph_rdunlock_main_loop();
3538 static int img_rebase(int argc
, char **argv
)
3540 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3541 uint8_t *buf_old
= NULL
;
3542 uint8_t *buf_new
= NULL
;
3543 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3544 BlockDriverState
*unfiltered_bs
, *unfiltered_bs_cow
;
3545 BlockDriverInfo bdi
= {0};
3547 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3548 int c
, flags
, src_flags
, ret
;
3549 BdrvRequestFlags write_flags
= 0;
3550 bool writethrough
, src_writethrough
;
3552 bool force_share
= false;
3555 bool compress
= false;
3556 Error
*local_err
= NULL
;
3557 bool image_opts
= false;
3558 int64_t write_align
;
3560 /* Parse commandline parameters */
3562 cache
= BDRV_DEFAULT_CACHE
;
3563 src_cache
= BDRV_DEFAULT_CACHE
;
3567 static const struct option long_options
[] = {
3568 {"help", no_argument
, 0, 'h'},
3569 {"object", required_argument
, 0, OPTION_OBJECT
},
3570 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3571 {"force-share", no_argument
, 0, 'U'},
3572 {"compress", no_argument
, 0, 'c'},
3575 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qUc",
3576 long_options
, NULL
);
3582 missing_argument(argv
[optind
- 1]);
3585 unrecognized_option(argv
[optind
- 1]);
3594 out_basefmt
= optarg
;
3597 out_baseimg
= optarg
;
3615 user_creatable_process_cmdline(optarg
);
3617 case OPTION_IMAGE_OPTS
:
3633 if (optind
!= argc
- 1) {
3634 error_exit("Expecting one image file name");
3636 if (!unsafe
&& !out_baseimg
) {
3637 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3639 filename
= argv
[optind
++];
3641 qemu_progress_init(progress
, 2.0);
3642 qemu_progress_print(0, 100);
3644 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3645 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3647 error_report("Invalid cache option: %s", cache
);
3652 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3654 error_report("Invalid source cache option: %s", src_cache
);
3658 /* The source files are opened read-only, don't care about WCE */
3659 assert((src_flags
& BDRV_O_RDWR
) == 0);
3660 (void) src_writethrough
;
3665 * Ignore the old backing file for unsafe rebase in case we want to correct
3666 * the reference to a renamed or moved backing file.
3668 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3676 bdrv_graph_rdlock_main_loop();
3677 unfiltered_bs
= bdrv_skip_filters(bs
);
3678 unfiltered_bs_cow
= bdrv_cow_bs(unfiltered_bs
);
3679 bdrv_graph_rdunlock_main_loop();
3681 if (compress
&& !block_driver_can_compress(unfiltered_bs
->drv
)) {
3682 error_report("Compression not supported for this file format");
3685 } else if (compress
) {
3686 write_flags
|= BDRV_REQ_WRITE_COMPRESSED
;
3689 if (out_basefmt
!= NULL
) {
3690 if (bdrv_find_format(out_basefmt
) == NULL
) {
3691 error_report("Invalid format name: '%s'", out_basefmt
);
3698 * We need overlay subcluster size (or cluster size in case writes are
3699 * compressed) to make sure write requests are aligned.
3701 ret
= bdrv_get_info(unfiltered_bs
, &bdi
);
3703 error_report("could not get block driver info");
3705 } else if (bdi
.subcluster_size
== 0) {
3706 bdi
.cluster_size
= bdi
.subcluster_size
= 1;
3709 write_align
= compress
? bdi
.cluster_size
: bdi
.subcluster_size
;
3711 /* For safe rebasing we need to compare old and new backing file */
3713 QDict
*options
= NULL
;
3714 BlockDriverState
*base_bs
;
3716 bdrv_graph_rdlock_main_loop();
3717 base_bs
= bdrv_cow_bs(unfiltered_bs
);
3718 bdrv_graph_rdunlock_main_loop();
3721 blk_old_backing
= blk_new(qemu_get_aio_context(),
3722 BLK_PERM_CONSISTENT_READ
,
3724 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3727 error_reportf_err(local_err
,
3728 "Could not reuse old backing file '%s': ",
3733 blk_old_backing
= NULL
;
3736 if (out_baseimg
[0]) {
3737 const char *overlay_filename
;
3738 char *out_real_path
;
3740 options
= qdict_new();
3742 qdict_put_str(options
, "driver", out_basefmt
);
3745 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3748 bdrv_graph_rdlock_main_loop();
3749 bdrv_refresh_filename(bs
);
3750 bdrv_graph_rdunlock_main_loop();
3751 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3754 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3758 qobject_unref(options
);
3759 error_reportf_err(local_err
,
3760 "Could not resolve backing filename: ");
3766 * Find out whether we rebase an image on top of a previous image
3769 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3770 if (prefix_chain_bs
) {
3771 qobject_unref(options
);
3772 g_free(out_real_path
);
3774 blk_new_backing
= blk_new(qemu_get_aio_context(),
3775 BLK_PERM_CONSISTENT_READ
,
3777 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3780 error_reportf_err(local_err
,
3781 "Could not reuse backing file '%s': ",
3786 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3787 options
, src_flags
, &local_err
);
3788 g_free(out_real_path
);
3789 if (!blk_new_backing
) {
3790 error_reportf_err(local_err
,
3791 "Could not open new backing file '%s': ",
3801 * Check each unallocated cluster in the COW file. If it is unallocated,
3802 * accesses go to the backing file. We must therefore compare this cluster
3803 * in the old and new backing file, and if they differ we need to copy it
3804 * from the old backing file into the COW file.
3806 * If qemu-img crashes during this step, no harm is done. The content of
3807 * the image is the same as the original one at any time.
3811 int64_t old_backing_size
= 0;
3812 int64_t new_backing_size
= 0;
3814 int64_t n
, n_old
= 0, n_new
= 0;
3815 float local_progress
= 0;
3817 if (blk_old_backing
&& bdrv_opt_mem_align(blk_bs(blk_old_backing
)) >
3818 bdrv_opt_mem_align(blk_bs(blk
))) {
3819 buf_old
= blk_blockalign(blk_old_backing
, IO_BUF_SIZE
);
3821 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3823 buf_new
= blk_blockalign(blk_new_backing
, IO_BUF_SIZE
);
3825 size
= blk_getlength(blk
);
3827 error_report("Could not get size of '%s': %s",
3828 filename
, strerror(-size
));
3832 if (blk_old_backing
) {
3833 old_backing_size
= blk_getlength(blk_old_backing
);
3834 if (old_backing_size
< 0) {
3835 char backing_name
[PATH_MAX
];
3837 bdrv_get_backing_filename(bs
, backing_name
,
3838 sizeof(backing_name
));
3839 error_report("Could not get size of '%s': %s",
3840 backing_name
, strerror(-old_backing_size
));
3845 if (blk_new_backing
) {
3846 new_backing_size
= blk_getlength(blk_new_backing
);
3847 if (new_backing_size
< 0) {
3848 error_report("Could not get size of '%s': %s",
3849 out_baseimg
, strerror(-new_backing_size
));
3856 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3859 for (offset
= 0; offset
< size
; offset
+= n
) {
3860 bool old_backing_eof
= false;
3863 /* How many bytes can we handle with the next read? */
3864 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3866 /* If the cluster is allocated, we don't need to take action */
3867 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3869 error_report("error while reading image metadata: %s",
3877 if (prefix_chain_bs
) {
3881 * If cluster wasn't changed since prefix_chain, we don't need
3884 ret
= bdrv_is_allocated_above(unfiltered_bs_cow
,
3885 prefix_chain_bs
, false,
3888 error_report("error while reading image metadata: %s",
3897 * If we've reached EOF of the old backing, it means that
3898 * offsets beyond the old backing size were read as zeroes.
3899 * Now we will need to explicitly zero the cluster in
3900 * order to preserve that state after the rebase.
3907 * At this point we know that the region [offset; offset + n)
3908 * is unallocated within the target image. This region might be
3909 * unaligned to the target image's (sub)cluster boundaries, as
3910 * old backing may have smaller clusters (or have subclusters).
3911 * We extend it to the aligned boundaries to avoid CoW on
3912 * partial writes in blk_pwrite(),
3914 n
+= offset
- QEMU_ALIGN_DOWN(offset
, write_align
);
3915 offset
= QEMU_ALIGN_DOWN(offset
, write_align
);
3916 n
+= QEMU_ALIGN_UP(offset
+ n
, write_align
) - (offset
+ n
);
3917 n
= MIN(n
, size
- offset
);
3918 assert(!bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n_alloc
) &&
3922 * Much like with the target image, we'll try to read as much
3923 * of the old and new backings as we can.
3925 n_old
= MIN(n
, MAX(0, old_backing_size
- (int64_t) offset
));
3926 n_new
= MIN(n
, MAX(0, new_backing_size
- (int64_t) offset
));
3929 * Read old and new backing file and take into consideration that
3930 * backing files may be smaller than the COW image.
3932 memset(buf_old
+ n_old
, 0, n
- n_old
);
3934 old_backing_eof
= true;
3936 ret
= blk_pread(blk_old_backing
, offset
, n_old
, buf_old
, 0);
3938 error_report("error while reading from old backing file");
3943 memset(buf_new
+ n_new
, 0, n
- n_new
);
3945 ret
= blk_pread(blk_new_backing
, offset
, n_new
, buf_new
, 0);
3947 error_report("error while reading from new backing file");
3952 /* If they differ, we need to write to the COW file */
3953 uint64_t written
= 0;
3955 while (written
< n
) {
3958 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3959 n
- written
, write_align
, &pnum
))
3961 if (old_backing_eof
) {
3962 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3964 assert(written
+ pnum
<= IO_BUF_SIZE
);
3965 ret
= blk_pwrite(blk
, offset
+ written
, pnum
,
3966 buf_old
+ written
, write_flags
);
3969 error_report("Error while writing to COW image: %s",
3976 if (offset
+ written
>= old_backing_size
) {
3977 old_backing_eof
= true;
3980 qemu_progress_print(local_progress
, 100);
3985 * Change the backing file. All clusters that are different from the old
3986 * backing file are overwritten in the COW file now, so the visible content
3987 * doesn't change when we switch the backing file.
3989 if (out_baseimg
&& *out_baseimg
) {
3990 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3993 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3996 if (ret
== -ENOSPC
) {
3997 error_report("Could not change the backing file to '%s': No "
3998 "space left in the file header", out_baseimg
);
3999 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
4000 error_report("Could not change the backing file to '%s': backing "
4001 "format must be specified", out_baseimg
);
4002 } else if (ret
< 0) {
4003 error_report("Could not change the backing file to '%s': %s",
4004 out_baseimg
, strerror(-ret
));
4007 qemu_progress_print(100, 0);
4009 * TODO At this point it is possible to check if any clusters that are
4010 * allocated in the COW file are the same in the backing file. If so, they
4011 * could be dropped from the COW file. Don't do this before switching the
4012 * backing file, in case of a crash this would lead to corruption.
4015 qemu_progress_end();
4018 blk_unref(blk_old_backing
);
4019 blk_unref(blk_new_backing
);
4021 qemu_vfree(buf_old
);
4022 qemu_vfree(buf_new
);
4031 static int img_resize(int argc
, char **argv
)
4034 int c
, ret
, relative
;
4035 const char *filename
, *fmt
, *size
;
4036 int64_t n
, total_size
, current_size
;
4038 BlockBackend
*blk
= NULL
;
4039 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
4042 static QemuOptsList resize_options
= {
4043 .name
= "resize_options",
4044 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
4047 .name
= BLOCK_OPT_SIZE
,
4048 .type
= QEMU_OPT_SIZE
,
4049 .help
= "Virtual disk size"
4055 bool image_opts
= false;
4056 bool shrink
= false;
4058 /* Remove size from argv manually so that negative numbers are not treated
4059 * as options by getopt. */
4061 error_exit("Not enough arguments");
4065 size
= argv
[--argc
];
4067 /* Parse getopt arguments */
4070 static const struct option long_options
[] = {
4071 {"help", no_argument
, 0, 'h'},
4072 {"object", required_argument
, 0, OPTION_OBJECT
},
4073 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4074 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
4075 {"shrink", no_argument
, 0, OPTION_SHRINK
},
4078 c
= getopt_long(argc
, argv
, ":f:hq",
4079 long_options
, NULL
);
4085 missing_argument(argv
[optind
- 1]);
4088 unrecognized_option(argv
[optind
- 1]);
4100 user_creatable_process_cmdline(optarg
);
4102 case OPTION_IMAGE_OPTS
:
4105 case OPTION_PREALLOCATION
:
4106 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
4107 PREALLOC_MODE__MAX
, NULL
);
4108 if (prealloc
== PREALLOC_MODE__MAX
) {
4109 error_report("Invalid preallocation mode '%s'", optarg
);
4118 if (optind
!= argc
- 1) {
4119 error_exit("Expecting image file name and size");
4121 filename
= argv
[optind
++];
4123 /* Choose grow, shrink, or absolute resize mode */
4139 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
4140 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
4141 error_report_err(err
);
4143 qemu_opts_del(param
);
4146 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
4147 qemu_opts_del(param
);
4149 blk
= img_open(image_opts
, filename
, fmt
,
4150 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4157 current_size
= blk_getlength(blk
);
4158 if (current_size
< 0) {
4159 error_report("Failed to inquire current image length: %s",
4160 strerror(-current_size
));
4166 total_size
= current_size
+ n
* relative
;
4170 if (total_size
<= 0) {
4171 error_report("New image size must be positive");
4176 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4177 error_report("Preallocation can only be used for growing images");
4182 if (total_size
< current_size
&& !shrink
) {
4183 error_report("Use the --shrink option to perform a shrink operation.");
4184 warn_report("Shrinking an image will delete all data beyond the "
4185 "shrunken image's end. Before performing such an "
4186 "operation, make sure there is no important data there.");
4192 * The user expects the image to have the desired size after
4193 * resizing, so pass @exact=true. It is of no use to report
4194 * success when the image has not actually been resized.
4196 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4198 qprintf(quiet
, "Image resized.\n");
4200 error_report_err(err
);
4210 static void amend_status_cb(BlockDriverState
*bs
,
4211 int64_t offset
, int64_t total_work_size
,
4214 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4217 static int print_amend_option_help(const char *format
)
4221 GRAPH_RDLOCK_GUARD_MAINLOOP();
4223 /* Find driver and parse its options */
4224 drv
= bdrv_find_format(format
);
4226 error_report("Unknown file format '%s'", format
);
4230 if (!drv
->bdrv_amend_options
) {
4231 error_report("Format driver '%s' does not support option amendment",
4236 /* Every driver supporting amendment must have amend_opts */
4237 assert(drv
->amend_opts
);
4239 printf("Amend options for '%s':\n", format
);
4240 qemu_opts_print_help(drv
->amend_opts
, false);
4244 static int img_amend(int argc
, char **argv
)
4248 char *options
= NULL
;
4249 QemuOptsList
*amend_opts
= NULL
;
4250 QemuOpts
*opts
= NULL
;
4251 const char *fmt
= NULL
, *filename
, *cache
;
4254 bool quiet
= false, progress
= false;
4255 BlockBackend
*blk
= NULL
;
4256 BlockDriverState
*bs
= NULL
;
4257 bool image_opts
= false;
4260 cache
= BDRV_DEFAULT_CACHE
;
4262 static const struct option long_options
[] = {
4263 {"help", no_argument
, 0, 'h'},
4264 {"object", required_argument
, 0, OPTION_OBJECT
},
4265 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4266 {"force", no_argument
, 0, OPTION_FORCE
},
4269 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4270 long_options
, NULL
);
4277 missing_argument(argv
[optind
- 1]);
4280 unrecognized_option(argv
[optind
- 1]);
4286 if (accumulate_options(&options
, optarg
) < 0) {
4288 goto out_no_progress
;
4304 user_creatable_process_cmdline(optarg
);
4306 case OPTION_IMAGE_OPTS
:
4316 error_exit("Must specify options (-o)");
4322 qemu_progress_init(progress
, 1.0);
4324 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4325 if (fmt
&& has_help_option(options
)) {
4326 /* If a format is explicitly specified (and possibly no filename is
4327 * given), print option help here */
4328 ret
= print_amend_option_help(fmt
);
4332 if (optind
!= argc
- 1) {
4333 error_report("Expecting one image file name");
4338 flags
= BDRV_O_RDWR
;
4339 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4341 error_report("Invalid cache option: %s", cache
);
4345 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4353 fmt
= bs
->drv
->format_name
;
4355 if (has_help_option(options
)) {
4356 /* If the format was auto-detected, print option help here */
4357 ret
= print_amend_option_help(fmt
);
4361 bdrv_graph_rdlock_main_loop();
4362 if (!bs
->drv
->bdrv_amend_options
) {
4363 error_report("Format driver '%s' does not support option amendment",
4365 bdrv_graph_rdunlock_main_loop();
4370 /* Every driver supporting amendment must have amend_opts */
4371 assert(bs
->drv
->amend_opts
);
4373 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4374 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4375 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4376 /* Try to parse options using the create options */
4377 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4378 qemu_opts_del(opts
);
4379 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4380 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4381 error_append_hint(&err
,
4382 "This option is only supported for image creation\n");
4385 bdrv_graph_rdunlock_main_loop();
4386 error_report_err(err
);
4391 /* In case the driver does not call amend_status_cb() */
4392 qemu_progress_print(0.f
, 0);
4393 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4394 qemu_progress_print(100.f
, 0);
4395 bdrv_graph_rdunlock_main_loop();
4398 error_report_err(err
);
4403 qemu_progress_end();
4407 qemu_opts_del(opts
);
4408 qemu_opts_free(amend_opts
);
4417 typedef struct BenchData
{
4419 uint64_t image_size
;
4426 bool drain_on_flush
;
4435 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4438 error_report("Failed flush request: %s", strerror(-ret
));
4443 static void bench_cb(void *opaque
, int ret
)
4445 BenchData
*b
= opaque
;
4449 error_report("Failed request: %s", strerror(-ret
));
4454 /* Just finished a flush with drained queue: Start next requests */
4455 assert(b
->in_flight
== 0);
4456 b
->in_flush
= false;
4457 } else if (b
->in_flight
> 0) {
4458 int remaining
= b
->n
- b
->in_flight
;
4463 /* Time for flush? Drain queue if requested, then flush */
4464 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4465 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4466 BlockCompletionFunc
*cb
;
4468 if (b
->drain_on_flush
) {
4472 cb
= bench_undrained_flush_cb
;
4475 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4477 error_report("Failed to issue flush request");
4481 if (b
->drain_on_flush
) {
4487 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4488 int64_t offset
= b
->offset
;
4489 /* blk_aio_* might look for completed I/Os and kick bench_cb
4490 * again, so make sure this operation is counted by in_flight
4491 * and b->offset is ready for the next submission.
4494 b
->offset
+= b
->step
;
4495 b
->offset
%= b
->image_size
;
4497 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4499 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4502 error_report("Failed to issue request");
4508 static int img_bench(int argc
, char **argv
)
4511 const char *fmt
= NULL
, *filename
;
4513 bool image_opts
= false;
4514 bool is_write
= false;
4518 size_t bufsize
= 4096;
4521 int flush_interval
= 0;
4522 bool drain_on_flush
= true;
4524 BlockBackend
*blk
= NULL
;
4525 BenchData data
= {};
4527 bool writethrough
= false;
4528 struct timeval t1
, t2
;
4530 bool force_share
= false;
4531 size_t buf_size
= 0;
4534 static const struct option long_options
[] = {
4535 {"help", no_argument
, 0, 'h'},
4536 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4537 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4538 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4539 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4540 {"force-share", no_argument
, 0, 'U'},
4543 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4551 missing_argument(argv
[optind
- 1]);
4554 unrecognized_option(argv
[optind
- 1]);
4563 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4564 error_report("Invalid request count specified");
4574 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4575 error_report("Invalid queue depth specified");
4585 flags
|= BDRV_O_NATIVE_AIO
;
4588 ret
= bdrv_parse_aio(optarg
, &flags
);
4590 error_report("Invalid aio option: %s", optarg
);
4597 offset
= cvtnum("offset", optarg
);
4611 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4623 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4632 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4634 error_report("Invalid cache mode");
4640 flags
|= BDRV_O_RDWR
;
4646 case OPTION_PATTERN
:
4650 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4651 error_report("Invalid pattern byte specified");
4657 case OPTION_FLUSH_INTERVAL
:
4661 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4662 error_report("Invalid flush interval specified");
4665 flush_interval
= res
;
4668 case OPTION_NO_DRAIN
:
4669 drain_on_flush
= false;
4671 case OPTION_IMAGE_OPTS
:
4677 if (optind
!= argc
- 1) {
4678 error_exit("Expecting one image file name");
4680 filename
= argv
[argc
- 1];
4682 if (!is_write
&& flush_interval
) {
4683 error_report("--flush-interval is only available in write tests");
4687 if (flush_interval
&& flush_interval
< depth
) {
4688 error_report("Flush interval can't be smaller than depth");
4693 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4700 image_size
= blk_getlength(blk
);
4701 if (image_size
< 0) {
4706 data
= (BenchData
) {
4708 .image_size
= image_size
,
4710 .step
= step
?: bufsize
,
4715 .flush_interval
= flush_interval
,
4716 .drain_on_flush
= drain_on_flush
,
4718 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4719 "(starting at offset %" PRId64
", step size %d)\n",
4720 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4721 data
.offset
, data
.step
);
4722 if (flush_interval
) {
4723 printf("Sending flush every %d requests\n", flush_interval
);
4726 buf_size
= data
.nrreq
* data
.bufsize
;
4727 data
.buf
= blk_blockalign(blk
, buf_size
);
4728 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4730 blk_register_buf(blk
, data
.buf
, buf_size
, &error_fatal
);
4732 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4733 for (i
= 0; i
< data
.nrreq
; i
++) {
4734 qemu_iovec_init(&data
.qiov
[i
], 1);
4735 qemu_iovec_add(&data
.qiov
[i
],
4736 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4739 gettimeofday(&t1
, NULL
);
4742 while (data
.n
> 0) {
4743 main_loop_wait(false);
4745 gettimeofday(&t2
, NULL
);
4747 printf("Run completed in %3.3f seconds.\n",
4748 (t2
.tv_sec
- t1
.tv_sec
)
4749 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4753 blk_unregister_buf(blk
, data
.buf
, buf_size
);
4755 qemu_vfree(data
.buf
);
4772 typedef struct ImgBitmapAction
{
4773 enum ImgBitmapAct act
;
4774 const char *src
; /* only used for merge */
4775 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4778 static int img_bitmap(int argc
, char **argv
)
4782 QemuOpts
*opts
= NULL
;
4783 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4784 const char *filename
, *bitmap
;
4785 BlockBackend
*blk
= NULL
, *src
= NULL
;
4786 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4787 bool image_opts
= false;
4788 int64_t granularity
= 0;
4789 bool add
= false, merge
= false;
4790 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4791 ImgBitmapAction
*act
, *act_next
;
4795 QSIMPLEQ_INIT(&actions
);
4798 static const struct option long_options
[] = {
4799 {"help", no_argument
, 0, 'h'},
4800 {"object", required_argument
, 0, OPTION_OBJECT
},
4801 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4802 {"add", no_argument
, 0, OPTION_ADD
},
4803 {"remove", no_argument
, 0, OPTION_REMOVE
},
4804 {"clear", no_argument
, 0, OPTION_CLEAR
},
4805 {"enable", no_argument
, 0, OPTION_ENABLE
},
4806 {"disable", no_argument
, 0, OPTION_DISABLE
},
4807 {"merge", required_argument
, 0, OPTION_MERGE
},
4808 {"granularity", required_argument
, 0, 'g'},
4809 {"source-file", required_argument
, 0, 'b'},
4810 {"source-format", required_argument
, 0, 'F'},
4813 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4820 missing_argument(argv
[optind
- 1]);
4823 unrecognized_option(argv
[optind
- 1]);
4829 src_filename
= optarg
;
4838 granularity
= cvtnum("granularity", optarg
);
4839 if (granularity
< 0) {
4844 act
= g_new0(ImgBitmapAction
, 1);
4845 act
->act
= BITMAP_ADD
;
4846 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4850 act
= g_new0(ImgBitmapAction
, 1);
4851 act
->act
= BITMAP_REMOVE
;
4852 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4855 act
= g_new0(ImgBitmapAction
, 1);
4856 act
->act
= BITMAP_CLEAR
;
4857 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4860 act
= g_new0(ImgBitmapAction
, 1);
4861 act
->act
= BITMAP_ENABLE
;
4862 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4864 case OPTION_DISABLE
:
4865 act
= g_new0(ImgBitmapAction
, 1);
4866 act
->act
= BITMAP_DISABLE
;
4867 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4870 act
= g_new0(ImgBitmapAction
, 1);
4871 act
->act
= BITMAP_MERGE
;
4873 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4877 user_creatable_process_cmdline(optarg
);
4879 case OPTION_IMAGE_OPTS
:
4885 if (QSIMPLEQ_EMPTY(&actions
)) {
4886 error_report("Need at least one of --add, --remove, --clear, "
4887 "--enable, --disable, or --merge");
4891 if (granularity
&& !add
) {
4892 error_report("granularity only supported with --add");
4895 if (src_fmt
&& !src_filename
) {
4896 error_report("-F only supported with -b");
4899 if (src_filename
&& !merge
) {
4900 error_report("Merge bitmap source file only supported with "
4905 if (optind
!= argc
- 2) {
4906 error_report("Expecting filename and bitmap name");
4910 filename
= argv
[optind
];
4911 bitmap
= argv
[optind
+ 1];
4914 * No need to open backing chains; we will be manipulating bitmaps
4915 * directly in this image without reference to image contents.
4917 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4918 false, false, false);
4924 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4925 false, false, false);
4929 src_bs
= blk_bs(src
);
4934 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4937 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4938 !!granularity
, granularity
, true, true,
4939 false, false, &err
);
4943 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4947 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4951 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4954 case BITMAP_DISABLE
:
4955 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4959 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4964 g_assert_not_reached();
4968 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4979 * Manually inactivate the images first because this way we can know whether
4980 * an error occurred. blk_unref() doesn't tell us about failures.
4982 inactivate_ret
= bdrv_inactivate_all();
4983 if (inactivate_ret
< 0) {
4984 error_report("Error while closing the image: %s", strerror(-inactivate_ret
));
4990 qemu_opts_del(opts
);
5006 int bsz
; /* Block size */
5014 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
5018 static int img_dd_bs(const char *arg
,
5019 struct DdIo
*in
, struct DdIo
*out
,
5024 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
5029 in
->bsz
= out
->bsz
= res
;
5034 static int img_dd_count(const char *arg
,
5035 struct DdIo
*in
, struct DdIo
*out
,
5038 dd
->count
= cvtnum("count", arg
);
5040 if (dd
->count
< 0) {
5047 static int img_dd_if(const char *arg
,
5048 struct DdIo
*in
, struct DdIo
*out
,
5051 in
->filename
= g_strdup(arg
);
5056 static int img_dd_of(const char *arg
,
5057 struct DdIo
*in
, struct DdIo
*out
,
5060 out
->filename
= g_strdup(arg
);
5065 static int img_dd_skip(const char *arg
,
5066 struct DdIo
*in
, struct DdIo
*out
,
5069 in
->offset
= cvtnum("skip", arg
);
5071 if (in
->offset
< 0) {
5078 static int img_dd(int argc
, char **argv
)
5083 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
5084 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
5085 QemuOpts
*opts
= NULL
;
5086 QemuOptsList
*create_opts
= NULL
;
5087 Error
*local_err
= NULL
;
5088 bool image_opts
= false;
5090 const char *out_fmt
= "raw";
5091 const char *fmt
= NULL
;
5093 int64_t out_pos
, in_pos
;
5094 bool force_share
= false;
5095 struct DdInfo dd
= {
5100 .bsz
= 512, /* Block size is by default 512 bytes */
5112 const struct DdOpts options
[] = {
5113 { "bs", img_dd_bs
, C_BS
},
5114 { "count", img_dd_count
, C_COUNT
},
5115 { "if", img_dd_if
, C_IF
},
5116 { "of", img_dd_of
, C_OF
},
5117 { "skip", img_dd_skip
, C_SKIP
},
5120 const struct option long_options
[] = {
5121 { "help", no_argument
, 0, 'h'},
5122 { "object", required_argument
, 0, OPTION_OBJECT
},
5123 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5124 { "force-share", no_argument
, 0, 'U'},
5128 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
5140 missing_argument(argv
[optind
- 1]);
5143 unrecognized_option(argv
[optind
- 1]);
5152 user_creatable_process_cmdline(optarg
);
5154 case OPTION_IMAGE_OPTS
:
5160 for (i
= optind
; i
< argc
; i
++) {
5162 arg
= g_strdup(argv
[i
]);
5164 tmp
= strchr(arg
, '=');
5166 error_report("unrecognized operand %s", arg
);
5173 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5174 if (!strcmp(arg
, options
[j
].name
)) {
5178 if (options
[j
].name
== NULL
) {
5179 error_report("unrecognized operand %s", arg
);
5184 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5188 dd
.flags
|= options
[j
].flag
;
5193 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5194 error_report("Must specify both input and output files");
5199 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5207 drv
= bdrv_find_format(out_fmt
);
5209 error_report("Unknown file format");
5213 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5216 error_report_err(local_err
);
5220 if (!drv
->create_opts
) {
5221 error_report("Format driver '%s' does not support image creation",
5226 if (!proto_drv
->create_opts
) {
5227 error_report("Protocol driver '%s' does not support image creation",
5228 proto_drv
->format_name
);
5232 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5233 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5235 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5237 size
= blk_getlength(blk1
);
5239 error_report("Failed to get size for '%s'", in
.filename
);
5244 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5245 dd
.count
* in
.bsz
< size
) {
5246 size
= dd
.count
* in
.bsz
;
5249 /* Overflow means the specified offset is beyond input image's size */
5250 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5251 size
< in
.bsz
* in
.offset
)) {
5252 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5254 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5255 size
- in
.bsz
* in
.offset
, &error_abort
);
5258 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5260 error_reportf_err(local_err
,
5261 "%s: error while creating output image: ",
5267 /* TODO, we can't honour --image-opts for the target,
5268 * since it needs to be given in a format compatible
5269 * with the bdrv_create() call above which does not
5270 * support image-opts style.
5272 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5273 false, false, false);
5280 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5281 size
< in
.offset
* in
.bsz
)) {
5282 /* We give a warning if the skip option is bigger than the input
5283 * size and create an empty output disk image (i.e. like dd(1)).
5285 error_report("%s: cannot skip to specified offset", in
.filename
);
5288 in_pos
= in
.offset
* in
.bsz
;
5291 in
.buf
= g_new(uint8_t, in
.bsz
);
5293 for (out_pos
= 0; in_pos
< size
; ) {
5294 int bytes
= (in_pos
+ in
.bsz
> size
) ? size
- in_pos
: in
.bsz
;
5296 ret
= blk_pread(blk1
, in_pos
, bytes
, in
.buf
, 0);
5298 error_report("error while reading from input image file: %s",
5304 ret
= blk_pwrite(blk2
, out_pos
, bytes
, in
.buf
, 0);
5306 error_report("error while writing to output image file: %s",
5315 qemu_opts_del(opts
);
5316 qemu_opts_free(create_opts
);
5319 g_free(in
.filename
);
5320 g_free(out
.filename
);
5330 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5334 Visitor
*v
= qobject_output_visitor_new(&obj
);
5336 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5337 visit_complete(v
, &obj
);
5338 str
= qobject_to_json_pretty(obj
, true);
5339 assert(str
!= NULL
);
5340 printf("%s\n", str
->str
);
5343 g_string_free(str
, true);
5346 static int img_measure(int argc
, char **argv
)
5348 static const struct option long_options
[] = {
5349 {"help", no_argument
, 0, 'h'},
5350 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5351 {"object", required_argument
, 0, OPTION_OBJECT
},
5352 {"output", required_argument
, 0, OPTION_OUTPUT
},
5353 {"size", required_argument
, 0, OPTION_SIZE
},
5354 {"force-share", no_argument
, 0, 'U'},
5357 OutputFormat output_format
= OFORMAT_HUMAN
;
5358 BlockBackend
*in_blk
= NULL
;
5360 const char *filename
= NULL
;
5361 const char *fmt
= NULL
;
5362 const char *out_fmt
= "raw";
5363 char *options
= NULL
;
5364 char *snapshot_name
= NULL
;
5365 bool force_share
= false;
5366 QemuOpts
*opts
= NULL
;
5367 QemuOpts
*object_opts
= NULL
;
5368 QemuOpts
*sn_opts
= NULL
;
5369 QemuOptsList
*create_opts
= NULL
;
5370 bool image_opts
= false;
5371 uint64_t img_size
= UINT64_MAX
;
5372 BlockMeasureInfo
*info
= NULL
;
5373 Error
*local_err
= NULL
;
5377 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5378 long_options
, NULL
)) != -1) {
5391 if (accumulate_options(&options
, optarg
) < 0) {
5396 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5397 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5400 error_report("Failed in parsing snapshot param '%s'",
5405 snapshot_name
= optarg
;
5412 user_creatable_process_cmdline(optarg
);
5414 case OPTION_IMAGE_OPTS
:
5418 if (!strcmp(optarg
, "json")) {
5419 output_format
= OFORMAT_JSON
;
5420 } else if (!strcmp(optarg
, "human")) {
5421 output_format
= OFORMAT_HUMAN
;
5423 error_report("--output must be used with human or json "
5432 sval
= cvtnum("image size", optarg
);
5436 img_size
= (uint64_t)sval
;
5442 if (argc
- optind
> 1) {
5443 error_report("At most one filename argument is allowed.");
5445 } else if (argc
- optind
== 1) {
5446 filename
= argv
[optind
];
5449 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5450 error_report("--image-opts, -f, and -l require a filename argument.");
5453 if (filename
&& img_size
!= UINT64_MAX
) {
5454 error_report("--size N cannot be used together with a filename.");
5457 if (!filename
&& img_size
== UINT64_MAX
) {
5458 error_report("Either --size N or one filename must be specified.");
5463 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5464 false, false, force_share
);
5470 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5471 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5472 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5474 } else if (snapshot_name
!= NULL
) {
5475 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5476 snapshot_name
, &local_err
);
5479 error_reportf_err(local_err
, "Failed to load snapshot: ");
5484 drv
= bdrv_find_format(out_fmt
);
5486 error_report("Unknown file format '%s'", out_fmt
);
5489 if (!drv
->create_opts
) {
5490 error_report("Format driver '%s' does not support image creation",
5495 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5496 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5497 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5499 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5500 error_report_err(local_err
);
5501 error_report("Invalid options for file format '%s'", out_fmt
);
5505 if (img_size
!= UINT64_MAX
) {
5506 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5509 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5511 error_report_err(local_err
);
5515 if (output_format
== OFORMAT_HUMAN
) {
5516 printf("required size: %" PRIu64
"\n", info
->required
);
5517 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5518 if (info
->has_bitmaps
) {
5519 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5522 dump_json_block_measure_info(info
);
5528 qapi_free_BlockMeasureInfo(info
);
5529 qemu_opts_del(object_opts
);
5530 qemu_opts_del(opts
);
5531 qemu_opts_del(sn_opts
);
5532 qemu_opts_free(create_opts
);
5538 static const img_cmd_t img_cmds
[] = {
5539 #define DEF(option, callback, arg_string) \
5540 { option, callback },
5541 #include "qemu-img-cmds.h"
5546 int main(int argc
, char **argv
)
5548 const img_cmd_t
*cmd
;
5549 const char *cmdname
;
5551 static const struct option long_options
[] = {
5552 {"help", no_argument
, 0, 'h'},
5553 {"version", no_argument
, 0, 'V'},
5554 {"trace", required_argument
, NULL
, 'T'},
5559 signal(SIGPIPE
, SIG_IGN
);
5563 error_init(argv
[0]);
5564 module_call_init(MODULE_INIT_TRACE
);
5565 qemu_init_exec_dir(argv
[0]);
5567 qemu_init_main_loop(&error_fatal
);
5569 qcrypto_init(&error_fatal
);
5571 module_call_init(MODULE_INIT_QOM
);
5574 error_exit("Not enough arguments");
5577 qemu_add_opts(&qemu_source_opts
);
5578 qemu_add_opts(&qemu_trace_opts
);
5580 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5583 missing_argument(argv
[optind
- 1]);
5586 unrecognized_option(argv
[optind
- 1]);
5592 printf(QEMU_IMG_VERSION
);
5595 trace_opt_parse(optarg
);
5600 cmdname
= argv
[optind
];
5602 /* reset getopt_long scanning */
5608 qemu_reset_optind();
5610 if (!trace_init_backends()) {
5614 qemu_set_log(LOG_TRACE
, &error_fatal
);
5616 /* find the command */
5617 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5618 if (!strcmp(cmdname
, cmd
->name
)) {
5619 return cmd
->handler(argc
, argv
);
5624 error_exit("Command not found: %s", cmdname
);