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 @optarg safe for accumulate_options()?
239 * It is when multiple of them can be joined together separated by ','.
240 * To make that work, @optarg 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 *optarg
)
249 size_t len
= strlen(optarg
);
252 if (!optarg
[0] || optarg
[0] == ',') {
256 for (i
= len
; i
> 0 && optarg
[i
- 1] == ','; i
--) {
265 static int accumulate_options(char **options
, char *optarg
)
269 if (!is_valid_option_list(optarg
)) {
270 error_report("Invalid option list: %s", optarg
);
275 *options
= g_strdup(optarg
);
277 new_options
= g_strdup_printf("%s,%s", *options
, optarg
);
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);
1054 base_bs
= bdrv_find_backing_image(bs
, base
);
1056 error_setg(&local_err
,
1057 "Did not find '%s' in the backing chain of '%s'",
1062 /* This is different from QMP, which by default uses the deepest file in
1063 * the backing chain (i.e., the very base); however, the traditional
1064 * behavior of qemu-img commit is using the immediate backing file. */
1065 base_bs
= bdrv_backing_chain_next(bs
);
1067 error_setg(&local_err
, "Image does not have a backing file");
1072 cbi
= (CommonBlockJobCBInfo
){
1077 aio_context
= bdrv_get_aio_context(bs
);
1078 aio_context_acquire(aio_context
);
1079 commit_active_start("commit", bs
, base_bs
, JOB_DEFAULT
, rate_limit
,
1080 BLOCKDEV_ON_ERROR_REPORT
, NULL
, common_block_job_cb
,
1081 &cbi
, false, &local_err
);
1082 aio_context_release(aio_context
);
1087 /* When the block job completes, the BlockBackend reference will point to
1088 * the old backing file. In order to avoid that the top image is already
1089 * deleted, so we can still empty it afterwards, increment the reference
1090 * counter here preemptively. */
1095 job
= block_job_get("commit");
1097 run_block_job(job
, &local_err
);
1103 BlockBackend
*old_backing_blk
;
1105 old_backing_blk
= blk_new_with_bs(bs
, BLK_PERM_WRITE
, BLK_PERM_ALL
,
1107 if (!old_backing_blk
) {
1110 ret
= blk_make_empty(old_backing_blk
, &local_err
);
1111 blk_unref(old_backing_blk
);
1112 if (ret
== -ENOTSUP
) {
1113 error_free(local_err
);
1115 } else if (ret
< 0) {
1126 qemu_progress_end();
1129 * Manually inactivate the image first because this way we can know whether
1130 * an error occurred. blk_unref() doesn't tell us about failures.
1132 ret
= bdrv_inactivate_all();
1133 if (ret
< 0 && !local_err
) {
1134 error_setg_errno(&local_err
, -ret
, "Error while closing the image");
1139 error_report_err(local_err
);
1143 qprintf(quiet
, "Image committed.\n");
1148 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1149 * of the first sector boundary within buf where the sector contains a
1150 * non-zero byte. This function is robust to a buffer that is not
1153 static int64_t find_nonzero(const uint8_t *buf
, int64_t n
)
1156 int64_t end
= QEMU_ALIGN_DOWN(n
, BDRV_SECTOR_SIZE
);
1158 for (i
= 0; i
< end
; i
+= BDRV_SECTOR_SIZE
) {
1159 if (!buffer_is_zero(buf
+ i
, BDRV_SECTOR_SIZE
)) {
1163 if (i
< n
&& !buffer_is_zero(buf
+ i
, n
- end
)) {
1170 * Returns true iff the first sector pointed to by 'buf' contains at least
1173 * 'pnum' is set to the number of sectors (including and immediately following
1174 * the first one) that are known to be in the same allocated/unallocated state.
1175 * The function will try to align the end offset to alignment boundaries so
1176 * that the request will at least end aligned and consecutive requests will
1177 * also start at an aligned offset.
1179 static int is_allocated_sectors(const uint8_t *buf
, int n
, int *pnum
,
1180 int64_t sector_num
, int alignment
)
1189 is_zero
= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
);
1190 for(i
= 1; i
< n
; i
++) {
1191 buf
+= BDRV_SECTOR_SIZE
;
1192 if (is_zero
!= buffer_is_zero(buf
, BDRV_SECTOR_SIZE
)) {
1199 * The whole buf is the same.
1200 * No reason to split it into chunks, so return now.
1206 tail
= (sector_num
+ i
) & (alignment
- 1);
1208 if (is_zero
&& i
<= tail
) {
1210 * For sure next sector after i is data, and it will rewrite this
1211 * tail anyway due to RMW. So, let's just write data now.
1216 /* If possible, align up end offset of allocated areas. */
1217 i
+= alignment
- tail
;
1221 * For sure next sector after i is data, and it will rewrite this
1222 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1233 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1234 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1235 * breaking up write requests for only small sparse areas.
1237 static int is_allocated_sectors_min(const uint8_t *buf
, int n
, int *pnum
,
1238 int min
, int64_t sector_num
, int alignment
)
1241 int num_checked
, num_used
;
1247 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1253 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1255 sector_num
+= *pnum
;
1256 num_checked
= num_used
;
1259 ret
= is_allocated_sectors(buf
, n
, pnum
, sector_num
, alignment
);
1261 buf
+= BDRV_SECTOR_SIZE
* *pnum
;
1263 sector_num
+= *pnum
;
1264 num_checked
+= *pnum
;
1266 num_used
= num_checked
;
1267 } else if (*pnum
>= min
) {
1277 * Compares two buffers sector by sector. Returns 0 if the first
1278 * sector of each buffer matches, non-zero otherwise.
1280 * pnum is set to the sector-aligned size of the buffer prefix that
1281 * has the same matching status as the first sector.
1283 static int compare_buffers(const uint8_t *buf1
, const uint8_t *buf2
,
1284 int64_t bytes
, int64_t *pnum
)
1287 int64_t i
= MIN(bytes
, BDRV_SECTOR_SIZE
);
1291 res
= !!memcmp(buf1
, buf2
, i
);
1293 int64_t len
= MIN(bytes
- i
, BDRV_SECTOR_SIZE
);
1295 if (!!memcmp(buf1
+ i
, buf2
+ i
, len
) != res
) {
1305 #define IO_BUF_SIZE (2 * MiB)
1308 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1310 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1311 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1312 * failure), and 4 on error (the exit status for read errors), after emitting
1315 * @param blk: BlockBackend for the image
1316 * @param offset: Starting offset to check
1317 * @param bytes: Number of bytes to check
1318 * @param filename: Name of disk file we are checking (logging purpose)
1319 * @param buffer: Allocated buffer for storing read data
1320 * @param quiet: Flag for quiet mode
1322 static int check_empty_sectors(BlockBackend
*blk
, int64_t offset
,
1323 int64_t bytes
, const char *filename
,
1324 uint8_t *buffer
, bool quiet
)
1329 ret
= blk_pread(blk
, offset
, bytes
, buffer
, 0);
1331 error_report("Error while reading offset %" PRId64
" of %s: %s",
1332 offset
, filename
, strerror(-ret
));
1335 idx
= find_nonzero(buffer
, bytes
);
1337 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1346 * Compares two images. Exit codes:
1348 * 0 - Images are identical or the requested help was printed
1350 * >1 - Error occurred
1352 static int img_compare(int argc
, char **argv
)
1354 const char *fmt1
= NULL
, *fmt2
= NULL
, *cache
, *filename1
, *filename2
;
1355 BlockBackend
*blk1
, *blk2
;
1356 BlockDriverState
*bs1
, *bs2
;
1357 int64_t total_size1
, total_size2
;
1358 uint8_t *buf1
= NULL
, *buf2
= NULL
;
1359 int64_t pnum1
, pnum2
;
1360 int allocated1
, allocated2
;
1361 int ret
= 0; /* return value - 0 Ident, 1 Different, >1 Error */
1362 bool progress
= false, quiet
= false, strict
= false;
1369 uint64_t progress_base
;
1370 bool image_opts
= false;
1371 bool force_share
= false;
1373 cache
= BDRV_DEFAULT_CACHE
;
1375 static const struct option long_options
[] = {
1376 {"help", no_argument
, 0, 'h'},
1377 {"object", required_argument
, 0, OPTION_OBJECT
},
1378 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
1379 {"force-share", no_argument
, 0, 'U'},
1382 c
= getopt_long(argc
, argv
, ":hf:F:T:pqsU",
1383 long_options
, NULL
);
1389 missing_argument(argv
[optind
- 1]);
1392 unrecognized_option(argv
[optind
- 1]);
1420 Error
*local_err
= NULL
;
1422 if (!user_creatable_add_from_str(optarg
, &local_err
)) {
1424 error_report_err(local_err
);
1427 /* Help was printed */
1433 case OPTION_IMAGE_OPTS
:
1439 /* Progress is not shown in Quiet mode */
1445 if (optind
!= argc
- 2) {
1446 error_exit("Expecting two image file names");
1448 filename1
= argv
[optind
++];
1449 filename2
= argv
[optind
++];
1451 /* Initialize before goto out */
1452 qemu_progress_init(progress
, 2.0);
1455 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
1457 error_report("Invalid source cache option: %s", cache
);
1462 blk1
= img_open(image_opts
, filename1
, fmt1
, flags
, writethrough
, quiet
,
1469 blk2
= img_open(image_opts
, filename2
, fmt2
, flags
, writethrough
, quiet
,
1478 buf1
= blk_blockalign(blk1
, IO_BUF_SIZE
);
1479 buf2
= blk_blockalign(blk2
, IO_BUF_SIZE
);
1480 total_size1
= blk_getlength(blk1
);
1481 if (total_size1
< 0) {
1482 error_report("Can't get size of %s: %s",
1483 filename1
, strerror(-total_size1
));
1487 total_size2
= blk_getlength(blk2
);
1488 if (total_size2
< 0) {
1489 error_report("Can't get size of %s: %s",
1490 filename2
, strerror(-total_size2
));
1494 total_size
= MIN(total_size1
, total_size2
);
1495 progress_base
= MAX(total_size1
, total_size2
);
1497 qemu_progress_print(0, 100);
1499 if (strict
&& total_size1
!= total_size2
) {
1501 qprintf(quiet
, "Strict mode: Image size mismatch!\n");
1505 while (offset
< total_size
) {
1506 int status1
, status2
;
1508 status1
= bdrv_block_status_above(bs1
, NULL
, offset
,
1509 total_size1
- offset
, &pnum1
, NULL
,
1513 error_report("Sector allocation test failed for %s", filename1
);
1516 allocated1
= status1
& BDRV_BLOCK_ALLOCATED
;
1518 status2
= bdrv_block_status_above(bs2
, NULL
, offset
,
1519 total_size2
- offset
, &pnum2
, NULL
,
1523 error_report("Sector allocation test failed for %s", filename2
);
1526 allocated2
= status2
& BDRV_BLOCK_ALLOCATED
;
1528 assert(pnum1
&& pnum2
);
1529 chunk
= MIN(pnum1
, pnum2
);
1532 if (status1
!= status2
) {
1534 qprintf(quiet
, "Strict mode: Offset %" PRId64
1535 " block status mismatch!\n", offset
);
1539 if ((status1
& BDRV_BLOCK_ZERO
) && (status2
& BDRV_BLOCK_ZERO
)) {
1541 } else if (allocated1
== allocated2
) {
1545 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1546 ret
= blk_pread(blk1
, offset
, chunk
, buf1
, 0);
1548 error_report("Error while reading offset %" PRId64
1550 offset
, filename1
, strerror(-ret
));
1554 ret
= blk_pread(blk2
, offset
, chunk
, buf2
, 0);
1556 error_report("Error while reading offset %" PRId64
1558 offset
, filename2
, strerror(-ret
));
1562 ret
= compare_buffers(buf1
, buf2
, chunk
, &pnum
);
1563 if (ret
|| pnum
!= chunk
) {
1564 qprintf(quiet
, "Content mismatch at offset %" PRId64
"!\n",
1565 offset
+ (ret
? 0 : pnum
));
1571 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1573 ret
= check_empty_sectors(blk1
, offset
, chunk
,
1574 filename1
, buf1
, quiet
);
1576 ret
= check_empty_sectors(blk2
, offset
, chunk
,
1577 filename2
, buf1
, quiet
);
1584 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1587 if (total_size1
!= total_size2
) {
1588 BlockBackend
*blk_over
;
1589 const char *filename_over
;
1591 qprintf(quiet
, "Warning: Image size mismatch!\n");
1592 if (total_size1
> total_size2
) {
1594 filename_over
= filename1
;
1597 filename_over
= filename2
;
1600 while (offset
< progress_base
) {
1601 ret
= bdrv_block_status_above(blk_bs(blk_over
), NULL
, offset
,
1602 progress_base
- offset
, &chunk
,
1606 error_report("Sector allocation test failed for %s",
1611 if (ret
& BDRV_BLOCK_ALLOCATED
&& !(ret
& BDRV_BLOCK_ZERO
)) {
1612 chunk
= MIN(chunk
, IO_BUF_SIZE
);
1613 ret
= check_empty_sectors(blk_over
, offset
, chunk
,
1614 filename_over
, buf1
, quiet
);
1620 qemu_progress_print(((float) chunk
/ progress_base
) * 100, 100);
1624 qprintf(quiet
, "Images are identical.\n");
1634 qemu_progress_end();
1638 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1639 static void do_dirty_bitmap_merge(const char *dst_node
, const char *dst_name
,
1640 const char *src_node
, const char *src_name
,
1643 BlockDirtyBitmapOrStr
*merge_src
;
1644 BlockDirtyBitmapOrStrList
*list
= NULL
;
1646 merge_src
= g_new0(BlockDirtyBitmapOrStr
, 1);
1647 merge_src
->type
= QTYPE_QDICT
;
1648 merge_src
->u
.external
.node
= g_strdup(src_node
);
1649 merge_src
->u
.external
.name
= g_strdup(src_name
);
1650 QAPI_LIST_PREPEND(list
, merge_src
);
1651 qmp_block_dirty_bitmap_merge(dst_node
, dst_name
, list
, errp
);
1652 qapi_free_BlockDirtyBitmapOrStrList(list
);
1655 enum ImgConvertBlockStatus
{
1661 #define MAX_COROUTINES 16
1662 #define CONVERT_THROTTLE_GROUP "img_convert"
1664 typedef struct ImgConvertState
{
1666 int64_t *src_sectors
;
1669 int64_t total_sectors
;
1670 int64_t allocated_sectors
;
1671 int64_t allocated_done
;
1674 enum ImgConvertBlockStatus status
;
1675 int64_t sector_next_status
;
1676 BlockBackend
*target
;
1680 bool target_has_backing
;
1681 int64_t target_backing_sectors
; /* negative if unknown */
1688 size_t cluster_sectors
;
1690 long num_coroutines
;
1691 int running_coroutines
;
1692 Coroutine
*co
[MAX_COROUTINES
];
1693 int64_t wait_sector_num
[MAX_COROUTINES
];
1698 static void convert_select_part(ImgConvertState
*s
, int64_t sector_num
,
1699 int *src_cur
, int64_t *src_cur_offset
)
1702 *src_cur_offset
= 0;
1703 while (sector_num
- *src_cur_offset
>= s
->src_sectors
[*src_cur
]) {
1704 *src_cur_offset
+= s
->src_sectors
[*src_cur
];
1706 assert(*src_cur
< s
->src_num
);
1710 static int convert_iteration_sectors(ImgConvertState
*s
, int64_t sector_num
)
1712 int64_t src_cur_offset
;
1713 int ret
, n
, src_cur
;
1714 bool post_backing_zero
= false;
1716 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1718 assert(s
->total_sectors
> sector_num
);
1719 n
= MIN(s
->total_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
1721 if (s
->target_backing_sectors
>= 0) {
1722 if (sector_num
>= s
->target_backing_sectors
) {
1723 post_backing_zero
= true;
1724 } else if (sector_num
+ n
> s
->target_backing_sectors
) {
1725 /* Split requests around target_backing_sectors (because
1726 * starting from there, zeros are handled differently) */
1727 n
= s
->target_backing_sectors
- sector_num
;
1731 if (s
->sector_next_status
<= sector_num
) {
1732 uint64_t offset
= (sector_num
- src_cur_offset
) * BDRV_SECTOR_SIZE
;
1735 BlockDriverState
*src_bs
= blk_bs(s
->src
[src_cur
]);
1736 BlockDriverState
*base
;
1738 if (s
->target_has_backing
) {
1739 base
= bdrv_cow_bs(bdrv_skip_filters(src_bs
));
1745 count
= n
* BDRV_SECTOR_SIZE
;
1747 ret
= bdrv_block_status_above(src_bs
, base
, offset
, count
, &count
,
1754 warn_report("error while reading block status at "
1755 "offset %" PRIu64
": %s", offset
,
1758 /* Just try to read the data, then */
1759 ret
= BDRV_BLOCK_DATA
;
1760 count
= BDRV_SECTOR_SIZE
;
1762 /* Retry on a shorter range */
1763 n
= DIV_ROUND_UP(n
, 4);
1766 error_report("error while reading block status at offset "
1767 "%" PRIu64
": %s", offset
, strerror(-ret
));
1773 n
= DIV_ROUND_UP(count
, BDRV_SECTOR_SIZE
);
1776 * Avoid that s->sector_next_status becomes unaligned to the source
1777 * request alignment and/or cluster size to avoid unnecessary read
1780 tail
= (sector_num
- src_cur_offset
+ n
) % s
->src_alignment
[src_cur
];
1785 if (ret
& BDRV_BLOCK_ZERO
) {
1786 s
->status
= post_backing_zero
? BLK_BACKING_FILE
: BLK_ZERO
;
1787 } else if (ret
& BDRV_BLOCK_DATA
) {
1788 s
->status
= BLK_DATA
;
1790 s
->status
= s
->target_has_backing
? BLK_BACKING_FILE
: BLK_DATA
;
1793 s
->sector_next_status
= sector_num
+ n
;
1796 n
= MIN(n
, s
->sector_next_status
- sector_num
);
1797 if (s
->status
== BLK_DATA
) {
1798 n
= MIN(n
, s
->buf_sectors
);
1801 /* We need to write complete clusters for compressed images, so if an
1802 * unallocated area is shorter than that, we must consider the whole
1803 * cluster allocated. */
1804 if (s
->compressed
) {
1805 if (n
< s
->cluster_sectors
) {
1806 n
= MIN(s
->cluster_sectors
, s
->total_sectors
- sector_num
);
1807 s
->status
= BLK_DATA
;
1809 n
= QEMU_ALIGN_DOWN(n
, s
->cluster_sectors
);
1816 static int coroutine_fn
convert_co_read(ImgConvertState
*s
, int64_t sector_num
,
1817 int nb_sectors
, uint8_t *buf
)
1819 uint64_t single_read_until
= 0;
1822 assert(nb_sectors
<= s
->buf_sectors
);
1823 while (nb_sectors
> 0) {
1826 int64_t bs_sectors
, src_cur_offset
;
1829 /* In the case of compression with multiple source files, we can get a
1830 * nb_sectors that spreads into the next part. So we must be able to
1831 * read across multiple BDSes for one convert_read() call. */
1832 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1833 blk
= s
->src
[src_cur
];
1834 bs_sectors
= s
->src_sectors
[src_cur
];
1836 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1838 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1839 if (single_read_until
> offset
) {
1843 ret
= blk_co_pread(blk
, offset
, n
<< BDRV_SECTOR_BITS
, buf
, 0);
1847 single_read_until
= offset
+ (n
<< BDRV_SECTOR_BITS
);
1851 warn_report("error while reading offset %" PRIu64
1852 ": %s", offset
, strerror(-ret
));
1854 memset(buf
, 0, BDRV_SECTOR_SIZE
);
1863 buf
+= n
* BDRV_SECTOR_SIZE
;
1870 static int coroutine_fn
convert_co_write(ImgConvertState
*s
, int64_t sector_num
,
1871 int nb_sectors
, uint8_t *buf
,
1872 enum ImgConvertBlockStatus status
)
1876 while (nb_sectors
> 0) {
1878 BdrvRequestFlags flags
= s
->compressed
? BDRV_REQ_WRITE_COMPRESSED
: 0;
1881 case BLK_BACKING_FILE
:
1882 /* If we have a backing file, leave clusters unallocated that are
1883 * unallocated in the source image, so that the backing file is
1884 * visible at the respective offset. */
1885 assert(s
->target_has_backing
);
1889 /* If we're told to keep the target fully allocated (-S 0) or there
1890 * is real non-zero data, we must write it. Otherwise we can treat
1891 * it as zero sectors.
1892 * Compressed clusters need to be written as a whole, so in that
1893 * case we can only save the write if the buffer is completely
1895 if (!s
->min_sparse
||
1897 is_allocated_sectors_min(buf
, n
, &n
, s
->min_sparse
,
1898 sector_num
, s
->alignment
)) ||
1900 !buffer_is_zero(buf
, n
* BDRV_SECTOR_SIZE
)))
1902 ret
= blk_co_pwrite(s
->target
, sector_num
<< BDRV_SECTOR_BITS
,
1903 n
<< BDRV_SECTOR_BITS
, buf
, flags
);
1912 if (s
->has_zero_init
) {
1913 assert(!s
->target_has_backing
);
1916 ret
= blk_co_pwrite_zeroes(s
->target
,
1917 sector_num
<< BDRV_SECTOR_BITS
,
1918 n
<< BDRV_SECTOR_BITS
,
1919 BDRV_REQ_MAY_UNMAP
);
1928 buf
+= n
* BDRV_SECTOR_SIZE
;
1934 static int coroutine_fn
convert_co_copy_range(ImgConvertState
*s
, int64_t sector_num
,
1939 while (nb_sectors
> 0) {
1942 int64_t bs_sectors
, src_cur_offset
;
1945 convert_select_part(s
, sector_num
, &src_cur
, &src_cur_offset
);
1946 offset
= (sector_num
- src_cur_offset
) << BDRV_SECTOR_BITS
;
1947 blk
= s
->src
[src_cur
];
1948 bs_sectors
= s
->src_sectors
[src_cur
];
1950 n
= MIN(nb_sectors
, bs_sectors
- (sector_num
- src_cur_offset
));
1952 ret
= blk_co_copy_range(blk
, offset
, s
->target
,
1953 sector_num
<< BDRV_SECTOR_BITS
,
1954 n
<< BDRV_SECTOR_BITS
, 0, 0);
1965 static void coroutine_fn
convert_co_do_copy(void *opaque
)
1967 ImgConvertState
*s
= opaque
;
1968 uint8_t *buf
= NULL
;
1972 for (i
= 0; i
< s
->num_coroutines
; i
++) {
1973 if (s
->co
[i
] == qemu_coroutine_self()) {
1980 s
->running_coroutines
++;
1981 buf
= blk_blockalign(s
->target
, s
->buf_sectors
* BDRV_SECTOR_SIZE
);
1986 enum ImgConvertBlockStatus status
;
1989 qemu_co_mutex_lock(&s
->lock
);
1990 if (s
->ret
!= -EINPROGRESS
|| s
->sector_num
>= s
->total_sectors
) {
1991 qemu_co_mutex_unlock(&s
->lock
);
1994 WITH_GRAPH_RDLOCK_GUARD() {
1995 n
= convert_iteration_sectors(s
, s
->sector_num
);
1998 qemu_co_mutex_unlock(&s
->lock
);
2002 /* save current sector and allocation status to local variables */
2003 sector_num
= s
->sector_num
;
2005 if (!s
->min_sparse
&& s
->status
== BLK_ZERO
) {
2006 n
= MIN(n
, s
->buf_sectors
);
2008 /* increment global sector counter so that other coroutines can
2009 * already continue reading beyond this request */
2011 qemu_co_mutex_unlock(&s
->lock
);
2013 if (status
== BLK_DATA
|| (!s
->min_sparse
&& status
== BLK_ZERO
)) {
2014 s
->allocated_done
+= n
;
2015 qemu_progress_print(100.0 * s
->allocated_done
/
2016 s
->allocated_sectors
, 0);
2020 copy_range
= s
->copy_range
&& s
->status
== BLK_DATA
;
2021 if (status
== BLK_DATA
&& !copy_range
) {
2022 ret
= convert_co_read(s
, sector_num
, n
, buf
);
2024 error_report("error while reading at byte %lld: %s",
2025 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2028 } else if (!s
->min_sparse
&& status
== BLK_ZERO
) {
2030 memset(buf
, 0x00, n
* BDRV_SECTOR_SIZE
);
2033 if (s
->wr_in_order
) {
2034 /* keep writes in order */
2035 while (s
->wr_offs
!= sector_num
&& s
->ret
== -EINPROGRESS
) {
2036 s
->wait_sector_num
[index
] = sector_num
;
2037 qemu_coroutine_yield();
2039 s
->wait_sector_num
[index
] = -1;
2042 if (s
->ret
== -EINPROGRESS
) {
2044 ret
= convert_co_copy_range(s
, sector_num
, n
);
2046 s
->copy_range
= false;
2050 ret
= convert_co_write(s
, sector_num
, n
, buf
, status
);
2053 error_report("error while writing at byte %lld: %s",
2054 sector_num
* BDRV_SECTOR_SIZE
, strerror(-ret
));
2059 if (s
->wr_in_order
) {
2060 /* reenter the coroutine that might have waited
2061 * for this write to complete */
2062 s
->wr_offs
= sector_num
+ n
;
2063 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2064 if (s
->co
[i
] && s
->wait_sector_num
[i
] == s
->wr_offs
) {
2066 * A -> B -> A cannot occur because A has
2067 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2068 * B will never enter A during this time window.
2070 qemu_coroutine_enter(s
->co
[i
]);
2078 s
->co
[index
] = NULL
;
2079 s
->running_coroutines
--;
2080 if (!s
->running_coroutines
&& s
->ret
== -EINPROGRESS
) {
2081 /* the convert job finished successfully */
2086 static int convert_do_copy(ImgConvertState
*s
)
2089 int64_t sector_num
= 0;
2091 /* Check whether we have zero initialisation or can get it efficiently */
2092 if (!s
->has_zero_init
&& s
->target_is_new
&& s
->min_sparse
&&
2093 !s
->target_has_backing
) {
2094 s
->has_zero_init
= bdrv_has_zero_init(blk_bs(s
->target
));
2097 /* Allocate buffer for copied data. For compressed images, only one cluster
2098 * can be copied at a time. */
2099 if (s
->compressed
) {
2100 if (s
->cluster_sectors
<= 0 || s
->cluster_sectors
> s
->buf_sectors
) {
2101 error_report("invalid cluster size");
2104 s
->buf_sectors
= s
->cluster_sectors
;
2107 while (sector_num
< s
->total_sectors
) {
2108 n
= convert_iteration_sectors(s
, sector_num
);
2112 if (s
->status
== BLK_DATA
|| (!s
->min_sparse
&& s
->status
== BLK_ZERO
))
2114 s
->allocated_sectors
+= n
;
2120 s
->sector_next_status
= 0;
2121 s
->ret
= -EINPROGRESS
;
2123 qemu_co_mutex_init(&s
->lock
);
2124 for (i
= 0; i
< s
->num_coroutines
; i
++) {
2125 s
->co
[i
] = qemu_coroutine_create(convert_co_do_copy
, s
);
2126 s
->wait_sector_num
[i
] = -1;
2127 qemu_coroutine_enter(s
->co
[i
]);
2130 while (s
->running_coroutines
) {
2131 main_loop_wait(false);
2134 if (s
->compressed
&& !s
->ret
) {
2135 /* signal EOF to align */
2136 ret
= blk_pwrite_compressed(s
->target
, 0, 0, NULL
);
2145 /* Check that bitmaps can be copied, or output an error */
2146 static int convert_check_bitmaps(BlockDriverState
*src
, bool skip_broken
)
2148 BdrvDirtyBitmap
*bm
;
2150 if (!bdrv_supports_persistent_dirty_bitmap(src
)) {
2151 error_report("Source lacks bitmap support");
2154 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2155 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2158 if (!skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2159 error_report("Cannot copy inconsistent bitmap '%s'",
2160 bdrv_dirty_bitmap_name(bm
));
2161 error_printf("Try --skip-broken-bitmaps, or "
2162 "use 'qemu-img bitmap --remove' to delete it\n");
2169 static int convert_copy_bitmaps(BlockDriverState
*src
, BlockDriverState
*dst
,
2172 BdrvDirtyBitmap
*bm
;
2175 FOR_EACH_DIRTY_BITMAP(src
, bm
) {
2178 if (!bdrv_dirty_bitmap_get_persistence(bm
)) {
2181 name
= bdrv_dirty_bitmap_name(bm
);
2182 if (skip_broken
&& bdrv_dirty_bitmap_inconsistent(bm
)) {
2183 warn_report("Skipping inconsistent bitmap '%s'", name
);
2186 qmp_block_dirty_bitmap_add(dst
->node_name
, name
,
2187 true, bdrv_dirty_bitmap_granularity(bm
),
2189 true, !bdrv_dirty_bitmap_enabled(bm
),
2192 error_reportf_err(err
, "Failed to create bitmap %s: ", name
);
2196 do_dirty_bitmap_merge(dst
->node_name
, name
, src
->node_name
, name
,
2199 error_reportf_err(err
, "Failed to populate bitmap %s: ", name
);
2200 qmp_block_dirty_bitmap_remove(dst
->node_name
, name
, NULL
);
2208 #define MAX_BUF_SECTORS 32768
2210 static void set_rate_limit(BlockBackend
*blk
, int64_t rate_limit
)
2214 throttle_config_init(&cfg
);
2215 cfg
.buckets
[THROTTLE_BPS_WRITE
].avg
= rate_limit
;
2217 blk_io_limits_enable(blk
, CONVERT_THROTTLE_GROUP
);
2218 blk_set_io_limits(blk
, &cfg
);
2221 static int img_convert(int argc
, char **argv
)
2223 int c
, bs_i
, flags
, src_flags
= BDRV_O_NO_SHARE
;
2224 const char *fmt
= NULL
, *out_fmt
= NULL
, *cache
= "unsafe",
2225 *src_cache
= BDRV_DEFAULT_CACHE
, *out_baseimg
= NULL
,
2226 *out_filename
, *out_baseimg_param
, *snapshot_name
= NULL
,
2227 *backing_fmt
= NULL
;
2228 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
2229 BlockDriverInfo bdi
;
2230 BlockDriverState
*out_bs
;
2231 QemuOpts
*opts
= NULL
, *sn_opts
= NULL
;
2232 QemuOptsList
*create_opts
= NULL
;
2233 QDict
*open_opts
= NULL
;
2234 char *options
= NULL
;
2235 Error
*local_err
= NULL
;
2236 bool writethrough
, src_writethrough
, image_opts
= false,
2237 skip_create
= false, progress
= false, tgt_image_opts
= false;
2238 int64_t ret
= -EINVAL
;
2239 bool force_share
= false;
2240 bool explict_min_sparse
= false;
2241 bool bitmaps
= false;
2242 bool skip_broken
= false;
2243 int64_t rate_limit
= 0;
2245 ImgConvertState s
= (ImgConvertState
) {
2246 /* Need at least 4k of zeros for sparse detection */
2248 .copy_range
= false,
2249 .buf_sectors
= IO_BUF_SIZE
/ BDRV_SECTOR_SIZE
,
2250 .wr_in_order
= true,
2251 .num_coroutines
= 8,
2255 static const struct option long_options
[] = {
2256 {"help", no_argument
, 0, 'h'},
2257 {"object", required_argument
, 0, OPTION_OBJECT
},
2258 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
2259 {"force-share", no_argument
, 0, 'U'},
2260 {"target-image-opts", no_argument
, 0, OPTION_TARGET_IMAGE_OPTS
},
2261 {"salvage", no_argument
, 0, OPTION_SALVAGE
},
2262 {"target-is-zero", no_argument
, 0, OPTION_TARGET_IS_ZERO
},
2263 {"bitmaps", no_argument
, 0, OPTION_BITMAPS
},
2264 {"skip-broken-bitmaps", no_argument
, 0, OPTION_SKIP_BROKEN
},
2267 c
= getopt_long(argc
, argv
, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
2268 long_options
, NULL
);
2274 missing_argument(argv
[optind
- 1]);
2277 unrecognized_option(argv
[optind
- 1]);
2289 out_baseimg
= optarg
;
2292 s
.copy_range
= true;
2295 s
.compressed
= true;
2298 backing_fmt
= optarg
;
2301 if (accumulate_options(&options
, optarg
) < 0) {
2306 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
2307 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
2310 error_report("Failed in parsing snapshot param '%s'",
2315 snapshot_name
= optarg
;
2322 sval
= cvtnum("buffer size for sparse output", optarg
);
2325 } else if (!QEMU_IS_ALIGNED(sval
, BDRV_SECTOR_SIZE
) ||
2326 sval
/ BDRV_SECTOR_SIZE
> MAX_BUF_SECTORS
) {
2327 error_report("Invalid buffer size for sparse output specified. "
2328 "Valid sizes are multiples of %llu up to %llu. Select "
2329 "0 to disable sparse detection (fully allocates output).",
2330 BDRV_SECTOR_SIZE
, MAX_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
2334 s
.min_sparse
= sval
/ BDRV_SECTOR_SIZE
;
2335 explict_min_sparse
= true;
2354 if (qemu_strtol(optarg
, NULL
, 0, &s
.num_coroutines
) ||
2355 s
.num_coroutines
< 1 || s
.num_coroutines
> MAX_COROUTINES
) {
2356 error_report("Invalid number of coroutines. Allowed number of"
2357 " coroutines is between 1 and %d", MAX_COROUTINES
);
2362 s
.wr_in_order
= false;
2368 rate_limit
= cvtnum("rate limit", optarg
);
2369 if (rate_limit
< 0) {
2374 user_creatable_process_cmdline(optarg
);
2376 case OPTION_IMAGE_OPTS
:
2379 case OPTION_SALVAGE
:
2382 case OPTION_TARGET_IMAGE_OPTS
:
2383 tgt_image_opts
= true;
2385 case OPTION_TARGET_IS_ZERO
:
2387 * The user asserting that the target is blank has the
2388 * same effect as the target driver supporting zero
2391 s
.has_zero_init
= true;
2393 case OPTION_BITMAPS
:
2396 case OPTION_SKIP_BROKEN
:
2402 if (!out_fmt
&& !tgt_image_opts
) {
2406 if (skip_broken
&& !bitmaps
) {
2407 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2411 if (s
.compressed
&& s
.copy_range
) {
2412 error_report("Cannot enable copy offloading when -c is used");
2416 if (explict_min_sparse
&& s
.copy_range
) {
2417 error_report("Cannot enable copy offloading when -S is used");
2421 if (s
.copy_range
&& s
.salvage
) {
2422 error_report("Cannot use copy offloading in salvaging mode");
2426 if (tgt_image_opts
&& !skip_create
) {
2427 error_report("--target-image-opts requires use of -n flag");
2431 if (skip_create
&& options
) {
2432 error_report("-o has no effect when skipping image creation");
2436 if (s
.has_zero_init
&& !skip_create
) {
2437 error_report("--target-is-zero requires use of -n flag");
2441 s
.src_num
= argc
- optind
- 1;
2442 out_filename
= s
.src_num
>= 1 ? argv
[argc
- 1] : NULL
;
2444 if (options
&& has_help_option(options
)) {
2446 ret
= print_block_option_help(out_filename
, out_fmt
);
2449 error_report("Option help requires a format be specified");
2454 if (s
.src_num
< 1) {
2455 error_report("Must specify image file name");
2459 /* ret is still -EINVAL until here */
2460 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
2462 error_report("Invalid source cache option: %s", src_cache
);
2466 /* Initialize before goto out */
2470 qemu_progress_init(progress
, 1.0);
2471 qemu_progress_print(0, 100);
2473 s
.src
= g_new0(BlockBackend
*, s
.src_num
);
2474 s
.src_sectors
= g_new(int64_t, s
.src_num
);
2475 s
.src_alignment
= g_new(int, s
.src_num
);
2477 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2478 BlockDriverState
*src_bs
;
2479 s
.src
[bs_i
] = img_open(image_opts
, argv
[optind
+ bs_i
],
2480 fmt
, src_flags
, src_writethrough
, s
.quiet
,
2486 s
.src_sectors
[bs_i
] = blk_nb_sectors(s
.src
[bs_i
]);
2487 if (s
.src_sectors
[bs_i
] < 0) {
2488 error_report("Could not get size of %s: %s",
2489 argv
[optind
+ bs_i
], strerror(-s
.src_sectors
[bs_i
]));
2493 src_bs
= blk_bs(s
.src
[bs_i
]);
2494 s
.src_alignment
[bs_i
] = DIV_ROUND_UP(src_bs
->bl
.request_alignment
,
2496 if (!bdrv_get_info(src_bs
, &bdi
)) {
2497 s
.src_alignment
[bs_i
] = MAX(s
.src_alignment
[bs_i
],
2498 bdi
.cluster_size
/ BDRV_SECTOR_SIZE
);
2500 s
.total_sectors
+= s
.src_sectors
[bs_i
];
2504 bdrv_snapshot_load_tmp(blk_bs(s
.src
[0]),
2505 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
2506 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
2508 } else if (snapshot_name
!= NULL
) {
2509 if (s
.src_num
> 1) {
2510 error_report("No support for concatenating multiple snapshot");
2515 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s
.src
[0]), snapshot_name
,
2519 error_reportf_err(local_err
, "Failed to load snapshot: ");
2525 /* Find driver and parse its options */
2526 drv
= bdrv_find_format(out_fmt
);
2528 error_report("Unknown file format '%s'", out_fmt
);
2533 proto_drv
= bdrv_find_protocol(out_filename
, true, &local_err
);
2535 error_report_err(local_err
);
2540 if (!drv
->create_opts
) {
2541 error_report("Format driver '%s' does not support image creation",
2547 if (!proto_drv
->create_opts
) {
2548 error_report("Protocol driver '%s' does not support image creation",
2549 proto_drv
->format_name
);
2554 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
2555 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
2557 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
2559 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
2560 error_report_err(local_err
);
2566 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
2567 s
.total_sectors
* BDRV_SECTOR_SIZE
, &error_abort
);
2568 ret
= add_old_style_options(out_fmt
, opts
, out_baseimg
, backing_fmt
);
2574 /* Get backing file name if -o backing_file was used */
2575 out_baseimg_param
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
2576 if (out_baseimg_param
) {
2577 out_baseimg
= out_baseimg_param
;
2579 s
.target_has_backing
= (bool) out_baseimg
;
2581 if (s
.has_zero_init
&& s
.target_has_backing
) {
2582 error_report("Cannot use --target-is-zero when the destination "
2583 "image has a backing file");
2587 if (s
.src_num
> 1 && out_baseimg
) {
2588 error_report("Having a backing file for the target makes no sense when "
2589 "concatenating multiple input images");
2594 if (out_baseimg_param
) {
2595 if (!qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
)) {
2596 error_report("Use of backing file requires explicit "
2603 /* Check if compression is supported */
2606 qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
, false);
2607 const char *encryptfmt
=
2608 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2609 const char *preallocation
=
2610 qemu_opt_get(opts
, BLOCK_OPT_PREALLOC
);
2612 if (drv
&& !block_driver_can_compress(drv
)) {
2613 error_report("Compression not supported for this file format");
2618 if (encryption
|| encryptfmt
) {
2619 error_report("Compression and encryption not supported at "
2626 && strcmp(preallocation
, "off"))
2628 error_report("Compression and preallocation not supported at "
2635 /* Determine if bitmaps need copying */
2637 if (s
.src_num
> 1) {
2638 error_report("Copying bitmaps only possible with single source");
2642 ret
= convert_check_bitmaps(blk_bs(s
.src
[0]), skip_broken
);
2649 * The later open call will need any decryption secrets, and
2650 * bdrv_create() will purge "opts", so extract them now before
2654 open_opts
= qdict_new();
2655 qemu_opt_foreach(opts
, img_add_key_secrets
, open_opts
, &error_abort
);
2657 /* Create the new image */
2658 ret
= bdrv_create(drv
, out_filename
, opts
, &local_err
);
2660 error_reportf_err(local_err
, "%s: error while converting %s: ",
2661 out_filename
, out_fmt
);
2666 s
.target_is_new
= !skip_create
;
2668 flags
= s
.min_sparse
? (BDRV_O_RDWR
| BDRV_O_UNMAP
) : BDRV_O_RDWR
;
2669 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
2671 error_report("Invalid cache option: %s", cache
);
2675 if (flags
& BDRV_O_NOCACHE
) {
2677 * If we open the target with O_DIRECT, it may be necessary to
2678 * extend its size to align to the physical sector size.
2680 flags
|= BDRV_O_RESIZE
;
2684 s
.target
= img_open(tgt_image_opts
, out_filename
, out_fmt
,
2685 flags
, writethrough
, s
.quiet
, false);
2687 /* TODO ultimately we should allow --target-image-opts
2688 * to be used even when -n is not given.
2689 * That has to wait for bdrv_create to be improved
2690 * to allow filenames in option syntax
2692 s
.target
= img_open_file(out_filename
, open_opts
, out_fmt
,
2693 flags
, writethrough
, s
.quiet
, false);
2694 open_opts
= NULL
; /* blk_new_open will have freed it */
2700 out_bs
= blk_bs(s
.target
);
2702 if (bitmaps
&& !bdrv_supports_persistent_dirty_bitmap(out_bs
)) {
2703 error_report("Format driver '%s' does not support bitmaps",
2704 out_bs
->drv
->format_name
);
2709 if (s
.compressed
&& !block_driver_can_compress(out_bs
->drv
)) {
2710 error_report("Compression not supported for this file format");
2715 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2716 * or discard_alignment of the out_bs is greater. Limit to
2717 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2718 s
.buf_sectors
= MIN(MAX_BUF_SECTORS
,
2720 MAX(out_bs
->bl
.opt_transfer
>> BDRV_SECTOR_BITS
,
2721 out_bs
->bl
.pdiscard_alignment
>>
2722 BDRV_SECTOR_BITS
)));
2724 /* try to align the write requests to the destination to avoid unnecessary
2726 s
.alignment
= MAX(pow2floor(s
.min_sparse
),
2727 DIV_ROUND_UP(out_bs
->bl
.request_alignment
,
2729 assert(is_power_of_2(s
.alignment
));
2732 int64_t output_sectors
= blk_nb_sectors(s
.target
);
2733 if (output_sectors
< 0) {
2734 error_report("unable to get output image length: %s",
2735 strerror(-output_sectors
));
2738 } else if (output_sectors
< s
.total_sectors
) {
2739 error_report("output file is smaller than input file");
2745 if (s
.target_has_backing
&& s
.target_is_new
) {
2746 /* Errors are treated as "backing length unknown" (which means
2747 * s.target_backing_sectors has to be negative, which it will
2748 * be automatically). The backing file length is used only
2749 * for optimizations, so such a case is not fatal. */
2750 s
.target_backing_sectors
=
2751 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs
));
2753 s
.target_backing_sectors
= -1;
2756 ret
= bdrv_get_info(out_bs
, &bdi
);
2759 error_report("could not get block driver info");
2763 s
.compressed
= s
.compressed
|| bdi
.needs_compressed_writes
;
2764 s
.cluster_sectors
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
2768 set_rate_limit(s
.target
, rate_limit
);
2771 ret
= convert_do_copy(&s
);
2773 /* Now copy the bitmaps */
2774 if (bitmaps
&& ret
== 0) {
2775 ret
= convert_copy_bitmaps(blk_bs(s
.src
[0]), out_bs
, skip_broken
);
2780 qemu_progress_print(100, 0);
2782 qemu_progress_end();
2783 qemu_opts_del(opts
);
2784 qemu_opts_free(create_opts
);
2785 qobject_unref(open_opts
);
2786 blk_unref(s
.target
);
2788 for (bs_i
= 0; bs_i
< s
.src_num
; bs_i
++) {
2789 blk_unref(s
.src
[bs_i
]);
2793 g_free(s
.src_sectors
);
2794 g_free(s
.src_alignment
);
2796 qemu_opts_del(sn_opts
);
2803 static void dump_snapshots(BlockDriverState
*bs
)
2805 QEMUSnapshotInfo
*sn_tab
, *sn
;
2808 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
2811 printf("Snapshot list:\n");
2812 bdrv_snapshot_dump(NULL
);
2814 for(i
= 0; i
< nb_sns
; i
++) {
2816 bdrv_snapshot_dump(sn
);
2822 static void dump_json_block_graph_info_list(BlockGraphInfoList
*list
)
2826 Visitor
*v
= qobject_output_visitor_new(&obj
);
2828 visit_type_BlockGraphInfoList(v
, NULL
, &list
, &error_abort
);
2829 visit_complete(v
, &obj
);
2830 str
= qobject_to_json_pretty(obj
, true);
2831 assert(str
!= NULL
);
2832 printf("%s\n", str
->str
);
2835 g_string_free(str
, true);
2838 static void dump_json_block_graph_info(BlockGraphInfo
*info
)
2842 Visitor
*v
= qobject_output_visitor_new(&obj
);
2844 visit_type_BlockGraphInfo(v
, NULL
, &info
, &error_abort
);
2845 visit_complete(v
, &obj
);
2846 str
= qobject_to_json_pretty(obj
, true);
2847 assert(str
!= NULL
);
2848 printf("%s\n", str
->str
);
2851 g_string_free(str
, true);
2854 static void dump_human_image_info(BlockGraphInfo
*info
, int indentation
,
2857 BlockChildInfoList
*children_list
;
2859 bdrv_node_info_dump(qapi_BlockGraphInfo_base(info
), indentation
,
2860 info
->children
== NULL
);
2862 for (children_list
= info
->children
; children_list
;
2863 children_list
= children_list
->next
)
2865 BlockChildInfo
*child
= children_list
->value
;
2866 g_autofree
char *child_path
= NULL
;
2868 printf("%*sChild node '%s%s':\n",
2869 indentation
* 4, "", path
, child
->name
);
2870 child_path
= g_strdup_printf("%s%s/", path
, child
->name
);
2871 dump_human_image_info(child
->info
, indentation
+ 1, child_path
);
2875 static void dump_human_image_info_list(BlockGraphInfoList
*list
)
2877 BlockGraphInfoList
*elem
;
2880 for (elem
= list
; elem
; elem
= elem
->next
) {
2886 dump_human_image_info(elem
->value
, 0, "/");
2890 static gboolean
str_equal_func(gconstpointer a
, gconstpointer b
)
2892 return strcmp(a
, b
) == 0;
2896 * Open an image file chain and return an BlockGraphInfoList
2898 * @filename: topmost image filename
2899 * @fmt: topmost image format (may be NULL to autodetect)
2900 * @chain: true - enumerate entire backing file chain
2901 * false - only topmost image file
2903 * Returns a list of BlockNodeInfo objects or NULL if there was an error
2904 * opening an image file. If there was an error a message will have been
2905 * printed to stderr.
2907 static BlockGraphInfoList
*collect_image_info_list(bool image_opts
,
2908 const char *filename
,
2910 bool chain
, bool force_share
)
2912 BlockGraphInfoList
*head
= NULL
;
2913 BlockGraphInfoList
**tail
= &head
;
2914 GHashTable
*filenames
;
2917 filenames
= g_hash_table_new_full(g_str_hash
, str_equal_func
, NULL
, NULL
);
2921 BlockDriverState
*bs
;
2922 BlockGraphInfo
*info
;
2924 if (g_hash_table_lookup_extended(filenames
, filename
, NULL
, NULL
)) {
2925 error_report("Backing file '%s' creates an infinite loop.",
2929 g_hash_table_insert(filenames
, (gpointer
)filename
, NULL
);
2931 blk
= img_open(image_opts
, filename
, fmt
,
2932 BDRV_O_NO_BACKING
| BDRV_O_NO_IO
, false, false,
2940 * Note that the returned BlockGraphInfo object will not have
2941 * information about this image's backing node, because we have opened
2942 * it with BDRV_O_NO_BACKING. Printing this object will therefore not
2943 * duplicate the backing chain information that we obtain by walking
2944 * the chain manually here.
2946 bdrv_query_block_graph_info(bs
, &info
, &err
);
2948 error_report_err(err
);
2953 QAPI_LIST_APPEND(tail
, info
);
2957 /* Clear parameters that only apply to the topmost image */
2958 filename
= fmt
= NULL
;
2962 if (info
->full_backing_filename
) {
2963 filename
= info
->full_backing_filename
;
2964 } else if (info
->backing_filename
) {
2965 error_report("Could not determine absolute backing filename,"
2966 " but backing filename '%s' present",
2967 info
->backing_filename
);
2970 if (info
->backing_filename_format
) {
2971 fmt
= info
->backing_filename_format
;
2975 g_hash_table_destroy(filenames
);
2979 qapi_free_BlockGraphInfoList(head
);
2980 g_hash_table_destroy(filenames
);
2984 static int img_info(int argc
, char **argv
)
2987 OutputFormat output_format
= OFORMAT_HUMAN
;
2989 const char *filename
, *fmt
, *output
;
2990 BlockGraphInfoList
*list
;
2991 bool image_opts
= false;
2992 bool force_share
= false;
2997 int option_index
= 0;
2998 static const struct option long_options
[] = {
2999 {"help", no_argument
, 0, 'h'},
3000 {"format", required_argument
, 0, 'f'},
3001 {"output", required_argument
, 0, OPTION_OUTPUT
},
3002 {"backing-chain", no_argument
, 0, OPTION_BACKING_CHAIN
},
3003 {"object", required_argument
, 0, OPTION_OBJECT
},
3004 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3005 {"force-share", no_argument
, 0, 'U'},
3008 c
= getopt_long(argc
, argv
, ":f:hU",
3009 long_options
, &option_index
);
3015 missing_argument(argv
[optind
- 1]);
3018 unrecognized_option(argv
[optind
- 1]);
3032 case OPTION_BACKING_CHAIN
:
3036 user_creatable_process_cmdline(optarg
);
3038 case OPTION_IMAGE_OPTS
:
3043 if (optind
!= argc
- 1) {
3044 error_exit("Expecting one image file name");
3046 filename
= argv
[optind
++];
3048 if (output
&& !strcmp(output
, "json")) {
3049 output_format
= OFORMAT_JSON
;
3050 } else if (output
&& !strcmp(output
, "human")) {
3051 output_format
= OFORMAT_HUMAN
;
3052 } else if (output
) {
3053 error_report("--output must be used with human or json as argument.");
3057 list
= collect_image_info_list(image_opts
, filename
, fmt
, chain
,
3063 switch (output_format
) {
3065 dump_human_image_info_list(list
);
3069 dump_json_block_graph_info_list(list
);
3071 dump_json_block_graph_info(list
->value
);
3076 qapi_free_BlockGraphInfoList(list
);
3080 static int dump_map_entry(OutputFormat output_format
, MapEntry
*e
,
3083 switch (output_format
) {
3085 if (e
->data
&& !e
->has_offset
) {
3086 error_report("File contains external, encrypted or compressed clusters.");
3089 if (e
->data
&& !e
->zero
) {
3090 printf("%#-16"PRIx64
"%#-16"PRIx64
"%#-16"PRIx64
"%s\n",
3091 e
->start
, e
->length
,
3092 e
->has_offset
? e
->offset
: 0,
3095 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3096 * Modify the flags here to allow more coalescing.
3098 if (next
&& (!next
->data
|| next
->zero
)) {
3104 printf("{ \"start\": %"PRId64
", \"length\": %"PRId64
","
3105 " \"depth\": %"PRId64
", \"present\": %s, \"zero\": %s,"
3106 " \"data\": %s", e
->start
, e
->length
, e
->depth
,
3107 e
->present
? "true" : "false",
3108 e
->zero
? "true" : "false",
3109 e
->data
? "true" : "false");
3110 if (e
->has_offset
) {
3111 printf(", \"offset\": %"PRId64
"", e
->offset
);
3123 static int get_block_status(BlockDriverState
*bs
, int64_t offset
,
3124 int64_t bytes
, MapEntry
*e
)
3128 BlockDriverState
*file
;
3131 char *filename
= NULL
;
3133 /* As an optimization, we could cache the current range of unallocated
3134 * clusters in each file of the chain, and avoid querying the same
3140 bs
= bdrv_skip_filters(bs
);
3141 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, &map
, &file
);
3146 if (ret
& (BDRV_BLOCK_ZERO
|BDRV_BLOCK_DATA
)) {
3149 bs
= bdrv_cow_bs(bs
);
3158 has_offset
= !!(ret
& BDRV_BLOCK_OFFSET_VALID
);
3160 if (file
&& has_offset
) {
3161 bdrv_refresh_filename(file
);
3162 filename
= file
->filename
;
3168 .data
= !!(ret
& BDRV_BLOCK_DATA
),
3169 .zero
= !!(ret
& BDRV_BLOCK_ZERO
),
3171 .has_offset
= has_offset
,
3173 .present
= !!(ret
& BDRV_BLOCK_ALLOCATED
),
3174 .filename
= filename
,
3180 static inline bool entry_mergeable(const MapEntry
*curr
, const MapEntry
*next
)
3182 if (curr
->length
== 0) {
3185 if (curr
->zero
!= next
->zero
||
3186 curr
->data
!= next
->data
||
3187 curr
->depth
!= next
->depth
||
3188 curr
->present
!= next
->present
||
3189 !curr
->filename
!= !next
->filename
||
3190 curr
->has_offset
!= next
->has_offset
) {
3193 if (curr
->filename
&& strcmp(curr
->filename
, next
->filename
)) {
3196 if (curr
->has_offset
&& curr
->offset
+ curr
->length
!= next
->offset
) {
3202 static int img_map(int argc
, char **argv
)
3205 OutputFormat output_format
= OFORMAT_HUMAN
;
3207 BlockDriverState
*bs
;
3208 const char *filename
, *fmt
, *output
;
3210 MapEntry curr
= { .length
= 0 }, next
;
3212 bool image_opts
= false;
3213 bool force_share
= false;
3214 int64_t start_offset
= 0;
3215 int64_t max_length
= -1;
3220 int option_index
= 0;
3221 static const struct option long_options
[] = {
3222 {"help", no_argument
, 0, 'h'},
3223 {"format", required_argument
, 0, 'f'},
3224 {"output", required_argument
, 0, OPTION_OUTPUT
},
3225 {"object", required_argument
, 0, OPTION_OBJECT
},
3226 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3227 {"force-share", no_argument
, 0, 'U'},
3228 {"start-offset", required_argument
, 0, 's'},
3229 {"max-length", required_argument
, 0, 'l'},
3232 c
= getopt_long(argc
, argv
, ":f:s:l:hU",
3233 long_options
, &option_index
);
3239 missing_argument(argv
[optind
- 1]);
3242 unrecognized_option(argv
[optind
- 1]);
3257 start_offset
= cvtnum("start offset", optarg
);
3258 if (start_offset
< 0) {
3263 max_length
= cvtnum("max length", optarg
);
3264 if (max_length
< 0) {
3269 user_creatable_process_cmdline(optarg
);
3271 case OPTION_IMAGE_OPTS
:
3276 if (optind
!= argc
- 1) {
3277 error_exit("Expecting one image file name");
3279 filename
= argv
[optind
];
3281 if (output
&& !strcmp(output
, "json")) {
3282 output_format
= OFORMAT_JSON
;
3283 } else if (output
&& !strcmp(output
, "human")) {
3284 output_format
= OFORMAT_HUMAN
;
3285 } else if (output
) {
3286 error_report("--output must be used with human or json as argument.");
3290 blk
= img_open(image_opts
, filename
, fmt
, 0, false, false, force_share
);
3296 if (output_format
== OFORMAT_HUMAN
) {
3297 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3298 } else if (output_format
== OFORMAT_JSON
) {
3302 length
= blk_getlength(blk
);
3304 error_report("Failed to get size for '%s'", filename
);
3307 if (max_length
!= -1) {
3308 length
= MIN(start_offset
+ max_length
, length
);
3311 curr
.start
= start_offset
;
3312 while (curr
.start
+ curr
.length
< length
) {
3313 int64_t offset
= curr
.start
+ curr
.length
;
3314 int64_t n
= length
- offset
;
3316 ret
= get_block_status(bs
, offset
, n
, &next
);
3318 error_report("Could not read file metadata: %s", strerror(-ret
));
3322 if (entry_mergeable(&curr
, &next
)) {
3323 curr
.length
+= next
.length
;
3327 if (curr
.length
> 0) {
3328 ret
= dump_map_entry(output_format
, &curr
, &next
);
3336 ret
= dump_map_entry(output_format
, &curr
, NULL
);
3337 if (output_format
== OFORMAT_JSON
) {
3346 #define SNAPSHOT_LIST 1
3347 #define SNAPSHOT_CREATE 2
3348 #define SNAPSHOT_APPLY 3
3349 #define SNAPSHOT_DELETE 4
3351 static int img_snapshot(int argc
, char **argv
)
3354 BlockDriverState
*bs
;
3355 QEMUSnapshotInfo sn
;
3356 char *filename
, *snapshot_name
= NULL
;
3357 int c
, ret
= 0, bdrv_oflags
;
3361 bool image_opts
= false;
3362 bool force_share
= false;
3365 bdrv_oflags
= BDRV_O_RDWR
;
3366 /* Parse commandline parameters */
3368 static const struct option long_options
[] = {
3369 {"help", no_argument
, 0, 'h'},
3370 {"object", required_argument
, 0, OPTION_OBJECT
},
3371 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3372 {"force-share", no_argument
, 0, 'U'},
3375 c
= getopt_long(argc
, argv
, ":la:c:d:hqU",
3376 long_options
, NULL
);
3382 missing_argument(argv
[optind
- 1]);
3385 unrecognized_option(argv
[optind
- 1]);
3392 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3395 action
= SNAPSHOT_LIST
;
3396 bdrv_oflags
&= ~BDRV_O_RDWR
; /* no need for RW */
3400 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3403 action
= SNAPSHOT_APPLY
;
3404 snapshot_name
= optarg
;
3408 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3411 action
= SNAPSHOT_CREATE
;
3412 snapshot_name
= optarg
;
3416 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3419 action
= SNAPSHOT_DELETE
;
3420 snapshot_name
= optarg
;
3429 user_creatable_process_cmdline(optarg
);
3431 case OPTION_IMAGE_OPTS
:
3437 if (optind
!= argc
- 1) {
3438 error_exit("Expecting one image file name");
3440 filename
= argv
[optind
++];
3442 /* Open the image */
3443 blk
= img_open(image_opts
, filename
, NULL
, bdrv_oflags
, false, quiet
,
3450 /* Perform the requested action */
3456 case SNAPSHOT_CREATE
:
3457 memset(&sn
, 0, sizeof(sn
));
3458 pstrcpy(sn
.name
, sizeof(sn
.name
), snapshot_name
);
3460 rt
= g_get_real_time();
3461 sn
.date_sec
= rt
/ G_USEC_PER_SEC
;
3462 sn
.date_nsec
= (rt
% G_USEC_PER_SEC
) * 1000;
3464 ret
= bdrv_snapshot_create(bs
, &sn
);
3466 error_report("Could not create snapshot '%s': %d (%s)",
3467 snapshot_name
, ret
, strerror(-ret
));
3471 case SNAPSHOT_APPLY
:
3472 ret
= bdrv_snapshot_goto(bs
, snapshot_name
, &err
);
3474 error_reportf_err(err
, "Could not apply snapshot '%s': ",
3479 case SNAPSHOT_DELETE
:
3480 ret
= bdrv_snapshot_find(bs
, &sn
, snapshot_name
);
3482 error_report("Could not delete snapshot '%s': snapshot not "
3483 "found", snapshot_name
);
3486 ret
= bdrv_snapshot_delete(bs
, sn
.id_str
, sn
.name
, &err
);
3488 error_reportf_err(err
, "Could not delete snapshot '%s': ",
3504 static int img_rebase(int argc
, char **argv
)
3506 BlockBackend
*blk
= NULL
, *blk_old_backing
= NULL
, *blk_new_backing
= NULL
;
3507 uint8_t *buf_old
= NULL
;
3508 uint8_t *buf_new
= NULL
;
3509 BlockDriverState
*bs
= NULL
, *prefix_chain_bs
= NULL
;
3510 BlockDriverState
*unfiltered_bs
;
3512 const char *fmt
, *cache
, *src_cache
, *out_basefmt
, *out_baseimg
;
3513 int c
, flags
, src_flags
, ret
;
3514 bool writethrough
, src_writethrough
;
3516 bool force_share
= false;
3519 Error
*local_err
= NULL
;
3520 bool image_opts
= false;
3522 /* Parse commandline parameters */
3524 cache
= BDRV_DEFAULT_CACHE
;
3525 src_cache
= BDRV_DEFAULT_CACHE
;
3529 static const struct option long_options
[] = {
3530 {"help", no_argument
, 0, 'h'},
3531 {"object", required_argument
, 0, OPTION_OBJECT
},
3532 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3533 {"force-share", no_argument
, 0, 'U'},
3536 c
= getopt_long(argc
, argv
, ":hf:F:b:upt:T:qU",
3537 long_options
, NULL
);
3543 missing_argument(argv
[optind
- 1]);
3546 unrecognized_option(argv
[optind
- 1]);
3555 out_basefmt
= optarg
;
3558 out_baseimg
= optarg
;
3576 user_creatable_process_cmdline(optarg
);
3578 case OPTION_IMAGE_OPTS
:
3591 if (optind
!= argc
- 1) {
3592 error_exit("Expecting one image file name");
3594 if (!unsafe
&& !out_baseimg
) {
3595 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3597 filename
= argv
[optind
++];
3599 qemu_progress_init(progress
, 2.0);
3600 qemu_progress_print(0, 100);
3602 flags
= BDRV_O_RDWR
| (unsafe
? BDRV_O_NO_BACKING
: 0);
3603 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
3605 error_report("Invalid cache option: %s", cache
);
3610 ret
= bdrv_parse_cache_mode(src_cache
, &src_flags
, &src_writethrough
);
3612 error_report("Invalid source cache option: %s", src_cache
);
3616 /* The source files are opened read-only, don't care about WCE */
3617 assert((src_flags
& BDRV_O_RDWR
) == 0);
3618 (void) src_writethrough
;
3623 * Ignore the old backing file for unsafe rebase in case we want to correct
3624 * the reference to a renamed or moved backing file.
3626 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
3634 unfiltered_bs
= bdrv_skip_filters(bs
);
3636 if (out_basefmt
!= NULL
) {
3637 if (bdrv_find_format(out_basefmt
) == NULL
) {
3638 error_report("Invalid format name: '%s'", out_basefmt
);
3644 /* For safe rebasing we need to compare old and new backing file */
3646 QDict
*options
= NULL
;
3647 BlockDriverState
*base_bs
= bdrv_cow_bs(unfiltered_bs
);
3650 blk_old_backing
= blk_new(qemu_get_aio_context(),
3651 BLK_PERM_CONSISTENT_READ
,
3653 ret
= blk_insert_bs(blk_old_backing
, base_bs
,
3656 error_reportf_err(local_err
,
3657 "Could not reuse old backing file '%s': ",
3662 blk_old_backing
= NULL
;
3665 if (out_baseimg
[0]) {
3666 const char *overlay_filename
;
3667 char *out_real_path
;
3669 options
= qdict_new();
3671 qdict_put_str(options
, "driver", out_basefmt
);
3674 qdict_put_bool(options
, BDRV_OPT_FORCE_SHARE
, true);
3677 bdrv_refresh_filename(bs
);
3678 overlay_filename
= bs
->exact_filename
[0] ? bs
->exact_filename
3681 bdrv_get_full_backing_filename_from_filename(overlay_filename
,
3685 qobject_unref(options
);
3686 error_reportf_err(local_err
,
3687 "Could not resolve backing filename: ");
3693 * Find out whether we rebase an image on top of a previous image
3696 prefix_chain_bs
= bdrv_find_backing_image(bs
, out_real_path
);
3697 if (prefix_chain_bs
) {
3698 qobject_unref(options
);
3699 g_free(out_real_path
);
3701 blk_new_backing
= blk_new(qemu_get_aio_context(),
3702 BLK_PERM_CONSISTENT_READ
,
3704 ret
= blk_insert_bs(blk_new_backing
, prefix_chain_bs
,
3707 error_reportf_err(local_err
,
3708 "Could not reuse backing file '%s': ",
3713 blk_new_backing
= blk_new_open(out_real_path
, NULL
,
3714 options
, src_flags
, &local_err
);
3715 g_free(out_real_path
);
3716 if (!blk_new_backing
) {
3717 error_reportf_err(local_err
,
3718 "Could not open new backing file '%s': ",
3728 * Check each unallocated cluster in the COW file. If it is unallocated,
3729 * accesses go to the backing file. We must therefore compare this cluster
3730 * in the old and new backing file, and if they differ we need to copy it
3731 * from the old backing file into the COW file.
3733 * If qemu-img crashes during this step, no harm is done. The content of
3734 * the image is the same as the original one at any time.
3738 int64_t old_backing_size
= 0;
3739 int64_t new_backing_size
= 0;
3742 float local_progress
= 0;
3744 buf_old
= blk_blockalign(blk
, IO_BUF_SIZE
);
3745 buf_new
= blk_blockalign(blk
, IO_BUF_SIZE
);
3747 size
= blk_getlength(blk
);
3749 error_report("Could not get size of '%s': %s",
3750 filename
, strerror(-size
));
3754 if (blk_old_backing
) {
3755 old_backing_size
= blk_getlength(blk_old_backing
);
3756 if (old_backing_size
< 0) {
3757 char backing_name
[PATH_MAX
];
3759 bdrv_get_backing_filename(bs
, backing_name
,
3760 sizeof(backing_name
));
3761 error_report("Could not get size of '%s': %s",
3762 backing_name
, strerror(-old_backing_size
));
3767 if (blk_new_backing
) {
3768 new_backing_size
= blk_getlength(blk_new_backing
);
3769 if (new_backing_size
< 0) {
3770 error_report("Could not get size of '%s': %s",
3771 out_baseimg
, strerror(-new_backing_size
));
3778 local_progress
= (float)100 / (size
/ MIN(size
, IO_BUF_SIZE
));
3781 for (offset
= 0; offset
< size
; offset
+= n
) {
3782 bool buf_old_is_zero
= false;
3784 /* How many bytes can we handle with the next read? */
3785 n
= MIN(IO_BUF_SIZE
, size
- offset
);
3787 /* If the cluster is allocated, we don't need to take action */
3788 ret
= bdrv_is_allocated(unfiltered_bs
, offset
, n
, &n
);
3790 error_report("error while reading image metadata: %s",
3798 if (prefix_chain_bs
) {
3800 * If cluster wasn't changed since prefix_chain, we don't need
3803 ret
= bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs
),
3804 prefix_chain_bs
, false,
3807 error_report("error while reading image metadata: %s",
3817 * Read old and new backing file and take into consideration that
3818 * backing files may be smaller than the COW image.
3820 if (offset
>= old_backing_size
) {
3821 memset(buf_old
, 0, n
);
3822 buf_old_is_zero
= true;
3824 if (offset
+ n
> old_backing_size
) {
3825 n
= old_backing_size
- offset
;
3828 ret
= blk_pread(blk_old_backing
, offset
, n
, buf_old
, 0);
3830 error_report("error while reading from old backing file");
3835 if (offset
>= new_backing_size
|| !blk_new_backing
) {
3836 memset(buf_new
, 0, n
);
3838 if (offset
+ n
> new_backing_size
) {
3839 n
= new_backing_size
- offset
;
3842 ret
= blk_pread(blk_new_backing
, offset
, n
, buf_new
, 0);
3844 error_report("error while reading from new backing file");
3849 /* If they differ, we need to write to the COW file */
3850 uint64_t written
= 0;
3852 while (written
< n
) {
3855 if (compare_buffers(buf_old
+ written
, buf_new
+ written
,
3856 n
- written
, &pnum
))
3858 if (buf_old_is_zero
) {
3859 ret
= blk_pwrite_zeroes(blk
, offset
+ written
, pnum
, 0);
3861 ret
= blk_pwrite(blk
, offset
+ written
, pnum
,
3862 buf_old
+ written
, 0);
3865 error_report("Error while writing to COW image: %s",
3873 qemu_progress_print(local_progress
, 100);
3878 * Change the backing file. All clusters that are different from the old
3879 * backing file are overwritten in the COW file now, so the visible content
3880 * doesn't change when we switch the backing file.
3882 if (out_baseimg
&& *out_baseimg
) {
3883 ret
= bdrv_change_backing_file(unfiltered_bs
, out_baseimg
, out_basefmt
,
3886 ret
= bdrv_change_backing_file(unfiltered_bs
, NULL
, NULL
, false);
3889 if (ret
== -ENOSPC
) {
3890 error_report("Could not change the backing file to '%s': No "
3891 "space left in the file header", out_baseimg
);
3892 } else if (ret
== -EINVAL
&& out_baseimg
&& !out_basefmt
) {
3893 error_report("Could not change the backing file to '%s': backing "
3894 "format must be specified", out_baseimg
);
3895 } else if (ret
< 0) {
3896 error_report("Could not change the backing file to '%s': %s",
3897 out_baseimg
, strerror(-ret
));
3900 qemu_progress_print(100, 0);
3902 * TODO At this point it is possible to check if any clusters that are
3903 * allocated in the COW file are the same in the backing file. If so, they
3904 * could be dropped from the COW file. Don't do this before switching the
3905 * backing file, in case of a crash this would lead to corruption.
3908 qemu_progress_end();
3911 blk_unref(blk_old_backing
);
3912 blk_unref(blk_new_backing
);
3914 qemu_vfree(buf_old
);
3915 qemu_vfree(buf_new
);
3924 static int img_resize(int argc
, char **argv
)
3927 int c
, ret
, relative
;
3928 const char *filename
, *fmt
, *size
;
3929 int64_t n
, total_size
, current_size
;
3931 BlockBackend
*blk
= NULL
;
3932 PreallocMode prealloc
= PREALLOC_MODE_OFF
;
3935 static QemuOptsList resize_options
= {
3936 .name
= "resize_options",
3937 .head
= QTAILQ_HEAD_INITIALIZER(resize_options
.head
),
3940 .name
= BLOCK_OPT_SIZE
,
3941 .type
= QEMU_OPT_SIZE
,
3942 .help
= "Virtual disk size"
3948 bool image_opts
= false;
3949 bool shrink
= false;
3951 /* Remove size from argv manually so that negative numbers are not treated
3952 * as options by getopt. */
3954 error_exit("Not enough arguments");
3958 size
= argv
[--argc
];
3960 /* Parse getopt arguments */
3963 static const struct option long_options
[] = {
3964 {"help", no_argument
, 0, 'h'},
3965 {"object", required_argument
, 0, OPTION_OBJECT
},
3966 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
3967 {"preallocation", required_argument
, 0, OPTION_PREALLOCATION
},
3968 {"shrink", no_argument
, 0, OPTION_SHRINK
},
3971 c
= getopt_long(argc
, argv
, ":f:hq",
3972 long_options
, NULL
);
3978 missing_argument(argv
[optind
- 1]);
3981 unrecognized_option(argv
[optind
- 1]);
3993 user_creatable_process_cmdline(optarg
);
3995 case OPTION_IMAGE_OPTS
:
3998 case OPTION_PREALLOCATION
:
3999 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optarg
,
4000 PREALLOC_MODE__MAX
, NULL
);
4001 if (prealloc
== PREALLOC_MODE__MAX
) {
4002 error_report("Invalid preallocation mode '%s'", optarg
);
4011 if (optind
!= argc
- 1) {
4012 error_exit("Expecting image file name and size");
4014 filename
= argv
[optind
++];
4016 /* Choose grow, shrink, or absolute resize mode */
4032 param
= qemu_opts_create(&resize_options
, NULL
, 0, &error_abort
);
4033 if (!qemu_opt_set(param
, BLOCK_OPT_SIZE
, size
, &err
)) {
4034 error_report_err(err
);
4036 qemu_opts_del(param
);
4039 n
= qemu_opt_get_size(param
, BLOCK_OPT_SIZE
, 0);
4040 qemu_opts_del(param
);
4042 blk
= img_open(image_opts
, filename
, fmt
,
4043 BDRV_O_RDWR
| BDRV_O_RESIZE
, false, quiet
,
4050 current_size
= blk_getlength(blk
);
4051 if (current_size
< 0) {
4052 error_report("Failed to inquire current image length: %s",
4053 strerror(-current_size
));
4059 total_size
= current_size
+ n
* relative
;
4063 if (total_size
<= 0) {
4064 error_report("New image size must be positive");
4069 if (total_size
<= current_size
&& prealloc
!= PREALLOC_MODE_OFF
) {
4070 error_report("Preallocation can only be used for growing images");
4075 if (total_size
< current_size
&& !shrink
) {
4076 error_report("Use the --shrink option to perform a shrink operation.");
4077 warn_report("Shrinking an image will delete all data beyond the "
4078 "shrunken image's end. Before performing such an "
4079 "operation, make sure there is no important data there.");
4085 * The user expects the image to have the desired size after
4086 * resizing, so pass @exact=true. It is of no use to report
4087 * success when the image has not actually been resized.
4089 ret
= blk_truncate(blk
, total_size
, true, prealloc
, 0, &err
);
4091 qprintf(quiet
, "Image resized.\n");
4093 error_report_err(err
);
4103 static void amend_status_cb(BlockDriverState
*bs
,
4104 int64_t offset
, int64_t total_work_size
,
4107 qemu_progress_print(100.f
* offset
/ total_work_size
, 0);
4110 static int print_amend_option_help(const char *format
)
4114 /* Find driver and parse its options */
4115 drv
= bdrv_find_format(format
);
4117 error_report("Unknown file format '%s'", format
);
4121 if (!drv
->bdrv_amend_options
) {
4122 error_report("Format driver '%s' does not support option amendment",
4127 /* Every driver supporting amendment must have amend_opts */
4128 assert(drv
->amend_opts
);
4130 printf("Amend options for '%s':\n", format
);
4131 qemu_opts_print_help(drv
->amend_opts
, false);
4135 static int img_amend(int argc
, char **argv
)
4139 char *options
= NULL
;
4140 QemuOptsList
*amend_opts
= NULL
;
4141 QemuOpts
*opts
= NULL
;
4142 const char *fmt
= NULL
, *filename
, *cache
;
4145 bool quiet
= false, progress
= false;
4146 BlockBackend
*blk
= NULL
;
4147 BlockDriverState
*bs
= NULL
;
4148 bool image_opts
= false;
4151 cache
= BDRV_DEFAULT_CACHE
;
4153 static const struct option long_options
[] = {
4154 {"help", no_argument
, 0, 'h'},
4155 {"object", required_argument
, 0, OPTION_OBJECT
},
4156 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4157 {"force", no_argument
, 0, OPTION_FORCE
},
4160 c
= getopt_long(argc
, argv
, ":ho:f:t:pq",
4161 long_options
, NULL
);
4168 missing_argument(argv
[optind
- 1]);
4171 unrecognized_option(argv
[optind
- 1]);
4177 if (accumulate_options(&options
, optarg
) < 0) {
4179 goto out_no_progress
;
4195 user_creatable_process_cmdline(optarg
);
4197 case OPTION_IMAGE_OPTS
:
4207 error_exit("Must specify options (-o)");
4213 qemu_progress_init(progress
, 1.0);
4215 filename
= (optind
== argc
- 1) ? argv
[argc
- 1] : NULL
;
4216 if (fmt
&& has_help_option(options
)) {
4217 /* If a format is explicitly specified (and possibly no filename is
4218 * given), print option help here */
4219 ret
= print_amend_option_help(fmt
);
4223 if (optind
!= argc
- 1) {
4224 error_report("Expecting one image file name");
4229 flags
= BDRV_O_RDWR
;
4230 ret
= bdrv_parse_cache_mode(cache
, &flags
, &writethrough
);
4232 error_report("Invalid cache option: %s", cache
);
4236 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4244 fmt
= bs
->drv
->format_name
;
4246 if (has_help_option(options
)) {
4247 /* If the format was auto-detected, print option help here */
4248 ret
= print_amend_option_help(fmt
);
4252 if (!bs
->drv
->bdrv_amend_options
) {
4253 error_report("Format driver '%s' does not support option amendment",
4259 /* Every driver supporting amendment must have amend_opts */
4260 assert(bs
->drv
->amend_opts
);
4262 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->amend_opts
);
4263 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4264 if (!qemu_opts_do_parse(opts
, options
, NULL
, &err
)) {
4265 /* Try to parse options using the create options */
4266 amend_opts
= qemu_opts_append(amend_opts
, bs
->drv
->create_opts
);
4267 qemu_opts_del(opts
);
4268 opts
= qemu_opts_create(amend_opts
, NULL
, 0, &error_abort
);
4269 if (qemu_opts_do_parse(opts
, options
, NULL
, NULL
)) {
4270 error_append_hint(&err
,
4271 "This option is only supported for image creation\n");
4274 error_report_err(err
);
4279 /* In case the driver does not call amend_status_cb() */
4280 qemu_progress_print(0.f
, 0);
4281 ret
= bdrv_amend_options(bs
, opts
, &amend_status_cb
, NULL
, force
, &err
);
4282 qemu_progress_print(100.f
, 0);
4284 error_report_err(err
);
4289 qemu_progress_end();
4293 qemu_opts_del(opts
);
4294 qemu_opts_free(amend_opts
);
4303 typedef struct BenchData
{
4305 uint64_t image_size
;
4312 bool drain_on_flush
;
4321 static void bench_undrained_flush_cb(void *opaque
, int ret
)
4324 error_report("Failed flush request: %s", strerror(-ret
));
4329 static void bench_cb(void *opaque
, int ret
)
4331 BenchData
*b
= opaque
;
4335 error_report("Failed request: %s", strerror(-ret
));
4340 /* Just finished a flush with drained queue: Start next requests */
4341 assert(b
->in_flight
== 0);
4342 b
->in_flush
= false;
4343 } else if (b
->in_flight
> 0) {
4344 int remaining
= b
->n
- b
->in_flight
;
4349 /* Time for flush? Drain queue if requested, then flush */
4350 if (b
->flush_interval
&& remaining
% b
->flush_interval
== 0) {
4351 if (!b
->in_flight
|| !b
->drain_on_flush
) {
4352 BlockCompletionFunc
*cb
;
4354 if (b
->drain_on_flush
) {
4358 cb
= bench_undrained_flush_cb
;
4361 acb
= blk_aio_flush(b
->blk
, cb
, b
);
4363 error_report("Failed to issue flush request");
4367 if (b
->drain_on_flush
) {
4373 while (b
->n
> b
->in_flight
&& b
->in_flight
< b
->nrreq
) {
4374 int64_t offset
= b
->offset
;
4375 /* blk_aio_* might look for completed I/Os and kick bench_cb
4376 * again, so make sure this operation is counted by in_flight
4377 * and b->offset is ready for the next submission.
4380 b
->offset
+= b
->step
;
4381 b
->offset
%= b
->image_size
;
4383 acb
= blk_aio_pwritev(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4385 acb
= blk_aio_preadv(b
->blk
, offset
, b
->qiov
, 0, bench_cb
, b
);
4388 error_report("Failed to issue request");
4394 static int img_bench(int argc
, char **argv
)
4397 const char *fmt
= NULL
, *filename
;
4399 bool image_opts
= false;
4400 bool is_write
= false;
4404 size_t bufsize
= 4096;
4407 int flush_interval
= 0;
4408 bool drain_on_flush
= true;
4410 BlockBackend
*blk
= NULL
;
4411 BenchData data
= {};
4413 bool writethrough
= false;
4414 struct timeval t1
, t2
;
4416 bool force_share
= false;
4417 size_t buf_size
= 0;
4420 static const struct option long_options
[] = {
4421 {"help", no_argument
, 0, 'h'},
4422 {"flush-interval", required_argument
, 0, OPTION_FLUSH_INTERVAL
},
4423 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4424 {"pattern", required_argument
, 0, OPTION_PATTERN
},
4425 {"no-drain", no_argument
, 0, OPTION_NO_DRAIN
},
4426 {"force-share", no_argument
, 0, 'U'},
4429 c
= getopt_long(argc
, argv
, ":hc:d:f:ni:o:qs:S:t:wU", long_options
,
4437 missing_argument(argv
[optind
- 1]);
4440 unrecognized_option(argv
[optind
- 1]);
4449 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4450 error_report("Invalid request count specified");
4460 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4461 error_report("Invalid queue depth specified");
4471 flags
|= BDRV_O_NATIVE_AIO
;
4474 ret
= bdrv_parse_aio(optarg
, &flags
);
4476 error_report("Invalid aio option: %s", optarg
);
4483 offset
= cvtnum("offset", optarg
);
4497 sval
= cvtnum_full("buffer size", optarg
, 0, INT_MAX
);
4509 sval
= cvtnum_full("step_size", optarg
, 0, INT_MAX
);
4518 ret
= bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
);
4520 error_report("Invalid cache mode");
4526 flags
|= BDRV_O_RDWR
;
4532 case OPTION_PATTERN
:
4536 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> 0xff) {
4537 error_report("Invalid pattern byte specified");
4543 case OPTION_FLUSH_INTERVAL
:
4547 if (qemu_strtoul(optarg
, NULL
, 0, &res
) < 0 || res
> INT_MAX
) {
4548 error_report("Invalid flush interval specified");
4551 flush_interval
= res
;
4554 case OPTION_NO_DRAIN
:
4555 drain_on_flush
= false;
4557 case OPTION_IMAGE_OPTS
:
4563 if (optind
!= argc
- 1) {
4564 error_exit("Expecting one image file name");
4566 filename
= argv
[argc
- 1];
4568 if (!is_write
&& flush_interval
) {
4569 error_report("--flush-interval is only available in write tests");
4573 if (flush_interval
&& flush_interval
< depth
) {
4574 error_report("Flush interval can't be smaller than depth");
4579 blk
= img_open(image_opts
, filename
, fmt
, flags
, writethrough
, quiet
,
4586 image_size
= blk_getlength(blk
);
4587 if (image_size
< 0) {
4592 data
= (BenchData
) {
4594 .image_size
= image_size
,
4596 .step
= step
?: bufsize
,
4601 .flush_interval
= flush_interval
,
4602 .drain_on_flush
= drain_on_flush
,
4604 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4605 "(starting at offset %" PRId64
", step size %d)\n",
4606 data
.n
, data
.write
? "write" : "read", data
.bufsize
, data
.nrreq
,
4607 data
.offset
, data
.step
);
4608 if (flush_interval
) {
4609 printf("Sending flush every %d requests\n", flush_interval
);
4612 buf_size
= data
.nrreq
* data
.bufsize
;
4613 data
.buf
= blk_blockalign(blk
, buf_size
);
4614 memset(data
.buf
, pattern
, data
.nrreq
* data
.bufsize
);
4616 blk_register_buf(blk
, data
.buf
, buf_size
, &error_fatal
);
4618 data
.qiov
= g_new(QEMUIOVector
, data
.nrreq
);
4619 for (i
= 0; i
< data
.nrreq
; i
++) {
4620 qemu_iovec_init(&data
.qiov
[i
], 1);
4621 qemu_iovec_add(&data
.qiov
[i
],
4622 data
.buf
+ i
* data
.bufsize
, data
.bufsize
);
4625 gettimeofday(&t1
, NULL
);
4628 while (data
.n
> 0) {
4629 main_loop_wait(false);
4631 gettimeofday(&t2
, NULL
);
4633 printf("Run completed in %3.3f seconds.\n",
4634 (t2
.tv_sec
- t1
.tv_sec
)
4635 + ((double)(t2
.tv_usec
- t1
.tv_usec
) / 1000000));
4639 blk_unregister_buf(blk
, data
.buf
, buf_size
);
4641 qemu_vfree(data
.buf
);
4658 typedef struct ImgBitmapAction
{
4659 enum ImgBitmapAct act
;
4660 const char *src
; /* only used for merge */
4661 QSIMPLEQ_ENTRY(ImgBitmapAction
) next
;
4664 static int img_bitmap(int argc
, char **argv
)
4668 QemuOpts
*opts
= NULL
;
4669 const char *fmt
= NULL
, *src_fmt
= NULL
, *src_filename
= NULL
;
4670 const char *filename
, *bitmap
;
4671 BlockBackend
*blk
= NULL
, *src
= NULL
;
4672 BlockDriverState
*bs
= NULL
, *src_bs
= NULL
;
4673 bool image_opts
= false;
4674 int64_t granularity
= 0;
4675 bool add
= false, merge
= false;
4676 QSIMPLEQ_HEAD(, ImgBitmapAction
) actions
;
4677 ImgBitmapAction
*act
, *act_next
;
4681 QSIMPLEQ_INIT(&actions
);
4684 static const struct option long_options
[] = {
4685 {"help", no_argument
, 0, 'h'},
4686 {"object", required_argument
, 0, OPTION_OBJECT
},
4687 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
4688 {"add", no_argument
, 0, OPTION_ADD
},
4689 {"remove", no_argument
, 0, OPTION_REMOVE
},
4690 {"clear", no_argument
, 0, OPTION_CLEAR
},
4691 {"enable", no_argument
, 0, OPTION_ENABLE
},
4692 {"disable", no_argument
, 0, OPTION_DISABLE
},
4693 {"merge", required_argument
, 0, OPTION_MERGE
},
4694 {"granularity", required_argument
, 0, 'g'},
4695 {"source-file", required_argument
, 0, 'b'},
4696 {"source-format", required_argument
, 0, 'F'},
4699 c
= getopt_long(argc
, argv
, ":b:f:F:g:h", long_options
, NULL
);
4706 missing_argument(argv
[optind
- 1]);
4709 unrecognized_option(argv
[optind
- 1]);
4715 src_filename
= optarg
;
4724 granularity
= cvtnum("granularity", optarg
);
4725 if (granularity
< 0) {
4730 act
= g_new0(ImgBitmapAction
, 1);
4731 act
->act
= BITMAP_ADD
;
4732 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4736 act
= g_new0(ImgBitmapAction
, 1);
4737 act
->act
= BITMAP_REMOVE
;
4738 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4741 act
= g_new0(ImgBitmapAction
, 1);
4742 act
->act
= BITMAP_CLEAR
;
4743 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4746 act
= g_new0(ImgBitmapAction
, 1);
4747 act
->act
= BITMAP_ENABLE
;
4748 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4750 case OPTION_DISABLE
:
4751 act
= g_new0(ImgBitmapAction
, 1);
4752 act
->act
= BITMAP_DISABLE
;
4753 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4756 act
= g_new0(ImgBitmapAction
, 1);
4757 act
->act
= BITMAP_MERGE
;
4759 QSIMPLEQ_INSERT_TAIL(&actions
, act
, next
);
4763 user_creatable_process_cmdline(optarg
);
4765 case OPTION_IMAGE_OPTS
:
4771 if (QSIMPLEQ_EMPTY(&actions
)) {
4772 error_report("Need at least one of --add, --remove, --clear, "
4773 "--enable, --disable, or --merge");
4777 if (granularity
&& !add
) {
4778 error_report("granularity only supported with --add");
4781 if (src_fmt
&& !src_filename
) {
4782 error_report("-F only supported with -b");
4785 if (src_filename
&& !merge
) {
4786 error_report("Merge bitmap source file only supported with "
4791 if (optind
!= argc
- 2) {
4792 error_report("Expecting filename and bitmap name");
4796 filename
= argv
[optind
];
4797 bitmap
= argv
[optind
+ 1];
4800 * No need to open backing chains; we will be manipulating bitmaps
4801 * directly in this image without reference to image contents.
4803 blk
= img_open(image_opts
, filename
, fmt
, BDRV_O_RDWR
| BDRV_O_NO_BACKING
,
4804 false, false, false);
4810 src
= img_open(false, src_filename
, src_fmt
, BDRV_O_NO_BACKING
,
4811 false, false, false);
4815 src_bs
= blk_bs(src
);
4820 QSIMPLEQ_FOREACH_SAFE(act
, &actions
, next
, act_next
) {
4823 qmp_block_dirty_bitmap_add(bs
->node_name
, bitmap
,
4824 !!granularity
, granularity
, true, true,
4825 false, false, &err
);
4829 qmp_block_dirty_bitmap_remove(bs
->node_name
, bitmap
, &err
);
4833 qmp_block_dirty_bitmap_clear(bs
->node_name
, bitmap
, &err
);
4837 qmp_block_dirty_bitmap_enable(bs
->node_name
, bitmap
, &err
);
4840 case BITMAP_DISABLE
:
4841 qmp_block_dirty_bitmap_disable(bs
->node_name
, bitmap
, &err
);
4845 do_dirty_bitmap_merge(bs
->node_name
, bitmap
, src_bs
->node_name
,
4850 g_assert_not_reached();
4854 error_reportf_err(err
, "Operation %s on bitmap %s failed: ",
4865 * Manually inactivate the images first because this way we can know whether
4866 * an error occurred. blk_unref() doesn't tell us about failures.
4868 inactivate_ret
= bdrv_inactivate_all();
4869 if (inactivate_ret
< 0) {
4870 error_report("Error while closing the image: %s", strerror(-inactivate_ret
));
4876 qemu_opts_del(opts
);
4892 int bsz
; /* Block size */
4900 int (*f
)(const char *, struct DdIo
*, struct DdIo
*, struct DdInfo
*);
4904 static int img_dd_bs(const char *arg
,
4905 struct DdIo
*in
, struct DdIo
*out
,
4910 res
= cvtnum_full("bs", arg
, 1, INT_MAX
);
4915 in
->bsz
= out
->bsz
= res
;
4920 static int img_dd_count(const char *arg
,
4921 struct DdIo
*in
, struct DdIo
*out
,
4924 dd
->count
= cvtnum("count", arg
);
4926 if (dd
->count
< 0) {
4933 static int img_dd_if(const char *arg
,
4934 struct DdIo
*in
, struct DdIo
*out
,
4937 in
->filename
= g_strdup(arg
);
4942 static int img_dd_of(const char *arg
,
4943 struct DdIo
*in
, struct DdIo
*out
,
4946 out
->filename
= g_strdup(arg
);
4951 static int img_dd_skip(const char *arg
,
4952 struct DdIo
*in
, struct DdIo
*out
,
4955 in
->offset
= cvtnum("skip", arg
);
4957 if (in
->offset
< 0) {
4964 static int img_dd(int argc
, char **argv
)
4969 BlockDriver
*drv
= NULL
, *proto_drv
= NULL
;
4970 BlockBackend
*blk1
= NULL
, *blk2
= NULL
;
4971 QemuOpts
*opts
= NULL
;
4972 QemuOptsList
*create_opts
= NULL
;
4973 Error
*local_err
= NULL
;
4974 bool image_opts
= false;
4976 const char *out_fmt
= "raw";
4977 const char *fmt
= NULL
;
4979 int64_t out_pos
, in_pos
;
4980 bool force_share
= false;
4981 struct DdInfo dd
= {
4986 .bsz
= 512, /* Block size is by default 512 bytes */
4998 const struct DdOpts options
[] = {
4999 { "bs", img_dd_bs
, C_BS
},
5000 { "count", img_dd_count
, C_COUNT
},
5001 { "if", img_dd_if
, C_IF
},
5002 { "of", img_dd_of
, C_OF
},
5003 { "skip", img_dd_skip
, C_SKIP
},
5006 const struct option long_options
[] = {
5007 { "help", no_argument
, 0, 'h'},
5008 { "object", required_argument
, 0, OPTION_OBJECT
},
5009 { "image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5010 { "force-share", no_argument
, 0, 'U'},
5014 while ((c
= getopt_long(argc
, argv
, ":hf:O:U", long_options
, NULL
))) {
5026 missing_argument(argv
[optind
- 1]);
5029 unrecognized_option(argv
[optind
- 1]);
5038 user_creatable_process_cmdline(optarg
);
5040 case OPTION_IMAGE_OPTS
:
5046 for (i
= optind
; i
< argc
; i
++) {
5048 arg
= g_strdup(argv
[i
]);
5050 tmp
= strchr(arg
, '=');
5052 error_report("unrecognized operand %s", arg
);
5059 for (j
= 0; options
[j
].name
!= NULL
; j
++) {
5060 if (!strcmp(arg
, options
[j
].name
)) {
5064 if (options
[j
].name
== NULL
) {
5065 error_report("unrecognized operand %s", arg
);
5070 if (options
[j
].f(tmp
, &in
, &out
, &dd
) != 0) {
5074 dd
.flags
|= options
[j
].flag
;
5079 if (!(dd
.flags
& C_IF
&& dd
.flags
& C_OF
)) {
5080 error_report("Must specify both input and output files");
5085 blk1
= img_open(image_opts
, in
.filename
, fmt
, 0, false, false,
5093 drv
= bdrv_find_format(out_fmt
);
5095 error_report("Unknown file format");
5099 proto_drv
= bdrv_find_protocol(out
.filename
, true, &local_err
);
5102 error_report_err(local_err
);
5106 if (!drv
->create_opts
) {
5107 error_report("Format driver '%s' does not support image creation",
5112 if (!proto_drv
->create_opts
) {
5113 error_report("Protocol driver '%s' does not support image creation",
5114 proto_drv
->format_name
);
5118 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5119 create_opts
= qemu_opts_append(create_opts
, proto_drv
->create_opts
);
5121 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5123 size
= blk_getlength(blk1
);
5125 error_report("Failed to get size for '%s'", in
.filename
);
5130 if (dd
.flags
& C_COUNT
&& dd
.count
<= INT64_MAX
/ in
.bsz
&&
5131 dd
.count
* in
.bsz
< size
) {
5132 size
= dd
.count
* in
.bsz
;
5135 /* Overflow means the specified offset is beyond input image's size */
5136 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5137 size
< in
.bsz
* in
.offset
)) {
5138 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, 0, &error_abort
);
5140 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
,
5141 size
- in
.bsz
* in
.offset
, &error_abort
);
5144 ret
= bdrv_create(drv
, out
.filename
, opts
, &local_err
);
5146 error_reportf_err(local_err
,
5147 "%s: error while creating output image: ",
5153 /* TODO, we can't honour --image-opts for the target,
5154 * since it needs to be given in a format compatible
5155 * with the bdrv_create() call above which does not
5156 * support image-opts style.
5158 blk2
= img_open_file(out
.filename
, NULL
, out_fmt
, BDRV_O_RDWR
,
5159 false, false, false);
5166 if (dd
.flags
& C_SKIP
&& (in
.offset
> INT64_MAX
/ in
.bsz
||
5167 size
< in
.offset
* in
.bsz
)) {
5168 /* We give a warning if the skip option is bigger than the input
5169 * size and create an empty output disk image (i.e. like dd(1)).
5171 error_report("%s: cannot skip to specified offset", in
.filename
);
5174 in_pos
= in
.offset
* in
.bsz
;
5177 in
.buf
= g_new(uint8_t, in
.bsz
);
5179 for (out_pos
= 0; in_pos
< size
; ) {
5180 int bytes
= (in_pos
+ in
.bsz
> size
) ? size
- in_pos
: in
.bsz
;
5182 ret
= blk_pread(blk1
, in_pos
, bytes
, in
.buf
, 0);
5184 error_report("error while reading from input image file: %s",
5190 ret
= blk_pwrite(blk2
, out_pos
, bytes
, in
.buf
, 0);
5192 error_report("error while writing to output image file: %s",
5201 qemu_opts_del(opts
);
5202 qemu_opts_free(create_opts
);
5205 g_free(in
.filename
);
5206 g_free(out
.filename
);
5216 static void dump_json_block_measure_info(BlockMeasureInfo
*info
)
5220 Visitor
*v
= qobject_output_visitor_new(&obj
);
5222 visit_type_BlockMeasureInfo(v
, NULL
, &info
, &error_abort
);
5223 visit_complete(v
, &obj
);
5224 str
= qobject_to_json_pretty(obj
, true);
5225 assert(str
!= NULL
);
5226 printf("%s\n", str
->str
);
5229 g_string_free(str
, true);
5232 static int img_measure(int argc
, char **argv
)
5234 static const struct option long_options
[] = {
5235 {"help", no_argument
, 0, 'h'},
5236 {"image-opts", no_argument
, 0, OPTION_IMAGE_OPTS
},
5237 {"object", required_argument
, 0, OPTION_OBJECT
},
5238 {"output", required_argument
, 0, OPTION_OUTPUT
},
5239 {"size", required_argument
, 0, OPTION_SIZE
},
5240 {"force-share", no_argument
, 0, 'U'},
5243 OutputFormat output_format
= OFORMAT_HUMAN
;
5244 BlockBackend
*in_blk
= NULL
;
5246 const char *filename
= NULL
;
5247 const char *fmt
= NULL
;
5248 const char *out_fmt
= "raw";
5249 char *options
= NULL
;
5250 char *snapshot_name
= NULL
;
5251 bool force_share
= false;
5252 QemuOpts
*opts
= NULL
;
5253 QemuOpts
*object_opts
= NULL
;
5254 QemuOpts
*sn_opts
= NULL
;
5255 QemuOptsList
*create_opts
= NULL
;
5256 bool image_opts
= false;
5257 uint64_t img_size
= UINT64_MAX
;
5258 BlockMeasureInfo
*info
= NULL
;
5259 Error
*local_err
= NULL
;
5263 while ((c
= getopt_long(argc
, argv
, "hf:O:o:l:U",
5264 long_options
, NULL
)) != -1) {
5277 if (accumulate_options(&options
, optarg
) < 0) {
5282 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
5283 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
5286 error_report("Failed in parsing snapshot param '%s'",
5291 snapshot_name
= optarg
;
5298 user_creatable_process_cmdline(optarg
);
5300 case OPTION_IMAGE_OPTS
:
5304 if (!strcmp(optarg
, "json")) {
5305 output_format
= OFORMAT_JSON
;
5306 } else if (!strcmp(optarg
, "human")) {
5307 output_format
= OFORMAT_HUMAN
;
5309 error_report("--output must be used with human or json "
5318 sval
= cvtnum("image size", optarg
);
5322 img_size
= (uint64_t)sval
;
5328 if (argc
- optind
> 1) {
5329 error_report("At most one filename argument is allowed.");
5331 } else if (argc
- optind
== 1) {
5332 filename
= argv
[optind
];
5335 if (!filename
&& (image_opts
|| fmt
|| snapshot_name
|| sn_opts
)) {
5336 error_report("--image-opts, -f, and -l require a filename argument.");
5339 if (filename
&& img_size
!= UINT64_MAX
) {
5340 error_report("--size N cannot be used together with a filename.");
5343 if (!filename
&& img_size
== UINT64_MAX
) {
5344 error_report("Either --size N or one filename must be specified.");
5349 in_blk
= img_open(image_opts
, filename
, fmt
, 0,
5350 false, false, force_share
);
5356 bdrv_snapshot_load_tmp(blk_bs(in_blk
),
5357 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
5358 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
5360 } else if (snapshot_name
!= NULL
) {
5361 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk
),
5362 snapshot_name
, &local_err
);
5365 error_reportf_err(local_err
, "Failed to load snapshot: ");
5370 drv
= bdrv_find_format(out_fmt
);
5372 error_report("Unknown file format '%s'", out_fmt
);
5375 if (!drv
->create_opts
) {
5376 error_report("Format driver '%s' does not support image creation",
5381 create_opts
= qemu_opts_append(create_opts
, drv
->create_opts
);
5382 create_opts
= qemu_opts_append(create_opts
, bdrv_file
.create_opts
);
5383 opts
= qemu_opts_create(create_opts
, NULL
, 0, &error_abort
);
5385 if (!qemu_opts_do_parse(opts
, options
, NULL
, &local_err
)) {
5386 error_report_err(local_err
);
5387 error_report("Invalid options for file format '%s'", out_fmt
);
5391 if (img_size
!= UINT64_MAX
) {
5392 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, img_size
, &error_abort
);
5395 info
= bdrv_measure(drv
, opts
, in_blk
? blk_bs(in_blk
) : NULL
, &local_err
);
5397 error_report_err(local_err
);
5401 if (output_format
== OFORMAT_HUMAN
) {
5402 printf("required size: %" PRIu64
"\n", info
->required
);
5403 printf("fully allocated size: %" PRIu64
"\n", info
->fully_allocated
);
5404 if (info
->has_bitmaps
) {
5405 printf("bitmaps size: %" PRIu64
"\n", info
->bitmaps
);
5408 dump_json_block_measure_info(info
);
5414 qapi_free_BlockMeasureInfo(info
);
5415 qemu_opts_del(object_opts
);
5416 qemu_opts_del(opts
);
5417 qemu_opts_del(sn_opts
);
5418 qemu_opts_free(create_opts
);
5424 static const img_cmd_t img_cmds
[] = {
5425 #define DEF(option, callback, arg_string) \
5426 { option, callback },
5427 #include "qemu-img-cmds.h"
5432 int main(int argc
, char **argv
)
5434 const img_cmd_t
*cmd
;
5435 const char *cmdname
;
5437 static const struct option long_options
[] = {
5438 {"help", no_argument
, 0, 'h'},
5439 {"version", no_argument
, 0, 'V'},
5440 {"trace", required_argument
, NULL
, 'T'},
5445 signal(SIGPIPE
, SIG_IGN
);
5449 error_init(argv
[0]);
5450 module_call_init(MODULE_INIT_TRACE
);
5451 qemu_init_exec_dir(argv
[0]);
5453 qemu_init_main_loop(&error_fatal
);
5455 qcrypto_init(&error_fatal
);
5457 module_call_init(MODULE_INIT_QOM
);
5460 error_exit("Not enough arguments");
5463 qemu_add_opts(&qemu_source_opts
);
5464 qemu_add_opts(&qemu_trace_opts
);
5466 while ((c
= getopt_long(argc
, argv
, "+:hVT:", long_options
, NULL
)) != -1) {
5469 missing_argument(argv
[optind
- 1]);
5472 unrecognized_option(argv
[optind
- 1]);
5478 printf(QEMU_IMG_VERSION
);
5481 trace_opt_parse(optarg
);
5486 cmdname
= argv
[optind
];
5488 /* reset getopt_long scanning */
5494 qemu_reset_optind();
5496 if (!trace_init_backends()) {
5500 qemu_set_log(LOG_TRACE
, &error_fatal
);
5502 /* find the command */
5503 for (cmd
= img_cmds
; cmd
->name
!= NULL
; cmd
++) {
5504 if (!strcmp(cmdname
, cmd
->name
)) {
5505 return cmd
->handler(argc
, argv
);
5510 error_exit("Command not found: %s", cmdname
);