qemu-img: Add convert --bitmaps option
[qemu/ericb.git] / qemu-img.c
blob8ecebe17889037c03875cba4e25bf6b199badbc3
1 /*
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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include <getopt.h>
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qemu/cutils.h"
38 #include "qemu/config-file.h"
39 #include "qemu/option.h"
40 #include "qemu/error-report.h"
41 #include "qemu/log.h"
42 #include "qemu/main-loop.h"
43 #include "qemu/module.h"
44 #include "qemu/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
53 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
54 "\n" QEMU_COPYRIGHT "\n"
56 typedef struct img_cmd_t {
57 const char *name;
58 int (*handler)(int argc, char **argv);
59 } img_cmd_t;
61 enum {
62 OPTION_OUTPUT = 256,
63 OPTION_BACKING_CHAIN = 257,
64 OPTION_OBJECT = 258,
65 OPTION_IMAGE_OPTS = 259,
66 OPTION_PATTERN = 260,
67 OPTION_FLUSH_INTERVAL = 261,
68 OPTION_NO_DRAIN = 262,
69 OPTION_TARGET_IMAGE_OPTS = 263,
70 OPTION_SIZE = 264,
71 OPTION_PREALLOCATION = 265,
72 OPTION_SHRINK = 266,
73 OPTION_SALVAGE = 267,
74 OPTION_TARGET_IS_ZERO = 268,
75 OPTION_ADD = 269,
76 OPTION_REMOVE = 270,
77 OPTION_CLEAR = 271,
78 OPTION_ENABLE = 272,
79 OPTION_DISABLE = 273,
80 OPTION_MERGE = 274,
81 OPTION_BITMAPS = 275,
84 typedef enum OutputFormat {
85 OFORMAT_JSON,
86 OFORMAT_HUMAN,
87 } OutputFormat;
89 /* Default to cache=writeback as data integrity is not important for qemu-img */
90 #define BDRV_DEFAULT_CACHE "writeback"
92 static void format_print(void *opaque, const char *name)
94 printf(" %s", name);
97 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
99 va_list ap;
101 va_start(ap, fmt);
102 error_vreport(fmt, ap);
103 va_end(ap);
105 error_printf("Try 'qemu-img --help' for more information\n");
106 exit(EXIT_FAILURE);
109 static void QEMU_NORETURN missing_argument(const char *option)
111 error_exit("missing argument for option '%s'", option);
114 static void QEMU_NORETURN unrecognized_option(const char *option)
116 error_exit("unrecognized option '%s'", option);
119 /* Please keep in synch with docs/tools/qemu-img.rst */
120 static void QEMU_NORETURN help(void)
122 const char *help_msg =
123 QEMU_IMG_VERSION
124 "usage: qemu-img [standard options] command [command options]\n"
125 "QEMU disk image utility\n"
126 "\n"
127 " '-h', '--help' display this help and exit\n"
128 " '-V', '--version' output version information and exit\n"
129 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
130 " specify tracing options\n"
131 "\n"
132 "Command syntax:\n"
133 #define DEF(option, callback, arg_string) \
134 " " arg_string "\n"
135 #include "qemu-img-cmds.h"
136 #undef DEF
137 "\n"
138 "Command parameters:\n"
139 " 'filename' is a disk image filename\n"
140 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
141 " manual page for a description of the object properties. The most common\n"
142 " object type is a 'secret', which is used to supply passwords and/or\n"
143 " encryption keys.\n"
144 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
145 " 'cache' is the cache mode used to write the output disk image, the valid\n"
146 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
147 " 'directsync' and 'unsafe' (default for convert)\n"
148 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
149 " options are the same as for the 'cache' option\n"
150 " 'size' is the disk image size in bytes. Optional suffixes\n"
151 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
152 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
153 " supported. 'b' is ignored.\n"
154 " 'output_filename' is the destination disk image filename\n"
155 " 'output_fmt' is the destination format\n"
156 " 'options' is a comma separated list of format specific options in a\n"
157 " name=value format. Use -o ? for an overview of the options supported by the\n"
158 " used format\n"
159 " 'snapshot_param' is param used for internal snapshot, format\n"
160 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
161 " '[ID_OR_NAME]'\n"
162 " '-c' indicates that target image must be compressed (qcow format only)\n"
163 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
164 " new backing file match exactly. The image doesn't need a working\n"
165 " backing file before rebasing in this case (useful for renaming the\n"
166 " backing file). For image creation, allow creating without attempting\n"
167 " to open the backing file.\n"
168 " '-h' with or without a command shows this help and lists the supported formats\n"
169 " '-p' show progress of command (only certain commands)\n"
170 " '-q' use Quiet mode - do not print any output (except errors)\n"
171 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
172 " contain only zeros for qemu-img to create a sparse image during\n"
173 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
174 " unallocated or zero sectors, and the destination image will always be\n"
175 " fully allocated\n"
176 " '--output' takes the format in which the output must be done (human or json)\n"
177 " '-n' skips the target volume creation (useful if the volume is created\n"
178 " prior to running qemu-img)\n"
179 "\n"
180 "Parameters to bitmap subcommand:\n"
181 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
182 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
183 " or '--merge source'\n"
184 " '-g granularity' sets the granularity for '--add' actions\n"
185 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
186 " bitmaps from an alternative file\n"
187 "\n"
188 "Parameters to check subcommand:\n"
189 " '-r' tries to repair any inconsistencies that are found during the check.\n"
190 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
191 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
192 " hiding corruption that has already occurred.\n"
193 "\n"
194 "Parameters to convert subcommand:\n"
195 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
196 " '-m' specifies how many coroutines work in parallel during the convert\n"
197 " process (defaults to 8)\n"
198 " '-W' allow to write to the target out of order rather than sequential\n"
199 "\n"
200 "Parameters to snapshot subcommand:\n"
201 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
202 " '-a' applies a snapshot (revert disk to saved state)\n"
203 " '-c' creates a snapshot\n"
204 " '-d' deletes a snapshot\n"
205 " '-l' lists all snapshots in the given image\n"
206 "\n"
207 "Parameters to compare subcommand:\n"
208 " '-f' first image format\n"
209 " '-F' second image format\n"
210 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
211 "\n"
212 "Parameters to dd subcommand:\n"
213 " 'bs=BYTES' read and write up to BYTES bytes at a time "
214 "(default: 512)\n"
215 " 'count=N' copy only N input blocks\n"
216 " 'if=FILE' read from FILE\n"
217 " 'of=FILE' write to FILE\n"
218 " 'skip=N' skip N bs-sized blocks at the start of input\n";
220 printf("%s\nSupported formats:", help_msg);
221 bdrv_iterate_format(format_print, NULL, false);
222 printf("\n\n" QEMU_HELP_BOTTOM "\n");
223 exit(EXIT_SUCCESS);
226 static QemuOptsList qemu_object_opts = {
227 .name = "object",
228 .implied_opt_name = "qom-type",
229 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
230 .desc = {
235 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
237 if (user_creatable_print_help(type, opts)) {
238 exit(0);
240 return true;
244 * Is @optarg safe for accumulate_options()?
245 * It is when multiple of them can be joined together separated by ','.
246 * To make that work, @optarg must not start with ',' (or else a
247 * separating ',' preceding it gets escaped), and it must not end with
248 * an odd number of ',' (or else a separating ',' following it gets
249 * escaped), or be empty (or else a separating ',' preceding it can
250 * escape a separating ',' following it).
253 static bool is_valid_option_list(const char *optarg)
255 size_t len = strlen(optarg);
256 size_t i;
258 if (!optarg[0] || optarg[0] == ',') {
259 return false;
262 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
264 if ((len - i) % 2) {
265 return false;
268 return true;
271 static int accumulate_options(char **options, char *optarg)
273 char *new_options;
275 if (!is_valid_option_list(optarg)) {
276 error_report("Invalid option list: %s", optarg);
277 return -1;
280 if (!*options) {
281 *options = g_strdup(optarg);
282 } else {
283 new_options = g_strdup_printf("%s,%s", *options, optarg);
284 g_free(*options);
285 *options = new_options;
287 return 0;
290 static QemuOptsList qemu_source_opts = {
291 .name = "source",
292 .implied_opt_name = "file",
293 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
294 .desc = {
299 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
301 int ret = 0;
302 if (!quiet) {
303 va_list args;
304 va_start(args, fmt);
305 ret = vprintf(fmt, args);
306 va_end(args);
308 return ret;
312 static int print_block_option_help(const char *filename, const char *fmt)
314 BlockDriver *drv, *proto_drv;
315 QemuOptsList *create_opts = NULL;
316 Error *local_err = NULL;
318 /* Find driver and parse its options */
319 drv = bdrv_find_format(fmt);
320 if (!drv) {
321 error_report("Unknown file format '%s'", fmt);
322 return 1;
325 if (!drv->create_opts) {
326 error_report("Format driver '%s' does not support image creation", fmt);
327 return 1;
330 create_opts = qemu_opts_append(create_opts, drv->create_opts);
331 if (filename) {
332 proto_drv = bdrv_find_protocol(filename, true, &local_err);
333 if (!proto_drv) {
334 error_report_err(local_err);
335 qemu_opts_free(create_opts);
336 return 1;
338 if (!proto_drv->create_opts) {
339 error_report("Protocol driver '%s' does not support image creation",
340 proto_drv->format_name);
341 qemu_opts_free(create_opts);
342 return 1;
344 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
347 if (filename) {
348 printf("Supported options:\n");
349 } else {
350 printf("Supported %s options:\n", fmt);
352 qemu_opts_print_help(create_opts, false);
353 qemu_opts_free(create_opts);
355 if (!filename) {
356 printf("\n"
357 "The protocol level may support further options.\n"
358 "Specify the target filename to include those options.\n");
361 return 0;
365 static BlockBackend *img_open_opts(const char *optstr,
366 QemuOpts *opts, int flags, bool writethrough,
367 bool quiet, bool force_share)
369 QDict *options;
370 Error *local_err = NULL;
371 BlockBackend *blk;
372 options = qemu_opts_to_qdict(opts, NULL);
373 if (force_share) {
374 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
375 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
376 error_report("--force-share/-U conflicts with image options");
377 qobject_unref(options);
378 return NULL;
380 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
382 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
383 if (!blk) {
384 error_reportf_err(local_err, "Could not open '%s': ", optstr);
385 return NULL;
387 blk_set_enable_write_cache(blk, !writethrough);
389 return blk;
392 static BlockBackend *img_open_file(const char *filename,
393 QDict *options,
394 const char *fmt, int flags,
395 bool writethrough, bool quiet,
396 bool force_share)
398 BlockBackend *blk;
399 Error *local_err = NULL;
401 if (!options) {
402 options = qdict_new();
404 if (fmt) {
405 qdict_put_str(options, "driver", fmt);
408 if (force_share) {
409 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
411 blk = blk_new_open(filename, NULL, options, flags, &local_err);
412 if (!blk) {
413 error_reportf_err(local_err, "Could not open '%s': ", filename);
414 return NULL;
416 blk_set_enable_write_cache(blk, !writethrough);
418 return blk;
422 static int img_add_key_secrets(void *opaque,
423 const char *name, const char *value,
424 Error **errp)
426 QDict *options = opaque;
428 if (g_str_has_suffix(name, "key-secret")) {
429 qdict_put_str(options, name, value);
432 return 0;
436 static BlockBackend *img_open(bool image_opts,
437 const char *filename,
438 const char *fmt, int flags, bool writethrough,
439 bool quiet, bool force_share)
441 BlockBackend *blk;
442 if (image_opts) {
443 QemuOpts *opts;
444 if (fmt) {
445 error_report("--image-opts and --format are mutually exclusive");
446 return NULL;
448 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
449 filename, true);
450 if (!opts) {
451 return NULL;
453 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
454 force_share);
455 } else {
456 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
457 force_share);
459 return blk;
463 static int add_old_style_options(const char *fmt, QemuOpts *opts,
464 const char *base_filename,
465 const char *base_fmt)
467 Error *err = NULL;
469 if (base_filename) {
470 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
471 if (err) {
472 error_report("Backing file not supported for file format '%s'",
473 fmt);
474 error_free(err);
475 return -1;
478 if (base_fmt) {
479 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
480 if (err) {
481 error_report("Backing file format not supported for file "
482 "format '%s'", fmt);
483 error_free(err);
484 return -1;
487 return 0;
490 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
491 int64_t max)
493 int err;
494 uint64_t res;
496 err = qemu_strtosz(value, NULL, &res);
497 if (err < 0 && err != -ERANGE) {
498 error_report("Invalid %s specified. You may use "
499 "k, M, G, T, P or E suffixes for", name);
500 error_report("kilobytes, megabytes, gigabytes, terabytes, "
501 "petabytes and exabytes.");
502 return err;
504 if (err == -ERANGE || res > max || res < min) {
505 error_report("Invalid %s specified. Must be between %" PRId64
506 " and %" PRId64 ".", name, min, max);
507 return -ERANGE;
509 return res;
512 static int64_t cvtnum(const char *name, const char *value)
514 return cvtnum_full(name, value, 0, INT64_MAX);
517 static int img_create(int argc, char **argv)
519 int c;
520 uint64_t img_size = -1;
521 const char *fmt = "raw";
522 const char *base_fmt = NULL;
523 const char *filename;
524 const char *base_filename = NULL;
525 char *options = NULL;
526 Error *local_err = NULL;
527 bool quiet = false;
528 int flags = 0;
530 for(;;) {
531 static const struct option long_options[] = {
532 {"help", no_argument, 0, 'h'},
533 {"object", required_argument, 0, OPTION_OBJECT},
534 {0, 0, 0, 0}
536 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
537 long_options, NULL);
538 if (c == -1) {
539 break;
541 switch(c) {
542 case ':':
543 missing_argument(argv[optind - 1]);
544 break;
545 case '?':
546 unrecognized_option(argv[optind - 1]);
547 break;
548 case 'h':
549 help();
550 break;
551 case 'F':
552 base_fmt = optarg;
553 break;
554 case 'b':
555 base_filename = optarg;
556 break;
557 case 'f':
558 fmt = optarg;
559 break;
560 case 'o':
561 if (accumulate_options(&options, optarg) < 0) {
562 goto fail;
564 break;
565 case 'q':
566 quiet = true;
567 break;
568 case 'u':
569 flags |= BDRV_O_NO_BACKING;
570 break;
571 case OPTION_OBJECT: {
572 QemuOpts *opts;
573 opts = qemu_opts_parse_noisily(&qemu_object_opts,
574 optarg, true);
575 if (!opts) {
576 goto fail;
578 } break;
582 /* Get the filename */
583 filename = (optind < argc) ? argv[optind] : NULL;
584 if (options && has_help_option(options)) {
585 g_free(options);
586 return print_block_option_help(filename, fmt);
589 if (optind >= argc) {
590 error_exit("Expecting image file name");
592 optind++;
594 if (qemu_opts_foreach(&qemu_object_opts,
595 user_creatable_add_opts_foreach,
596 qemu_img_object_print_help, &error_fatal)) {
597 goto fail;
600 /* Get image size, if specified */
601 if (optind < argc) {
602 int64_t sval;
604 sval = cvtnum("image size", argv[optind++]);
605 if (sval < 0) {
606 goto fail;
608 img_size = (uint64_t)sval;
610 if (optind != argc) {
611 error_exit("Unexpected argument: %s", argv[optind]);
614 bdrv_img_create(filename, fmt, base_filename, base_fmt,
615 options, img_size, flags, quiet, &local_err);
616 if (local_err) {
617 error_reportf_err(local_err, "%s: ", filename);
618 goto fail;
621 g_free(options);
622 return 0;
624 fail:
625 g_free(options);
626 return 1;
629 static void dump_json_image_check(ImageCheck *check, bool quiet)
631 QString *str;
632 QObject *obj;
633 Visitor *v = qobject_output_visitor_new(&obj);
635 visit_type_ImageCheck(v, NULL, &check, &error_abort);
636 visit_complete(v, &obj);
637 str = qobject_to_json_pretty(obj);
638 assert(str != NULL);
639 qprintf(quiet, "%s\n", qstring_get_str(str));
640 qobject_unref(obj);
641 visit_free(v);
642 qobject_unref(str);
645 static void dump_human_image_check(ImageCheck *check, bool quiet)
647 if (!(check->corruptions || check->leaks || check->check_errors)) {
648 qprintf(quiet, "No errors were found on the image.\n");
649 } else {
650 if (check->corruptions) {
651 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
652 "Data may be corrupted, or further writes to the image "
653 "may corrupt it.\n",
654 check->corruptions);
657 if (check->leaks) {
658 qprintf(quiet,
659 "\n%" PRId64 " leaked clusters were found on the image.\n"
660 "This means waste of disk space, but no harm to data.\n",
661 check->leaks);
664 if (check->check_errors) {
665 qprintf(quiet,
666 "\n%" PRId64
667 " internal errors have occurred during the check.\n",
668 check->check_errors);
672 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
673 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
674 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
675 check->allocated_clusters, check->total_clusters,
676 check->allocated_clusters * 100.0 / check->total_clusters,
677 check->fragmented_clusters * 100.0 / check->allocated_clusters,
678 check->compressed_clusters * 100.0 /
679 check->allocated_clusters);
682 if (check->image_end_offset) {
683 qprintf(quiet,
684 "Image end offset: %" PRId64 "\n", check->image_end_offset);
688 static int collect_image_check(BlockDriverState *bs,
689 ImageCheck *check,
690 const char *filename,
691 const char *fmt,
692 int fix)
694 int ret;
695 BdrvCheckResult result;
697 ret = bdrv_check(bs, &result, fix);
698 if (ret < 0) {
699 return ret;
702 check->filename = g_strdup(filename);
703 check->format = g_strdup(bdrv_get_format_name(bs));
704 check->check_errors = result.check_errors;
705 check->corruptions = result.corruptions;
706 check->has_corruptions = result.corruptions != 0;
707 check->leaks = result.leaks;
708 check->has_leaks = result.leaks != 0;
709 check->corruptions_fixed = result.corruptions_fixed;
710 check->has_corruptions_fixed = result.corruptions_fixed != 0;
711 check->leaks_fixed = result.leaks_fixed;
712 check->has_leaks_fixed = result.leaks_fixed != 0;
713 check->image_end_offset = result.image_end_offset;
714 check->has_image_end_offset = result.image_end_offset != 0;
715 check->total_clusters = result.bfi.total_clusters;
716 check->has_total_clusters = result.bfi.total_clusters != 0;
717 check->allocated_clusters = result.bfi.allocated_clusters;
718 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
719 check->fragmented_clusters = result.bfi.fragmented_clusters;
720 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
721 check->compressed_clusters = result.bfi.compressed_clusters;
722 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
724 return 0;
728 * Checks an image for consistency. Exit codes:
730 * 0 - Check completed, image is good
731 * 1 - Check not completed because of internal errors
732 * 2 - Check completed, image is corrupted
733 * 3 - Check completed, image has leaked clusters, but is good otherwise
734 * 63 - Checks are not supported by the image format
736 static int img_check(int argc, char **argv)
738 int c, ret;
739 OutputFormat output_format = OFORMAT_HUMAN;
740 const char *filename, *fmt, *output, *cache;
741 BlockBackend *blk;
742 BlockDriverState *bs;
743 int fix = 0;
744 int flags = BDRV_O_CHECK;
745 bool writethrough;
746 ImageCheck *check;
747 bool quiet = false;
748 bool image_opts = false;
749 bool force_share = false;
751 fmt = NULL;
752 output = NULL;
753 cache = BDRV_DEFAULT_CACHE;
755 for(;;) {
756 int option_index = 0;
757 static const struct option long_options[] = {
758 {"help", no_argument, 0, 'h'},
759 {"format", required_argument, 0, 'f'},
760 {"repair", required_argument, 0, 'r'},
761 {"output", required_argument, 0, OPTION_OUTPUT},
762 {"object", required_argument, 0, OPTION_OBJECT},
763 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
764 {"force-share", no_argument, 0, 'U'},
765 {0, 0, 0, 0}
767 c = getopt_long(argc, argv, ":hf:r:T:qU",
768 long_options, &option_index);
769 if (c == -1) {
770 break;
772 switch(c) {
773 case ':':
774 missing_argument(argv[optind - 1]);
775 break;
776 case '?':
777 unrecognized_option(argv[optind - 1]);
778 break;
779 case 'h':
780 help();
781 break;
782 case 'f':
783 fmt = optarg;
784 break;
785 case 'r':
786 flags |= BDRV_O_RDWR;
788 if (!strcmp(optarg, "leaks")) {
789 fix = BDRV_FIX_LEAKS;
790 } else if (!strcmp(optarg, "all")) {
791 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
792 } else {
793 error_exit("Unknown option value for -r "
794 "(expecting 'leaks' or 'all'): %s", optarg);
796 break;
797 case OPTION_OUTPUT:
798 output = optarg;
799 break;
800 case 'T':
801 cache = optarg;
802 break;
803 case 'q':
804 quiet = true;
805 break;
806 case 'U':
807 force_share = true;
808 break;
809 case OPTION_OBJECT: {
810 QemuOpts *opts;
811 opts = qemu_opts_parse_noisily(&qemu_object_opts,
812 optarg, true);
813 if (!opts) {
814 return 1;
816 } break;
817 case OPTION_IMAGE_OPTS:
818 image_opts = true;
819 break;
822 if (optind != argc - 1) {
823 error_exit("Expecting one image file name");
825 filename = argv[optind++];
827 if (output && !strcmp(output, "json")) {
828 output_format = OFORMAT_JSON;
829 } else if (output && !strcmp(output, "human")) {
830 output_format = OFORMAT_HUMAN;
831 } else if (output) {
832 error_report("--output must be used with human or json as argument.");
833 return 1;
836 if (qemu_opts_foreach(&qemu_object_opts,
837 user_creatable_add_opts_foreach,
838 qemu_img_object_print_help, &error_fatal)) {
839 return 1;
842 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
843 if (ret < 0) {
844 error_report("Invalid source cache option: %s", cache);
845 return 1;
848 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
849 force_share);
850 if (!blk) {
851 return 1;
853 bs = blk_bs(blk);
855 check = g_new0(ImageCheck, 1);
856 ret = collect_image_check(bs, check, filename, fmt, fix);
858 if (ret == -ENOTSUP) {
859 error_report("This image format does not support checks");
860 ret = 63;
861 goto fail;
864 if (check->corruptions_fixed || check->leaks_fixed) {
865 int corruptions_fixed, leaks_fixed;
866 bool has_leaks_fixed, has_corruptions_fixed;
868 leaks_fixed = check->leaks_fixed;
869 has_leaks_fixed = check->has_leaks_fixed;
870 corruptions_fixed = check->corruptions_fixed;
871 has_corruptions_fixed = check->has_corruptions_fixed;
873 if (output_format == OFORMAT_HUMAN) {
874 qprintf(quiet,
875 "The following inconsistencies were found and repaired:\n\n"
876 " %" PRId64 " leaked clusters\n"
877 " %" PRId64 " corruptions\n\n"
878 "Double checking the fixed image now...\n",
879 check->leaks_fixed,
880 check->corruptions_fixed);
883 qapi_free_ImageCheck(check);
884 check = g_new0(ImageCheck, 1);
885 ret = collect_image_check(bs, check, filename, fmt, 0);
887 check->leaks_fixed = leaks_fixed;
888 check->has_leaks_fixed = has_leaks_fixed;
889 check->corruptions_fixed = corruptions_fixed;
890 check->has_corruptions_fixed = has_corruptions_fixed;
893 if (!ret) {
894 switch (output_format) {
895 case OFORMAT_HUMAN:
896 dump_human_image_check(check, quiet);
897 break;
898 case OFORMAT_JSON:
899 dump_json_image_check(check, quiet);
900 break;
904 if (ret || check->check_errors) {
905 if (ret) {
906 error_report("Check failed: %s", strerror(-ret));
907 } else {
908 error_report("Check failed");
910 ret = 1;
911 goto fail;
914 if (check->corruptions) {
915 ret = 2;
916 } else if (check->leaks) {
917 ret = 3;
918 } else {
919 ret = 0;
922 fail:
923 qapi_free_ImageCheck(check);
924 blk_unref(blk);
925 return ret;
928 typedef struct CommonBlockJobCBInfo {
929 BlockDriverState *bs;
930 Error **errp;
931 } CommonBlockJobCBInfo;
933 static void common_block_job_cb(void *opaque, int ret)
935 CommonBlockJobCBInfo *cbi = opaque;
937 if (ret < 0) {
938 error_setg_errno(cbi->errp, -ret, "Block job failed");
942 static void run_block_job(BlockJob *job, Error **errp)
944 AioContext *aio_context = blk_get_aio_context(job->blk);
945 int ret = 0;
947 aio_context_acquire(aio_context);
948 job_ref(&job->job);
949 do {
950 float progress = 0.0f;
951 aio_poll(aio_context, true);
952 if (job->job.progress.total) {
953 progress = (float)job->job.progress.current /
954 job->job.progress.total * 100.f;
956 qemu_progress_print(progress, 0);
957 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
959 if (!job_is_completed(&job->job)) {
960 ret = job_complete_sync(&job->job, errp);
961 } else {
962 ret = job->job.ret;
964 job_unref(&job->job);
965 aio_context_release(aio_context);
967 /* publish completion progress only when success */
968 if (!ret) {
969 qemu_progress_print(100.f, 0);
973 static int img_commit(int argc, char **argv)
975 int c, ret, flags;
976 const char *filename, *fmt, *cache, *base;
977 BlockBackend *blk;
978 BlockDriverState *bs, *base_bs;
979 BlockJob *job;
980 bool progress = false, quiet = false, drop = false;
981 bool writethrough;
982 Error *local_err = NULL;
983 CommonBlockJobCBInfo cbi;
984 bool image_opts = false;
985 AioContext *aio_context;
987 fmt = NULL;
988 cache = BDRV_DEFAULT_CACHE;
989 base = NULL;
990 for(;;) {
991 static const struct option long_options[] = {
992 {"help", no_argument, 0, 'h'},
993 {"object", required_argument, 0, OPTION_OBJECT},
994 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
995 {0, 0, 0, 0}
997 c = getopt_long(argc, argv, ":f:ht:b:dpq",
998 long_options, NULL);
999 if (c == -1) {
1000 break;
1002 switch(c) {
1003 case ':':
1004 missing_argument(argv[optind - 1]);
1005 break;
1006 case '?':
1007 unrecognized_option(argv[optind - 1]);
1008 break;
1009 case 'h':
1010 help();
1011 break;
1012 case 'f':
1013 fmt = optarg;
1014 break;
1015 case 't':
1016 cache = optarg;
1017 break;
1018 case 'b':
1019 base = optarg;
1020 /* -b implies -d */
1021 drop = true;
1022 break;
1023 case 'd':
1024 drop = true;
1025 break;
1026 case 'p':
1027 progress = true;
1028 break;
1029 case 'q':
1030 quiet = true;
1031 break;
1032 case OPTION_OBJECT: {
1033 QemuOpts *opts;
1034 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1035 optarg, true);
1036 if (!opts) {
1037 return 1;
1039 } break;
1040 case OPTION_IMAGE_OPTS:
1041 image_opts = true;
1042 break;
1046 /* Progress is not shown in Quiet mode */
1047 if (quiet) {
1048 progress = false;
1051 if (optind != argc - 1) {
1052 error_exit("Expecting one image file name");
1054 filename = argv[optind++];
1056 if (qemu_opts_foreach(&qemu_object_opts,
1057 user_creatable_add_opts_foreach,
1058 qemu_img_object_print_help, &error_fatal)) {
1059 return 1;
1062 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1063 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1064 if (ret < 0) {
1065 error_report("Invalid cache option: %s", cache);
1066 return 1;
1069 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1070 false);
1071 if (!blk) {
1072 return 1;
1074 bs = blk_bs(blk);
1076 qemu_progress_init(progress, 1.f);
1077 qemu_progress_print(0.f, 100);
1079 if (base) {
1080 base_bs = bdrv_find_backing_image(bs, base);
1081 if (!base_bs) {
1082 error_setg(&local_err,
1083 "Did not find '%s' in the backing chain of '%s'",
1084 base, filename);
1085 goto done;
1087 } else {
1088 /* This is different from QMP, which by default uses the deepest file in
1089 * the backing chain (i.e., the very base); however, the traditional
1090 * behavior of qemu-img commit is using the immediate backing file. */
1091 base_bs = backing_bs(bs);
1092 if (!base_bs) {
1093 error_setg(&local_err, "Image does not have a backing file");
1094 goto done;
1098 cbi = (CommonBlockJobCBInfo){
1099 .errp = &local_err,
1100 .bs = bs,
1103 aio_context = bdrv_get_aio_context(bs);
1104 aio_context_acquire(aio_context);
1105 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1106 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1107 &cbi, false, &local_err);
1108 aio_context_release(aio_context);
1109 if (local_err) {
1110 goto done;
1113 /* When the block job completes, the BlockBackend reference will point to
1114 * the old backing file. In order to avoid that the top image is already
1115 * deleted, so we can still empty it afterwards, increment the reference
1116 * counter here preemptively. */
1117 if (!drop) {
1118 bdrv_ref(bs);
1121 job = block_job_get("commit");
1122 assert(job);
1123 run_block_job(job, &local_err);
1124 if (local_err) {
1125 goto unref_backing;
1128 if (!drop) {
1129 BlockBackend *old_backing_blk;
1131 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1132 &local_err);
1133 if (!old_backing_blk) {
1134 goto unref_backing;
1136 ret = blk_make_empty(old_backing_blk, &local_err);
1137 blk_unref(old_backing_blk);
1138 if (ret == -ENOTSUP) {
1139 error_free(local_err);
1140 local_err = NULL;
1141 } else if (ret < 0) {
1142 goto unref_backing;
1146 unref_backing:
1147 if (!drop) {
1148 bdrv_unref(bs);
1151 done:
1152 qemu_progress_end();
1154 blk_unref(blk);
1156 if (local_err) {
1157 error_report_err(local_err);
1158 return 1;
1161 qprintf(quiet, "Image committed.\n");
1162 return 0;
1166 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1167 * of the first sector boundary within buf where the sector contains a
1168 * non-zero byte. This function is robust to a buffer that is not
1169 * sector-aligned.
1171 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1173 int64_t i;
1174 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1176 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1177 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1178 return i;
1181 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1182 return i;
1184 return -1;
1188 * Returns true iff the first sector pointed to by 'buf' contains at least
1189 * a non-NUL byte.
1191 * 'pnum' is set to the number of sectors (including and immediately following
1192 * the first one) that are known to be in the same allocated/unallocated state.
1193 * The function will try to align the end offset to alignment boundaries so
1194 * that the request will at least end aligned and consequtive requests will
1195 * also start at an aligned offset.
1197 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1198 int64_t sector_num, int alignment)
1200 bool is_zero;
1201 int i, tail;
1203 if (n <= 0) {
1204 *pnum = 0;
1205 return 0;
1207 is_zero = buffer_is_zero(buf, 512);
1208 for(i = 1; i < n; i++) {
1209 buf += 512;
1210 if (is_zero != buffer_is_zero(buf, 512)) {
1211 break;
1215 tail = (sector_num + i) & (alignment - 1);
1216 if (tail) {
1217 if (is_zero && i <= tail) {
1218 /* treat unallocated areas which only consist
1219 * of a small tail as allocated. */
1220 is_zero = false;
1222 if (!is_zero) {
1223 /* align up end offset of allocated areas. */
1224 i += alignment - tail;
1225 i = MIN(i, n);
1226 } else {
1227 /* align down end offset of zero areas. */
1228 i -= tail;
1231 *pnum = i;
1232 return !is_zero;
1236 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1237 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1238 * breaking up write requests for only small sparse areas.
1240 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1241 int min, int64_t sector_num, int alignment)
1243 int ret;
1244 int num_checked, num_used;
1246 if (n < min) {
1247 min = n;
1250 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1251 if (!ret) {
1252 return ret;
1255 num_used = *pnum;
1256 buf += BDRV_SECTOR_SIZE * *pnum;
1257 n -= *pnum;
1258 sector_num += *pnum;
1259 num_checked = num_used;
1261 while (n > 0) {
1262 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1264 buf += BDRV_SECTOR_SIZE * *pnum;
1265 n -= *pnum;
1266 sector_num += *pnum;
1267 num_checked += *pnum;
1268 if (ret) {
1269 num_used = num_checked;
1270 } else if (*pnum >= min) {
1271 break;
1275 *pnum = num_used;
1276 return 1;
1280 * Compares two buffers sector by sector. Returns 0 if the first
1281 * sector of each buffer matches, non-zero otherwise.
1283 * pnum is set to the sector-aligned size of the buffer prefix that
1284 * has the same matching status as the first sector.
1286 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1287 int64_t bytes, int64_t *pnum)
1289 bool res;
1290 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1292 assert(bytes > 0);
1294 res = !!memcmp(buf1, buf2, i);
1295 while (i < bytes) {
1296 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1298 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1299 break;
1301 i += len;
1304 *pnum = i;
1305 return res;
1308 #define IO_BUF_SIZE (2 * MiB)
1311 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1313 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1314 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1315 * failure), and 4 on error (the exit status for read errors), after emitting
1316 * an error message.
1318 * @param blk: BlockBackend for the image
1319 * @param offset: Starting offset to check
1320 * @param bytes: Number of bytes to check
1321 * @param filename: Name of disk file we are checking (logging purpose)
1322 * @param buffer: Allocated buffer for storing read data
1323 * @param quiet: Flag for quiet mode
1325 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1326 int64_t bytes, const char *filename,
1327 uint8_t *buffer, bool quiet)
1329 int ret = 0;
1330 int64_t idx;
1332 ret = blk_pread(blk, offset, buffer, bytes);
1333 if (ret < 0) {
1334 error_report("Error while reading offset %" PRId64 " of %s: %s",
1335 offset, filename, strerror(-ret));
1336 return 4;
1338 idx = find_nonzero(buffer, bytes);
1339 if (idx >= 0) {
1340 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1341 offset + idx);
1342 return 1;
1345 return 0;
1349 * Compares two images. Exit codes:
1351 * 0 - Images are identical
1352 * 1 - Images differ
1353 * >1 - Error occurred
1355 static int img_compare(int argc, char **argv)
1357 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1358 BlockBackend *blk1, *blk2;
1359 BlockDriverState *bs1, *bs2;
1360 int64_t total_size1, total_size2;
1361 uint8_t *buf1 = NULL, *buf2 = NULL;
1362 int64_t pnum1, pnum2;
1363 int allocated1, allocated2;
1364 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1365 bool progress = false, quiet = false, strict = false;
1366 int flags;
1367 bool writethrough;
1368 int64_t total_size;
1369 int64_t offset = 0;
1370 int64_t chunk;
1371 int c;
1372 uint64_t progress_base;
1373 bool image_opts = false;
1374 bool force_share = false;
1376 cache = BDRV_DEFAULT_CACHE;
1377 for (;;) {
1378 static const struct option long_options[] = {
1379 {"help", no_argument, 0, 'h'},
1380 {"object", required_argument, 0, OPTION_OBJECT},
1381 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1382 {"force-share", no_argument, 0, 'U'},
1383 {0, 0, 0, 0}
1385 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1386 long_options, NULL);
1387 if (c == -1) {
1388 break;
1390 switch (c) {
1391 case ':':
1392 missing_argument(argv[optind - 1]);
1393 break;
1394 case '?':
1395 unrecognized_option(argv[optind - 1]);
1396 break;
1397 case 'h':
1398 help();
1399 break;
1400 case 'f':
1401 fmt1 = optarg;
1402 break;
1403 case 'F':
1404 fmt2 = optarg;
1405 break;
1406 case 'T':
1407 cache = optarg;
1408 break;
1409 case 'p':
1410 progress = true;
1411 break;
1412 case 'q':
1413 quiet = true;
1414 break;
1415 case 's':
1416 strict = true;
1417 break;
1418 case 'U':
1419 force_share = true;
1420 break;
1421 case OPTION_OBJECT: {
1422 QemuOpts *opts;
1423 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1424 optarg, true);
1425 if (!opts) {
1426 ret = 2;
1427 goto out4;
1429 } break;
1430 case OPTION_IMAGE_OPTS:
1431 image_opts = true;
1432 break;
1436 /* Progress is not shown in Quiet mode */
1437 if (quiet) {
1438 progress = false;
1442 if (optind != argc - 2) {
1443 error_exit("Expecting two image file names");
1445 filename1 = argv[optind++];
1446 filename2 = argv[optind++];
1448 if (qemu_opts_foreach(&qemu_object_opts,
1449 user_creatable_add_opts_foreach,
1450 qemu_img_object_print_help, &error_fatal)) {
1451 ret = 2;
1452 goto out4;
1455 /* Initialize before goto out */
1456 qemu_progress_init(progress, 2.0);
1458 flags = 0;
1459 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1460 if (ret < 0) {
1461 error_report("Invalid source cache option: %s", cache);
1462 ret = 2;
1463 goto out3;
1466 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1467 force_share);
1468 if (!blk1) {
1469 ret = 2;
1470 goto out3;
1473 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1474 force_share);
1475 if (!blk2) {
1476 ret = 2;
1477 goto out2;
1479 bs1 = blk_bs(blk1);
1480 bs2 = blk_bs(blk2);
1482 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1483 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1484 total_size1 = blk_getlength(blk1);
1485 if (total_size1 < 0) {
1486 error_report("Can't get size of %s: %s",
1487 filename1, strerror(-total_size1));
1488 ret = 4;
1489 goto out;
1491 total_size2 = blk_getlength(blk2);
1492 if (total_size2 < 0) {
1493 error_report("Can't get size of %s: %s",
1494 filename2, strerror(-total_size2));
1495 ret = 4;
1496 goto out;
1498 total_size = MIN(total_size1, total_size2);
1499 progress_base = MAX(total_size1, total_size2);
1501 qemu_progress_print(0, 100);
1503 if (strict && total_size1 != total_size2) {
1504 ret = 1;
1505 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1506 goto out;
1509 while (offset < total_size) {
1510 int status1, status2;
1512 status1 = bdrv_block_status_above(bs1, NULL, offset,
1513 total_size1 - offset, &pnum1, NULL,
1514 NULL);
1515 if (status1 < 0) {
1516 ret = 3;
1517 error_report("Sector allocation test failed for %s", filename1);
1518 goto out;
1520 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1522 status2 = bdrv_block_status_above(bs2, NULL, offset,
1523 total_size2 - offset, &pnum2, NULL,
1524 NULL);
1525 if (status2 < 0) {
1526 ret = 3;
1527 error_report("Sector allocation test failed for %s", filename2);
1528 goto out;
1530 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1532 assert(pnum1 && pnum2);
1533 chunk = MIN(pnum1, pnum2);
1535 if (strict) {
1536 if (status1 != status2) {
1537 ret = 1;
1538 qprintf(quiet, "Strict mode: Offset %" PRId64
1539 " block status mismatch!\n", offset);
1540 goto out;
1543 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1544 /* nothing to do */
1545 } else if (allocated1 == allocated2) {
1546 if (allocated1) {
1547 int64_t pnum;
1549 chunk = MIN(chunk, IO_BUF_SIZE);
1550 ret = blk_pread(blk1, offset, buf1, chunk);
1551 if (ret < 0) {
1552 error_report("Error while reading offset %" PRId64
1553 " of %s: %s",
1554 offset, filename1, strerror(-ret));
1555 ret = 4;
1556 goto out;
1558 ret = blk_pread(blk2, offset, buf2, chunk);
1559 if (ret < 0) {
1560 error_report("Error while reading offset %" PRId64
1561 " of %s: %s",
1562 offset, filename2, strerror(-ret));
1563 ret = 4;
1564 goto out;
1566 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1567 if (ret || pnum != chunk) {
1568 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1569 offset + (ret ? 0 : pnum));
1570 ret = 1;
1571 goto out;
1574 } else {
1575 chunk = MIN(chunk, IO_BUF_SIZE);
1576 if (allocated1) {
1577 ret = check_empty_sectors(blk1, offset, chunk,
1578 filename1, buf1, quiet);
1579 } else {
1580 ret = check_empty_sectors(blk2, offset, chunk,
1581 filename2, buf1, quiet);
1583 if (ret) {
1584 goto out;
1587 offset += chunk;
1588 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1591 if (total_size1 != total_size2) {
1592 BlockBackend *blk_over;
1593 const char *filename_over;
1595 qprintf(quiet, "Warning: Image size mismatch!\n");
1596 if (total_size1 > total_size2) {
1597 blk_over = blk1;
1598 filename_over = filename1;
1599 } else {
1600 blk_over = blk2;
1601 filename_over = filename2;
1604 while (offset < progress_base) {
1605 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1606 progress_base - offset, &chunk,
1607 NULL, NULL);
1608 if (ret < 0) {
1609 ret = 3;
1610 error_report("Sector allocation test failed for %s",
1611 filename_over);
1612 goto out;
1615 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1616 chunk = MIN(chunk, IO_BUF_SIZE);
1617 ret = check_empty_sectors(blk_over, offset, chunk,
1618 filename_over, buf1, quiet);
1619 if (ret) {
1620 goto out;
1623 offset += chunk;
1624 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1628 qprintf(quiet, "Images are identical.\n");
1629 ret = 0;
1631 out:
1632 qemu_vfree(buf1);
1633 qemu_vfree(buf2);
1634 blk_unref(blk2);
1635 out2:
1636 blk_unref(blk1);
1637 out3:
1638 qemu_progress_end();
1639 out4:
1640 return ret;
1643 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1644 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1645 const char *src_node, const char *src_name,
1646 Error **errp)
1648 BlockDirtyBitmapMergeSource *merge_src;
1649 BlockDirtyBitmapMergeSourceList *list;
1651 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1652 merge_src->type = QTYPE_QDICT;
1653 merge_src->u.external.node = g_strdup(src_node);
1654 merge_src->u.external.name = g_strdup(src_name);
1655 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1656 list->value = merge_src;
1657 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1658 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1661 enum ImgConvertBlockStatus {
1662 BLK_DATA,
1663 BLK_ZERO,
1664 BLK_BACKING_FILE,
1667 #define MAX_COROUTINES 16
1669 typedef struct ImgConvertState {
1670 BlockBackend **src;
1671 int64_t *src_sectors;
1672 int src_num;
1673 int64_t total_sectors;
1674 int64_t allocated_sectors;
1675 int64_t allocated_done;
1676 int64_t sector_num;
1677 int64_t wr_offs;
1678 enum ImgConvertBlockStatus status;
1679 int64_t sector_next_status;
1680 BlockBackend *target;
1681 bool has_zero_init;
1682 bool compressed;
1683 bool unallocated_blocks_are_zero;
1684 bool target_is_new;
1685 bool target_has_backing;
1686 int64_t target_backing_sectors; /* negative if unknown */
1687 bool wr_in_order;
1688 bool copy_range;
1689 bool salvage;
1690 bool quiet;
1691 int min_sparse;
1692 int alignment;
1693 size_t cluster_sectors;
1694 size_t buf_sectors;
1695 long num_coroutines;
1696 int running_coroutines;
1697 Coroutine *co[MAX_COROUTINES];
1698 int64_t wait_sector_num[MAX_COROUTINES];
1699 CoMutex lock;
1700 int ret;
1701 } ImgConvertState;
1703 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1704 int *src_cur, int64_t *src_cur_offset)
1706 *src_cur = 0;
1707 *src_cur_offset = 0;
1708 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1709 *src_cur_offset += s->src_sectors[*src_cur];
1710 (*src_cur)++;
1711 assert(*src_cur < s->src_num);
1715 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1717 int64_t src_cur_offset;
1718 int ret, n, src_cur;
1719 bool post_backing_zero = false;
1721 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1723 assert(s->total_sectors > sector_num);
1724 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1726 if (s->target_backing_sectors >= 0) {
1727 if (sector_num >= s->target_backing_sectors) {
1728 post_backing_zero = s->unallocated_blocks_are_zero;
1729 } else if (sector_num + n > s->target_backing_sectors) {
1730 /* Split requests around target_backing_sectors (because
1731 * starting from there, zeros are handled differently) */
1732 n = s->target_backing_sectors - sector_num;
1736 if (s->sector_next_status <= sector_num) {
1737 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1738 int64_t count;
1740 do {
1741 count = n * BDRV_SECTOR_SIZE;
1743 if (s->target_has_backing) {
1744 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1745 count, &count, NULL, NULL);
1746 } else {
1747 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1748 offset, count, &count, NULL,
1749 NULL);
1752 if (ret < 0) {
1753 if (s->salvage) {
1754 if (n == 1) {
1755 if (!s->quiet) {
1756 warn_report("error while reading block status at "
1757 "offset %" PRIu64 ": %s", offset,
1758 strerror(-ret));
1760 /* Just try to read the data, then */
1761 ret = BDRV_BLOCK_DATA;
1762 count = BDRV_SECTOR_SIZE;
1763 } else {
1764 /* Retry on a shorter range */
1765 n = DIV_ROUND_UP(n, 4);
1767 } else {
1768 error_report("error while reading block status at offset "
1769 "%" PRIu64 ": %s", offset, strerror(-ret));
1770 return ret;
1773 } while (ret < 0);
1775 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1777 if (ret & BDRV_BLOCK_ZERO) {
1778 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1779 } else if (ret & BDRV_BLOCK_DATA) {
1780 s->status = BLK_DATA;
1781 } else {
1782 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1785 s->sector_next_status = sector_num + n;
1788 n = MIN(n, s->sector_next_status - sector_num);
1789 if (s->status == BLK_DATA) {
1790 n = MIN(n, s->buf_sectors);
1793 /* We need to write complete clusters for compressed images, so if an
1794 * unallocated area is shorter than that, we must consider the whole
1795 * cluster allocated. */
1796 if (s->compressed) {
1797 if (n < s->cluster_sectors) {
1798 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1799 s->status = BLK_DATA;
1800 } else {
1801 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1805 return n;
1808 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1809 int nb_sectors, uint8_t *buf)
1811 uint64_t single_read_until = 0;
1812 int n, ret;
1814 assert(nb_sectors <= s->buf_sectors);
1815 while (nb_sectors > 0) {
1816 BlockBackend *blk;
1817 int src_cur;
1818 int64_t bs_sectors, src_cur_offset;
1819 uint64_t offset;
1821 /* In the case of compression with multiple source files, we can get a
1822 * nb_sectors that spreads into the next part. So we must be able to
1823 * read across multiple BDSes for one convert_read() call. */
1824 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1825 blk = s->src[src_cur];
1826 bs_sectors = s->src_sectors[src_cur];
1828 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1830 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1831 if (single_read_until > offset) {
1832 n = 1;
1835 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1836 if (ret < 0) {
1837 if (s->salvage) {
1838 if (n > 1) {
1839 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1840 continue;
1841 } else {
1842 if (!s->quiet) {
1843 warn_report("error while reading offset %" PRIu64
1844 ": %s", offset, strerror(-ret));
1846 memset(buf, 0, BDRV_SECTOR_SIZE);
1848 } else {
1849 return ret;
1853 sector_num += n;
1854 nb_sectors -= n;
1855 buf += n * BDRV_SECTOR_SIZE;
1858 return 0;
1862 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1863 int nb_sectors, uint8_t *buf,
1864 enum ImgConvertBlockStatus status)
1866 int ret;
1868 while (nb_sectors > 0) {
1869 int n = nb_sectors;
1870 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1872 switch (status) {
1873 case BLK_BACKING_FILE:
1874 /* If we have a backing file, leave clusters unallocated that are
1875 * unallocated in the source image, so that the backing file is
1876 * visible at the respective offset. */
1877 assert(s->target_has_backing);
1878 break;
1880 case BLK_DATA:
1881 /* If we're told to keep the target fully allocated (-S 0) or there
1882 * is real non-zero data, we must write it. Otherwise we can treat
1883 * it as zero sectors.
1884 * Compressed clusters need to be written as a whole, so in that
1885 * case we can only save the write if the buffer is completely
1886 * zeroed. */
1887 if (!s->min_sparse ||
1888 (!s->compressed &&
1889 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1890 sector_num, s->alignment)) ||
1891 (s->compressed &&
1892 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1894 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1895 n << BDRV_SECTOR_BITS, buf, flags);
1896 if (ret < 0) {
1897 return ret;
1899 break;
1901 /* fall-through */
1903 case BLK_ZERO:
1904 if (s->has_zero_init) {
1905 assert(!s->target_has_backing);
1906 break;
1908 ret = blk_co_pwrite_zeroes(s->target,
1909 sector_num << BDRV_SECTOR_BITS,
1910 n << BDRV_SECTOR_BITS,
1911 BDRV_REQ_MAY_UNMAP);
1912 if (ret < 0) {
1913 return ret;
1915 break;
1918 sector_num += n;
1919 nb_sectors -= n;
1920 buf += n * BDRV_SECTOR_SIZE;
1923 return 0;
1926 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1927 int nb_sectors)
1929 int n, ret;
1931 while (nb_sectors > 0) {
1932 BlockBackend *blk;
1933 int src_cur;
1934 int64_t bs_sectors, src_cur_offset;
1935 int64_t offset;
1937 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1938 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1939 blk = s->src[src_cur];
1940 bs_sectors = s->src_sectors[src_cur];
1942 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1944 ret = blk_co_copy_range(blk, offset, s->target,
1945 sector_num << BDRV_SECTOR_BITS,
1946 n << BDRV_SECTOR_BITS, 0, 0);
1947 if (ret < 0) {
1948 return ret;
1951 sector_num += n;
1952 nb_sectors -= n;
1954 return 0;
1957 static void coroutine_fn convert_co_do_copy(void *opaque)
1959 ImgConvertState *s = opaque;
1960 uint8_t *buf = NULL;
1961 int ret, i;
1962 int index = -1;
1964 for (i = 0; i < s->num_coroutines; i++) {
1965 if (s->co[i] == qemu_coroutine_self()) {
1966 index = i;
1967 break;
1970 assert(index >= 0);
1972 s->running_coroutines++;
1973 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1975 while (1) {
1976 int n;
1977 int64_t sector_num;
1978 enum ImgConvertBlockStatus status;
1979 bool copy_range;
1981 qemu_co_mutex_lock(&s->lock);
1982 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1983 qemu_co_mutex_unlock(&s->lock);
1984 break;
1986 n = convert_iteration_sectors(s, s->sector_num);
1987 if (n < 0) {
1988 qemu_co_mutex_unlock(&s->lock);
1989 s->ret = n;
1990 break;
1992 /* save current sector and allocation status to local variables */
1993 sector_num = s->sector_num;
1994 status = s->status;
1995 if (!s->min_sparse && s->status == BLK_ZERO) {
1996 n = MIN(n, s->buf_sectors);
1998 /* increment global sector counter so that other coroutines can
1999 * already continue reading beyond this request */
2000 s->sector_num += n;
2001 qemu_co_mutex_unlock(&s->lock);
2003 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2004 s->allocated_done += n;
2005 qemu_progress_print(100.0 * s->allocated_done /
2006 s->allocated_sectors, 0);
2009 retry:
2010 copy_range = s->copy_range && s->status == BLK_DATA;
2011 if (status == BLK_DATA && !copy_range) {
2012 ret = convert_co_read(s, sector_num, n, buf);
2013 if (ret < 0) {
2014 error_report("error while reading at byte %lld: %s",
2015 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2016 s->ret = ret;
2018 } else if (!s->min_sparse && status == BLK_ZERO) {
2019 status = BLK_DATA;
2020 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2023 if (s->wr_in_order) {
2024 /* keep writes in order */
2025 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2026 s->wait_sector_num[index] = sector_num;
2027 qemu_coroutine_yield();
2029 s->wait_sector_num[index] = -1;
2032 if (s->ret == -EINPROGRESS) {
2033 if (copy_range) {
2034 ret = convert_co_copy_range(s, sector_num, n);
2035 if (ret) {
2036 s->copy_range = false;
2037 goto retry;
2039 } else {
2040 ret = convert_co_write(s, sector_num, n, buf, status);
2042 if (ret < 0) {
2043 error_report("error while writing at byte %lld: %s",
2044 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2045 s->ret = ret;
2049 if (s->wr_in_order) {
2050 /* reenter the coroutine that might have waited
2051 * for this write to complete */
2052 s->wr_offs = sector_num + n;
2053 for (i = 0; i < s->num_coroutines; i++) {
2054 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2056 * A -> B -> A cannot occur because A has
2057 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2058 * B will never enter A during this time window.
2060 qemu_coroutine_enter(s->co[i]);
2061 break;
2067 qemu_vfree(buf);
2068 s->co[index] = NULL;
2069 s->running_coroutines--;
2070 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2071 /* the convert job finished successfully */
2072 s->ret = 0;
2076 static int convert_do_copy(ImgConvertState *s)
2078 int ret, i, n;
2079 int64_t sector_num = 0;
2081 /* Check whether we have zero initialisation or can get it efficiently */
2082 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2083 !s->target_has_backing) {
2084 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2087 if (!s->has_zero_init && !s->target_has_backing &&
2088 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
2090 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
2091 if (ret == 0) {
2092 s->has_zero_init = true;
2096 /* Allocate buffer for copied data. For compressed images, only one cluster
2097 * can be copied at a time. */
2098 if (s->compressed) {
2099 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2100 error_report("invalid cluster size");
2101 return -EINVAL;
2103 s->buf_sectors = s->cluster_sectors;
2106 while (sector_num < s->total_sectors) {
2107 n = convert_iteration_sectors(s, sector_num);
2108 if (n < 0) {
2109 return n;
2111 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2113 s->allocated_sectors += n;
2115 sector_num += n;
2118 /* Do the copy */
2119 s->sector_next_status = 0;
2120 s->ret = -EINPROGRESS;
2122 qemu_co_mutex_init(&s->lock);
2123 for (i = 0; i < s->num_coroutines; i++) {
2124 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2125 s->wait_sector_num[i] = -1;
2126 qemu_coroutine_enter(s->co[i]);
2129 while (s->running_coroutines) {
2130 main_loop_wait(false);
2133 if (s->compressed && !s->ret) {
2134 /* signal EOF to align */
2135 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2136 if (ret < 0) {
2137 return ret;
2141 return s->ret;
2144 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2146 BdrvDirtyBitmap *bm;
2147 Error *err = NULL;
2149 FOR_EACH_DIRTY_BITMAP(src, bm) {
2150 const char *name;
2152 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2153 continue;
2155 name = bdrv_dirty_bitmap_name(bm);
2156 qmp_block_dirty_bitmap_add(dst->node_name, name,
2157 true, bdrv_dirty_bitmap_granularity(bm),
2158 true, true,
2159 true, !bdrv_dirty_bitmap_enabled(bm),
2160 &err);
2161 if (err) {
2162 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2163 return -1;
2166 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2167 &err);
2168 if (err) {
2169 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2170 return -1;
2174 return 0;
2177 #define MAX_BUF_SECTORS 32768
2179 static int img_convert(int argc, char **argv)
2181 int c, bs_i, flags, src_flags = 0;
2182 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2183 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2184 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2185 BlockDriver *drv = NULL, *proto_drv = NULL;
2186 BlockDriverInfo bdi;
2187 BlockDriverState *out_bs;
2188 QemuOpts *opts = NULL, *sn_opts = NULL;
2189 QemuOptsList *create_opts = NULL;
2190 QDict *open_opts = NULL;
2191 char *options = NULL;
2192 Error *local_err = NULL;
2193 bool writethrough, src_writethrough, image_opts = false,
2194 skip_create = false, progress = false, tgt_image_opts = false;
2195 int64_t ret = -EINVAL;
2196 bool force_share = false;
2197 bool explict_min_sparse = false;
2198 bool bitmaps = false;
2199 size_t nbitmaps = 0;
2201 ImgConvertState s = (ImgConvertState) {
2202 /* Need at least 4k of zeros for sparse detection */
2203 .min_sparse = 8,
2204 .copy_range = false,
2205 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2206 .wr_in_order = true,
2207 .num_coroutines = 8,
2210 for(;;) {
2211 static const struct option long_options[] = {
2212 {"help", no_argument, 0, 'h'},
2213 {"object", required_argument, 0, OPTION_OBJECT},
2214 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2215 {"force-share", no_argument, 0, 'U'},
2216 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2217 {"salvage", no_argument, 0, OPTION_SALVAGE},
2218 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2219 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2220 {0, 0, 0, 0}
2222 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2223 long_options, NULL);
2224 if (c == -1) {
2225 break;
2227 switch(c) {
2228 case ':':
2229 missing_argument(argv[optind - 1]);
2230 break;
2231 case '?':
2232 unrecognized_option(argv[optind - 1]);
2233 break;
2234 case 'h':
2235 help();
2236 break;
2237 case 'f':
2238 fmt = optarg;
2239 break;
2240 case 'O':
2241 out_fmt = optarg;
2242 break;
2243 case 'B':
2244 out_baseimg = optarg;
2245 break;
2246 case 'C':
2247 s.copy_range = true;
2248 break;
2249 case 'c':
2250 s.compressed = true;
2251 break;
2252 case 'o':
2253 if (accumulate_options(&options, optarg) < 0) {
2254 goto fail_getopt;
2256 break;
2257 case 'l':
2258 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2259 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2260 optarg, false);
2261 if (!sn_opts) {
2262 error_report("Failed in parsing snapshot param '%s'",
2263 optarg);
2264 goto fail_getopt;
2266 } else {
2267 snapshot_name = optarg;
2269 break;
2270 case 'S':
2272 int64_t sval;
2274 sval = cvtnum("buffer size for sparse output", optarg);
2275 if (sval < 0) {
2276 goto fail_getopt;
2277 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2278 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2279 error_report("Invalid buffer size for sparse output specified. "
2280 "Valid sizes are multiples of %llu up to %llu. Select "
2281 "0 to disable sparse detection (fully allocates output).",
2282 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2283 goto fail_getopt;
2286 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2287 explict_min_sparse = true;
2288 break;
2290 case 'p':
2291 progress = true;
2292 break;
2293 case 't':
2294 cache = optarg;
2295 break;
2296 case 'T':
2297 src_cache = optarg;
2298 break;
2299 case 'q':
2300 s.quiet = true;
2301 break;
2302 case 'n':
2303 skip_create = true;
2304 break;
2305 case 'm':
2306 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2307 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2308 error_report("Invalid number of coroutines. Allowed number of"
2309 " coroutines is between 1 and %d", MAX_COROUTINES);
2310 goto fail_getopt;
2312 break;
2313 case 'W':
2314 s.wr_in_order = false;
2315 break;
2316 case 'U':
2317 force_share = true;
2318 break;
2319 case OPTION_OBJECT: {
2320 QemuOpts *object_opts;
2321 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2322 optarg, true);
2323 if (!object_opts) {
2324 goto fail_getopt;
2326 break;
2328 case OPTION_IMAGE_OPTS:
2329 image_opts = true;
2330 break;
2331 case OPTION_SALVAGE:
2332 s.salvage = true;
2333 break;
2334 case OPTION_TARGET_IMAGE_OPTS:
2335 tgt_image_opts = true;
2336 break;
2337 case OPTION_TARGET_IS_ZERO:
2339 * The user asserting that the target is blank has the
2340 * same effect as the target driver supporting zero
2341 * initialisation.
2343 s.has_zero_init = true;
2344 break;
2345 case OPTION_BITMAPS:
2346 bitmaps = true;
2347 break;
2351 if (!out_fmt && !tgt_image_opts) {
2352 out_fmt = "raw";
2355 if (qemu_opts_foreach(&qemu_object_opts,
2356 user_creatable_add_opts_foreach,
2357 qemu_img_object_print_help, &error_fatal)) {
2358 goto fail_getopt;
2361 if (s.compressed && s.copy_range) {
2362 error_report("Cannot enable copy offloading when -c is used");
2363 goto fail_getopt;
2366 if (explict_min_sparse && s.copy_range) {
2367 error_report("Cannot enable copy offloading when -S is used");
2368 goto fail_getopt;
2371 if (s.copy_range && s.salvage) {
2372 error_report("Cannot use copy offloading in salvaging mode");
2373 goto fail_getopt;
2376 if (tgt_image_opts && !skip_create) {
2377 error_report("--target-image-opts requires use of -n flag");
2378 goto fail_getopt;
2381 if (skip_create && options) {
2382 warn_report("-o has no effect when skipping image creation");
2383 warn_report("This will become an error in future QEMU versions.");
2386 if (s.has_zero_init && !skip_create) {
2387 error_report("--target-is-zero requires use of -n flag");
2388 goto fail_getopt;
2391 s.src_num = argc - optind - 1;
2392 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2394 if (options && has_help_option(options)) {
2395 if (out_fmt) {
2396 ret = print_block_option_help(out_filename, out_fmt);
2397 goto fail_getopt;
2398 } else {
2399 error_report("Option help requires a format be specified");
2400 goto fail_getopt;
2404 if (s.src_num < 1) {
2405 error_report("Must specify image file name");
2406 goto fail_getopt;
2409 /* ret is still -EINVAL until here */
2410 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2411 if (ret < 0) {
2412 error_report("Invalid source cache option: %s", src_cache);
2413 goto fail_getopt;
2416 /* Initialize before goto out */
2417 if (s.quiet) {
2418 progress = false;
2420 qemu_progress_init(progress, 1.0);
2421 qemu_progress_print(0, 100);
2423 s.src = g_new0(BlockBackend *, s.src_num);
2424 s.src_sectors = g_new(int64_t, s.src_num);
2426 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2427 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2428 fmt, src_flags, src_writethrough, s.quiet,
2429 force_share);
2430 if (!s.src[bs_i]) {
2431 ret = -1;
2432 goto out;
2434 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2435 if (s.src_sectors[bs_i] < 0) {
2436 error_report("Could not get size of %s: %s",
2437 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2438 ret = -1;
2439 goto out;
2441 s.total_sectors += s.src_sectors[bs_i];
2444 if (sn_opts) {
2445 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2446 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2447 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2448 &local_err);
2449 } else if (snapshot_name != NULL) {
2450 if (s.src_num > 1) {
2451 error_report("No support for concatenating multiple snapshot");
2452 ret = -1;
2453 goto out;
2456 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2457 &local_err);
2459 if (local_err) {
2460 error_reportf_err(local_err, "Failed to load snapshot: ");
2461 ret = -1;
2462 goto out;
2465 if (!skip_create) {
2466 /* Find driver and parse its options */
2467 drv = bdrv_find_format(out_fmt);
2468 if (!drv) {
2469 error_report("Unknown file format '%s'", out_fmt);
2470 ret = -1;
2471 goto out;
2474 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2475 if (!proto_drv) {
2476 error_report_err(local_err);
2477 ret = -1;
2478 goto out;
2481 if (!drv->create_opts) {
2482 error_report("Format driver '%s' does not support image creation",
2483 drv->format_name);
2484 ret = -1;
2485 goto out;
2488 if (!proto_drv->create_opts) {
2489 error_report("Protocol driver '%s' does not support image creation",
2490 proto_drv->format_name);
2491 ret = -1;
2492 goto out;
2495 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2496 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2498 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2499 if (options) {
2500 qemu_opts_do_parse(opts, options, NULL, &local_err);
2501 if (local_err) {
2502 error_report_err(local_err);
2503 ret = -1;
2504 goto out;
2508 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2509 &error_abort);
2510 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2511 if (ret < 0) {
2512 goto out;
2516 /* Get backing file name if -o backing_file was used */
2517 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2518 if (out_baseimg_param) {
2519 out_baseimg = out_baseimg_param;
2521 s.target_has_backing = (bool) out_baseimg;
2523 if (s.has_zero_init && s.target_has_backing) {
2524 error_report("Cannot use --target-is-zero when the destination "
2525 "image has a backing file");
2526 goto out;
2529 if (s.src_num > 1 && out_baseimg) {
2530 error_report("Having a backing file for the target makes no sense when "
2531 "concatenating multiple input images");
2532 ret = -1;
2533 goto out;
2536 /* Check if compression is supported */
2537 if (s.compressed) {
2538 bool encryption =
2539 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2540 const char *encryptfmt =
2541 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2542 const char *preallocation =
2543 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2545 if (drv && !block_driver_can_compress(drv)) {
2546 error_report("Compression not supported for this file format");
2547 ret = -1;
2548 goto out;
2551 if (encryption || encryptfmt) {
2552 error_report("Compression and encryption not supported at "
2553 "the same time");
2554 ret = -1;
2555 goto out;
2558 if (preallocation
2559 && strcmp(preallocation, "off"))
2561 error_report("Compression and preallocation not supported at "
2562 "the same time");
2563 ret = -1;
2564 goto out;
2568 /* Determine how many bitmaps need copying */
2569 if (bitmaps) {
2570 BdrvDirtyBitmap *bm;
2572 if (s.src_num > 1) {
2573 error_report("Copying bitmaps only possible with single source");
2574 ret = -1;
2575 goto out;
2577 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2578 error_report("Source lacks bitmap support");
2579 ret = -1;
2580 goto out;
2582 FOR_EACH_DIRTY_BITMAP(blk_bs(s.src[0]), bm) {
2583 if (bdrv_dirty_bitmap_get_persistence(bm)) {
2584 nbitmaps++;
2590 * The later open call will need any decryption secrets, and
2591 * bdrv_create() will purge "opts", so extract them now before
2592 * they are lost.
2594 if (!skip_create) {
2595 open_opts = qdict_new();
2596 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2598 /* Create the new image */
2599 ret = bdrv_create(drv, out_filename, opts, &local_err);
2600 if (ret < 0) {
2601 error_reportf_err(local_err, "%s: error while converting %s: ",
2602 out_filename, out_fmt);
2603 goto out;
2607 s.target_is_new = !skip_create;
2609 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2610 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2611 if (ret < 0) {
2612 error_report("Invalid cache option: %s", cache);
2613 goto out;
2616 if (skip_create) {
2617 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2618 flags, writethrough, s.quiet, false);
2619 } else {
2620 /* TODO ultimately we should allow --target-image-opts
2621 * to be used even when -n is not given.
2622 * That has to wait for bdrv_create to be improved
2623 * to allow filenames in option syntax
2625 s.target = img_open_file(out_filename, open_opts, out_fmt,
2626 flags, writethrough, s.quiet, false);
2627 open_opts = NULL; /* blk_new_open will have freed it */
2629 if (!s.target) {
2630 ret = -1;
2631 goto out;
2633 out_bs = blk_bs(s.target);
2635 if (nbitmaps > 0 && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2636 error_report("Format driver '%s' does not support bitmaps",
2637 out_fmt);
2638 ret = -1;
2639 goto out;
2642 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2643 error_report("Compression not supported for this file format");
2644 ret = -1;
2645 goto out;
2648 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2649 * or discard_alignment of the out_bs is greater. Limit to
2650 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2651 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2652 MAX(s.buf_sectors,
2653 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2654 out_bs->bl.pdiscard_alignment >>
2655 BDRV_SECTOR_BITS)));
2657 /* try to align the write requests to the destination to avoid unnecessary
2658 * RMW cycles. */
2659 s.alignment = MAX(pow2floor(s.min_sparse),
2660 DIV_ROUND_UP(out_bs->bl.request_alignment,
2661 BDRV_SECTOR_SIZE));
2662 assert(is_power_of_2(s.alignment));
2664 if (skip_create) {
2665 int64_t output_sectors = blk_nb_sectors(s.target);
2666 if (output_sectors < 0) {
2667 error_report("unable to get output image length: %s",
2668 strerror(-output_sectors));
2669 ret = -1;
2670 goto out;
2671 } else if (output_sectors < s.total_sectors) {
2672 error_report("output file is smaller than input file");
2673 ret = -1;
2674 goto out;
2678 if (s.target_has_backing && s.target_is_new) {
2679 /* Errors are treated as "backing length unknown" (which means
2680 * s.target_backing_sectors has to be negative, which it will
2681 * be automatically). The backing file length is used only
2682 * for optimizations, so such a case is not fatal. */
2683 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2684 } else {
2685 s.target_backing_sectors = -1;
2688 ret = bdrv_get_info(out_bs, &bdi);
2689 if (ret < 0) {
2690 if (s.compressed) {
2691 error_report("could not get block driver info");
2692 goto out;
2694 } else {
2695 s.compressed = s.compressed || bdi.needs_compressed_writes;
2696 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2697 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2700 ret = convert_do_copy(&s);
2702 /* Now copy the bitmaps */
2703 if (nbitmaps > 0 && ret == 0) {
2704 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2707 out:
2708 if (!ret) {
2709 qemu_progress_print(100, 0);
2711 qemu_progress_end();
2712 qemu_opts_del(opts);
2713 qemu_opts_free(create_opts);
2714 qemu_opts_del(sn_opts);
2715 qobject_unref(open_opts);
2716 blk_unref(s.target);
2717 if (s.src) {
2718 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2719 blk_unref(s.src[bs_i]);
2721 g_free(s.src);
2723 g_free(s.src_sectors);
2724 fail_getopt:
2725 g_free(options);
2727 return !!ret;
2731 static void dump_snapshots(BlockDriverState *bs)
2733 QEMUSnapshotInfo *sn_tab, *sn;
2734 int nb_sns, i;
2736 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2737 if (nb_sns <= 0)
2738 return;
2739 printf("Snapshot list:\n");
2740 bdrv_snapshot_dump(NULL);
2741 printf("\n");
2742 for(i = 0; i < nb_sns; i++) {
2743 sn = &sn_tab[i];
2744 bdrv_snapshot_dump(sn);
2745 printf("\n");
2747 g_free(sn_tab);
2750 static void dump_json_image_info_list(ImageInfoList *list)
2752 QString *str;
2753 QObject *obj;
2754 Visitor *v = qobject_output_visitor_new(&obj);
2756 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2757 visit_complete(v, &obj);
2758 str = qobject_to_json_pretty(obj);
2759 assert(str != NULL);
2760 printf("%s\n", qstring_get_str(str));
2761 qobject_unref(obj);
2762 visit_free(v);
2763 qobject_unref(str);
2766 static void dump_json_image_info(ImageInfo *info)
2768 QString *str;
2769 QObject *obj;
2770 Visitor *v = qobject_output_visitor_new(&obj);
2772 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2773 visit_complete(v, &obj);
2774 str = qobject_to_json_pretty(obj);
2775 assert(str != NULL);
2776 printf("%s\n", qstring_get_str(str));
2777 qobject_unref(obj);
2778 visit_free(v);
2779 qobject_unref(str);
2782 static void dump_human_image_info_list(ImageInfoList *list)
2784 ImageInfoList *elem;
2785 bool delim = false;
2787 for (elem = list; elem; elem = elem->next) {
2788 if (delim) {
2789 printf("\n");
2791 delim = true;
2793 bdrv_image_info_dump(elem->value);
2797 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2799 return strcmp(a, b) == 0;
2803 * Open an image file chain and return an ImageInfoList
2805 * @filename: topmost image filename
2806 * @fmt: topmost image format (may be NULL to autodetect)
2807 * @chain: true - enumerate entire backing file chain
2808 * false - only topmost image file
2810 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2811 * image file. If there was an error a message will have been printed to
2812 * stderr.
2814 static ImageInfoList *collect_image_info_list(bool image_opts,
2815 const char *filename,
2816 const char *fmt,
2817 bool chain, bool force_share)
2819 ImageInfoList *head = NULL;
2820 ImageInfoList **last = &head;
2821 GHashTable *filenames;
2822 Error *err = NULL;
2824 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2826 while (filename) {
2827 BlockBackend *blk;
2828 BlockDriverState *bs;
2829 ImageInfo *info;
2830 ImageInfoList *elem;
2832 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2833 error_report("Backing file '%s' creates an infinite loop.",
2834 filename);
2835 goto err;
2837 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2839 blk = img_open(image_opts, filename, fmt,
2840 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2841 force_share);
2842 if (!blk) {
2843 goto err;
2845 bs = blk_bs(blk);
2847 bdrv_query_image_info(bs, &info, &err);
2848 if (err) {
2849 error_report_err(err);
2850 blk_unref(blk);
2851 goto err;
2854 elem = g_new0(ImageInfoList, 1);
2855 elem->value = info;
2856 *last = elem;
2857 last = &elem->next;
2859 blk_unref(blk);
2861 /* Clear parameters that only apply to the topmost image */
2862 filename = fmt = NULL;
2863 image_opts = false;
2865 if (chain) {
2866 if (info->has_full_backing_filename) {
2867 filename = info->full_backing_filename;
2868 } else if (info->has_backing_filename) {
2869 error_report("Could not determine absolute backing filename,"
2870 " but backing filename '%s' present",
2871 info->backing_filename);
2872 goto err;
2874 if (info->has_backing_filename_format) {
2875 fmt = info->backing_filename_format;
2879 g_hash_table_destroy(filenames);
2880 return head;
2882 err:
2883 qapi_free_ImageInfoList(head);
2884 g_hash_table_destroy(filenames);
2885 return NULL;
2888 static int img_info(int argc, char **argv)
2890 int c;
2891 OutputFormat output_format = OFORMAT_HUMAN;
2892 bool chain = false;
2893 const char *filename, *fmt, *output;
2894 ImageInfoList *list;
2895 bool image_opts = false;
2896 bool force_share = false;
2898 fmt = NULL;
2899 output = NULL;
2900 for(;;) {
2901 int option_index = 0;
2902 static const struct option long_options[] = {
2903 {"help", no_argument, 0, 'h'},
2904 {"format", required_argument, 0, 'f'},
2905 {"output", required_argument, 0, OPTION_OUTPUT},
2906 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2907 {"object", required_argument, 0, OPTION_OBJECT},
2908 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2909 {"force-share", no_argument, 0, 'U'},
2910 {0, 0, 0, 0}
2912 c = getopt_long(argc, argv, ":f:hU",
2913 long_options, &option_index);
2914 if (c == -1) {
2915 break;
2917 switch(c) {
2918 case ':':
2919 missing_argument(argv[optind - 1]);
2920 break;
2921 case '?':
2922 unrecognized_option(argv[optind - 1]);
2923 break;
2924 case 'h':
2925 help();
2926 break;
2927 case 'f':
2928 fmt = optarg;
2929 break;
2930 case 'U':
2931 force_share = true;
2932 break;
2933 case OPTION_OUTPUT:
2934 output = optarg;
2935 break;
2936 case OPTION_BACKING_CHAIN:
2937 chain = true;
2938 break;
2939 case OPTION_OBJECT: {
2940 QemuOpts *opts;
2941 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2942 optarg, true);
2943 if (!opts) {
2944 return 1;
2946 } break;
2947 case OPTION_IMAGE_OPTS:
2948 image_opts = true;
2949 break;
2952 if (optind != argc - 1) {
2953 error_exit("Expecting one image file name");
2955 filename = argv[optind++];
2957 if (output && !strcmp(output, "json")) {
2958 output_format = OFORMAT_JSON;
2959 } else if (output && !strcmp(output, "human")) {
2960 output_format = OFORMAT_HUMAN;
2961 } else if (output) {
2962 error_report("--output must be used with human or json as argument.");
2963 return 1;
2966 if (qemu_opts_foreach(&qemu_object_opts,
2967 user_creatable_add_opts_foreach,
2968 qemu_img_object_print_help, &error_fatal)) {
2969 return 1;
2972 list = collect_image_info_list(image_opts, filename, fmt, chain,
2973 force_share);
2974 if (!list) {
2975 return 1;
2978 switch (output_format) {
2979 case OFORMAT_HUMAN:
2980 dump_human_image_info_list(list);
2981 break;
2982 case OFORMAT_JSON:
2983 if (chain) {
2984 dump_json_image_info_list(list);
2985 } else {
2986 dump_json_image_info(list->value);
2988 break;
2991 qapi_free_ImageInfoList(list);
2992 return 0;
2995 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2996 MapEntry *next)
2998 switch (output_format) {
2999 case OFORMAT_HUMAN:
3000 if (e->data && !e->has_offset) {
3001 error_report("File contains external, encrypted or compressed clusters.");
3002 return -1;
3004 if (e->data && !e->zero) {
3005 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
3006 e->start, e->length,
3007 e->has_offset ? e->offset : 0,
3008 e->has_filename ? e->filename : "");
3010 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3011 * Modify the flags here to allow more coalescing.
3013 if (next && (!next->data || next->zero)) {
3014 next->data = false;
3015 next->zero = true;
3017 break;
3018 case OFORMAT_JSON:
3019 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3020 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3021 e->start, e->length, e->depth,
3022 e->zero ? "true" : "false",
3023 e->data ? "true" : "false");
3024 if (e->has_offset) {
3025 printf(", \"offset\": %"PRId64"", e->offset);
3027 putchar('}');
3029 if (next) {
3030 puts(",");
3032 break;
3034 return 0;
3037 static int get_block_status(BlockDriverState *bs, int64_t offset,
3038 int64_t bytes, MapEntry *e)
3040 int ret;
3041 int depth;
3042 BlockDriverState *file;
3043 bool has_offset;
3044 int64_t map;
3045 char *filename = NULL;
3047 /* As an optimization, we could cache the current range of unallocated
3048 * clusters in each file of the chain, and avoid querying the same
3049 * range repeatedly.
3052 depth = 0;
3053 for (;;) {
3054 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3055 if (ret < 0) {
3056 return ret;
3058 assert(bytes);
3059 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3060 break;
3062 bs = backing_bs(bs);
3063 if (bs == NULL) {
3064 ret = 0;
3065 break;
3068 depth++;
3071 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3073 if (file && has_offset) {
3074 bdrv_refresh_filename(file);
3075 filename = file->filename;
3078 *e = (MapEntry) {
3079 .start = offset,
3080 .length = bytes,
3081 .data = !!(ret & BDRV_BLOCK_DATA),
3082 .zero = !!(ret & BDRV_BLOCK_ZERO),
3083 .offset = map,
3084 .has_offset = has_offset,
3085 .depth = depth,
3086 .has_filename = filename,
3087 .filename = filename,
3090 return 0;
3093 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3095 if (curr->length == 0) {
3096 return false;
3098 if (curr->zero != next->zero ||
3099 curr->data != next->data ||
3100 curr->depth != next->depth ||
3101 curr->has_filename != next->has_filename ||
3102 curr->has_offset != next->has_offset) {
3103 return false;
3105 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3106 return false;
3108 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3109 return false;
3111 return true;
3114 static int img_map(int argc, char **argv)
3116 int c;
3117 OutputFormat output_format = OFORMAT_HUMAN;
3118 BlockBackend *blk;
3119 BlockDriverState *bs;
3120 const char *filename, *fmt, *output;
3121 int64_t length;
3122 MapEntry curr = { .length = 0 }, next;
3123 int ret = 0;
3124 bool image_opts = false;
3125 bool force_share = false;
3126 int64_t start_offset = 0;
3127 int64_t max_length = -1;
3129 fmt = NULL;
3130 output = NULL;
3131 for (;;) {
3132 int option_index = 0;
3133 static const struct option long_options[] = {
3134 {"help", no_argument, 0, 'h'},
3135 {"format", required_argument, 0, 'f'},
3136 {"output", required_argument, 0, OPTION_OUTPUT},
3137 {"object", required_argument, 0, OPTION_OBJECT},
3138 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3139 {"force-share", no_argument, 0, 'U'},
3140 {"start-offset", required_argument, 0, 's'},
3141 {"max-length", required_argument, 0, 'l'},
3142 {0, 0, 0, 0}
3144 c = getopt_long(argc, argv, ":f:s:l:hU",
3145 long_options, &option_index);
3146 if (c == -1) {
3147 break;
3149 switch (c) {
3150 case ':':
3151 missing_argument(argv[optind - 1]);
3152 break;
3153 case '?':
3154 unrecognized_option(argv[optind - 1]);
3155 break;
3156 case 'h':
3157 help();
3158 break;
3159 case 'f':
3160 fmt = optarg;
3161 break;
3162 case 'U':
3163 force_share = true;
3164 break;
3165 case OPTION_OUTPUT:
3166 output = optarg;
3167 break;
3168 case 's':
3169 start_offset = cvtnum("start offset", optarg);
3170 if (start_offset < 0) {
3171 return 1;
3173 break;
3174 case 'l':
3175 max_length = cvtnum("max length", optarg);
3176 if (max_length < 0) {
3177 return 1;
3179 break;
3180 case OPTION_OBJECT: {
3181 QemuOpts *opts;
3182 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3183 optarg, true);
3184 if (!opts) {
3185 return 1;
3187 } break;
3188 case OPTION_IMAGE_OPTS:
3189 image_opts = true;
3190 break;
3193 if (optind != argc - 1) {
3194 error_exit("Expecting one image file name");
3196 filename = argv[optind];
3198 if (output && !strcmp(output, "json")) {
3199 output_format = OFORMAT_JSON;
3200 } else if (output && !strcmp(output, "human")) {
3201 output_format = OFORMAT_HUMAN;
3202 } else if (output) {
3203 error_report("--output must be used with human or json as argument.");
3204 return 1;
3207 if (qemu_opts_foreach(&qemu_object_opts,
3208 user_creatable_add_opts_foreach,
3209 qemu_img_object_print_help, &error_fatal)) {
3210 return 1;
3213 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3214 if (!blk) {
3215 return 1;
3217 bs = blk_bs(blk);
3219 if (output_format == OFORMAT_HUMAN) {
3220 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3221 } else if (output_format == OFORMAT_JSON) {
3222 putchar('[');
3225 length = blk_getlength(blk);
3226 if (length < 0) {
3227 error_report("Failed to get size for '%s'", filename);
3228 return 1;
3230 if (max_length != -1) {
3231 length = MIN(start_offset + max_length, length);
3234 curr.start = start_offset;
3235 while (curr.start + curr.length < length) {
3236 int64_t offset = curr.start + curr.length;
3237 int64_t n;
3239 /* Probe up to 1 GiB at a time. */
3240 n = MIN(1 * GiB, length - offset);
3241 ret = get_block_status(bs, offset, n, &next);
3243 if (ret < 0) {
3244 error_report("Could not read file metadata: %s", strerror(-ret));
3245 goto out;
3248 if (entry_mergeable(&curr, &next)) {
3249 curr.length += next.length;
3250 continue;
3253 if (curr.length > 0) {
3254 ret = dump_map_entry(output_format, &curr, &next);
3255 if (ret < 0) {
3256 goto out;
3259 curr = next;
3262 ret = dump_map_entry(output_format, &curr, NULL);
3263 if (output_format == OFORMAT_JSON) {
3264 puts("]");
3267 out:
3268 blk_unref(blk);
3269 return ret < 0;
3272 #define SNAPSHOT_LIST 1
3273 #define SNAPSHOT_CREATE 2
3274 #define SNAPSHOT_APPLY 3
3275 #define SNAPSHOT_DELETE 4
3277 static int img_snapshot(int argc, char **argv)
3279 BlockBackend *blk;
3280 BlockDriverState *bs;
3281 QEMUSnapshotInfo sn;
3282 char *filename, *snapshot_name = NULL;
3283 int c, ret = 0, bdrv_oflags;
3284 int action = 0;
3285 qemu_timeval tv;
3286 bool quiet = false;
3287 Error *err = NULL;
3288 bool image_opts = false;
3289 bool force_share = false;
3291 bdrv_oflags = BDRV_O_RDWR;
3292 /* Parse commandline parameters */
3293 for(;;) {
3294 static const struct option long_options[] = {
3295 {"help", no_argument, 0, 'h'},
3296 {"object", required_argument, 0, OPTION_OBJECT},
3297 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3298 {"force-share", no_argument, 0, 'U'},
3299 {0, 0, 0, 0}
3301 c = getopt_long(argc, argv, ":la:c:d:hqU",
3302 long_options, NULL);
3303 if (c == -1) {
3304 break;
3306 switch(c) {
3307 case ':':
3308 missing_argument(argv[optind - 1]);
3309 break;
3310 case '?':
3311 unrecognized_option(argv[optind - 1]);
3312 break;
3313 case 'h':
3314 help();
3315 return 0;
3316 case 'l':
3317 if (action) {
3318 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3319 return 0;
3321 action = SNAPSHOT_LIST;
3322 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3323 break;
3324 case 'a':
3325 if (action) {
3326 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3327 return 0;
3329 action = SNAPSHOT_APPLY;
3330 snapshot_name = optarg;
3331 break;
3332 case 'c':
3333 if (action) {
3334 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3335 return 0;
3337 action = SNAPSHOT_CREATE;
3338 snapshot_name = optarg;
3339 break;
3340 case 'd':
3341 if (action) {
3342 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3343 return 0;
3345 action = SNAPSHOT_DELETE;
3346 snapshot_name = optarg;
3347 break;
3348 case 'q':
3349 quiet = true;
3350 break;
3351 case 'U':
3352 force_share = true;
3353 break;
3354 case OPTION_OBJECT: {
3355 QemuOpts *opts;
3356 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3357 optarg, true);
3358 if (!opts) {
3359 return 1;
3361 } break;
3362 case OPTION_IMAGE_OPTS:
3363 image_opts = true;
3364 break;
3368 if (optind != argc - 1) {
3369 error_exit("Expecting one image file name");
3371 filename = argv[optind++];
3373 if (qemu_opts_foreach(&qemu_object_opts,
3374 user_creatable_add_opts_foreach,
3375 qemu_img_object_print_help, &error_fatal)) {
3376 return 1;
3379 /* Open the image */
3380 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3381 force_share);
3382 if (!blk) {
3383 return 1;
3385 bs = blk_bs(blk);
3387 /* Perform the requested action */
3388 switch(action) {
3389 case SNAPSHOT_LIST:
3390 dump_snapshots(bs);
3391 break;
3393 case SNAPSHOT_CREATE:
3394 memset(&sn, 0, sizeof(sn));
3395 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3397 qemu_gettimeofday(&tv);
3398 sn.date_sec = tv.tv_sec;
3399 sn.date_nsec = tv.tv_usec * 1000;
3401 ret = bdrv_snapshot_create(bs, &sn);
3402 if (ret) {
3403 error_report("Could not create snapshot '%s': %d (%s)",
3404 snapshot_name, ret, strerror(-ret));
3406 break;
3408 case SNAPSHOT_APPLY:
3409 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3410 if (ret) {
3411 error_reportf_err(err, "Could not apply snapshot '%s': ",
3412 snapshot_name);
3414 break;
3416 case SNAPSHOT_DELETE:
3417 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3418 if (ret < 0) {
3419 error_report("Could not delete snapshot '%s': snapshot not "
3420 "found", snapshot_name);
3421 ret = 1;
3422 } else {
3423 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3424 if (ret < 0) {
3425 error_reportf_err(err, "Could not delete snapshot '%s': ",
3426 snapshot_name);
3427 ret = 1;
3430 break;
3433 /* Cleanup */
3434 blk_unref(blk);
3435 if (ret) {
3436 return 1;
3438 return 0;
3441 static int img_rebase(int argc, char **argv)
3443 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3444 uint8_t *buf_old = NULL;
3445 uint8_t *buf_new = NULL;
3446 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3447 char *filename;
3448 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3449 int c, flags, src_flags, ret;
3450 bool writethrough, src_writethrough;
3451 int unsafe = 0;
3452 bool force_share = false;
3453 int progress = 0;
3454 bool quiet = false;
3455 Error *local_err = NULL;
3456 bool image_opts = false;
3458 /* Parse commandline parameters */
3459 fmt = NULL;
3460 cache = BDRV_DEFAULT_CACHE;
3461 src_cache = BDRV_DEFAULT_CACHE;
3462 out_baseimg = NULL;
3463 out_basefmt = NULL;
3464 for(;;) {
3465 static const struct option long_options[] = {
3466 {"help", no_argument, 0, 'h'},
3467 {"object", required_argument, 0, OPTION_OBJECT},
3468 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3469 {"force-share", no_argument, 0, 'U'},
3470 {0, 0, 0, 0}
3472 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3473 long_options, NULL);
3474 if (c == -1) {
3475 break;
3477 switch(c) {
3478 case ':':
3479 missing_argument(argv[optind - 1]);
3480 break;
3481 case '?':
3482 unrecognized_option(argv[optind - 1]);
3483 break;
3484 case 'h':
3485 help();
3486 return 0;
3487 case 'f':
3488 fmt = optarg;
3489 break;
3490 case 'F':
3491 out_basefmt = optarg;
3492 break;
3493 case 'b':
3494 out_baseimg = optarg;
3495 break;
3496 case 'u':
3497 unsafe = 1;
3498 break;
3499 case 'p':
3500 progress = 1;
3501 break;
3502 case 't':
3503 cache = optarg;
3504 break;
3505 case 'T':
3506 src_cache = optarg;
3507 break;
3508 case 'q':
3509 quiet = true;
3510 break;
3511 case OPTION_OBJECT: {
3512 QemuOpts *opts;
3513 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3514 optarg, true);
3515 if (!opts) {
3516 return 1;
3518 } break;
3519 case OPTION_IMAGE_OPTS:
3520 image_opts = true;
3521 break;
3522 case 'U':
3523 force_share = true;
3524 break;
3528 if (quiet) {
3529 progress = 0;
3532 if (optind != argc - 1) {
3533 error_exit("Expecting one image file name");
3535 if (!unsafe && !out_baseimg) {
3536 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3538 filename = argv[optind++];
3540 if (qemu_opts_foreach(&qemu_object_opts,
3541 user_creatable_add_opts_foreach,
3542 qemu_img_object_print_help, &error_fatal)) {
3543 return 1;
3546 qemu_progress_init(progress, 2.0);
3547 qemu_progress_print(0, 100);
3549 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3550 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3551 if (ret < 0) {
3552 error_report("Invalid cache option: %s", cache);
3553 goto out;
3556 src_flags = 0;
3557 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3558 if (ret < 0) {
3559 error_report("Invalid source cache option: %s", src_cache);
3560 goto out;
3563 /* The source files are opened read-only, don't care about WCE */
3564 assert((src_flags & BDRV_O_RDWR) == 0);
3565 (void) src_writethrough;
3568 * Open the images.
3570 * Ignore the old backing file for unsafe rebase in case we want to correct
3571 * the reference to a renamed or moved backing file.
3573 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3574 false);
3575 if (!blk) {
3576 ret = -1;
3577 goto out;
3579 bs = blk_bs(blk);
3581 if (out_basefmt != NULL) {
3582 if (bdrv_find_format(out_basefmt) == NULL) {
3583 error_report("Invalid format name: '%s'", out_basefmt);
3584 ret = -1;
3585 goto out;
3589 /* For safe rebasing we need to compare old and new backing file */
3590 if (!unsafe) {
3591 QDict *options = NULL;
3592 BlockDriverState *base_bs = backing_bs(bs);
3594 if (base_bs) {
3595 blk_old_backing = blk_new(qemu_get_aio_context(),
3596 BLK_PERM_CONSISTENT_READ,
3597 BLK_PERM_ALL);
3598 ret = blk_insert_bs(blk_old_backing, base_bs,
3599 &local_err);
3600 if (ret < 0) {
3601 error_reportf_err(local_err,
3602 "Could not reuse old backing file '%s': ",
3603 base_bs->filename);
3604 goto out;
3606 } else {
3607 blk_old_backing = NULL;
3610 if (out_baseimg[0]) {
3611 const char *overlay_filename;
3612 char *out_real_path;
3614 options = qdict_new();
3615 if (out_basefmt) {
3616 qdict_put_str(options, "driver", out_basefmt);
3618 if (force_share) {
3619 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3622 bdrv_refresh_filename(bs);
3623 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3624 : bs->filename;
3625 out_real_path =
3626 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3627 out_baseimg,
3628 &local_err);
3629 if (local_err) {
3630 qobject_unref(options);
3631 error_reportf_err(local_err,
3632 "Could not resolve backing filename: ");
3633 ret = -1;
3634 goto out;
3638 * Find out whether we rebase an image on top of a previous image
3639 * in its chain.
3641 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3642 if (prefix_chain_bs) {
3643 qobject_unref(options);
3644 g_free(out_real_path);
3646 blk_new_backing = blk_new(qemu_get_aio_context(),
3647 BLK_PERM_CONSISTENT_READ,
3648 BLK_PERM_ALL);
3649 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3650 &local_err);
3651 if (ret < 0) {
3652 error_reportf_err(local_err,
3653 "Could not reuse backing file '%s': ",
3654 out_baseimg);
3655 goto out;
3657 } else {
3658 blk_new_backing = blk_new_open(out_real_path, NULL,
3659 options, src_flags, &local_err);
3660 g_free(out_real_path);
3661 if (!blk_new_backing) {
3662 error_reportf_err(local_err,
3663 "Could not open new backing file '%s': ",
3664 out_baseimg);
3665 ret = -1;
3666 goto out;
3673 * Check each unallocated cluster in the COW file. If it is unallocated,
3674 * accesses go to the backing file. We must therefore compare this cluster
3675 * in the old and new backing file, and if they differ we need to copy it
3676 * from the old backing file into the COW file.
3678 * If qemu-img crashes during this step, no harm is done. The content of
3679 * the image is the same as the original one at any time.
3681 if (!unsafe) {
3682 int64_t size;
3683 int64_t old_backing_size = 0;
3684 int64_t new_backing_size = 0;
3685 uint64_t offset;
3686 int64_t n;
3687 float local_progress = 0;
3689 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3690 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3692 size = blk_getlength(blk);
3693 if (size < 0) {
3694 error_report("Could not get size of '%s': %s",
3695 filename, strerror(-size));
3696 ret = -1;
3697 goto out;
3699 if (blk_old_backing) {
3700 old_backing_size = blk_getlength(blk_old_backing);
3701 if (old_backing_size < 0) {
3702 char backing_name[PATH_MAX];
3704 bdrv_get_backing_filename(bs, backing_name,
3705 sizeof(backing_name));
3706 error_report("Could not get size of '%s': %s",
3707 backing_name, strerror(-old_backing_size));
3708 ret = -1;
3709 goto out;
3712 if (blk_new_backing) {
3713 new_backing_size = blk_getlength(blk_new_backing);
3714 if (new_backing_size < 0) {
3715 error_report("Could not get size of '%s': %s",
3716 out_baseimg, strerror(-new_backing_size));
3717 ret = -1;
3718 goto out;
3722 if (size != 0) {
3723 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3726 for (offset = 0; offset < size; offset += n) {
3727 bool buf_old_is_zero = false;
3729 /* How many bytes can we handle with the next read? */
3730 n = MIN(IO_BUF_SIZE, size - offset);
3732 /* If the cluster is allocated, we don't need to take action */
3733 ret = bdrv_is_allocated(bs, offset, n, &n);
3734 if (ret < 0) {
3735 error_report("error while reading image metadata: %s",
3736 strerror(-ret));
3737 goto out;
3739 if (ret) {
3740 continue;
3743 if (prefix_chain_bs) {
3745 * If cluster wasn't changed since prefix_chain, we don't need
3746 * to take action
3748 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3749 false, offset, n, &n);
3750 if (ret < 0) {
3751 error_report("error while reading image metadata: %s",
3752 strerror(-ret));
3753 goto out;
3755 if (!ret) {
3756 continue;
3761 * Read old and new backing file and take into consideration that
3762 * backing files may be smaller than the COW image.
3764 if (offset >= old_backing_size) {
3765 memset(buf_old, 0, n);
3766 buf_old_is_zero = true;
3767 } else {
3768 if (offset + n > old_backing_size) {
3769 n = old_backing_size - offset;
3772 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3773 if (ret < 0) {
3774 error_report("error while reading from old backing file");
3775 goto out;
3779 if (offset >= new_backing_size || !blk_new_backing) {
3780 memset(buf_new, 0, n);
3781 } else {
3782 if (offset + n > new_backing_size) {
3783 n = new_backing_size - offset;
3786 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3787 if (ret < 0) {
3788 error_report("error while reading from new backing file");
3789 goto out;
3793 /* If they differ, we need to write to the COW file */
3794 uint64_t written = 0;
3796 while (written < n) {
3797 int64_t pnum;
3799 if (compare_buffers(buf_old + written, buf_new + written,
3800 n - written, &pnum))
3802 if (buf_old_is_zero) {
3803 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3804 } else {
3805 ret = blk_pwrite(blk, offset + written,
3806 buf_old + written, pnum, 0);
3808 if (ret < 0) {
3809 error_report("Error while writing to COW image: %s",
3810 strerror(-ret));
3811 goto out;
3815 written += pnum;
3817 qemu_progress_print(local_progress, 100);
3822 * Change the backing file. All clusters that are different from the old
3823 * backing file are overwritten in the COW file now, so the visible content
3824 * doesn't change when we switch the backing file.
3826 if (out_baseimg && *out_baseimg) {
3827 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3828 } else {
3829 ret = bdrv_change_backing_file(bs, NULL, NULL);
3832 if (ret == -ENOSPC) {
3833 error_report("Could not change the backing file to '%s': No "
3834 "space left in the file header", out_baseimg);
3835 } else if (ret < 0) {
3836 error_report("Could not change the backing file to '%s': %s",
3837 out_baseimg, strerror(-ret));
3840 qemu_progress_print(100, 0);
3842 * TODO At this point it is possible to check if any clusters that are
3843 * allocated in the COW file are the same in the backing file. If so, they
3844 * could be dropped from the COW file. Don't do this before switching the
3845 * backing file, in case of a crash this would lead to corruption.
3847 out:
3848 qemu_progress_end();
3849 /* Cleanup */
3850 if (!unsafe) {
3851 blk_unref(blk_old_backing);
3852 blk_unref(blk_new_backing);
3854 qemu_vfree(buf_old);
3855 qemu_vfree(buf_new);
3857 blk_unref(blk);
3858 if (ret) {
3859 return 1;
3861 return 0;
3864 static int img_resize(int argc, char **argv)
3866 Error *err = NULL;
3867 int c, ret, relative;
3868 const char *filename, *fmt, *size;
3869 int64_t n, total_size, current_size;
3870 bool quiet = false;
3871 BlockBackend *blk = NULL;
3872 PreallocMode prealloc = PREALLOC_MODE_OFF;
3873 QemuOpts *param;
3875 static QemuOptsList resize_options = {
3876 .name = "resize_options",
3877 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3878 .desc = {
3880 .name = BLOCK_OPT_SIZE,
3881 .type = QEMU_OPT_SIZE,
3882 .help = "Virtual disk size"
3883 }, {
3884 /* end of list */
3888 bool image_opts = false;
3889 bool shrink = false;
3891 /* Remove size from argv manually so that negative numbers are not treated
3892 * as options by getopt. */
3893 if (argc < 3) {
3894 error_exit("Not enough arguments");
3895 return 1;
3898 size = argv[--argc];
3900 /* Parse getopt arguments */
3901 fmt = NULL;
3902 for(;;) {
3903 static const struct option long_options[] = {
3904 {"help", no_argument, 0, 'h'},
3905 {"object", required_argument, 0, OPTION_OBJECT},
3906 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3907 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3908 {"shrink", no_argument, 0, OPTION_SHRINK},
3909 {0, 0, 0, 0}
3911 c = getopt_long(argc, argv, ":f:hq",
3912 long_options, NULL);
3913 if (c == -1) {
3914 break;
3916 switch(c) {
3917 case ':':
3918 missing_argument(argv[optind - 1]);
3919 break;
3920 case '?':
3921 unrecognized_option(argv[optind - 1]);
3922 break;
3923 case 'h':
3924 help();
3925 break;
3926 case 'f':
3927 fmt = optarg;
3928 break;
3929 case 'q':
3930 quiet = true;
3931 break;
3932 case OPTION_OBJECT: {
3933 QemuOpts *opts;
3934 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3935 optarg, true);
3936 if (!opts) {
3937 return 1;
3939 } break;
3940 case OPTION_IMAGE_OPTS:
3941 image_opts = true;
3942 break;
3943 case OPTION_PREALLOCATION:
3944 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3945 PREALLOC_MODE__MAX, NULL);
3946 if (prealloc == PREALLOC_MODE__MAX) {
3947 error_report("Invalid preallocation mode '%s'", optarg);
3948 return 1;
3950 break;
3951 case OPTION_SHRINK:
3952 shrink = true;
3953 break;
3956 if (optind != argc - 1) {
3957 error_exit("Expecting image file name and size");
3959 filename = argv[optind++];
3961 if (qemu_opts_foreach(&qemu_object_opts,
3962 user_creatable_add_opts_foreach,
3963 qemu_img_object_print_help, &error_fatal)) {
3964 return 1;
3967 /* Choose grow, shrink, or absolute resize mode */
3968 switch (size[0]) {
3969 case '+':
3970 relative = 1;
3971 size++;
3972 break;
3973 case '-':
3974 relative = -1;
3975 size++;
3976 break;
3977 default:
3978 relative = 0;
3979 break;
3982 /* Parse size */
3983 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3984 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3985 if (err) {
3986 error_report_err(err);
3987 ret = -1;
3988 qemu_opts_del(param);
3989 goto out;
3991 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3992 qemu_opts_del(param);
3994 blk = img_open(image_opts, filename, fmt,
3995 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3996 false);
3997 if (!blk) {
3998 ret = -1;
3999 goto out;
4002 current_size = blk_getlength(blk);
4003 if (current_size < 0) {
4004 error_report("Failed to inquire current image length: %s",
4005 strerror(-current_size));
4006 ret = -1;
4007 goto out;
4010 if (relative) {
4011 total_size = current_size + n * relative;
4012 } else {
4013 total_size = n;
4015 if (total_size <= 0) {
4016 error_report("New image size must be positive");
4017 ret = -1;
4018 goto out;
4021 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4022 error_report("Preallocation can only be used for growing images");
4023 ret = -1;
4024 goto out;
4027 if (total_size < current_size && !shrink) {
4028 warn_report("Shrinking an image will delete all data beyond the "
4029 "shrunken image's end. Before performing such an "
4030 "operation, make sure there is no important data there.");
4032 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4033 error_report(
4034 "Use the --shrink option to perform a shrink operation.");
4035 ret = -1;
4036 goto out;
4037 } else {
4038 warn_report("Using the --shrink option will suppress this message. "
4039 "Note that future versions of qemu-img may refuse to "
4040 "shrink images without this option.");
4045 * The user expects the image to have the desired size after
4046 * resizing, so pass @exact=true. It is of no use to report
4047 * success when the image has not actually been resized.
4049 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4050 if (!ret) {
4051 qprintf(quiet, "Image resized.\n");
4052 } else {
4053 error_report_err(err);
4055 out:
4056 blk_unref(blk);
4057 if (ret) {
4058 return 1;
4060 return 0;
4063 static void amend_status_cb(BlockDriverState *bs,
4064 int64_t offset, int64_t total_work_size,
4065 void *opaque)
4067 qemu_progress_print(100.f * offset / total_work_size, 0);
4070 static int print_amend_option_help(const char *format)
4072 BlockDriver *drv;
4074 /* Find driver and parse its options */
4075 drv = bdrv_find_format(format);
4076 if (!drv) {
4077 error_report("Unknown file format '%s'", format);
4078 return 1;
4081 if (!drv->bdrv_amend_options) {
4082 error_report("Format driver '%s' does not support option amendment",
4083 format);
4084 return 1;
4087 /* Every driver supporting amendment must have create_opts */
4088 assert(drv->create_opts);
4090 printf("Creation options for '%s':\n", format);
4091 qemu_opts_print_help(drv->create_opts, false);
4092 printf("\nNote that not all of these options may be amendable.\n");
4093 return 0;
4096 static int img_amend(int argc, char **argv)
4098 Error *err = NULL;
4099 int c, ret = 0;
4100 char *options = NULL;
4101 QemuOptsList *create_opts = NULL;
4102 QemuOpts *opts = NULL;
4103 const char *fmt = NULL, *filename, *cache;
4104 int flags;
4105 bool writethrough;
4106 bool quiet = false, progress = false;
4107 BlockBackend *blk = NULL;
4108 BlockDriverState *bs = NULL;
4109 bool image_opts = false;
4111 cache = BDRV_DEFAULT_CACHE;
4112 for (;;) {
4113 static const struct option long_options[] = {
4114 {"help", no_argument, 0, 'h'},
4115 {"object", required_argument, 0, OPTION_OBJECT},
4116 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4117 {0, 0, 0, 0}
4119 c = getopt_long(argc, argv, ":ho:f:t:pq",
4120 long_options, NULL);
4121 if (c == -1) {
4122 break;
4125 switch (c) {
4126 case ':':
4127 missing_argument(argv[optind - 1]);
4128 break;
4129 case '?':
4130 unrecognized_option(argv[optind - 1]);
4131 break;
4132 case 'h':
4133 help();
4134 break;
4135 case 'o':
4136 if (accumulate_options(&options, optarg) < 0) {
4137 ret = -1;
4138 goto out_no_progress;
4140 break;
4141 case 'f':
4142 fmt = optarg;
4143 break;
4144 case 't':
4145 cache = optarg;
4146 break;
4147 case 'p':
4148 progress = true;
4149 break;
4150 case 'q':
4151 quiet = true;
4152 break;
4153 case OPTION_OBJECT:
4154 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4155 optarg, true);
4156 if (!opts) {
4157 ret = -1;
4158 goto out_no_progress;
4160 break;
4161 case OPTION_IMAGE_OPTS:
4162 image_opts = true;
4163 break;
4167 if (!options) {
4168 error_exit("Must specify options (-o)");
4171 if (qemu_opts_foreach(&qemu_object_opts,
4172 user_creatable_add_opts_foreach,
4173 qemu_img_object_print_help, &error_fatal)) {
4174 ret = -1;
4175 goto out_no_progress;
4178 if (quiet) {
4179 progress = false;
4181 qemu_progress_init(progress, 1.0);
4183 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4184 if (fmt && has_help_option(options)) {
4185 /* If a format is explicitly specified (and possibly no filename is
4186 * given), print option help here */
4187 ret = print_amend_option_help(fmt);
4188 goto out;
4191 if (optind != argc - 1) {
4192 error_report("Expecting one image file name");
4193 ret = -1;
4194 goto out;
4197 flags = BDRV_O_RDWR;
4198 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4199 if (ret < 0) {
4200 error_report("Invalid cache option: %s", cache);
4201 goto out;
4204 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4205 false);
4206 if (!blk) {
4207 ret = -1;
4208 goto out;
4210 bs = blk_bs(blk);
4212 fmt = bs->drv->format_name;
4214 if (has_help_option(options)) {
4215 /* If the format was auto-detected, print option help here */
4216 ret = print_amend_option_help(fmt);
4217 goto out;
4220 if (!bs->drv->bdrv_amend_options) {
4221 error_report("Format driver '%s' does not support option amendment",
4222 fmt);
4223 ret = -1;
4224 goto out;
4227 /* Every driver supporting amendment must have create_opts */
4228 assert(bs->drv->create_opts);
4230 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
4231 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4232 qemu_opts_do_parse(opts, options, NULL, &err);
4233 if (err) {
4234 error_report_err(err);
4235 ret = -1;
4236 goto out;
4239 /* In case the driver does not call amend_status_cb() */
4240 qemu_progress_print(0.f, 0);
4241 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
4242 qemu_progress_print(100.f, 0);
4243 if (ret < 0) {
4244 error_report_err(err);
4245 goto out;
4248 out:
4249 qemu_progress_end();
4251 out_no_progress:
4252 blk_unref(blk);
4253 qemu_opts_del(opts);
4254 qemu_opts_free(create_opts);
4255 g_free(options);
4257 if (ret) {
4258 return 1;
4260 return 0;
4263 typedef struct BenchData {
4264 BlockBackend *blk;
4265 uint64_t image_size;
4266 bool write;
4267 int bufsize;
4268 int step;
4269 int nrreq;
4270 int n;
4271 int flush_interval;
4272 bool drain_on_flush;
4273 uint8_t *buf;
4274 QEMUIOVector *qiov;
4276 int in_flight;
4277 bool in_flush;
4278 uint64_t offset;
4279 } BenchData;
4281 static void bench_undrained_flush_cb(void *opaque, int ret)
4283 if (ret < 0) {
4284 error_report("Failed flush request: %s", strerror(-ret));
4285 exit(EXIT_FAILURE);
4289 static void bench_cb(void *opaque, int ret)
4291 BenchData *b = opaque;
4292 BlockAIOCB *acb;
4294 if (ret < 0) {
4295 error_report("Failed request: %s", strerror(-ret));
4296 exit(EXIT_FAILURE);
4299 if (b->in_flush) {
4300 /* Just finished a flush with drained queue: Start next requests */
4301 assert(b->in_flight == 0);
4302 b->in_flush = false;
4303 } else if (b->in_flight > 0) {
4304 int remaining = b->n - b->in_flight;
4306 b->n--;
4307 b->in_flight--;
4309 /* Time for flush? Drain queue if requested, then flush */
4310 if (b->flush_interval && remaining % b->flush_interval == 0) {
4311 if (!b->in_flight || !b->drain_on_flush) {
4312 BlockCompletionFunc *cb;
4314 if (b->drain_on_flush) {
4315 b->in_flush = true;
4316 cb = bench_cb;
4317 } else {
4318 cb = bench_undrained_flush_cb;
4321 acb = blk_aio_flush(b->blk, cb, b);
4322 if (!acb) {
4323 error_report("Failed to issue flush request");
4324 exit(EXIT_FAILURE);
4327 if (b->drain_on_flush) {
4328 return;
4333 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4334 int64_t offset = b->offset;
4335 /* blk_aio_* might look for completed I/Os and kick bench_cb
4336 * again, so make sure this operation is counted by in_flight
4337 * and b->offset is ready for the next submission.
4339 b->in_flight++;
4340 b->offset += b->step;
4341 b->offset %= b->image_size;
4342 if (b->write) {
4343 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4344 } else {
4345 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4347 if (!acb) {
4348 error_report("Failed to issue request");
4349 exit(EXIT_FAILURE);
4354 static int img_bench(int argc, char **argv)
4356 int c, ret = 0;
4357 const char *fmt = NULL, *filename;
4358 bool quiet = false;
4359 bool image_opts = false;
4360 bool is_write = false;
4361 int count = 75000;
4362 int depth = 64;
4363 int64_t offset = 0;
4364 size_t bufsize = 4096;
4365 int pattern = 0;
4366 size_t step = 0;
4367 int flush_interval = 0;
4368 bool drain_on_flush = true;
4369 int64_t image_size;
4370 BlockBackend *blk = NULL;
4371 BenchData data = {};
4372 int flags = 0;
4373 bool writethrough = false;
4374 struct timeval t1, t2;
4375 int i;
4376 bool force_share = false;
4377 size_t buf_size;
4379 for (;;) {
4380 static const struct option long_options[] = {
4381 {"help", no_argument, 0, 'h'},
4382 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4383 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4384 {"pattern", required_argument, 0, OPTION_PATTERN},
4385 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4386 {"force-share", no_argument, 0, 'U'},
4387 {0, 0, 0, 0}
4389 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4390 NULL);
4391 if (c == -1) {
4392 break;
4395 switch (c) {
4396 case ':':
4397 missing_argument(argv[optind - 1]);
4398 break;
4399 case '?':
4400 unrecognized_option(argv[optind - 1]);
4401 break;
4402 case 'h':
4403 help();
4404 break;
4405 case 'c':
4407 unsigned long res;
4409 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4410 error_report("Invalid request count specified");
4411 return 1;
4413 count = res;
4414 break;
4416 case 'd':
4418 unsigned long res;
4420 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4421 error_report("Invalid queue depth specified");
4422 return 1;
4424 depth = res;
4425 break;
4427 case 'f':
4428 fmt = optarg;
4429 break;
4430 case 'n':
4431 flags |= BDRV_O_NATIVE_AIO;
4432 break;
4433 case 'i':
4434 ret = bdrv_parse_aio(optarg, &flags);
4435 if (ret < 0) {
4436 error_report("Invalid aio option: %s", optarg);
4437 ret = -1;
4438 goto out;
4440 break;
4441 case 'o':
4443 offset = cvtnum("offset", optarg);
4444 if (offset < 0) {
4445 return 1;
4447 break;
4449 break;
4450 case 'q':
4451 quiet = true;
4452 break;
4453 case 's':
4455 int64_t sval;
4457 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4458 if (sval < 0) {
4459 return 1;
4462 bufsize = sval;
4463 break;
4465 case 'S':
4467 int64_t sval;
4469 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4470 if (sval < 0) {
4471 return 1;
4474 step = sval;
4475 break;
4477 case 't':
4478 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4479 if (ret < 0) {
4480 error_report("Invalid cache mode");
4481 ret = -1;
4482 goto out;
4484 break;
4485 case 'w':
4486 flags |= BDRV_O_RDWR;
4487 is_write = true;
4488 break;
4489 case 'U':
4490 force_share = true;
4491 break;
4492 case OPTION_PATTERN:
4494 unsigned long res;
4496 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4497 error_report("Invalid pattern byte specified");
4498 return 1;
4500 pattern = res;
4501 break;
4503 case OPTION_FLUSH_INTERVAL:
4505 unsigned long res;
4507 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4508 error_report("Invalid flush interval specified");
4509 return 1;
4511 flush_interval = res;
4512 break;
4514 case OPTION_NO_DRAIN:
4515 drain_on_flush = false;
4516 break;
4517 case OPTION_IMAGE_OPTS:
4518 image_opts = true;
4519 break;
4523 if (optind != argc - 1) {
4524 error_exit("Expecting one image file name");
4526 filename = argv[argc - 1];
4528 if (!is_write && flush_interval) {
4529 error_report("--flush-interval is only available in write tests");
4530 ret = -1;
4531 goto out;
4533 if (flush_interval && flush_interval < depth) {
4534 error_report("Flush interval can't be smaller than depth");
4535 ret = -1;
4536 goto out;
4539 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4540 force_share);
4541 if (!blk) {
4542 ret = -1;
4543 goto out;
4546 image_size = blk_getlength(blk);
4547 if (image_size < 0) {
4548 ret = image_size;
4549 goto out;
4552 data = (BenchData) {
4553 .blk = blk,
4554 .image_size = image_size,
4555 .bufsize = bufsize,
4556 .step = step ?: bufsize,
4557 .nrreq = depth,
4558 .n = count,
4559 .offset = offset,
4560 .write = is_write,
4561 .flush_interval = flush_interval,
4562 .drain_on_flush = drain_on_flush,
4564 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4565 "(starting at offset %" PRId64 ", step size %d)\n",
4566 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4567 data.offset, data.step);
4568 if (flush_interval) {
4569 printf("Sending flush every %d requests\n", flush_interval);
4572 buf_size = data.nrreq * data.bufsize;
4573 data.buf = blk_blockalign(blk, buf_size);
4574 memset(data.buf, pattern, data.nrreq * data.bufsize);
4576 blk_register_buf(blk, data.buf, buf_size);
4578 data.qiov = g_new(QEMUIOVector, data.nrreq);
4579 for (i = 0; i < data.nrreq; i++) {
4580 qemu_iovec_init(&data.qiov[i], 1);
4581 qemu_iovec_add(&data.qiov[i],
4582 data.buf + i * data.bufsize, data.bufsize);
4585 gettimeofday(&t1, NULL);
4586 bench_cb(&data, 0);
4588 while (data.n > 0) {
4589 main_loop_wait(false);
4591 gettimeofday(&t2, NULL);
4593 printf("Run completed in %3.3f seconds.\n",
4594 (t2.tv_sec - t1.tv_sec)
4595 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4597 out:
4598 if (data.buf) {
4599 blk_unregister_buf(blk, data.buf);
4601 qemu_vfree(data.buf);
4602 blk_unref(blk);
4604 if (ret) {
4605 return 1;
4607 return 0;
4610 enum ImgBitmapAct {
4611 BITMAP_ADD,
4612 BITMAP_REMOVE,
4613 BITMAP_CLEAR,
4614 BITMAP_ENABLE,
4615 BITMAP_DISABLE,
4616 BITMAP_MERGE,
4618 typedef struct ImgBitmapAction {
4619 enum ImgBitmapAct act;
4620 const char *src; /* only used for merge */
4621 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4622 } ImgBitmapAction;
4624 static int img_bitmap(int argc, char **argv)
4626 Error *err = NULL;
4627 int c, ret = 1;
4628 QemuOpts *opts = NULL;
4629 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4630 const char *filename, *bitmap;
4631 BlockBackend *blk = NULL, *src = NULL;
4632 BlockDriverState *bs = NULL, *src_bs = NULL;
4633 bool image_opts = false;
4634 int64_t granularity = 0;
4635 bool add = false, merge = false;
4636 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4637 ImgBitmapAction *act, *act_next;
4638 const char *op;
4640 QSIMPLEQ_INIT(&actions);
4642 for (;;) {
4643 static const struct option long_options[] = {
4644 {"help", no_argument, 0, 'h'},
4645 {"object", required_argument, 0, OPTION_OBJECT},
4646 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4647 {"add", no_argument, 0, OPTION_ADD},
4648 {"remove", no_argument, 0, OPTION_REMOVE},
4649 {"clear", no_argument, 0, OPTION_CLEAR},
4650 {"enable", no_argument, 0, OPTION_ENABLE},
4651 {"disable", no_argument, 0, OPTION_DISABLE},
4652 {"merge", required_argument, 0, OPTION_MERGE},
4653 {"granularity", required_argument, 0, 'g'},
4654 {"source-file", required_argument, 0, 'b'},
4655 {"source-format", required_argument, 0, 'F'},
4656 {0, 0, 0, 0}
4658 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4659 if (c == -1) {
4660 break;
4663 switch (c) {
4664 case ':':
4665 missing_argument(argv[optind - 1]);
4666 break;
4667 case '?':
4668 unrecognized_option(argv[optind - 1]);
4669 break;
4670 case 'h':
4671 help();
4672 break;
4673 case 'b':
4674 src_filename = optarg;
4675 break;
4676 case 'f':
4677 fmt = optarg;
4678 break;
4679 case 'F':
4680 src_fmt = optarg;
4681 break;
4682 case 'g':
4683 granularity = cvtnum("granularity", optarg);
4684 if (granularity < 0) {
4685 return 1;
4687 break;
4688 case OPTION_ADD:
4689 act = g_new0(ImgBitmapAction, 1);
4690 act->act = BITMAP_ADD;
4691 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4692 add = true;
4693 break;
4694 case OPTION_REMOVE:
4695 act = g_new0(ImgBitmapAction, 1);
4696 act->act = BITMAP_REMOVE;
4697 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4698 break;
4699 case OPTION_CLEAR:
4700 act = g_new0(ImgBitmapAction, 1);
4701 act->act = BITMAP_CLEAR;
4702 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4703 break;
4704 case OPTION_ENABLE:
4705 act = g_new0(ImgBitmapAction, 1);
4706 act->act = BITMAP_ENABLE;
4707 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4708 break;
4709 case OPTION_DISABLE:
4710 act = g_new0(ImgBitmapAction, 1);
4711 act->act = BITMAP_DISABLE;
4712 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4713 break;
4714 case OPTION_MERGE:
4715 act = g_new0(ImgBitmapAction, 1);
4716 act->act = BITMAP_MERGE;
4717 act->src = optarg;
4718 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4719 merge = true;
4720 break;
4721 case OPTION_OBJECT:
4722 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4723 if (!opts) {
4724 goto out;
4726 break;
4727 case OPTION_IMAGE_OPTS:
4728 image_opts = true;
4729 break;
4733 if (qemu_opts_foreach(&qemu_object_opts,
4734 user_creatable_add_opts_foreach,
4735 qemu_img_object_print_help, &error_fatal)) {
4736 goto out;
4739 if (QSIMPLEQ_EMPTY(&actions)) {
4740 error_report("Need at least one of --add, --remove, --clear, "
4741 "--enable, --disable, or --merge");
4742 goto out;
4745 if (granularity && !add) {
4746 error_report("granularity only supported with --add");
4747 goto out;
4749 if (src_fmt && !src_filename) {
4750 error_report("-F only supported with -b");
4751 goto out;
4753 if (src_filename && !merge) {
4754 error_report("Merge bitmap source file only supported with "
4755 "--merge");
4756 goto out;
4759 if (optind != argc - 2) {
4760 error_report("Expecting filename and bitmap name");
4761 goto out;
4764 filename = argv[optind];
4765 bitmap = argv[optind + 1];
4767 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4768 false);
4769 if (!blk) {
4770 goto out;
4772 bs = blk_bs(blk);
4773 if (src_filename) {
4774 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4775 if (!src) {
4776 goto out;
4778 src_bs = blk_bs(src);
4779 } else {
4780 src_bs = bs;
4783 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4784 switch (act->act) {
4785 case BITMAP_ADD:
4786 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4787 !!granularity, granularity, true, true,
4788 false, false, &err);
4789 op = "add";
4790 break;
4791 case BITMAP_REMOVE:
4792 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4793 op = "remove";
4794 break;
4795 case BITMAP_CLEAR:
4796 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4797 op = "clear";
4798 break;
4799 case BITMAP_ENABLE:
4800 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4801 op = "enable";
4802 break;
4803 case BITMAP_DISABLE:
4804 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4805 op = "disable";
4806 break;
4807 case BITMAP_MERGE:
4808 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4809 act->src, &err);
4810 op = "merge";
4811 break;
4812 default:
4813 g_assert_not_reached();
4816 if (err) {
4817 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4818 op, bitmap);
4819 goto out;
4821 g_free(act);
4824 ret = 0;
4826 out:
4827 blk_unref(src);
4828 blk_unref(blk);
4829 qemu_opts_del(opts);
4830 return ret;
4833 #define C_BS 01
4834 #define C_COUNT 02
4835 #define C_IF 04
4836 #define C_OF 010
4837 #define C_SKIP 020
4839 struct DdInfo {
4840 unsigned int flags;
4841 int64_t count;
4844 struct DdIo {
4845 int bsz; /* Block size */
4846 char *filename;
4847 uint8_t *buf;
4848 int64_t offset;
4851 struct DdOpts {
4852 const char *name;
4853 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4854 unsigned int flag;
4857 static int img_dd_bs(const char *arg,
4858 struct DdIo *in, struct DdIo *out,
4859 struct DdInfo *dd)
4861 int64_t res;
4863 res = cvtnum_full("bs", arg, 1, INT_MAX);
4865 if (res < 0) {
4866 return 1;
4868 in->bsz = out->bsz = res;
4870 return 0;
4873 static int img_dd_count(const char *arg,
4874 struct DdIo *in, struct DdIo *out,
4875 struct DdInfo *dd)
4877 dd->count = cvtnum("count", arg);
4879 if (dd->count < 0) {
4880 return 1;
4883 return 0;
4886 static int img_dd_if(const char *arg,
4887 struct DdIo *in, struct DdIo *out,
4888 struct DdInfo *dd)
4890 in->filename = g_strdup(arg);
4892 return 0;
4895 static int img_dd_of(const char *arg,
4896 struct DdIo *in, struct DdIo *out,
4897 struct DdInfo *dd)
4899 out->filename = g_strdup(arg);
4901 return 0;
4904 static int img_dd_skip(const char *arg,
4905 struct DdIo *in, struct DdIo *out,
4906 struct DdInfo *dd)
4908 in->offset = cvtnum("skip", arg);
4910 if (in->offset < 0) {
4911 return 1;
4914 return 0;
4917 static int img_dd(int argc, char **argv)
4919 int ret = 0;
4920 char *arg = NULL;
4921 char *tmp;
4922 BlockDriver *drv = NULL, *proto_drv = NULL;
4923 BlockBackend *blk1 = NULL, *blk2 = NULL;
4924 QemuOpts *opts = NULL;
4925 QemuOptsList *create_opts = NULL;
4926 Error *local_err = NULL;
4927 bool image_opts = false;
4928 int c, i;
4929 const char *out_fmt = "raw";
4930 const char *fmt = NULL;
4931 int64_t size = 0;
4932 int64_t block_count = 0, out_pos, in_pos;
4933 bool force_share = false;
4934 struct DdInfo dd = {
4935 .flags = 0,
4936 .count = 0,
4938 struct DdIo in = {
4939 .bsz = 512, /* Block size is by default 512 bytes */
4940 .filename = NULL,
4941 .buf = NULL,
4942 .offset = 0
4944 struct DdIo out = {
4945 .bsz = 512,
4946 .filename = NULL,
4947 .buf = NULL,
4948 .offset = 0
4951 const struct DdOpts options[] = {
4952 { "bs", img_dd_bs, C_BS },
4953 { "count", img_dd_count, C_COUNT },
4954 { "if", img_dd_if, C_IF },
4955 { "of", img_dd_of, C_OF },
4956 { "skip", img_dd_skip, C_SKIP },
4957 { NULL, NULL, 0 }
4959 const struct option long_options[] = {
4960 { "help", no_argument, 0, 'h'},
4961 { "object", required_argument, 0, OPTION_OBJECT},
4962 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4963 { "force-share", no_argument, 0, 'U'},
4964 { 0, 0, 0, 0 }
4967 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4968 if (c == EOF) {
4969 break;
4971 switch (c) {
4972 case 'O':
4973 out_fmt = optarg;
4974 break;
4975 case 'f':
4976 fmt = optarg;
4977 break;
4978 case ':':
4979 missing_argument(argv[optind - 1]);
4980 break;
4981 case '?':
4982 unrecognized_option(argv[optind - 1]);
4983 break;
4984 case 'h':
4985 help();
4986 break;
4987 case 'U':
4988 force_share = true;
4989 break;
4990 case OPTION_OBJECT:
4991 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4992 ret = -1;
4993 goto out;
4995 break;
4996 case OPTION_IMAGE_OPTS:
4997 image_opts = true;
4998 break;
5002 for (i = optind; i < argc; i++) {
5003 int j;
5004 arg = g_strdup(argv[i]);
5006 tmp = strchr(arg, '=');
5007 if (tmp == NULL) {
5008 error_report("unrecognized operand %s", arg);
5009 ret = -1;
5010 goto out;
5013 *tmp++ = '\0';
5015 for (j = 0; options[j].name != NULL; j++) {
5016 if (!strcmp(arg, options[j].name)) {
5017 break;
5020 if (options[j].name == NULL) {
5021 error_report("unrecognized operand %s", arg);
5022 ret = -1;
5023 goto out;
5026 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5027 ret = -1;
5028 goto out;
5030 dd.flags |= options[j].flag;
5031 g_free(arg);
5032 arg = NULL;
5035 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5036 error_report("Must specify both input and output files");
5037 ret = -1;
5038 goto out;
5041 if (qemu_opts_foreach(&qemu_object_opts,
5042 user_creatable_add_opts_foreach,
5043 qemu_img_object_print_help, &error_fatal)) {
5044 ret = -1;
5045 goto out;
5048 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5049 force_share);
5051 if (!blk1) {
5052 ret = -1;
5053 goto out;
5056 drv = bdrv_find_format(out_fmt);
5057 if (!drv) {
5058 error_report("Unknown file format");
5059 ret = -1;
5060 goto out;
5062 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5064 if (!proto_drv) {
5065 error_report_err(local_err);
5066 ret = -1;
5067 goto out;
5069 if (!drv->create_opts) {
5070 error_report("Format driver '%s' does not support image creation",
5071 drv->format_name);
5072 ret = -1;
5073 goto out;
5075 if (!proto_drv->create_opts) {
5076 error_report("Protocol driver '%s' does not support image creation",
5077 proto_drv->format_name);
5078 ret = -1;
5079 goto out;
5081 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5082 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5084 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5086 size = blk_getlength(blk1);
5087 if (size < 0) {
5088 error_report("Failed to get size for '%s'", in.filename);
5089 ret = -1;
5090 goto out;
5093 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5094 dd.count * in.bsz < size) {
5095 size = dd.count * in.bsz;
5098 /* Overflow means the specified offset is beyond input image's size */
5099 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5100 size < in.bsz * in.offset)) {
5101 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5102 } else {
5103 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5104 size - in.bsz * in.offset, &error_abort);
5107 ret = bdrv_create(drv, out.filename, opts, &local_err);
5108 if (ret < 0) {
5109 error_reportf_err(local_err,
5110 "%s: error while creating output image: ",
5111 out.filename);
5112 ret = -1;
5113 goto out;
5116 /* TODO, we can't honour --image-opts for the target,
5117 * since it needs to be given in a format compatible
5118 * with the bdrv_create() call above which does not
5119 * support image-opts style.
5121 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5122 false, false, false);
5124 if (!blk2) {
5125 ret = -1;
5126 goto out;
5129 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5130 size < in.offset * in.bsz)) {
5131 /* We give a warning if the skip option is bigger than the input
5132 * size and create an empty output disk image (i.e. like dd(1)).
5134 error_report("%s: cannot skip to specified offset", in.filename);
5135 in_pos = size;
5136 } else {
5137 in_pos = in.offset * in.bsz;
5140 in.buf = g_new(uint8_t, in.bsz);
5142 for (out_pos = 0; in_pos < size; block_count++) {
5143 int in_ret, out_ret;
5145 if (in_pos + in.bsz > size) {
5146 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5147 } else {
5148 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5150 if (in_ret < 0) {
5151 error_report("error while reading from input image file: %s",
5152 strerror(-in_ret));
5153 ret = -1;
5154 goto out;
5156 in_pos += in_ret;
5158 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5160 if (out_ret < 0) {
5161 error_report("error while writing to output image file: %s",
5162 strerror(-out_ret));
5163 ret = -1;
5164 goto out;
5166 out_pos += out_ret;
5169 out:
5170 g_free(arg);
5171 qemu_opts_del(opts);
5172 qemu_opts_free(create_opts);
5173 blk_unref(blk1);
5174 blk_unref(blk2);
5175 g_free(in.filename);
5176 g_free(out.filename);
5177 g_free(in.buf);
5178 g_free(out.buf);
5180 if (ret) {
5181 return 1;
5183 return 0;
5186 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5188 QString *str;
5189 QObject *obj;
5190 Visitor *v = qobject_output_visitor_new(&obj);
5192 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5193 visit_complete(v, &obj);
5194 str = qobject_to_json_pretty(obj);
5195 assert(str != NULL);
5196 printf("%s\n", qstring_get_str(str));
5197 qobject_unref(obj);
5198 visit_free(v);
5199 qobject_unref(str);
5202 static int img_measure(int argc, char **argv)
5204 static const struct option long_options[] = {
5205 {"help", no_argument, 0, 'h'},
5206 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5207 {"object", required_argument, 0, OPTION_OBJECT},
5208 {"output", required_argument, 0, OPTION_OUTPUT},
5209 {"size", required_argument, 0, OPTION_SIZE},
5210 {"force-share", no_argument, 0, 'U'},
5211 {0, 0, 0, 0}
5213 OutputFormat output_format = OFORMAT_HUMAN;
5214 BlockBackend *in_blk = NULL;
5215 BlockDriver *drv;
5216 const char *filename = NULL;
5217 const char *fmt = NULL;
5218 const char *out_fmt = "raw";
5219 char *options = NULL;
5220 char *snapshot_name = NULL;
5221 bool force_share = false;
5222 QemuOpts *opts = NULL;
5223 QemuOpts *object_opts = NULL;
5224 QemuOpts *sn_opts = NULL;
5225 QemuOptsList *create_opts = NULL;
5226 bool image_opts = false;
5227 uint64_t img_size = UINT64_MAX;
5228 BlockMeasureInfo *info = NULL;
5229 Error *local_err = NULL;
5230 int ret = 1;
5231 int c;
5233 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5234 long_options, NULL)) != -1) {
5235 switch (c) {
5236 case '?':
5237 case 'h':
5238 help();
5239 break;
5240 case 'f':
5241 fmt = optarg;
5242 break;
5243 case 'O':
5244 out_fmt = optarg;
5245 break;
5246 case 'o':
5247 if (accumulate_options(&options, optarg) < 0) {
5248 goto out;
5250 break;
5251 case 'l':
5252 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5253 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5254 optarg, false);
5255 if (!sn_opts) {
5256 error_report("Failed in parsing snapshot param '%s'",
5257 optarg);
5258 goto out;
5260 } else {
5261 snapshot_name = optarg;
5263 break;
5264 case 'U':
5265 force_share = true;
5266 break;
5267 case OPTION_OBJECT:
5268 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5269 optarg, true);
5270 if (!object_opts) {
5271 goto out;
5273 break;
5274 case OPTION_IMAGE_OPTS:
5275 image_opts = true;
5276 break;
5277 case OPTION_OUTPUT:
5278 if (!strcmp(optarg, "json")) {
5279 output_format = OFORMAT_JSON;
5280 } else if (!strcmp(optarg, "human")) {
5281 output_format = OFORMAT_HUMAN;
5282 } else {
5283 error_report("--output must be used with human or json "
5284 "as argument.");
5285 goto out;
5287 break;
5288 case OPTION_SIZE:
5290 int64_t sval;
5292 sval = cvtnum("image size", optarg);
5293 if (sval < 0) {
5294 goto out;
5296 img_size = (uint64_t)sval;
5298 break;
5302 if (qemu_opts_foreach(&qemu_object_opts,
5303 user_creatable_add_opts_foreach,
5304 qemu_img_object_print_help, &error_fatal)) {
5305 goto out;
5308 if (argc - optind > 1) {
5309 error_report("At most one filename argument is allowed.");
5310 goto out;
5311 } else if (argc - optind == 1) {
5312 filename = argv[optind];
5315 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5316 error_report("--image-opts, -f, and -l require a filename argument.");
5317 goto out;
5319 if (filename && img_size != UINT64_MAX) {
5320 error_report("--size N cannot be used together with a filename.");
5321 goto out;
5323 if (!filename && img_size == UINT64_MAX) {
5324 error_report("Either --size N or one filename must be specified.");
5325 goto out;
5328 if (filename) {
5329 in_blk = img_open(image_opts, filename, fmt, 0,
5330 false, false, force_share);
5331 if (!in_blk) {
5332 goto out;
5335 if (sn_opts) {
5336 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5337 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5338 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5339 &local_err);
5340 } else if (snapshot_name != NULL) {
5341 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5342 snapshot_name, &local_err);
5344 if (local_err) {
5345 error_reportf_err(local_err, "Failed to load snapshot: ");
5346 goto out;
5350 drv = bdrv_find_format(out_fmt);
5351 if (!drv) {
5352 error_report("Unknown file format '%s'", out_fmt);
5353 goto out;
5355 if (!drv->create_opts) {
5356 error_report("Format driver '%s' does not support image creation",
5357 drv->format_name);
5358 goto out;
5361 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5362 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5363 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5364 if (options) {
5365 qemu_opts_do_parse(opts, options, NULL, &local_err);
5366 if (local_err) {
5367 error_report_err(local_err);
5368 error_report("Invalid options for file format '%s'", out_fmt);
5369 goto out;
5372 if (img_size != UINT64_MAX) {
5373 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5376 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5377 if (local_err) {
5378 error_report_err(local_err);
5379 goto out;
5382 if (output_format == OFORMAT_HUMAN) {
5383 printf("required size: %" PRIu64 "\n", info->required);
5384 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5385 if (info->has_bitmaps) {
5386 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5388 } else {
5389 dump_json_block_measure_info(info);
5392 ret = 0;
5394 out:
5395 qapi_free_BlockMeasureInfo(info);
5396 qemu_opts_del(object_opts);
5397 qemu_opts_del(opts);
5398 qemu_opts_del(sn_opts);
5399 qemu_opts_free(create_opts);
5400 g_free(options);
5401 blk_unref(in_blk);
5402 return ret;
5405 static const img_cmd_t img_cmds[] = {
5406 #define DEF(option, callback, arg_string) \
5407 { option, callback },
5408 #include "qemu-img-cmds.h"
5409 #undef DEF
5410 { NULL, NULL, },
5413 int main(int argc, char **argv)
5415 const img_cmd_t *cmd;
5416 const char *cmdname;
5417 Error *local_error = NULL;
5418 char *trace_file = NULL;
5419 int c;
5420 static const struct option long_options[] = {
5421 {"help", no_argument, 0, 'h'},
5422 {"version", no_argument, 0, 'V'},
5423 {"trace", required_argument, NULL, 'T'},
5424 {0, 0, 0, 0}
5427 #ifdef CONFIG_POSIX
5428 signal(SIGPIPE, SIG_IGN);
5429 #endif
5431 error_init(argv[0]);
5432 module_call_init(MODULE_INIT_TRACE);
5433 qemu_init_exec_dir(argv[0]);
5435 if (qemu_init_main_loop(&local_error)) {
5436 error_report_err(local_error);
5437 exit(EXIT_FAILURE);
5440 qcrypto_init(&error_fatal);
5442 module_call_init(MODULE_INIT_QOM);
5443 bdrv_init();
5444 if (argc < 2) {
5445 error_exit("Not enough arguments");
5448 qemu_add_opts(&qemu_object_opts);
5449 qemu_add_opts(&qemu_source_opts);
5450 qemu_add_opts(&qemu_trace_opts);
5452 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5453 switch (c) {
5454 case ':':
5455 missing_argument(argv[optind - 1]);
5456 return 0;
5457 case '?':
5458 unrecognized_option(argv[optind - 1]);
5459 return 0;
5460 case 'h':
5461 help();
5462 return 0;
5463 case 'V':
5464 printf(QEMU_IMG_VERSION);
5465 return 0;
5466 case 'T':
5467 g_free(trace_file);
5468 trace_file = trace_opt_parse(optarg);
5469 break;
5473 cmdname = argv[optind];
5475 /* reset getopt_long scanning */
5476 argc -= optind;
5477 if (argc < 1) {
5478 return 0;
5480 argv += optind;
5481 qemu_reset_optind();
5483 if (!trace_init_backends()) {
5484 exit(1);
5486 trace_init_file(trace_file);
5487 qemu_set_log(LOG_TRACE);
5489 /* find the command */
5490 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5491 if (!strcmp(cmdname, cmd->name)) {
5492 return cmd->handler(argc, argv);
5496 /* not found */
5497 error_exit("Command not found: %s", cmdname);