block/crypto: rename two functions
[qemu/ar7.git] / qemu-img.c
blob7f4938a5efbdea3f799d67888678ac1b8c96ebc7
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,
82 OPTION_FORCE = 276,
85 typedef enum OutputFormat {
86 OFORMAT_JSON,
87 OFORMAT_HUMAN,
88 } OutputFormat;
90 /* Default to cache=writeback as data integrity is not important for qemu-img */
91 #define BDRV_DEFAULT_CACHE "writeback"
93 static void format_print(void *opaque, const char *name)
95 printf(" %s", name);
98 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
100 va_list ap;
102 va_start(ap, fmt);
103 error_vreport(fmt, ap);
104 va_end(ap);
106 error_printf("Try 'qemu-img --help' for more information\n");
107 exit(EXIT_FAILURE);
110 static void QEMU_NORETURN missing_argument(const char *option)
112 error_exit("missing argument for option '%s'", option);
115 static void QEMU_NORETURN unrecognized_option(const char *option)
117 error_exit("unrecognized option '%s'", option);
120 /* Please keep in synch with docs/tools/qemu-img.rst */
121 static void QEMU_NORETURN help(void)
123 const char *help_msg =
124 QEMU_IMG_VERSION
125 "usage: qemu-img [standard options] command [command options]\n"
126 "QEMU disk image utility\n"
127 "\n"
128 " '-h', '--help' display this help and exit\n"
129 " '-V', '--version' output version information and exit\n"
130 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
131 " specify tracing options\n"
132 "\n"
133 "Command syntax:\n"
134 #define DEF(option, callback, arg_string) \
135 " " arg_string "\n"
136 #include "qemu-img-cmds.h"
137 #undef DEF
138 "\n"
139 "Command parameters:\n"
140 " 'filename' is a disk image filename\n"
141 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
142 " manual page for a description of the object properties. The most common\n"
143 " object type is a 'secret', which is used to supply passwords and/or\n"
144 " encryption keys.\n"
145 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
146 " 'cache' is the cache mode used to write the output disk image, the valid\n"
147 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
148 " 'directsync' and 'unsafe' (default for convert)\n"
149 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
150 " options are the same as for the 'cache' option\n"
151 " 'size' is the disk image size in bytes. Optional suffixes\n"
152 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
153 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
154 " supported. 'b' is ignored.\n"
155 " 'output_filename' is the destination disk image filename\n"
156 " 'output_fmt' is the destination format\n"
157 " 'options' is a comma separated list of format specific options in a\n"
158 " name=value format. Use -o ? for an overview of the options supported by the\n"
159 " used format\n"
160 " 'snapshot_param' is param used for internal snapshot, format\n"
161 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
162 " '[ID_OR_NAME]'\n"
163 " '-c' indicates that target image must be compressed (qcow format only)\n"
164 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
165 " new backing file match exactly. The image doesn't need a working\n"
166 " backing file before rebasing in this case (useful for renaming the\n"
167 " backing file). For image creation, allow creating without attempting\n"
168 " to open the backing file.\n"
169 " '-h' with or without a command shows this help and lists the supported formats\n"
170 " '-p' show progress of command (only certain commands)\n"
171 " '-q' use Quiet mode - do not print any output (except errors)\n"
172 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
173 " contain only zeros for qemu-img to create a sparse image during\n"
174 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
175 " unallocated or zero sectors, and the destination image will always be\n"
176 " fully allocated\n"
177 " '--output' takes the format in which the output must be done (human or json)\n"
178 " '-n' skips the target volume creation (useful if the volume is created\n"
179 " prior to running qemu-img)\n"
180 "\n"
181 "Parameters to bitmap subcommand:\n"
182 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
183 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
184 " or '--merge source'\n"
185 " '-g granularity' sets the granularity for '--add' actions\n"
186 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
187 " bitmaps from an alternative file\n"
188 "\n"
189 "Parameters to check subcommand:\n"
190 " '-r' tries to repair any inconsistencies that are found during the check.\n"
191 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
192 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
193 " hiding corruption that has already occurred.\n"
194 "\n"
195 "Parameters to convert subcommand:\n"
196 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
197 " '-m' specifies how many coroutines work in parallel during the convert\n"
198 " process (defaults to 8)\n"
199 " '-W' allow to write to the target out of order rather than sequential\n"
200 "\n"
201 "Parameters to snapshot subcommand:\n"
202 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
203 " '-a' applies a snapshot (revert disk to saved state)\n"
204 " '-c' creates a snapshot\n"
205 " '-d' deletes a snapshot\n"
206 " '-l' lists all snapshots in the given image\n"
207 "\n"
208 "Parameters to compare subcommand:\n"
209 " '-f' first image format\n"
210 " '-F' second image format\n"
211 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
212 "\n"
213 "Parameters to dd subcommand:\n"
214 " 'bs=BYTES' read and write up to BYTES bytes at a time "
215 "(default: 512)\n"
216 " 'count=N' copy only N input blocks\n"
217 " 'if=FILE' read from FILE\n"
218 " 'of=FILE' write to FILE\n"
219 " 'skip=N' skip N bs-sized blocks at the start of input\n";
221 printf("%s\nSupported formats:", help_msg);
222 bdrv_iterate_format(format_print, NULL, false);
223 printf("\n\n" QEMU_HELP_BOTTOM "\n");
224 exit(EXIT_SUCCESS);
227 static QemuOptsList qemu_object_opts = {
228 .name = "object",
229 .implied_opt_name = "qom-type",
230 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
231 .desc = {
236 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
238 if (user_creatable_print_help(type, opts)) {
239 exit(0);
241 return true;
245 * Is @optarg safe for accumulate_options()?
246 * It is when multiple of them can be joined together separated by ','.
247 * To make that work, @optarg must not start with ',' (or else a
248 * separating ',' preceding it gets escaped), and it must not end with
249 * an odd number of ',' (or else a separating ',' following it gets
250 * escaped), or be empty (or else a separating ',' preceding it can
251 * escape a separating ',' following it).
254 static bool is_valid_option_list(const char *optarg)
256 size_t len = strlen(optarg);
257 size_t i;
259 if (!optarg[0] || optarg[0] == ',') {
260 return false;
263 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
265 if ((len - i) % 2) {
266 return false;
269 return true;
272 static int accumulate_options(char **options, char *optarg)
274 char *new_options;
276 if (!is_valid_option_list(optarg)) {
277 error_report("Invalid option list: %s", optarg);
278 return -1;
281 if (!*options) {
282 *options = g_strdup(optarg);
283 } else {
284 new_options = g_strdup_printf("%s,%s", *options, optarg);
285 g_free(*options);
286 *options = new_options;
288 return 0;
291 static QemuOptsList qemu_source_opts = {
292 .name = "source",
293 .implied_opt_name = "file",
294 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
295 .desc = {
300 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
302 int ret = 0;
303 if (!quiet) {
304 va_list args;
305 va_start(args, fmt);
306 ret = vprintf(fmt, args);
307 va_end(args);
309 return ret;
313 static int print_block_option_help(const char *filename, const char *fmt)
315 BlockDriver *drv, *proto_drv;
316 QemuOptsList *create_opts = NULL;
317 Error *local_err = NULL;
319 /* Find driver and parse its options */
320 drv = bdrv_find_format(fmt);
321 if (!drv) {
322 error_report("Unknown file format '%s'", fmt);
323 return 1;
326 if (!drv->create_opts) {
327 error_report("Format driver '%s' does not support image creation", fmt);
328 return 1;
331 create_opts = qemu_opts_append(create_opts, drv->create_opts);
332 if (filename) {
333 proto_drv = bdrv_find_protocol(filename, true, &local_err);
334 if (!proto_drv) {
335 error_report_err(local_err);
336 qemu_opts_free(create_opts);
337 return 1;
339 if (!proto_drv->create_opts) {
340 error_report("Protocol driver '%s' does not support image creation",
341 proto_drv->format_name);
342 qemu_opts_free(create_opts);
343 return 1;
345 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
348 if (filename) {
349 printf("Supported options:\n");
350 } else {
351 printf("Supported %s options:\n", fmt);
353 qemu_opts_print_help(create_opts, false);
354 qemu_opts_free(create_opts);
356 if (!filename) {
357 printf("\n"
358 "The protocol level may support further options.\n"
359 "Specify the target filename to include those options.\n");
362 return 0;
366 static BlockBackend *img_open_opts(const char *optstr,
367 QemuOpts *opts, int flags, bool writethrough,
368 bool quiet, bool force_share)
370 QDict *options;
371 Error *local_err = NULL;
372 BlockBackend *blk;
373 options = qemu_opts_to_qdict(opts, NULL);
374 if (force_share) {
375 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
376 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
377 error_report("--force-share/-U conflicts with image options");
378 qobject_unref(options);
379 return NULL;
381 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
383 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
384 if (!blk) {
385 error_reportf_err(local_err, "Could not open '%s': ", optstr);
386 return NULL;
388 blk_set_enable_write_cache(blk, !writethrough);
390 return blk;
393 static BlockBackend *img_open_file(const char *filename,
394 QDict *options,
395 const char *fmt, int flags,
396 bool writethrough, bool quiet,
397 bool force_share)
399 BlockBackend *blk;
400 Error *local_err = NULL;
402 if (!options) {
403 options = qdict_new();
405 if (fmt) {
406 qdict_put_str(options, "driver", fmt);
409 if (force_share) {
410 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
412 blk = blk_new_open(filename, NULL, options, flags, &local_err);
413 if (!blk) {
414 error_reportf_err(local_err, "Could not open '%s': ", filename);
415 return NULL;
417 blk_set_enable_write_cache(blk, !writethrough);
419 return blk;
423 static int img_add_key_secrets(void *opaque,
424 const char *name, const char *value,
425 Error **errp)
427 QDict *options = opaque;
429 if (g_str_has_suffix(name, "key-secret")) {
430 qdict_put_str(options, name, value);
433 return 0;
437 static BlockBackend *img_open(bool image_opts,
438 const char *filename,
439 const char *fmt, int flags, bool writethrough,
440 bool quiet, bool force_share)
442 BlockBackend *blk;
443 if (image_opts) {
444 QemuOpts *opts;
445 if (fmt) {
446 error_report("--image-opts and --format are mutually exclusive");
447 return NULL;
449 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
450 filename, true);
451 if (!opts) {
452 return NULL;
454 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
455 force_share);
456 } else {
457 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
458 force_share);
460 return blk;
464 static int add_old_style_options(const char *fmt, QemuOpts *opts,
465 const char *base_filename,
466 const char *base_fmt)
468 Error *err = NULL;
470 if (base_filename) {
471 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
472 if (err) {
473 error_report("Backing file not supported for file format '%s'",
474 fmt);
475 error_free(err);
476 return -1;
479 if (base_fmt) {
480 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
481 if (err) {
482 error_report("Backing file format not supported for file "
483 "format '%s'", fmt);
484 error_free(err);
485 return -1;
488 return 0;
491 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
492 int64_t max)
494 int err;
495 uint64_t res;
497 err = qemu_strtosz(value, NULL, &res);
498 if (err < 0 && err != -ERANGE) {
499 error_report("Invalid %s specified. You may use "
500 "k, M, G, T, P or E suffixes for", name);
501 error_report("kilobytes, megabytes, gigabytes, terabytes, "
502 "petabytes and exabytes.");
503 return err;
505 if (err == -ERANGE || res > max || res < min) {
506 error_report("Invalid %s specified. Must be between %" PRId64
507 " and %" PRId64 ".", name, min, max);
508 return -ERANGE;
510 return res;
513 static int64_t cvtnum(const char *name, const char *value)
515 return cvtnum_full(name, value, 0, INT64_MAX);
518 static int img_create(int argc, char **argv)
520 int c;
521 uint64_t img_size = -1;
522 const char *fmt = "raw";
523 const char *base_fmt = NULL;
524 const char *filename;
525 const char *base_filename = NULL;
526 char *options = NULL;
527 Error *local_err = NULL;
528 bool quiet = false;
529 int flags = 0;
531 for(;;) {
532 static const struct option long_options[] = {
533 {"help", no_argument, 0, 'h'},
534 {"object", required_argument, 0, OPTION_OBJECT},
535 {0, 0, 0, 0}
537 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
538 long_options, NULL);
539 if (c == -1) {
540 break;
542 switch(c) {
543 case ':':
544 missing_argument(argv[optind - 1]);
545 break;
546 case '?':
547 unrecognized_option(argv[optind - 1]);
548 break;
549 case 'h':
550 help();
551 break;
552 case 'F':
553 base_fmt = optarg;
554 break;
555 case 'b':
556 base_filename = optarg;
557 break;
558 case 'f':
559 fmt = optarg;
560 break;
561 case 'o':
562 if (accumulate_options(&options, optarg) < 0) {
563 goto fail;
565 break;
566 case 'q':
567 quiet = true;
568 break;
569 case 'u':
570 flags |= BDRV_O_NO_BACKING;
571 break;
572 case OPTION_OBJECT: {
573 QemuOpts *opts;
574 opts = qemu_opts_parse_noisily(&qemu_object_opts,
575 optarg, true);
576 if (!opts) {
577 goto fail;
579 } break;
583 /* Get the filename */
584 filename = (optind < argc) ? argv[optind] : NULL;
585 if (options && has_help_option(options)) {
586 g_free(options);
587 return print_block_option_help(filename, fmt);
590 if (optind >= argc) {
591 error_exit("Expecting image file name");
593 optind++;
595 if (qemu_opts_foreach(&qemu_object_opts,
596 user_creatable_add_opts_foreach,
597 qemu_img_object_print_help, &error_fatal)) {
598 goto fail;
601 /* Get image size, if specified */
602 if (optind < argc) {
603 int64_t sval;
605 sval = cvtnum("image size", argv[optind++]);
606 if (sval < 0) {
607 goto fail;
609 img_size = (uint64_t)sval;
611 if (optind != argc) {
612 error_exit("Unexpected argument: %s", argv[optind]);
615 bdrv_img_create(filename, fmt, base_filename, base_fmt,
616 options, img_size, flags, quiet, &local_err);
617 if (local_err) {
618 error_reportf_err(local_err, "%s: ", filename);
619 goto fail;
622 g_free(options);
623 return 0;
625 fail:
626 g_free(options);
627 return 1;
630 static void dump_json_image_check(ImageCheck *check, bool quiet)
632 QString *str;
633 QObject *obj;
634 Visitor *v = qobject_output_visitor_new(&obj);
636 visit_type_ImageCheck(v, NULL, &check, &error_abort);
637 visit_complete(v, &obj);
638 str = qobject_to_json_pretty(obj);
639 assert(str != NULL);
640 qprintf(quiet, "%s\n", qstring_get_str(str));
641 qobject_unref(obj);
642 visit_free(v);
643 qobject_unref(str);
646 static void dump_human_image_check(ImageCheck *check, bool quiet)
648 if (!(check->corruptions || check->leaks || check->check_errors)) {
649 qprintf(quiet, "No errors were found on the image.\n");
650 } else {
651 if (check->corruptions) {
652 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
653 "Data may be corrupted, or further writes to the image "
654 "may corrupt it.\n",
655 check->corruptions);
658 if (check->leaks) {
659 qprintf(quiet,
660 "\n%" PRId64 " leaked clusters were found on the image.\n"
661 "This means waste of disk space, but no harm to data.\n",
662 check->leaks);
665 if (check->check_errors) {
666 qprintf(quiet,
667 "\n%" PRId64
668 " internal errors have occurred during the check.\n",
669 check->check_errors);
673 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
674 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
675 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
676 check->allocated_clusters, check->total_clusters,
677 check->allocated_clusters * 100.0 / check->total_clusters,
678 check->fragmented_clusters * 100.0 / check->allocated_clusters,
679 check->compressed_clusters * 100.0 /
680 check->allocated_clusters);
683 if (check->image_end_offset) {
684 qprintf(quiet,
685 "Image end offset: %" PRId64 "\n", check->image_end_offset);
689 static int collect_image_check(BlockDriverState *bs,
690 ImageCheck *check,
691 const char *filename,
692 const char *fmt,
693 int fix)
695 int ret;
696 BdrvCheckResult result;
698 ret = bdrv_check(bs, &result, fix);
699 if (ret < 0) {
700 return ret;
703 check->filename = g_strdup(filename);
704 check->format = g_strdup(bdrv_get_format_name(bs));
705 check->check_errors = result.check_errors;
706 check->corruptions = result.corruptions;
707 check->has_corruptions = result.corruptions != 0;
708 check->leaks = result.leaks;
709 check->has_leaks = result.leaks != 0;
710 check->corruptions_fixed = result.corruptions_fixed;
711 check->has_corruptions_fixed = result.corruptions_fixed != 0;
712 check->leaks_fixed = result.leaks_fixed;
713 check->has_leaks_fixed = result.leaks_fixed != 0;
714 check->image_end_offset = result.image_end_offset;
715 check->has_image_end_offset = result.image_end_offset != 0;
716 check->total_clusters = result.bfi.total_clusters;
717 check->has_total_clusters = result.bfi.total_clusters != 0;
718 check->allocated_clusters = result.bfi.allocated_clusters;
719 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
720 check->fragmented_clusters = result.bfi.fragmented_clusters;
721 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
722 check->compressed_clusters = result.bfi.compressed_clusters;
723 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
725 return 0;
729 * Checks an image for consistency. Exit codes:
731 * 0 - Check completed, image is good
732 * 1 - Check not completed because of internal errors
733 * 2 - Check completed, image is corrupted
734 * 3 - Check completed, image has leaked clusters, but is good otherwise
735 * 63 - Checks are not supported by the image format
737 static int img_check(int argc, char **argv)
739 int c, ret;
740 OutputFormat output_format = OFORMAT_HUMAN;
741 const char *filename, *fmt, *output, *cache;
742 BlockBackend *blk;
743 BlockDriverState *bs;
744 int fix = 0;
745 int flags = BDRV_O_CHECK;
746 bool writethrough;
747 ImageCheck *check;
748 bool quiet = false;
749 bool image_opts = false;
750 bool force_share = false;
752 fmt = NULL;
753 output = NULL;
754 cache = BDRV_DEFAULT_CACHE;
756 for(;;) {
757 int option_index = 0;
758 static const struct option long_options[] = {
759 {"help", no_argument, 0, 'h'},
760 {"format", required_argument, 0, 'f'},
761 {"repair", required_argument, 0, 'r'},
762 {"output", required_argument, 0, OPTION_OUTPUT},
763 {"object", required_argument, 0, OPTION_OBJECT},
764 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
765 {"force-share", no_argument, 0, 'U'},
766 {0, 0, 0, 0}
768 c = getopt_long(argc, argv, ":hf:r:T:qU",
769 long_options, &option_index);
770 if (c == -1) {
771 break;
773 switch(c) {
774 case ':':
775 missing_argument(argv[optind - 1]);
776 break;
777 case '?':
778 unrecognized_option(argv[optind - 1]);
779 break;
780 case 'h':
781 help();
782 break;
783 case 'f':
784 fmt = optarg;
785 break;
786 case 'r':
787 flags |= BDRV_O_RDWR;
789 if (!strcmp(optarg, "leaks")) {
790 fix = BDRV_FIX_LEAKS;
791 } else if (!strcmp(optarg, "all")) {
792 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
793 } else {
794 error_exit("Unknown option value for -r "
795 "(expecting 'leaks' or 'all'): %s", optarg);
797 break;
798 case OPTION_OUTPUT:
799 output = optarg;
800 break;
801 case 'T':
802 cache = optarg;
803 break;
804 case 'q':
805 quiet = true;
806 break;
807 case 'U':
808 force_share = true;
809 break;
810 case OPTION_OBJECT: {
811 QemuOpts *opts;
812 opts = qemu_opts_parse_noisily(&qemu_object_opts,
813 optarg, true);
814 if (!opts) {
815 return 1;
817 } break;
818 case OPTION_IMAGE_OPTS:
819 image_opts = true;
820 break;
823 if (optind != argc - 1) {
824 error_exit("Expecting one image file name");
826 filename = argv[optind++];
828 if (output && !strcmp(output, "json")) {
829 output_format = OFORMAT_JSON;
830 } else if (output && !strcmp(output, "human")) {
831 output_format = OFORMAT_HUMAN;
832 } else if (output) {
833 error_report("--output must be used with human or json as argument.");
834 return 1;
837 if (qemu_opts_foreach(&qemu_object_opts,
838 user_creatable_add_opts_foreach,
839 qemu_img_object_print_help, &error_fatal)) {
840 return 1;
843 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
844 if (ret < 0) {
845 error_report("Invalid source cache option: %s", cache);
846 return 1;
849 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
850 force_share);
851 if (!blk) {
852 return 1;
854 bs = blk_bs(blk);
856 check = g_new0(ImageCheck, 1);
857 ret = collect_image_check(bs, check, filename, fmt, fix);
859 if (ret == -ENOTSUP) {
860 error_report("This image format does not support checks");
861 ret = 63;
862 goto fail;
865 if (check->corruptions_fixed || check->leaks_fixed) {
866 int corruptions_fixed, leaks_fixed;
867 bool has_leaks_fixed, has_corruptions_fixed;
869 leaks_fixed = check->leaks_fixed;
870 has_leaks_fixed = check->has_leaks_fixed;
871 corruptions_fixed = check->corruptions_fixed;
872 has_corruptions_fixed = check->has_corruptions_fixed;
874 if (output_format == OFORMAT_HUMAN) {
875 qprintf(quiet,
876 "The following inconsistencies were found and repaired:\n\n"
877 " %" PRId64 " leaked clusters\n"
878 " %" PRId64 " corruptions\n\n"
879 "Double checking the fixed image now...\n",
880 check->leaks_fixed,
881 check->corruptions_fixed);
884 qapi_free_ImageCheck(check);
885 check = g_new0(ImageCheck, 1);
886 ret = collect_image_check(bs, check, filename, fmt, 0);
888 check->leaks_fixed = leaks_fixed;
889 check->has_leaks_fixed = has_leaks_fixed;
890 check->corruptions_fixed = corruptions_fixed;
891 check->has_corruptions_fixed = has_corruptions_fixed;
894 if (!ret) {
895 switch (output_format) {
896 case OFORMAT_HUMAN:
897 dump_human_image_check(check, quiet);
898 break;
899 case OFORMAT_JSON:
900 dump_json_image_check(check, quiet);
901 break;
905 if (ret || check->check_errors) {
906 if (ret) {
907 error_report("Check failed: %s", strerror(-ret));
908 } else {
909 error_report("Check failed");
911 ret = 1;
912 goto fail;
915 if (check->corruptions) {
916 ret = 2;
917 } else if (check->leaks) {
918 ret = 3;
919 } else {
920 ret = 0;
923 fail:
924 qapi_free_ImageCheck(check);
925 blk_unref(blk);
926 return ret;
929 typedef struct CommonBlockJobCBInfo {
930 BlockDriverState *bs;
931 Error **errp;
932 } CommonBlockJobCBInfo;
934 static void common_block_job_cb(void *opaque, int ret)
936 CommonBlockJobCBInfo *cbi = opaque;
938 if (ret < 0) {
939 error_setg_errno(cbi->errp, -ret, "Block job failed");
943 static void run_block_job(BlockJob *job, Error **errp)
945 AioContext *aio_context = blk_get_aio_context(job->blk);
946 int ret = 0;
948 aio_context_acquire(aio_context);
949 job_ref(&job->job);
950 do {
951 float progress = 0.0f;
952 aio_poll(aio_context, true);
953 if (job->job.progress.total) {
954 progress = (float)job->job.progress.current /
955 job->job.progress.total * 100.f;
957 qemu_progress_print(progress, 0);
958 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
960 if (!job_is_completed(&job->job)) {
961 ret = job_complete_sync(&job->job, errp);
962 } else {
963 ret = job->job.ret;
965 job_unref(&job->job);
966 aio_context_release(aio_context);
968 /* publish completion progress only when success */
969 if (!ret) {
970 qemu_progress_print(100.f, 0);
974 static int img_commit(int argc, char **argv)
976 int c, ret, flags;
977 const char *filename, *fmt, *cache, *base;
978 BlockBackend *blk;
979 BlockDriverState *bs, *base_bs;
980 BlockJob *job;
981 bool progress = false, quiet = false, drop = false;
982 bool writethrough;
983 Error *local_err = NULL;
984 CommonBlockJobCBInfo cbi;
985 bool image_opts = false;
986 AioContext *aio_context;
988 fmt = NULL;
989 cache = BDRV_DEFAULT_CACHE;
990 base = NULL;
991 for(;;) {
992 static const struct option long_options[] = {
993 {"help", no_argument, 0, 'h'},
994 {"object", required_argument, 0, OPTION_OBJECT},
995 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
996 {0, 0, 0, 0}
998 c = getopt_long(argc, argv, ":f:ht:b:dpq",
999 long_options, NULL);
1000 if (c == -1) {
1001 break;
1003 switch(c) {
1004 case ':':
1005 missing_argument(argv[optind - 1]);
1006 break;
1007 case '?':
1008 unrecognized_option(argv[optind - 1]);
1009 break;
1010 case 'h':
1011 help();
1012 break;
1013 case 'f':
1014 fmt = optarg;
1015 break;
1016 case 't':
1017 cache = optarg;
1018 break;
1019 case 'b':
1020 base = optarg;
1021 /* -b implies -d */
1022 drop = true;
1023 break;
1024 case 'd':
1025 drop = true;
1026 break;
1027 case 'p':
1028 progress = true;
1029 break;
1030 case 'q':
1031 quiet = true;
1032 break;
1033 case OPTION_OBJECT: {
1034 QemuOpts *opts;
1035 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1036 optarg, true);
1037 if (!opts) {
1038 return 1;
1040 } break;
1041 case OPTION_IMAGE_OPTS:
1042 image_opts = true;
1043 break;
1047 /* Progress is not shown in Quiet mode */
1048 if (quiet) {
1049 progress = false;
1052 if (optind != argc - 1) {
1053 error_exit("Expecting one image file name");
1055 filename = argv[optind++];
1057 if (qemu_opts_foreach(&qemu_object_opts,
1058 user_creatable_add_opts_foreach,
1059 qemu_img_object_print_help, &error_fatal)) {
1060 return 1;
1063 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1064 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1065 if (ret < 0) {
1066 error_report("Invalid cache option: %s", cache);
1067 return 1;
1070 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1071 false);
1072 if (!blk) {
1073 return 1;
1075 bs = blk_bs(blk);
1077 qemu_progress_init(progress, 1.f);
1078 qemu_progress_print(0.f, 100);
1080 if (base) {
1081 base_bs = bdrv_find_backing_image(bs, base);
1082 if (!base_bs) {
1083 error_setg(&local_err,
1084 "Did not find '%s' in the backing chain of '%s'",
1085 base, filename);
1086 goto done;
1088 } else {
1089 /* This is different from QMP, which by default uses the deepest file in
1090 * the backing chain (i.e., the very base); however, the traditional
1091 * behavior of qemu-img commit is using the immediate backing file. */
1092 base_bs = backing_bs(bs);
1093 if (!base_bs) {
1094 error_setg(&local_err, "Image does not have a backing file");
1095 goto done;
1099 cbi = (CommonBlockJobCBInfo){
1100 .errp = &local_err,
1101 .bs = bs,
1104 aio_context = bdrv_get_aio_context(bs);
1105 aio_context_acquire(aio_context);
1106 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1107 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1108 &cbi, false, &local_err);
1109 aio_context_release(aio_context);
1110 if (local_err) {
1111 goto done;
1114 /* When the block job completes, the BlockBackend reference will point to
1115 * the old backing file. In order to avoid that the top image is already
1116 * deleted, so we can still empty it afterwards, increment the reference
1117 * counter here preemptively. */
1118 if (!drop) {
1119 bdrv_ref(bs);
1122 job = block_job_get("commit");
1123 assert(job);
1124 run_block_job(job, &local_err);
1125 if (local_err) {
1126 goto unref_backing;
1129 if (!drop) {
1130 BlockBackend *old_backing_blk;
1132 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1133 &local_err);
1134 if (!old_backing_blk) {
1135 goto unref_backing;
1137 ret = blk_make_empty(old_backing_blk, &local_err);
1138 blk_unref(old_backing_blk);
1139 if (ret == -ENOTSUP) {
1140 error_free(local_err);
1141 local_err = NULL;
1142 } else if (ret < 0) {
1143 goto unref_backing;
1147 unref_backing:
1148 if (!drop) {
1149 bdrv_unref(bs);
1152 done:
1153 qemu_progress_end();
1155 blk_unref(blk);
1157 if (local_err) {
1158 error_report_err(local_err);
1159 return 1;
1162 qprintf(quiet, "Image committed.\n");
1163 return 0;
1167 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1168 * of the first sector boundary within buf where the sector contains a
1169 * non-zero byte. This function is robust to a buffer that is not
1170 * sector-aligned.
1172 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1174 int64_t i;
1175 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1177 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1178 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1179 return i;
1182 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1183 return i;
1185 return -1;
1189 * Returns true iff the first sector pointed to by 'buf' contains at least
1190 * a non-NUL byte.
1192 * 'pnum' is set to the number of sectors (including and immediately following
1193 * the first one) that are known to be in the same allocated/unallocated state.
1194 * The function will try to align the end offset to alignment boundaries so
1195 * that the request will at least end aligned and consequtive requests will
1196 * also start at an aligned offset.
1198 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1199 int64_t sector_num, int alignment)
1201 bool is_zero;
1202 int i, tail;
1204 if (n <= 0) {
1205 *pnum = 0;
1206 return 0;
1208 is_zero = buffer_is_zero(buf, 512);
1209 for(i = 1; i < n; i++) {
1210 buf += 512;
1211 if (is_zero != buffer_is_zero(buf, 512)) {
1212 break;
1216 tail = (sector_num + i) & (alignment - 1);
1217 if (tail) {
1218 if (is_zero && i <= tail) {
1219 /* treat unallocated areas which only consist
1220 * of a small tail as allocated. */
1221 is_zero = false;
1223 if (!is_zero) {
1224 /* align up end offset of allocated areas. */
1225 i += alignment - tail;
1226 i = MIN(i, n);
1227 } else {
1228 /* align down end offset of zero areas. */
1229 i -= tail;
1232 *pnum = i;
1233 return !is_zero;
1237 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1238 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1239 * breaking up write requests for only small sparse areas.
1241 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1242 int min, int64_t sector_num, int alignment)
1244 int ret;
1245 int num_checked, num_used;
1247 if (n < min) {
1248 min = n;
1251 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1252 if (!ret) {
1253 return ret;
1256 num_used = *pnum;
1257 buf += BDRV_SECTOR_SIZE * *pnum;
1258 n -= *pnum;
1259 sector_num += *pnum;
1260 num_checked = num_used;
1262 while (n > 0) {
1263 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1265 buf += BDRV_SECTOR_SIZE * *pnum;
1266 n -= *pnum;
1267 sector_num += *pnum;
1268 num_checked += *pnum;
1269 if (ret) {
1270 num_used = num_checked;
1271 } else if (*pnum >= min) {
1272 break;
1276 *pnum = num_used;
1277 return 1;
1281 * Compares two buffers sector by sector. Returns 0 if the first
1282 * sector of each buffer matches, non-zero otherwise.
1284 * pnum is set to the sector-aligned size of the buffer prefix that
1285 * has the same matching status as the first sector.
1287 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1288 int64_t bytes, int64_t *pnum)
1290 bool res;
1291 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1293 assert(bytes > 0);
1295 res = !!memcmp(buf1, buf2, i);
1296 while (i < bytes) {
1297 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1299 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1300 break;
1302 i += len;
1305 *pnum = i;
1306 return res;
1309 #define IO_BUF_SIZE (2 * MiB)
1312 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1314 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1315 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1316 * failure), and 4 on error (the exit status for read errors), after emitting
1317 * an error message.
1319 * @param blk: BlockBackend for the image
1320 * @param offset: Starting offset to check
1321 * @param bytes: Number of bytes to check
1322 * @param filename: Name of disk file we are checking (logging purpose)
1323 * @param buffer: Allocated buffer for storing read data
1324 * @param quiet: Flag for quiet mode
1326 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1327 int64_t bytes, const char *filename,
1328 uint8_t *buffer, bool quiet)
1330 int ret = 0;
1331 int64_t idx;
1333 ret = blk_pread(blk, offset, buffer, bytes);
1334 if (ret < 0) {
1335 error_report("Error while reading offset %" PRId64 " of %s: %s",
1336 offset, filename, strerror(-ret));
1337 return 4;
1339 idx = find_nonzero(buffer, bytes);
1340 if (idx >= 0) {
1341 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1342 offset + idx);
1343 return 1;
1346 return 0;
1350 * Compares two images. Exit codes:
1352 * 0 - Images are identical
1353 * 1 - Images differ
1354 * >1 - Error occurred
1356 static int img_compare(int argc, char **argv)
1358 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1359 BlockBackend *blk1, *blk2;
1360 BlockDriverState *bs1, *bs2;
1361 int64_t total_size1, total_size2;
1362 uint8_t *buf1 = NULL, *buf2 = NULL;
1363 int64_t pnum1, pnum2;
1364 int allocated1, allocated2;
1365 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1366 bool progress = false, quiet = false, strict = false;
1367 int flags;
1368 bool writethrough;
1369 int64_t total_size;
1370 int64_t offset = 0;
1371 int64_t chunk;
1372 int c;
1373 uint64_t progress_base;
1374 bool image_opts = false;
1375 bool force_share = false;
1377 cache = BDRV_DEFAULT_CACHE;
1378 for (;;) {
1379 static const struct option long_options[] = {
1380 {"help", no_argument, 0, 'h'},
1381 {"object", required_argument, 0, OPTION_OBJECT},
1382 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1383 {"force-share", no_argument, 0, 'U'},
1384 {0, 0, 0, 0}
1386 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1387 long_options, NULL);
1388 if (c == -1) {
1389 break;
1391 switch (c) {
1392 case ':':
1393 missing_argument(argv[optind - 1]);
1394 break;
1395 case '?':
1396 unrecognized_option(argv[optind - 1]);
1397 break;
1398 case 'h':
1399 help();
1400 break;
1401 case 'f':
1402 fmt1 = optarg;
1403 break;
1404 case 'F':
1405 fmt2 = optarg;
1406 break;
1407 case 'T':
1408 cache = optarg;
1409 break;
1410 case 'p':
1411 progress = true;
1412 break;
1413 case 'q':
1414 quiet = true;
1415 break;
1416 case 's':
1417 strict = true;
1418 break;
1419 case 'U':
1420 force_share = true;
1421 break;
1422 case OPTION_OBJECT: {
1423 QemuOpts *opts;
1424 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1425 optarg, true);
1426 if (!opts) {
1427 ret = 2;
1428 goto out4;
1430 } break;
1431 case OPTION_IMAGE_OPTS:
1432 image_opts = true;
1433 break;
1437 /* Progress is not shown in Quiet mode */
1438 if (quiet) {
1439 progress = false;
1443 if (optind != argc - 2) {
1444 error_exit("Expecting two image file names");
1446 filename1 = argv[optind++];
1447 filename2 = argv[optind++];
1449 if (qemu_opts_foreach(&qemu_object_opts,
1450 user_creatable_add_opts_foreach,
1451 qemu_img_object_print_help, &error_fatal)) {
1452 ret = 2;
1453 goto out4;
1456 /* Initialize before goto out */
1457 qemu_progress_init(progress, 2.0);
1459 flags = 0;
1460 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1461 if (ret < 0) {
1462 error_report("Invalid source cache option: %s", cache);
1463 ret = 2;
1464 goto out3;
1467 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1468 force_share);
1469 if (!blk1) {
1470 ret = 2;
1471 goto out3;
1474 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1475 force_share);
1476 if (!blk2) {
1477 ret = 2;
1478 goto out2;
1480 bs1 = blk_bs(blk1);
1481 bs2 = blk_bs(blk2);
1483 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1484 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1485 total_size1 = blk_getlength(blk1);
1486 if (total_size1 < 0) {
1487 error_report("Can't get size of %s: %s",
1488 filename1, strerror(-total_size1));
1489 ret = 4;
1490 goto out;
1492 total_size2 = blk_getlength(blk2);
1493 if (total_size2 < 0) {
1494 error_report("Can't get size of %s: %s",
1495 filename2, strerror(-total_size2));
1496 ret = 4;
1497 goto out;
1499 total_size = MIN(total_size1, total_size2);
1500 progress_base = MAX(total_size1, total_size2);
1502 qemu_progress_print(0, 100);
1504 if (strict && total_size1 != total_size2) {
1505 ret = 1;
1506 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1507 goto out;
1510 while (offset < total_size) {
1511 int status1, status2;
1513 status1 = bdrv_block_status_above(bs1, NULL, offset,
1514 total_size1 - offset, &pnum1, NULL,
1515 NULL);
1516 if (status1 < 0) {
1517 ret = 3;
1518 error_report("Sector allocation test failed for %s", filename1);
1519 goto out;
1521 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1523 status2 = bdrv_block_status_above(bs2, NULL, offset,
1524 total_size2 - offset, &pnum2, NULL,
1525 NULL);
1526 if (status2 < 0) {
1527 ret = 3;
1528 error_report("Sector allocation test failed for %s", filename2);
1529 goto out;
1531 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1533 assert(pnum1 && pnum2);
1534 chunk = MIN(pnum1, pnum2);
1536 if (strict) {
1537 if (status1 != status2) {
1538 ret = 1;
1539 qprintf(quiet, "Strict mode: Offset %" PRId64
1540 " block status mismatch!\n", offset);
1541 goto out;
1544 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1545 /* nothing to do */
1546 } else if (allocated1 == allocated2) {
1547 if (allocated1) {
1548 int64_t pnum;
1550 chunk = MIN(chunk, IO_BUF_SIZE);
1551 ret = blk_pread(blk1, offset, buf1, chunk);
1552 if (ret < 0) {
1553 error_report("Error while reading offset %" PRId64
1554 " of %s: %s",
1555 offset, filename1, strerror(-ret));
1556 ret = 4;
1557 goto out;
1559 ret = blk_pread(blk2, offset, buf2, chunk);
1560 if (ret < 0) {
1561 error_report("Error while reading offset %" PRId64
1562 " of %s: %s",
1563 offset, filename2, strerror(-ret));
1564 ret = 4;
1565 goto out;
1567 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1568 if (ret || pnum != chunk) {
1569 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1570 offset + (ret ? 0 : pnum));
1571 ret = 1;
1572 goto out;
1575 } else {
1576 chunk = MIN(chunk, IO_BUF_SIZE);
1577 if (allocated1) {
1578 ret = check_empty_sectors(blk1, offset, chunk,
1579 filename1, buf1, quiet);
1580 } else {
1581 ret = check_empty_sectors(blk2, offset, chunk,
1582 filename2, buf1, quiet);
1584 if (ret) {
1585 goto out;
1588 offset += chunk;
1589 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1592 if (total_size1 != total_size2) {
1593 BlockBackend *blk_over;
1594 const char *filename_over;
1596 qprintf(quiet, "Warning: Image size mismatch!\n");
1597 if (total_size1 > total_size2) {
1598 blk_over = blk1;
1599 filename_over = filename1;
1600 } else {
1601 blk_over = blk2;
1602 filename_over = filename2;
1605 while (offset < progress_base) {
1606 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1607 progress_base - offset, &chunk,
1608 NULL, NULL);
1609 if (ret < 0) {
1610 ret = 3;
1611 error_report("Sector allocation test failed for %s",
1612 filename_over);
1613 goto out;
1616 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1617 chunk = MIN(chunk, IO_BUF_SIZE);
1618 ret = check_empty_sectors(blk_over, offset, chunk,
1619 filename_over, buf1, quiet);
1620 if (ret) {
1621 goto out;
1624 offset += chunk;
1625 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1629 qprintf(quiet, "Images are identical.\n");
1630 ret = 0;
1632 out:
1633 qemu_vfree(buf1);
1634 qemu_vfree(buf2);
1635 blk_unref(blk2);
1636 out2:
1637 blk_unref(blk1);
1638 out3:
1639 qemu_progress_end();
1640 out4:
1641 return ret;
1644 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1645 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1646 const char *src_node, const char *src_name,
1647 Error **errp)
1649 BlockDirtyBitmapMergeSource *merge_src;
1650 BlockDirtyBitmapMergeSourceList *list;
1652 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1653 merge_src->type = QTYPE_QDICT;
1654 merge_src->u.external.node = g_strdup(src_node);
1655 merge_src->u.external.name = g_strdup(src_name);
1656 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1657 list->value = merge_src;
1658 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1659 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1662 enum ImgConvertBlockStatus {
1663 BLK_DATA,
1664 BLK_ZERO,
1665 BLK_BACKING_FILE,
1668 #define MAX_COROUTINES 16
1670 typedef struct ImgConvertState {
1671 BlockBackend **src;
1672 int64_t *src_sectors;
1673 int src_num;
1674 int64_t total_sectors;
1675 int64_t allocated_sectors;
1676 int64_t allocated_done;
1677 int64_t sector_num;
1678 int64_t wr_offs;
1679 enum ImgConvertBlockStatus status;
1680 int64_t sector_next_status;
1681 BlockBackend *target;
1682 bool has_zero_init;
1683 bool compressed;
1684 bool unallocated_blocks_are_zero;
1685 bool target_is_new;
1686 bool target_has_backing;
1687 int64_t target_backing_sectors; /* negative if unknown */
1688 bool wr_in_order;
1689 bool copy_range;
1690 bool salvage;
1691 bool quiet;
1692 int min_sparse;
1693 int alignment;
1694 size_t cluster_sectors;
1695 size_t buf_sectors;
1696 long num_coroutines;
1697 int running_coroutines;
1698 Coroutine *co[MAX_COROUTINES];
1699 int64_t wait_sector_num[MAX_COROUTINES];
1700 CoMutex lock;
1701 int ret;
1702 } ImgConvertState;
1704 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1705 int *src_cur, int64_t *src_cur_offset)
1707 *src_cur = 0;
1708 *src_cur_offset = 0;
1709 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1710 *src_cur_offset += s->src_sectors[*src_cur];
1711 (*src_cur)++;
1712 assert(*src_cur < s->src_num);
1716 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1718 int64_t src_cur_offset;
1719 int ret, n, src_cur;
1720 bool post_backing_zero = false;
1722 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1724 assert(s->total_sectors > sector_num);
1725 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1727 if (s->target_backing_sectors >= 0) {
1728 if (sector_num >= s->target_backing_sectors) {
1729 post_backing_zero = s->unallocated_blocks_are_zero;
1730 } else if (sector_num + n > s->target_backing_sectors) {
1731 /* Split requests around target_backing_sectors (because
1732 * starting from there, zeros are handled differently) */
1733 n = s->target_backing_sectors - sector_num;
1737 if (s->sector_next_status <= sector_num) {
1738 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1739 int64_t count;
1741 do {
1742 count = n * BDRV_SECTOR_SIZE;
1744 if (s->target_has_backing) {
1745 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1746 count, &count, NULL, NULL);
1747 } else {
1748 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1749 offset, count, &count, NULL,
1750 NULL);
1753 if (ret < 0) {
1754 if (s->salvage) {
1755 if (n == 1) {
1756 if (!s->quiet) {
1757 warn_report("error while reading block status at "
1758 "offset %" PRIu64 ": %s", offset,
1759 strerror(-ret));
1761 /* Just try to read the data, then */
1762 ret = BDRV_BLOCK_DATA;
1763 count = BDRV_SECTOR_SIZE;
1764 } else {
1765 /* Retry on a shorter range */
1766 n = DIV_ROUND_UP(n, 4);
1768 } else {
1769 error_report("error while reading block status at offset "
1770 "%" PRIu64 ": %s", offset, strerror(-ret));
1771 return ret;
1774 } while (ret < 0);
1776 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1778 if (ret & BDRV_BLOCK_ZERO) {
1779 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1780 } else if (ret & BDRV_BLOCK_DATA) {
1781 s->status = BLK_DATA;
1782 } else {
1783 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1786 s->sector_next_status = sector_num + n;
1789 n = MIN(n, s->sector_next_status - sector_num);
1790 if (s->status == BLK_DATA) {
1791 n = MIN(n, s->buf_sectors);
1794 /* We need to write complete clusters for compressed images, so if an
1795 * unallocated area is shorter than that, we must consider the whole
1796 * cluster allocated. */
1797 if (s->compressed) {
1798 if (n < s->cluster_sectors) {
1799 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1800 s->status = BLK_DATA;
1801 } else {
1802 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1806 return n;
1809 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1810 int nb_sectors, uint8_t *buf)
1812 uint64_t single_read_until = 0;
1813 int n, ret;
1815 assert(nb_sectors <= s->buf_sectors);
1816 while (nb_sectors > 0) {
1817 BlockBackend *blk;
1818 int src_cur;
1819 int64_t bs_sectors, src_cur_offset;
1820 uint64_t offset;
1822 /* In the case of compression with multiple source files, we can get a
1823 * nb_sectors that spreads into the next part. So we must be able to
1824 * read across multiple BDSes for one convert_read() call. */
1825 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1826 blk = s->src[src_cur];
1827 bs_sectors = s->src_sectors[src_cur];
1829 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1831 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1832 if (single_read_until > offset) {
1833 n = 1;
1836 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1837 if (ret < 0) {
1838 if (s->salvage) {
1839 if (n > 1) {
1840 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1841 continue;
1842 } else {
1843 if (!s->quiet) {
1844 warn_report("error while reading offset %" PRIu64
1845 ": %s", offset, strerror(-ret));
1847 memset(buf, 0, BDRV_SECTOR_SIZE);
1849 } else {
1850 return ret;
1854 sector_num += n;
1855 nb_sectors -= n;
1856 buf += n * BDRV_SECTOR_SIZE;
1859 return 0;
1863 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1864 int nb_sectors, uint8_t *buf,
1865 enum ImgConvertBlockStatus status)
1867 int ret;
1869 while (nb_sectors > 0) {
1870 int n = nb_sectors;
1871 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1873 switch (status) {
1874 case BLK_BACKING_FILE:
1875 /* If we have a backing file, leave clusters unallocated that are
1876 * unallocated in the source image, so that the backing file is
1877 * visible at the respective offset. */
1878 assert(s->target_has_backing);
1879 break;
1881 case BLK_DATA:
1882 /* If we're told to keep the target fully allocated (-S 0) or there
1883 * is real non-zero data, we must write it. Otherwise we can treat
1884 * it as zero sectors.
1885 * Compressed clusters need to be written as a whole, so in that
1886 * case we can only save the write if the buffer is completely
1887 * zeroed. */
1888 if (!s->min_sparse ||
1889 (!s->compressed &&
1890 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1891 sector_num, s->alignment)) ||
1892 (s->compressed &&
1893 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1895 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1896 n << BDRV_SECTOR_BITS, buf, flags);
1897 if (ret < 0) {
1898 return ret;
1900 break;
1902 /* fall-through */
1904 case BLK_ZERO:
1905 if (s->has_zero_init) {
1906 assert(!s->target_has_backing);
1907 break;
1909 ret = blk_co_pwrite_zeroes(s->target,
1910 sector_num << BDRV_SECTOR_BITS,
1911 n << BDRV_SECTOR_BITS,
1912 BDRV_REQ_MAY_UNMAP);
1913 if (ret < 0) {
1914 return ret;
1916 break;
1919 sector_num += n;
1920 nb_sectors -= n;
1921 buf += n * BDRV_SECTOR_SIZE;
1924 return 0;
1927 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1928 int nb_sectors)
1930 int n, ret;
1932 while (nb_sectors > 0) {
1933 BlockBackend *blk;
1934 int src_cur;
1935 int64_t bs_sectors, src_cur_offset;
1936 int64_t offset;
1938 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1939 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1940 blk = s->src[src_cur];
1941 bs_sectors = s->src_sectors[src_cur];
1943 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1945 ret = blk_co_copy_range(blk, offset, s->target,
1946 sector_num << BDRV_SECTOR_BITS,
1947 n << BDRV_SECTOR_BITS, 0, 0);
1948 if (ret < 0) {
1949 return ret;
1952 sector_num += n;
1953 nb_sectors -= n;
1955 return 0;
1958 static void coroutine_fn convert_co_do_copy(void *opaque)
1960 ImgConvertState *s = opaque;
1961 uint8_t *buf = NULL;
1962 int ret, i;
1963 int index = -1;
1965 for (i = 0; i < s->num_coroutines; i++) {
1966 if (s->co[i] == qemu_coroutine_self()) {
1967 index = i;
1968 break;
1971 assert(index >= 0);
1973 s->running_coroutines++;
1974 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1976 while (1) {
1977 int n;
1978 int64_t sector_num;
1979 enum ImgConvertBlockStatus status;
1980 bool copy_range;
1982 qemu_co_mutex_lock(&s->lock);
1983 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1984 qemu_co_mutex_unlock(&s->lock);
1985 break;
1987 n = convert_iteration_sectors(s, s->sector_num);
1988 if (n < 0) {
1989 qemu_co_mutex_unlock(&s->lock);
1990 s->ret = n;
1991 break;
1993 /* save current sector and allocation status to local variables */
1994 sector_num = s->sector_num;
1995 status = s->status;
1996 if (!s->min_sparse && s->status == BLK_ZERO) {
1997 n = MIN(n, s->buf_sectors);
1999 /* increment global sector counter so that other coroutines can
2000 * already continue reading beyond this request */
2001 s->sector_num += n;
2002 qemu_co_mutex_unlock(&s->lock);
2004 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2005 s->allocated_done += n;
2006 qemu_progress_print(100.0 * s->allocated_done /
2007 s->allocated_sectors, 0);
2010 retry:
2011 copy_range = s->copy_range && s->status == BLK_DATA;
2012 if (status == BLK_DATA && !copy_range) {
2013 ret = convert_co_read(s, sector_num, n, buf);
2014 if (ret < 0) {
2015 error_report("error while reading at byte %lld: %s",
2016 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2017 s->ret = ret;
2019 } else if (!s->min_sparse && status == BLK_ZERO) {
2020 status = BLK_DATA;
2021 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2024 if (s->wr_in_order) {
2025 /* keep writes in order */
2026 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2027 s->wait_sector_num[index] = sector_num;
2028 qemu_coroutine_yield();
2030 s->wait_sector_num[index] = -1;
2033 if (s->ret == -EINPROGRESS) {
2034 if (copy_range) {
2035 ret = convert_co_copy_range(s, sector_num, n);
2036 if (ret) {
2037 s->copy_range = false;
2038 goto retry;
2040 } else {
2041 ret = convert_co_write(s, sector_num, n, buf, status);
2043 if (ret < 0) {
2044 error_report("error while writing at byte %lld: %s",
2045 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2046 s->ret = ret;
2050 if (s->wr_in_order) {
2051 /* reenter the coroutine that might have waited
2052 * for this write to complete */
2053 s->wr_offs = sector_num + n;
2054 for (i = 0; i < s->num_coroutines; i++) {
2055 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2057 * A -> B -> A cannot occur because A has
2058 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2059 * B will never enter A during this time window.
2061 qemu_coroutine_enter(s->co[i]);
2062 break;
2068 qemu_vfree(buf);
2069 s->co[index] = NULL;
2070 s->running_coroutines--;
2071 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2072 /* the convert job finished successfully */
2073 s->ret = 0;
2077 static int convert_do_copy(ImgConvertState *s)
2079 int ret, i, n;
2080 int64_t sector_num = 0;
2082 /* Check whether we have zero initialisation or can get it efficiently */
2083 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2084 !s->target_has_backing) {
2085 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2088 /* Allocate buffer for copied data. For compressed images, only one cluster
2089 * can be copied at a time. */
2090 if (s->compressed) {
2091 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2092 error_report("invalid cluster size");
2093 return -EINVAL;
2095 s->buf_sectors = s->cluster_sectors;
2098 while (sector_num < s->total_sectors) {
2099 n = convert_iteration_sectors(s, sector_num);
2100 if (n < 0) {
2101 return n;
2103 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2105 s->allocated_sectors += n;
2107 sector_num += n;
2110 /* Do the copy */
2111 s->sector_next_status = 0;
2112 s->ret = -EINPROGRESS;
2114 qemu_co_mutex_init(&s->lock);
2115 for (i = 0; i < s->num_coroutines; i++) {
2116 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2117 s->wait_sector_num[i] = -1;
2118 qemu_coroutine_enter(s->co[i]);
2121 while (s->running_coroutines) {
2122 main_loop_wait(false);
2125 if (s->compressed && !s->ret) {
2126 /* signal EOF to align */
2127 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2128 if (ret < 0) {
2129 return ret;
2133 return s->ret;
2136 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2138 BdrvDirtyBitmap *bm;
2139 Error *err = NULL;
2141 FOR_EACH_DIRTY_BITMAP(src, bm) {
2142 const char *name;
2144 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2145 continue;
2147 name = bdrv_dirty_bitmap_name(bm);
2148 qmp_block_dirty_bitmap_add(dst->node_name, name,
2149 true, bdrv_dirty_bitmap_granularity(bm),
2150 true, true,
2151 true, !bdrv_dirty_bitmap_enabled(bm),
2152 &err);
2153 if (err) {
2154 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2155 return -1;
2158 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2159 &err);
2160 if (err) {
2161 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2162 return -1;
2166 return 0;
2169 #define MAX_BUF_SECTORS 32768
2171 static int img_convert(int argc, char **argv)
2173 int c, bs_i, flags, src_flags = 0;
2174 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2175 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2176 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2177 BlockDriver *drv = NULL, *proto_drv = NULL;
2178 BlockDriverInfo bdi;
2179 BlockDriverState *out_bs;
2180 QemuOpts *opts = NULL, *sn_opts = NULL;
2181 QemuOptsList *create_opts = NULL;
2182 QDict *open_opts = NULL;
2183 char *options = NULL;
2184 Error *local_err = NULL;
2185 bool writethrough, src_writethrough, image_opts = false,
2186 skip_create = false, progress = false, tgt_image_opts = false;
2187 int64_t ret = -EINVAL;
2188 bool force_share = false;
2189 bool explict_min_sparse = false;
2190 bool bitmaps = false;
2192 ImgConvertState s = (ImgConvertState) {
2193 /* Need at least 4k of zeros for sparse detection */
2194 .min_sparse = 8,
2195 .copy_range = false,
2196 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2197 .wr_in_order = true,
2198 .num_coroutines = 8,
2201 for(;;) {
2202 static const struct option long_options[] = {
2203 {"help", no_argument, 0, 'h'},
2204 {"object", required_argument, 0, OPTION_OBJECT},
2205 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2206 {"force-share", no_argument, 0, 'U'},
2207 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2208 {"salvage", no_argument, 0, OPTION_SALVAGE},
2209 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2210 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2211 {0, 0, 0, 0}
2213 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2214 long_options, NULL);
2215 if (c == -1) {
2216 break;
2218 switch(c) {
2219 case ':':
2220 missing_argument(argv[optind - 1]);
2221 break;
2222 case '?':
2223 unrecognized_option(argv[optind - 1]);
2224 break;
2225 case 'h':
2226 help();
2227 break;
2228 case 'f':
2229 fmt = optarg;
2230 break;
2231 case 'O':
2232 out_fmt = optarg;
2233 break;
2234 case 'B':
2235 out_baseimg = optarg;
2236 break;
2237 case 'C':
2238 s.copy_range = true;
2239 break;
2240 case 'c':
2241 s.compressed = true;
2242 break;
2243 case 'o':
2244 if (accumulate_options(&options, optarg) < 0) {
2245 goto fail_getopt;
2247 break;
2248 case 'l':
2249 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2250 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2251 optarg, false);
2252 if (!sn_opts) {
2253 error_report("Failed in parsing snapshot param '%s'",
2254 optarg);
2255 goto fail_getopt;
2257 } else {
2258 snapshot_name = optarg;
2260 break;
2261 case 'S':
2263 int64_t sval;
2265 sval = cvtnum("buffer size for sparse output", optarg);
2266 if (sval < 0) {
2267 goto fail_getopt;
2268 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2269 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2270 error_report("Invalid buffer size for sparse output specified. "
2271 "Valid sizes are multiples of %llu up to %llu. Select "
2272 "0 to disable sparse detection (fully allocates output).",
2273 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2274 goto fail_getopt;
2277 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2278 explict_min_sparse = true;
2279 break;
2281 case 'p':
2282 progress = true;
2283 break;
2284 case 't':
2285 cache = optarg;
2286 break;
2287 case 'T':
2288 src_cache = optarg;
2289 break;
2290 case 'q':
2291 s.quiet = true;
2292 break;
2293 case 'n':
2294 skip_create = true;
2295 break;
2296 case 'm':
2297 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2298 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2299 error_report("Invalid number of coroutines. Allowed number of"
2300 " coroutines is between 1 and %d", MAX_COROUTINES);
2301 goto fail_getopt;
2303 break;
2304 case 'W':
2305 s.wr_in_order = false;
2306 break;
2307 case 'U':
2308 force_share = true;
2309 break;
2310 case OPTION_OBJECT: {
2311 QemuOpts *object_opts;
2312 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2313 optarg, true);
2314 if (!object_opts) {
2315 goto fail_getopt;
2317 break;
2319 case OPTION_IMAGE_OPTS:
2320 image_opts = true;
2321 break;
2322 case OPTION_SALVAGE:
2323 s.salvage = true;
2324 break;
2325 case OPTION_TARGET_IMAGE_OPTS:
2326 tgt_image_opts = true;
2327 break;
2328 case OPTION_TARGET_IS_ZERO:
2330 * The user asserting that the target is blank has the
2331 * same effect as the target driver supporting zero
2332 * initialisation.
2334 s.has_zero_init = true;
2335 break;
2336 case OPTION_BITMAPS:
2337 bitmaps = true;
2338 break;
2342 if (!out_fmt && !tgt_image_opts) {
2343 out_fmt = "raw";
2346 if (qemu_opts_foreach(&qemu_object_opts,
2347 user_creatable_add_opts_foreach,
2348 qemu_img_object_print_help, &error_fatal)) {
2349 goto fail_getopt;
2352 if (s.compressed && s.copy_range) {
2353 error_report("Cannot enable copy offloading when -c is used");
2354 goto fail_getopt;
2357 if (explict_min_sparse && s.copy_range) {
2358 error_report("Cannot enable copy offloading when -S is used");
2359 goto fail_getopt;
2362 if (s.copy_range && s.salvage) {
2363 error_report("Cannot use copy offloading in salvaging mode");
2364 goto fail_getopt;
2367 if (tgt_image_opts && !skip_create) {
2368 error_report("--target-image-opts requires use of -n flag");
2369 goto fail_getopt;
2372 if (skip_create && options) {
2373 warn_report("-o has no effect when skipping image creation");
2374 warn_report("This will become an error in future QEMU versions.");
2377 if (s.has_zero_init && !skip_create) {
2378 error_report("--target-is-zero requires use of -n flag");
2379 goto fail_getopt;
2382 s.src_num = argc - optind - 1;
2383 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2385 if (options && has_help_option(options)) {
2386 if (out_fmt) {
2387 ret = print_block_option_help(out_filename, out_fmt);
2388 goto fail_getopt;
2389 } else {
2390 error_report("Option help requires a format be specified");
2391 goto fail_getopt;
2395 if (s.src_num < 1) {
2396 error_report("Must specify image file name");
2397 goto fail_getopt;
2400 /* ret is still -EINVAL until here */
2401 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2402 if (ret < 0) {
2403 error_report("Invalid source cache option: %s", src_cache);
2404 goto fail_getopt;
2407 /* Initialize before goto out */
2408 if (s.quiet) {
2409 progress = false;
2411 qemu_progress_init(progress, 1.0);
2412 qemu_progress_print(0, 100);
2414 s.src = g_new0(BlockBackend *, s.src_num);
2415 s.src_sectors = g_new(int64_t, s.src_num);
2417 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2418 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2419 fmt, src_flags, src_writethrough, s.quiet,
2420 force_share);
2421 if (!s.src[bs_i]) {
2422 ret = -1;
2423 goto out;
2425 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2426 if (s.src_sectors[bs_i] < 0) {
2427 error_report("Could not get size of %s: %s",
2428 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2429 ret = -1;
2430 goto out;
2432 s.total_sectors += s.src_sectors[bs_i];
2435 if (sn_opts) {
2436 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2437 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2438 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2439 &local_err);
2440 } else if (snapshot_name != NULL) {
2441 if (s.src_num > 1) {
2442 error_report("No support for concatenating multiple snapshot");
2443 ret = -1;
2444 goto out;
2447 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2448 &local_err);
2450 if (local_err) {
2451 error_reportf_err(local_err, "Failed to load snapshot: ");
2452 ret = -1;
2453 goto out;
2456 if (!skip_create) {
2457 /* Find driver and parse its options */
2458 drv = bdrv_find_format(out_fmt);
2459 if (!drv) {
2460 error_report("Unknown file format '%s'", out_fmt);
2461 ret = -1;
2462 goto out;
2465 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2466 if (!proto_drv) {
2467 error_report_err(local_err);
2468 ret = -1;
2469 goto out;
2472 if (!drv->create_opts) {
2473 error_report("Format driver '%s' does not support image creation",
2474 drv->format_name);
2475 ret = -1;
2476 goto out;
2479 if (!proto_drv->create_opts) {
2480 error_report("Protocol driver '%s' does not support image creation",
2481 proto_drv->format_name);
2482 ret = -1;
2483 goto out;
2486 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2487 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2489 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2490 if (options) {
2491 qemu_opts_do_parse(opts, options, NULL, &local_err);
2492 if (local_err) {
2493 error_report_err(local_err);
2494 ret = -1;
2495 goto out;
2499 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2500 &error_abort);
2501 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2502 if (ret < 0) {
2503 goto out;
2507 /* Get backing file name if -o backing_file was used */
2508 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2509 if (out_baseimg_param) {
2510 out_baseimg = out_baseimg_param;
2512 s.target_has_backing = (bool) out_baseimg;
2514 if (s.has_zero_init && s.target_has_backing) {
2515 error_report("Cannot use --target-is-zero when the destination "
2516 "image has a backing file");
2517 goto out;
2520 if (s.src_num > 1 && out_baseimg) {
2521 error_report("Having a backing file for the target makes no sense when "
2522 "concatenating multiple input images");
2523 ret = -1;
2524 goto out;
2527 /* Check if compression is supported */
2528 if (s.compressed) {
2529 bool encryption =
2530 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2531 const char *encryptfmt =
2532 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2533 const char *preallocation =
2534 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2536 if (drv && !block_driver_can_compress(drv)) {
2537 error_report("Compression not supported for this file format");
2538 ret = -1;
2539 goto out;
2542 if (encryption || encryptfmt) {
2543 error_report("Compression and encryption not supported at "
2544 "the same time");
2545 ret = -1;
2546 goto out;
2549 if (preallocation
2550 && strcmp(preallocation, "off"))
2552 error_report("Compression and preallocation not supported at "
2553 "the same time");
2554 ret = -1;
2555 goto out;
2559 /* Determine if bitmaps need copying */
2560 if (bitmaps) {
2561 if (s.src_num > 1) {
2562 error_report("Copying bitmaps only possible with single source");
2563 ret = -1;
2564 goto out;
2566 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2567 error_report("Source lacks bitmap support");
2568 ret = -1;
2569 goto out;
2574 * The later open call will need any decryption secrets, and
2575 * bdrv_create() will purge "opts", so extract them now before
2576 * they are lost.
2578 if (!skip_create) {
2579 open_opts = qdict_new();
2580 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2582 /* Create the new image */
2583 ret = bdrv_create(drv, out_filename, opts, &local_err);
2584 if (ret < 0) {
2585 error_reportf_err(local_err, "%s: error while converting %s: ",
2586 out_filename, out_fmt);
2587 goto out;
2591 s.target_is_new = !skip_create;
2593 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2594 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2595 if (ret < 0) {
2596 error_report("Invalid cache option: %s", cache);
2597 goto out;
2600 if (skip_create) {
2601 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2602 flags, writethrough, s.quiet, false);
2603 } else {
2604 /* TODO ultimately we should allow --target-image-opts
2605 * to be used even when -n is not given.
2606 * That has to wait for bdrv_create to be improved
2607 * to allow filenames in option syntax
2609 s.target = img_open_file(out_filename, open_opts, out_fmt,
2610 flags, writethrough, s.quiet, false);
2611 open_opts = NULL; /* blk_new_open will have freed it */
2613 if (!s.target) {
2614 ret = -1;
2615 goto out;
2617 out_bs = blk_bs(s.target);
2619 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2620 error_report("Format driver '%s' does not support bitmaps",
2621 out_bs->drv->format_name);
2622 ret = -1;
2623 goto out;
2626 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2627 error_report("Compression not supported for this file format");
2628 ret = -1;
2629 goto out;
2632 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2633 * or discard_alignment of the out_bs is greater. Limit to
2634 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2635 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2636 MAX(s.buf_sectors,
2637 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2638 out_bs->bl.pdiscard_alignment >>
2639 BDRV_SECTOR_BITS)));
2641 /* try to align the write requests to the destination to avoid unnecessary
2642 * RMW cycles. */
2643 s.alignment = MAX(pow2floor(s.min_sparse),
2644 DIV_ROUND_UP(out_bs->bl.request_alignment,
2645 BDRV_SECTOR_SIZE));
2646 assert(is_power_of_2(s.alignment));
2648 if (skip_create) {
2649 int64_t output_sectors = blk_nb_sectors(s.target);
2650 if (output_sectors < 0) {
2651 error_report("unable to get output image length: %s",
2652 strerror(-output_sectors));
2653 ret = -1;
2654 goto out;
2655 } else if (output_sectors < s.total_sectors) {
2656 error_report("output file is smaller than input file");
2657 ret = -1;
2658 goto out;
2662 if (s.target_has_backing && s.target_is_new) {
2663 /* Errors are treated as "backing length unknown" (which means
2664 * s.target_backing_sectors has to be negative, which it will
2665 * be automatically). The backing file length is used only
2666 * for optimizations, so such a case is not fatal. */
2667 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2668 } else {
2669 s.target_backing_sectors = -1;
2672 ret = bdrv_get_info(out_bs, &bdi);
2673 if (ret < 0) {
2674 if (s.compressed) {
2675 error_report("could not get block driver info");
2676 goto out;
2678 } else {
2679 s.compressed = s.compressed || bdi.needs_compressed_writes;
2680 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2681 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2684 ret = convert_do_copy(&s);
2686 /* Now copy the bitmaps */
2687 if (bitmaps && ret == 0) {
2688 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2691 out:
2692 if (!ret) {
2693 qemu_progress_print(100, 0);
2695 qemu_progress_end();
2696 qemu_opts_del(opts);
2697 qemu_opts_free(create_opts);
2698 qemu_opts_del(sn_opts);
2699 qobject_unref(open_opts);
2700 blk_unref(s.target);
2701 if (s.src) {
2702 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2703 blk_unref(s.src[bs_i]);
2705 g_free(s.src);
2707 g_free(s.src_sectors);
2708 fail_getopt:
2709 g_free(options);
2711 return !!ret;
2715 static void dump_snapshots(BlockDriverState *bs)
2717 QEMUSnapshotInfo *sn_tab, *sn;
2718 int nb_sns, i;
2720 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2721 if (nb_sns <= 0)
2722 return;
2723 printf("Snapshot list:\n");
2724 bdrv_snapshot_dump(NULL);
2725 printf("\n");
2726 for(i = 0; i < nb_sns; i++) {
2727 sn = &sn_tab[i];
2728 bdrv_snapshot_dump(sn);
2729 printf("\n");
2731 g_free(sn_tab);
2734 static void dump_json_image_info_list(ImageInfoList *list)
2736 QString *str;
2737 QObject *obj;
2738 Visitor *v = qobject_output_visitor_new(&obj);
2740 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2741 visit_complete(v, &obj);
2742 str = qobject_to_json_pretty(obj);
2743 assert(str != NULL);
2744 printf("%s\n", qstring_get_str(str));
2745 qobject_unref(obj);
2746 visit_free(v);
2747 qobject_unref(str);
2750 static void dump_json_image_info(ImageInfo *info)
2752 QString *str;
2753 QObject *obj;
2754 Visitor *v = qobject_output_visitor_new(&obj);
2756 visit_type_ImageInfo(v, NULL, &info, &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_human_image_info_list(ImageInfoList *list)
2768 ImageInfoList *elem;
2769 bool delim = false;
2771 for (elem = list; elem; elem = elem->next) {
2772 if (delim) {
2773 printf("\n");
2775 delim = true;
2777 bdrv_image_info_dump(elem->value);
2781 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2783 return strcmp(a, b) == 0;
2787 * Open an image file chain and return an ImageInfoList
2789 * @filename: topmost image filename
2790 * @fmt: topmost image format (may be NULL to autodetect)
2791 * @chain: true - enumerate entire backing file chain
2792 * false - only topmost image file
2794 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2795 * image file. If there was an error a message will have been printed to
2796 * stderr.
2798 static ImageInfoList *collect_image_info_list(bool image_opts,
2799 const char *filename,
2800 const char *fmt,
2801 bool chain, bool force_share)
2803 ImageInfoList *head = NULL;
2804 ImageInfoList **last = &head;
2805 GHashTable *filenames;
2806 Error *err = NULL;
2808 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2810 while (filename) {
2811 BlockBackend *blk;
2812 BlockDriverState *bs;
2813 ImageInfo *info;
2814 ImageInfoList *elem;
2816 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2817 error_report("Backing file '%s' creates an infinite loop.",
2818 filename);
2819 goto err;
2821 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2823 blk = img_open(image_opts, filename, fmt,
2824 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2825 force_share);
2826 if (!blk) {
2827 goto err;
2829 bs = blk_bs(blk);
2831 bdrv_query_image_info(bs, &info, &err);
2832 if (err) {
2833 error_report_err(err);
2834 blk_unref(blk);
2835 goto err;
2838 elem = g_new0(ImageInfoList, 1);
2839 elem->value = info;
2840 *last = elem;
2841 last = &elem->next;
2843 blk_unref(blk);
2845 /* Clear parameters that only apply to the topmost image */
2846 filename = fmt = NULL;
2847 image_opts = false;
2849 if (chain) {
2850 if (info->has_full_backing_filename) {
2851 filename = info->full_backing_filename;
2852 } else if (info->has_backing_filename) {
2853 error_report("Could not determine absolute backing filename,"
2854 " but backing filename '%s' present",
2855 info->backing_filename);
2856 goto err;
2858 if (info->has_backing_filename_format) {
2859 fmt = info->backing_filename_format;
2863 g_hash_table_destroy(filenames);
2864 return head;
2866 err:
2867 qapi_free_ImageInfoList(head);
2868 g_hash_table_destroy(filenames);
2869 return NULL;
2872 static int img_info(int argc, char **argv)
2874 int c;
2875 OutputFormat output_format = OFORMAT_HUMAN;
2876 bool chain = false;
2877 const char *filename, *fmt, *output;
2878 ImageInfoList *list;
2879 bool image_opts = false;
2880 bool force_share = false;
2882 fmt = NULL;
2883 output = NULL;
2884 for(;;) {
2885 int option_index = 0;
2886 static const struct option long_options[] = {
2887 {"help", no_argument, 0, 'h'},
2888 {"format", required_argument, 0, 'f'},
2889 {"output", required_argument, 0, OPTION_OUTPUT},
2890 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2891 {"object", required_argument, 0, OPTION_OBJECT},
2892 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2893 {"force-share", no_argument, 0, 'U'},
2894 {0, 0, 0, 0}
2896 c = getopt_long(argc, argv, ":f:hU",
2897 long_options, &option_index);
2898 if (c == -1) {
2899 break;
2901 switch(c) {
2902 case ':':
2903 missing_argument(argv[optind - 1]);
2904 break;
2905 case '?':
2906 unrecognized_option(argv[optind - 1]);
2907 break;
2908 case 'h':
2909 help();
2910 break;
2911 case 'f':
2912 fmt = optarg;
2913 break;
2914 case 'U':
2915 force_share = true;
2916 break;
2917 case OPTION_OUTPUT:
2918 output = optarg;
2919 break;
2920 case OPTION_BACKING_CHAIN:
2921 chain = true;
2922 break;
2923 case OPTION_OBJECT: {
2924 QemuOpts *opts;
2925 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2926 optarg, true);
2927 if (!opts) {
2928 return 1;
2930 } break;
2931 case OPTION_IMAGE_OPTS:
2932 image_opts = true;
2933 break;
2936 if (optind != argc - 1) {
2937 error_exit("Expecting one image file name");
2939 filename = argv[optind++];
2941 if (output && !strcmp(output, "json")) {
2942 output_format = OFORMAT_JSON;
2943 } else if (output && !strcmp(output, "human")) {
2944 output_format = OFORMAT_HUMAN;
2945 } else if (output) {
2946 error_report("--output must be used with human or json as argument.");
2947 return 1;
2950 if (qemu_opts_foreach(&qemu_object_opts,
2951 user_creatable_add_opts_foreach,
2952 qemu_img_object_print_help, &error_fatal)) {
2953 return 1;
2956 list = collect_image_info_list(image_opts, filename, fmt, chain,
2957 force_share);
2958 if (!list) {
2959 return 1;
2962 switch (output_format) {
2963 case OFORMAT_HUMAN:
2964 dump_human_image_info_list(list);
2965 break;
2966 case OFORMAT_JSON:
2967 if (chain) {
2968 dump_json_image_info_list(list);
2969 } else {
2970 dump_json_image_info(list->value);
2972 break;
2975 qapi_free_ImageInfoList(list);
2976 return 0;
2979 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2980 MapEntry *next)
2982 switch (output_format) {
2983 case OFORMAT_HUMAN:
2984 if (e->data && !e->has_offset) {
2985 error_report("File contains external, encrypted or compressed clusters.");
2986 return -1;
2988 if (e->data && !e->zero) {
2989 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2990 e->start, e->length,
2991 e->has_offset ? e->offset : 0,
2992 e->has_filename ? e->filename : "");
2994 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2995 * Modify the flags here to allow more coalescing.
2997 if (next && (!next->data || next->zero)) {
2998 next->data = false;
2999 next->zero = true;
3001 break;
3002 case OFORMAT_JSON:
3003 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3004 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3005 e->start, e->length, e->depth,
3006 e->zero ? "true" : "false",
3007 e->data ? "true" : "false");
3008 if (e->has_offset) {
3009 printf(", \"offset\": %"PRId64"", e->offset);
3011 putchar('}');
3013 if (next) {
3014 puts(",");
3016 break;
3018 return 0;
3021 static int get_block_status(BlockDriverState *bs, int64_t offset,
3022 int64_t bytes, MapEntry *e)
3024 int ret;
3025 int depth;
3026 BlockDriverState *file;
3027 bool has_offset;
3028 int64_t map;
3029 char *filename = NULL;
3031 /* As an optimization, we could cache the current range of unallocated
3032 * clusters in each file of the chain, and avoid querying the same
3033 * range repeatedly.
3036 depth = 0;
3037 for (;;) {
3038 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3039 if (ret < 0) {
3040 return ret;
3042 assert(bytes);
3043 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3044 break;
3046 bs = backing_bs(bs);
3047 if (bs == NULL) {
3048 ret = 0;
3049 break;
3052 depth++;
3055 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3057 if (file && has_offset) {
3058 bdrv_refresh_filename(file);
3059 filename = file->filename;
3062 *e = (MapEntry) {
3063 .start = offset,
3064 .length = bytes,
3065 .data = !!(ret & BDRV_BLOCK_DATA),
3066 .zero = !!(ret & BDRV_BLOCK_ZERO),
3067 .offset = map,
3068 .has_offset = has_offset,
3069 .depth = depth,
3070 .has_filename = filename,
3071 .filename = filename,
3074 return 0;
3077 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3079 if (curr->length == 0) {
3080 return false;
3082 if (curr->zero != next->zero ||
3083 curr->data != next->data ||
3084 curr->depth != next->depth ||
3085 curr->has_filename != next->has_filename ||
3086 curr->has_offset != next->has_offset) {
3087 return false;
3089 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3090 return false;
3092 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3093 return false;
3095 return true;
3098 static int img_map(int argc, char **argv)
3100 int c;
3101 OutputFormat output_format = OFORMAT_HUMAN;
3102 BlockBackend *blk;
3103 BlockDriverState *bs;
3104 const char *filename, *fmt, *output;
3105 int64_t length;
3106 MapEntry curr = { .length = 0 }, next;
3107 int ret = 0;
3108 bool image_opts = false;
3109 bool force_share = false;
3110 int64_t start_offset = 0;
3111 int64_t max_length = -1;
3113 fmt = NULL;
3114 output = NULL;
3115 for (;;) {
3116 int option_index = 0;
3117 static const struct option long_options[] = {
3118 {"help", no_argument, 0, 'h'},
3119 {"format", required_argument, 0, 'f'},
3120 {"output", required_argument, 0, OPTION_OUTPUT},
3121 {"object", required_argument, 0, OPTION_OBJECT},
3122 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3123 {"force-share", no_argument, 0, 'U'},
3124 {"start-offset", required_argument, 0, 's'},
3125 {"max-length", required_argument, 0, 'l'},
3126 {0, 0, 0, 0}
3128 c = getopt_long(argc, argv, ":f:s:l:hU",
3129 long_options, &option_index);
3130 if (c == -1) {
3131 break;
3133 switch (c) {
3134 case ':':
3135 missing_argument(argv[optind - 1]);
3136 break;
3137 case '?':
3138 unrecognized_option(argv[optind - 1]);
3139 break;
3140 case 'h':
3141 help();
3142 break;
3143 case 'f':
3144 fmt = optarg;
3145 break;
3146 case 'U':
3147 force_share = true;
3148 break;
3149 case OPTION_OUTPUT:
3150 output = optarg;
3151 break;
3152 case 's':
3153 start_offset = cvtnum("start offset", optarg);
3154 if (start_offset < 0) {
3155 return 1;
3157 break;
3158 case 'l':
3159 max_length = cvtnum("max length", optarg);
3160 if (max_length < 0) {
3161 return 1;
3163 break;
3164 case OPTION_OBJECT: {
3165 QemuOpts *opts;
3166 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3167 optarg, true);
3168 if (!opts) {
3169 return 1;
3171 } break;
3172 case OPTION_IMAGE_OPTS:
3173 image_opts = true;
3174 break;
3177 if (optind != argc - 1) {
3178 error_exit("Expecting one image file name");
3180 filename = argv[optind];
3182 if (output && !strcmp(output, "json")) {
3183 output_format = OFORMAT_JSON;
3184 } else if (output && !strcmp(output, "human")) {
3185 output_format = OFORMAT_HUMAN;
3186 } else if (output) {
3187 error_report("--output must be used with human or json as argument.");
3188 return 1;
3191 if (qemu_opts_foreach(&qemu_object_opts,
3192 user_creatable_add_opts_foreach,
3193 qemu_img_object_print_help, &error_fatal)) {
3194 return 1;
3197 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3198 if (!blk) {
3199 return 1;
3201 bs = blk_bs(blk);
3203 if (output_format == OFORMAT_HUMAN) {
3204 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3205 } else if (output_format == OFORMAT_JSON) {
3206 putchar('[');
3209 length = blk_getlength(blk);
3210 if (length < 0) {
3211 error_report("Failed to get size for '%s'", filename);
3212 return 1;
3214 if (max_length != -1) {
3215 length = MIN(start_offset + max_length, length);
3218 curr.start = start_offset;
3219 while (curr.start + curr.length < length) {
3220 int64_t offset = curr.start + curr.length;
3221 int64_t n;
3223 /* Probe up to 1 GiB at a time. */
3224 n = MIN(1 * GiB, length - offset);
3225 ret = get_block_status(bs, offset, n, &next);
3227 if (ret < 0) {
3228 error_report("Could not read file metadata: %s", strerror(-ret));
3229 goto out;
3232 if (entry_mergeable(&curr, &next)) {
3233 curr.length += next.length;
3234 continue;
3237 if (curr.length > 0) {
3238 ret = dump_map_entry(output_format, &curr, &next);
3239 if (ret < 0) {
3240 goto out;
3243 curr = next;
3246 ret = dump_map_entry(output_format, &curr, NULL);
3247 if (output_format == OFORMAT_JSON) {
3248 puts("]");
3251 out:
3252 blk_unref(blk);
3253 return ret < 0;
3256 #define SNAPSHOT_LIST 1
3257 #define SNAPSHOT_CREATE 2
3258 #define SNAPSHOT_APPLY 3
3259 #define SNAPSHOT_DELETE 4
3261 static int img_snapshot(int argc, char **argv)
3263 BlockBackend *blk;
3264 BlockDriverState *bs;
3265 QEMUSnapshotInfo sn;
3266 char *filename, *snapshot_name = NULL;
3267 int c, ret = 0, bdrv_oflags;
3268 int action = 0;
3269 qemu_timeval tv;
3270 bool quiet = false;
3271 Error *err = NULL;
3272 bool image_opts = false;
3273 bool force_share = false;
3275 bdrv_oflags = BDRV_O_RDWR;
3276 /* Parse commandline parameters */
3277 for(;;) {
3278 static const struct option long_options[] = {
3279 {"help", no_argument, 0, 'h'},
3280 {"object", required_argument, 0, OPTION_OBJECT},
3281 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3282 {"force-share", no_argument, 0, 'U'},
3283 {0, 0, 0, 0}
3285 c = getopt_long(argc, argv, ":la:c:d:hqU",
3286 long_options, NULL);
3287 if (c == -1) {
3288 break;
3290 switch(c) {
3291 case ':':
3292 missing_argument(argv[optind - 1]);
3293 break;
3294 case '?':
3295 unrecognized_option(argv[optind - 1]);
3296 break;
3297 case 'h':
3298 help();
3299 return 0;
3300 case 'l':
3301 if (action) {
3302 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3303 return 0;
3305 action = SNAPSHOT_LIST;
3306 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3307 break;
3308 case 'a':
3309 if (action) {
3310 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3311 return 0;
3313 action = SNAPSHOT_APPLY;
3314 snapshot_name = optarg;
3315 break;
3316 case 'c':
3317 if (action) {
3318 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3319 return 0;
3321 action = SNAPSHOT_CREATE;
3322 snapshot_name = optarg;
3323 break;
3324 case 'd':
3325 if (action) {
3326 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3327 return 0;
3329 action = SNAPSHOT_DELETE;
3330 snapshot_name = optarg;
3331 break;
3332 case 'q':
3333 quiet = true;
3334 break;
3335 case 'U':
3336 force_share = true;
3337 break;
3338 case OPTION_OBJECT: {
3339 QemuOpts *opts;
3340 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3341 optarg, true);
3342 if (!opts) {
3343 return 1;
3345 } break;
3346 case OPTION_IMAGE_OPTS:
3347 image_opts = true;
3348 break;
3352 if (optind != argc - 1) {
3353 error_exit("Expecting one image file name");
3355 filename = argv[optind++];
3357 if (qemu_opts_foreach(&qemu_object_opts,
3358 user_creatable_add_opts_foreach,
3359 qemu_img_object_print_help, &error_fatal)) {
3360 return 1;
3363 /* Open the image */
3364 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3365 force_share);
3366 if (!blk) {
3367 return 1;
3369 bs = blk_bs(blk);
3371 /* Perform the requested action */
3372 switch(action) {
3373 case SNAPSHOT_LIST:
3374 dump_snapshots(bs);
3375 break;
3377 case SNAPSHOT_CREATE:
3378 memset(&sn, 0, sizeof(sn));
3379 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3381 qemu_gettimeofday(&tv);
3382 sn.date_sec = tv.tv_sec;
3383 sn.date_nsec = tv.tv_usec * 1000;
3385 ret = bdrv_snapshot_create(bs, &sn);
3386 if (ret) {
3387 error_report("Could not create snapshot '%s': %d (%s)",
3388 snapshot_name, ret, strerror(-ret));
3390 break;
3392 case SNAPSHOT_APPLY:
3393 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3394 if (ret) {
3395 error_reportf_err(err, "Could not apply snapshot '%s': ",
3396 snapshot_name);
3398 break;
3400 case SNAPSHOT_DELETE:
3401 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3402 if (ret < 0) {
3403 error_report("Could not delete snapshot '%s': snapshot not "
3404 "found", snapshot_name);
3405 ret = 1;
3406 } else {
3407 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3408 if (ret < 0) {
3409 error_reportf_err(err, "Could not delete snapshot '%s': ",
3410 snapshot_name);
3411 ret = 1;
3414 break;
3417 /* Cleanup */
3418 blk_unref(blk);
3419 if (ret) {
3420 return 1;
3422 return 0;
3425 static int img_rebase(int argc, char **argv)
3427 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3428 uint8_t *buf_old = NULL;
3429 uint8_t *buf_new = NULL;
3430 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3431 char *filename;
3432 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3433 int c, flags, src_flags, ret;
3434 bool writethrough, src_writethrough;
3435 int unsafe = 0;
3436 bool force_share = false;
3437 int progress = 0;
3438 bool quiet = false;
3439 Error *local_err = NULL;
3440 bool image_opts = false;
3442 /* Parse commandline parameters */
3443 fmt = NULL;
3444 cache = BDRV_DEFAULT_CACHE;
3445 src_cache = BDRV_DEFAULT_CACHE;
3446 out_baseimg = NULL;
3447 out_basefmt = NULL;
3448 for(;;) {
3449 static const struct option long_options[] = {
3450 {"help", no_argument, 0, 'h'},
3451 {"object", required_argument, 0, OPTION_OBJECT},
3452 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3453 {"force-share", no_argument, 0, 'U'},
3454 {0, 0, 0, 0}
3456 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3457 long_options, NULL);
3458 if (c == -1) {
3459 break;
3461 switch(c) {
3462 case ':':
3463 missing_argument(argv[optind - 1]);
3464 break;
3465 case '?':
3466 unrecognized_option(argv[optind - 1]);
3467 break;
3468 case 'h':
3469 help();
3470 return 0;
3471 case 'f':
3472 fmt = optarg;
3473 break;
3474 case 'F':
3475 out_basefmt = optarg;
3476 break;
3477 case 'b':
3478 out_baseimg = optarg;
3479 break;
3480 case 'u':
3481 unsafe = 1;
3482 break;
3483 case 'p':
3484 progress = 1;
3485 break;
3486 case 't':
3487 cache = optarg;
3488 break;
3489 case 'T':
3490 src_cache = optarg;
3491 break;
3492 case 'q':
3493 quiet = true;
3494 break;
3495 case OPTION_OBJECT: {
3496 QemuOpts *opts;
3497 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3498 optarg, true);
3499 if (!opts) {
3500 return 1;
3502 } break;
3503 case OPTION_IMAGE_OPTS:
3504 image_opts = true;
3505 break;
3506 case 'U':
3507 force_share = true;
3508 break;
3512 if (quiet) {
3513 progress = 0;
3516 if (optind != argc - 1) {
3517 error_exit("Expecting one image file name");
3519 if (!unsafe && !out_baseimg) {
3520 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3522 filename = argv[optind++];
3524 if (qemu_opts_foreach(&qemu_object_opts,
3525 user_creatable_add_opts_foreach,
3526 qemu_img_object_print_help, &error_fatal)) {
3527 return 1;
3530 qemu_progress_init(progress, 2.0);
3531 qemu_progress_print(0, 100);
3533 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3534 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3535 if (ret < 0) {
3536 error_report("Invalid cache option: %s", cache);
3537 goto out;
3540 src_flags = 0;
3541 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3542 if (ret < 0) {
3543 error_report("Invalid source cache option: %s", src_cache);
3544 goto out;
3547 /* The source files are opened read-only, don't care about WCE */
3548 assert((src_flags & BDRV_O_RDWR) == 0);
3549 (void) src_writethrough;
3552 * Open the images.
3554 * Ignore the old backing file for unsafe rebase in case we want to correct
3555 * the reference to a renamed or moved backing file.
3557 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3558 false);
3559 if (!blk) {
3560 ret = -1;
3561 goto out;
3563 bs = blk_bs(blk);
3565 if (out_basefmt != NULL) {
3566 if (bdrv_find_format(out_basefmt) == NULL) {
3567 error_report("Invalid format name: '%s'", out_basefmt);
3568 ret = -1;
3569 goto out;
3573 /* For safe rebasing we need to compare old and new backing file */
3574 if (!unsafe) {
3575 QDict *options = NULL;
3576 BlockDriverState *base_bs = backing_bs(bs);
3578 if (base_bs) {
3579 blk_old_backing = blk_new(qemu_get_aio_context(),
3580 BLK_PERM_CONSISTENT_READ,
3581 BLK_PERM_ALL);
3582 ret = blk_insert_bs(blk_old_backing, base_bs,
3583 &local_err);
3584 if (ret < 0) {
3585 error_reportf_err(local_err,
3586 "Could not reuse old backing file '%s': ",
3587 base_bs->filename);
3588 goto out;
3590 } else {
3591 blk_old_backing = NULL;
3594 if (out_baseimg[0]) {
3595 const char *overlay_filename;
3596 char *out_real_path;
3598 options = qdict_new();
3599 if (out_basefmt) {
3600 qdict_put_str(options, "driver", out_basefmt);
3602 if (force_share) {
3603 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3606 bdrv_refresh_filename(bs);
3607 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3608 : bs->filename;
3609 out_real_path =
3610 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3611 out_baseimg,
3612 &local_err);
3613 if (local_err) {
3614 qobject_unref(options);
3615 error_reportf_err(local_err,
3616 "Could not resolve backing filename: ");
3617 ret = -1;
3618 goto out;
3622 * Find out whether we rebase an image on top of a previous image
3623 * in its chain.
3625 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3626 if (prefix_chain_bs) {
3627 qobject_unref(options);
3628 g_free(out_real_path);
3630 blk_new_backing = blk_new(qemu_get_aio_context(),
3631 BLK_PERM_CONSISTENT_READ,
3632 BLK_PERM_ALL);
3633 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3634 &local_err);
3635 if (ret < 0) {
3636 error_reportf_err(local_err,
3637 "Could not reuse backing file '%s': ",
3638 out_baseimg);
3639 goto out;
3641 } else {
3642 blk_new_backing = blk_new_open(out_real_path, NULL,
3643 options, src_flags, &local_err);
3644 g_free(out_real_path);
3645 if (!blk_new_backing) {
3646 error_reportf_err(local_err,
3647 "Could not open new backing file '%s': ",
3648 out_baseimg);
3649 ret = -1;
3650 goto out;
3657 * Check each unallocated cluster in the COW file. If it is unallocated,
3658 * accesses go to the backing file. We must therefore compare this cluster
3659 * in the old and new backing file, and if they differ we need to copy it
3660 * from the old backing file into the COW file.
3662 * If qemu-img crashes during this step, no harm is done. The content of
3663 * the image is the same as the original one at any time.
3665 if (!unsafe) {
3666 int64_t size;
3667 int64_t old_backing_size = 0;
3668 int64_t new_backing_size = 0;
3669 uint64_t offset;
3670 int64_t n;
3671 float local_progress = 0;
3673 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3674 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3676 size = blk_getlength(blk);
3677 if (size < 0) {
3678 error_report("Could not get size of '%s': %s",
3679 filename, strerror(-size));
3680 ret = -1;
3681 goto out;
3683 if (blk_old_backing) {
3684 old_backing_size = blk_getlength(blk_old_backing);
3685 if (old_backing_size < 0) {
3686 char backing_name[PATH_MAX];
3688 bdrv_get_backing_filename(bs, backing_name,
3689 sizeof(backing_name));
3690 error_report("Could not get size of '%s': %s",
3691 backing_name, strerror(-old_backing_size));
3692 ret = -1;
3693 goto out;
3696 if (blk_new_backing) {
3697 new_backing_size = blk_getlength(blk_new_backing);
3698 if (new_backing_size < 0) {
3699 error_report("Could not get size of '%s': %s",
3700 out_baseimg, strerror(-new_backing_size));
3701 ret = -1;
3702 goto out;
3706 if (size != 0) {
3707 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3710 for (offset = 0; offset < size; offset += n) {
3711 bool buf_old_is_zero = false;
3713 /* How many bytes can we handle with the next read? */
3714 n = MIN(IO_BUF_SIZE, size - offset);
3716 /* If the cluster is allocated, we don't need to take action */
3717 ret = bdrv_is_allocated(bs, offset, n, &n);
3718 if (ret < 0) {
3719 error_report("error while reading image metadata: %s",
3720 strerror(-ret));
3721 goto out;
3723 if (ret) {
3724 continue;
3727 if (prefix_chain_bs) {
3729 * If cluster wasn't changed since prefix_chain, we don't need
3730 * to take action
3732 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3733 false, 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;
3745 * Read old and new backing file and take into consideration that
3746 * backing files may be smaller than the COW image.
3748 if (offset >= old_backing_size) {
3749 memset(buf_old, 0, n);
3750 buf_old_is_zero = true;
3751 } else {
3752 if (offset + n > old_backing_size) {
3753 n = old_backing_size - offset;
3756 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3757 if (ret < 0) {
3758 error_report("error while reading from old backing file");
3759 goto out;
3763 if (offset >= new_backing_size || !blk_new_backing) {
3764 memset(buf_new, 0, n);
3765 } else {
3766 if (offset + n > new_backing_size) {
3767 n = new_backing_size - offset;
3770 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3771 if (ret < 0) {
3772 error_report("error while reading from new backing file");
3773 goto out;
3777 /* If they differ, we need to write to the COW file */
3778 uint64_t written = 0;
3780 while (written < n) {
3781 int64_t pnum;
3783 if (compare_buffers(buf_old + written, buf_new + written,
3784 n - written, &pnum))
3786 if (buf_old_is_zero) {
3787 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3788 } else {
3789 ret = blk_pwrite(blk, offset + written,
3790 buf_old + written, pnum, 0);
3792 if (ret < 0) {
3793 error_report("Error while writing to COW image: %s",
3794 strerror(-ret));
3795 goto out;
3799 written += pnum;
3801 qemu_progress_print(local_progress, 100);
3806 * Change the backing file. All clusters that are different from the old
3807 * backing file are overwritten in the COW file now, so the visible content
3808 * doesn't change when we switch the backing file.
3810 if (out_baseimg && *out_baseimg) {
3811 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3812 } else {
3813 ret = bdrv_change_backing_file(bs, NULL, NULL);
3816 if (ret == -ENOSPC) {
3817 error_report("Could not change the backing file to '%s': No "
3818 "space left in the file header", out_baseimg);
3819 } else if (ret < 0) {
3820 error_report("Could not change the backing file to '%s': %s",
3821 out_baseimg, strerror(-ret));
3824 qemu_progress_print(100, 0);
3826 * TODO At this point it is possible to check if any clusters that are
3827 * allocated in the COW file are the same in the backing file. If so, they
3828 * could be dropped from the COW file. Don't do this before switching the
3829 * backing file, in case of a crash this would lead to corruption.
3831 out:
3832 qemu_progress_end();
3833 /* Cleanup */
3834 if (!unsafe) {
3835 blk_unref(blk_old_backing);
3836 blk_unref(blk_new_backing);
3838 qemu_vfree(buf_old);
3839 qemu_vfree(buf_new);
3841 blk_unref(blk);
3842 if (ret) {
3843 return 1;
3845 return 0;
3848 static int img_resize(int argc, char **argv)
3850 Error *err = NULL;
3851 int c, ret, relative;
3852 const char *filename, *fmt, *size;
3853 int64_t n, total_size, current_size;
3854 bool quiet = false;
3855 BlockBackend *blk = NULL;
3856 PreallocMode prealloc = PREALLOC_MODE_OFF;
3857 QemuOpts *param;
3859 static QemuOptsList resize_options = {
3860 .name = "resize_options",
3861 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3862 .desc = {
3864 .name = BLOCK_OPT_SIZE,
3865 .type = QEMU_OPT_SIZE,
3866 .help = "Virtual disk size"
3867 }, {
3868 /* end of list */
3872 bool image_opts = false;
3873 bool shrink = false;
3875 /* Remove size from argv manually so that negative numbers are not treated
3876 * as options by getopt. */
3877 if (argc < 3) {
3878 error_exit("Not enough arguments");
3879 return 1;
3882 size = argv[--argc];
3884 /* Parse getopt arguments */
3885 fmt = NULL;
3886 for(;;) {
3887 static const struct option long_options[] = {
3888 {"help", no_argument, 0, 'h'},
3889 {"object", required_argument, 0, OPTION_OBJECT},
3890 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3891 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3892 {"shrink", no_argument, 0, OPTION_SHRINK},
3893 {0, 0, 0, 0}
3895 c = getopt_long(argc, argv, ":f:hq",
3896 long_options, NULL);
3897 if (c == -1) {
3898 break;
3900 switch(c) {
3901 case ':':
3902 missing_argument(argv[optind - 1]);
3903 break;
3904 case '?':
3905 unrecognized_option(argv[optind - 1]);
3906 break;
3907 case 'h':
3908 help();
3909 break;
3910 case 'f':
3911 fmt = optarg;
3912 break;
3913 case 'q':
3914 quiet = true;
3915 break;
3916 case OPTION_OBJECT: {
3917 QemuOpts *opts;
3918 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3919 optarg, true);
3920 if (!opts) {
3921 return 1;
3923 } break;
3924 case OPTION_IMAGE_OPTS:
3925 image_opts = true;
3926 break;
3927 case OPTION_PREALLOCATION:
3928 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3929 PREALLOC_MODE__MAX, NULL);
3930 if (prealloc == PREALLOC_MODE__MAX) {
3931 error_report("Invalid preallocation mode '%s'", optarg);
3932 return 1;
3934 break;
3935 case OPTION_SHRINK:
3936 shrink = true;
3937 break;
3940 if (optind != argc - 1) {
3941 error_exit("Expecting image file name and size");
3943 filename = argv[optind++];
3945 if (qemu_opts_foreach(&qemu_object_opts,
3946 user_creatable_add_opts_foreach,
3947 qemu_img_object_print_help, &error_fatal)) {
3948 return 1;
3951 /* Choose grow, shrink, or absolute resize mode */
3952 switch (size[0]) {
3953 case '+':
3954 relative = 1;
3955 size++;
3956 break;
3957 case '-':
3958 relative = -1;
3959 size++;
3960 break;
3961 default:
3962 relative = 0;
3963 break;
3966 /* Parse size */
3967 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3968 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3969 if (err) {
3970 error_report_err(err);
3971 ret = -1;
3972 qemu_opts_del(param);
3973 goto out;
3975 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3976 qemu_opts_del(param);
3978 blk = img_open(image_opts, filename, fmt,
3979 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3980 false);
3981 if (!blk) {
3982 ret = -1;
3983 goto out;
3986 current_size = blk_getlength(blk);
3987 if (current_size < 0) {
3988 error_report("Failed to inquire current image length: %s",
3989 strerror(-current_size));
3990 ret = -1;
3991 goto out;
3994 if (relative) {
3995 total_size = current_size + n * relative;
3996 } else {
3997 total_size = n;
3999 if (total_size <= 0) {
4000 error_report("New image size must be positive");
4001 ret = -1;
4002 goto out;
4005 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4006 error_report("Preallocation can only be used for growing images");
4007 ret = -1;
4008 goto out;
4011 if (total_size < current_size && !shrink) {
4012 warn_report("Shrinking an image will delete all data beyond the "
4013 "shrunken image's end. Before performing such an "
4014 "operation, make sure there is no important data there.");
4016 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4017 error_report(
4018 "Use the --shrink option to perform a shrink operation.");
4019 ret = -1;
4020 goto out;
4021 } else {
4022 warn_report("Using the --shrink option will suppress this message. "
4023 "Note that future versions of qemu-img may refuse to "
4024 "shrink images without this option.");
4029 * The user expects the image to have the desired size after
4030 * resizing, so pass @exact=true. It is of no use to report
4031 * success when the image has not actually been resized.
4033 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4034 if (!ret) {
4035 qprintf(quiet, "Image resized.\n");
4036 } else {
4037 error_report_err(err);
4039 out:
4040 blk_unref(blk);
4041 if (ret) {
4042 return 1;
4044 return 0;
4047 static void amend_status_cb(BlockDriverState *bs,
4048 int64_t offset, int64_t total_work_size,
4049 void *opaque)
4051 qemu_progress_print(100.f * offset / total_work_size, 0);
4054 static int print_amend_option_help(const char *format)
4056 BlockDriver *drv;
4058 /* Find driver and parse its options */
4059 drv = bdrv_find_format(format);
4060 if (!drv) {
4061 error_report("Unknown file format '%s'", format);
4062 return 1;
4065 if (!drv->bdrv_amend_options) {
4066 error_report("Format driver '%s' does not support option amendment",
4067 format);
4068 return 1;
4071 /* Every driver supporting amendment must have amend_opts */
4072 assert(drv->amend_opts);
4074 printf("Amend options for '%s':\n", format);
4075 qemu_opts_print_help(drv->amend_opts, false);
4076 return 0;
4079 static int img_amend(int argc, char **argv)
4081 Error *err = NULL;
4082 int c, ret = 0;
4083 char *options = NULL;
4084 QemuOptsList *amend_opts = NULL;
4085 QemuOpts *opts = NULL;
4086 const char *fmt = NULL, *filename, *cache;
4087 int flags;
4088 bool writethrough;
4089 bool quiet = false, progress = false;
4090 BlockBackend *blk = NULL;
4091 BlockDriverState *bs = NULL;
4092 bool image_opts = false;
4093 bool force = false;
4095 cache = BDRV_DEFAULT_CACHE;
4096 for (;;) {
4097 static const struct option long_options[] = {
4098 {"help", no_argument, 0, 'h'},
4099 {"object", required_argument, 0, OPTION_OBJECT},
4100 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4101 {"force", no_argument, 0, OPTION_FORCE},
4102 {0, 0, 0, 0}
4104 c = getopt_long(argc, argv, ":ho:f:t:pq",
4105 long_options, NULL);
4106 if (c == -1) {
4107 break;
4110 switch (c) {
4111 case ':':
4112 missing_argument(argv[optind - 1]);
4113 break;
4114 case '?':
4115 unrecognized_option(argv[optind - 1]);
4116 break;
4117 case 'h':
4118 help();
4119 break;
4120 case 'o':
4121 if (accumulate_options(&options, optarg) < 0) {
4122 ret = -1;
4123 goto out_no_progress;
4125 break;
4126 case 'f':
4127 fmt = optarg;
4128 break;
4129 case 't':
4130 cache = optarg;
4131 break;
4132 case 'p':
4133 progress = true;
4134 break;
4135 case 'q':
4136 quiet = true;
4137 break;
4138 case OPTION_OBJECT:
4139 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4140 optarg, true);
4141 if (!opts) {
4142 ret = -1;
4143 goto out_no_progress;
4145 break;
4146 case OPTION_IMAGE_OPTS:
4147 image_opts = true;
4148 break;
4149 case OPTION_FORCE:
4150 force = true;
4151 break;
4155 if (!options) {
4156 error_exit("Must specify options (-o)");
4159 if (qemu_opts_foreach(&qemu_object_opts,
4160 user_creatable_add_opts_foreach,
4161 qemu_img_object_print_help, &error_fatal)) {
4162 ret = -1;
4163 goto out_no_progress;
4166 if (quiet) {
4167 progress = false;
4169 qemu_progress_init(progress, 1.0);
4171 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4172 if (fmt && has_help_option(options)) {
4173 /* If a format is explicitly specified (and possibly no filename is
4174 * given), print option help here */
4175 ret = print_amend_option_help(fmt);
4176 goto out;
4179 if (optind != argc - 1) {
4180 error_report("Expecting one image file name");
4181 ret = -1;
4182 goto out;
4185 flags = BDRV_O_RDWR;
4186 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4187 if (ret < 0) {
4188 error_report("Invalid cache option: %s", cache);
4189 goto out;
4192 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4193 false);
4194 if (!blk) {
4195 ret = -1;
4196 goto out;
4198 bs = blk_bs(blk);
4200 fmt = bs->drv->format_name;
4202 if (has_help_option(options)) {
4203 /* If the format was auto-detected, print option help here */
4204 ret = print_amend_option_help(fmt);
4205 goto out;
4208 if (!bs->drv->bdrv_amend_options) {
4209 error_report("Format driver '%s' does not support option amendment",
4210 fmt);
4211 ret = -1;
4212 goto out;
4215 /* Every driver supporting amendment must have amend_opts */
4216 assert(bs->drv->amend_opts);
4218 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4219 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4220 qemu_opts_do_parse(opts, options, NULL, &err);
4222 if (err) {
4223 /* Try to parse options using the create options */
4224 Error *err1 = NULL;
4225 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4226 qemu_opts_del(opts);
4227 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4228 qemu_opts_do_parse(opts, options, NULL, &err1);
4230 if (!err1) {
4231 error_append_hint(&err,
4232 "This option is only supported for image creation\n");
4233 } else {
4234 error_free(err1);
4237 error_report_err(err);
4238 ret = -1;
4239 goto out;
4242 /* In case the driver does not call amend_status_cb() */
4243 qemu_progress_print(0.f, 0);
4244 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4245 qemu_progress_print(100.f, 0);
4246 if (ret < 0) {
4247 error_report_err(err);
4248 goto out;
4251 out:
4252 qemu_progress_end();
4254 out_no_progress:
4255 blk_unref(blk);
4256 qemu_opts_del(opts);
4257 qemu_opts_free(amend_opts);
4258 g_free(options);
4260 if (ret) {
4261 return 1;
4263 return 0;
4266 typedef struct BenchData {
4267 BlockBackend *blk;
4268 uint64_t image_size;
4269 bool write;
4270 int bufsize;
4271 int step;
4272 int nrreq;
4273 int n;
4274 int flush_interval;
4275 bool drain_on_flush;
4276 uint8_t *buf;
4277 QEMUIOVector *qiov;
4279 int in_flight;
4280 bool in_flush;
4281 uint64_t offset;
4282 } BenchData;
4284 static void bench_undrained_flush_cb(void *opaque, int ret)
4286 if (ret < 0) {
4287 error_report("Failed flush request: %s", strerror(-ret));
4288 exit(EXIT_FAILURE);
4292 static void bench_cb(void *opaque, int ret)
4294 BenchData *b = opaque;
4295 BlockAIOCB *acb;
4297 if (ret < 0) {
4298 error_report("Failed request: %s", strerror(-ret));
4299 exit(EXIT_FAILURE);
4302 if (b->in_flush) {
4303 /* Just finished a flush with drained queue: Start next requests */
4304 assert(b->in_flight == 0);
4305 b->in_flush = false;
4306 } else if (b->in_flight > 0) {
4307 int remaining = b->n - b->in_flight;
4309 b->n--;
4310 b->in_flight--;
4312 /* Time for flush? Drain queue if requested, then flush */
4313 if (b->flush_interval && remaining % b->flush_interval == 0) {
4314 if (!b->in_flight || !b->drain_on_flush) {
4315 BlockCompletionFunc *cb;
4317 if (b->drain_on_flush) {
4318 b->in_flush = true;
4319 cb = bench_cb;
4320 } else {
4321 cb = bench_undrained_flush_cb;
4324 acb = blk_aio_flush(b->blk, cb, b);
4325 if (!acb) {
4326 error_report("Failed to issue flush request");
4327 exit(EXIT_FAILURE);
4330 if (b->drain_on_flush) {
4331 return;
4336 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4337 int64_t offset = b->offset;
4338 /* blk_aio_* might look for completed I/Os and kick bench_cb
4339 * again, so make sure this operation is counted by in_flight
4340 * and b->offset is ready for the next submission.
4342 b->in_flight++;
4343 b->offset += b->step;
4344 b->offset %= b->image_size;
4345 if (b->write) {
4346 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4347 } else {
4348 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4350 if (!acb) {
4351 error_report("Failed to issue request");
4352 exit(EXIT_FAILURE);
4357 static int img_bench(int argc, char **argv)
4359 int c, ret = 0;
4360 const char *fmt = NULL, *filename;
4361 bool quiet = false;
4362 bool image_opts = false;
4363 bool is_write = false;
4364 int count = 75000;
4365 int depth = 64;
4366 int64_t offset = 0;
4367 size_t bufsize = 4096;
4368 int pattern = 0;
4369 size_t step = 0;
4370 int flush_interval = 0;
4371 bool drain_on_flush = true;
4372 int64_t image_size;
4373 BlockBackend *blk = NULL;
4374 BenchData data = {};
4375 int flags = 0;
4376 bool writethrough = false;
4377 struct timeval t1, t2;
4378 int i;
4379 bool force_share = false;
4380 size_t buf_size;
4382 for (;;) {
4383 static const struct option long_options[] = {
4384 {"help", no_argument, 0, 'h'},
4385 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4386 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4387 {"pattern", required_argument, 0, OPTION_PATTERN},
4388 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4389 {"force-share", no_argument, 0, 'U'},
4390 {0, 0, 0, 0}
4392 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4393 NULL);
4394 if (c == -1) {
4395 break;
4398 switch (c) {
4399 case ':':
4400 missing_argument(argv[optind - 1]);
4401 break;
4402 case '?':
4403 unrecognized_option(argv[optind - 1]);
4404 break;
4405 case 'h':
4406 help();
4407 break;
4408 case 'c':
4410 unsigned long res;
4412 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4413 error_report("Invalid request count specified");
4414 return 1;
4416 count = res;
4417 break;
4419 case 'd':
4421 unsigned long res;
4423 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4424 error_report("Invalid queue depth specified");
4425 return 1;
4427 depth = res;
4428 break;
4430 case 'f':
4431 fmt = optarg;
4432 break;
4433 case 'n':
4434 flags |= BDRV_O_NATIVE_AIO;
4435 break;
4436 case 'i':
4437 ret = bdrv_parse_aio(optarg, &flags);
4438 if (ret < 0) {
4439 error_report("Invalid aio option: %s", optarg);
4440 ret = -1;
4441 goto out;
4443 break;
4444 case 'o':
4446 offset = cvtnum("offset", optarg);
4447 if (offset < 0) {
4448 return 1;
4450 break;
4452 break;
4453 case 'q':
4454 quiet = true;
4455 break;
4456 case 's':
4458 int64_t sval;
4460 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4461 if (sval < 0) {
4462 return 1;
4465 bufsize = sval;
4466 break;
4468 case 'S':
4470 int64_t sval;
4472 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4473 if (sval < 0) {
4474 return 1;
4477 step = sval;
4478 break;
4480 case 't':
4481 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4482 if (ret < 0) {
4483 error_report("Invalid cache mode");
4484 ret = -1;
4485 goto out;
4487 break;
4488 case 'w':
4489 flags |= BDRV_O_RDWR;
4490 is_write = true;
4491 break;
4492 case 'U':
4493 force_share = true;
4494 break;
4495 case OPTION_PATTERN:
4497 unsigned long res;
4499 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4500 error_report("Invalid pattern byte specified");
4501 return 1;
4503 pattern = res;
4504 break;
4506 case OPTION_FLUSH_INTERVAL:
4508 unsigned long res;
4510 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4511 error_report("Invalid flush interval specified");
4512 return 1;
4514 flush_interval = res;
4515 break;
4517 case OPTION_NO_DRAIN:
4518 drain_on_flush = false;
4519 break;
4520 case OPTION_IMAGE_OPTS:
4521 image_opts = true;
4522 break;
4526 if (optind != argc - 1) {
4527 error_exit("Expecting one image file name");
4529 filename = argv[argc - 1];
4531 if (!is_write && flush_interval) {
4532 error_report("--flush-interval is only available in write tests");
4533 ret = -1;
4534 goto out;
4536 if (flush_interval && flush_interval < depth) {
4537 error_report("Flush interval can't be smaller than depth");
4538 ret = -1;
4539 goto out;
4542 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4543 force_share);
4544 if (!blk) {
4545 ret = -1;
4546 goto out;
4549 image_size = blk_getlength(blk);
4550 if (image_size < 0) {
4551 ret = image_size;
4552 goto out;
4555 data = (BenchData) {
4556 .blk = blk,
4557 .image_size = image_size,
4558 .bufsize = bufsize,
4559 .step = step ?: bufsize,
4560 .nrreq = depth,
4561 .n = count,
4562 .offset = offset,
4563 .write = is_write,
4564 .flush_interval = flush_interval,
4565 .drain_on_flush = drain_on_flush,
4567 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4568 "(starting at offset %" PRId64 ", step size %d)\n",
4569 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4570 data.offset, data.step);
4571 if (flush_interval) {
4572 printf("Sending flush every %d requests\n", flush_interval);
4575 buf_size = data.nrreq * data.bufsize;
4576 data.buf = blk_blockalign(blk, buf_size);
4577 memset(data.buf, pattern, data.nrreq * data.bufsize);
4579 blk_register_buf(blk, data.buf, buf_size);
4581 data.qiov = g_new(QEMUIOVector, data.nrreq);
4582 for (i = 0; i < data.nrreq; i++) {
4583 qemu_iovec_init(&data.qiov[i], 1);
4584 qemu_iovec_add(&data.qiov[i],
4585 data.buf + i * data.bufsize, data.bufsize);
4588 gettimeofday(&t1, NULL);
4589 bench_cb(&data, 0);
4591 while (data.n > 0) {
4592 main_loop_wait(false);
4594 gettimeofday(&t2, NULL);
4596 printf("Run completed in %3.3f seconds.\n",
4597 (t2.tv_sec - t1.tv_sec)
4598 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4600 out:
4601 if (data.buf) {
4602 blk_unregister_buf(blk, data.buf);
4604 qemu_vfree(data.buf);
4605 blk_unref(blk);
4607 if (ret) {
4608 return 1;
4610 return 0;
4613 enum ImgBitmapAct {
4614 BITMAP_ADD,
4615 BITMAP_REMOVE,
4616 BITMAP_CLEAR,
4617 BITMAP_ENABLE,
4618 BITMAP_DISABLE,
4619 BITMAP_MERGE,
4621 typedef struct ImgBitmapAction {
4622 enum ImgBitmapAct act;
4623 const char *src; /* only used for merge */
4624 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4625 } ImgBitmapAction;
4627 static int img_bitmap(int argc, char **argv)
4629 Error *err = NULL;
4630 int c, ret = 1;
4631 QemuOpts *opts = NULL;
4632 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4633 const char *filename, *bitmap;
4634 BlockBackend *blk = NULL, *src = NULL;
4635 BlockDriverState *bs = NULL, *src_bs = NULL;
4636 bool image_opts = false;
4637 int64_t granularity = 0;
4638 bool add = false, merge = false;
4639 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4640 ImgBitmapAction *act, *act_next;
4641 const char *op;
4643 QSIMPLEQ_INIT(&actions);
4645 for (;;) {
4646 static const struct option long_options[] = {
4647 {"help", no_argument, 0, 'h'},
4648 {"object", required_argument, 0, OPTION_OBJECT},
4649 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4650 {"add", no_argument, 0, OPTION_ADD},
4651 {"remove", no_argument, 0, OPTION_REMOVE},
4652 {"clear", no_argument, 0, OPTION_CLEAR},
4653 {"enable", no_argument, 0, OPTION_ENABLE},
4654 {"disable", no_argument, 0, OPTION_DISABLE},
4655 {"merge", required_argument, 0, OPTION_MERGE},
4656 {"granularity", required_argument, 0, 'g'},
4657 {"source-file", required_argument, 0, 'b'},
4658 {"source-format", required_argument, 0, 'F'},
4659 {0, 0, 0, 0}
4661 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4662 if (c == -1) {
4663 break;
4666 switch (c) {
4667 case ':':
4668 missing_argument(argv[optind - 1]);
4669 break;
4670 case '?':
4671 unrecognized_option(argv[optind - 1]);
4672 break;
4673 case 'h':
4674 help();
4675 break;
4676 case 'b':
4677 src_filename = optarg;
4678 break;
4679 case 'f':
4680 fmt = optarg;
4681 break;
4682 case 'F':
4683 src_fmt = optarg;
4684 break;
4685 case 'g':
4686 granularity = cvtnum("granularity", optarg);
4687 if (granularity < 0) {
4688 return 1;
4690 break;
4691 case OPTION_ADD:
4692 act = g_new0(ImgBitmapAction, 1);
4693 act->act = BITMAP_ADD;
4694 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4695 add = true;
4696 break;
4697 case OPTION_REMOVE:
4698 act = g_new0(ImgBitmapAction, 1);
4699 act->act = BITMAP_REMOVE;
4700 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4701 break;
4702 case OPTION_CLEAR:
4703 act = g_new0(ImgBitmapAction, 1);
4704 act->act = BITMAP_CLEAR;
4705 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4706 break;
4707 case OPTION_ENABLE:
4708 act = g_new0(ImgBitmapAction, 1);
4709 act->act = BITMAP_ENABLE;
4710 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4711 break;
4712 case OPTION_DISABLE:
4713 act = g_new0(ImgBitmapAction, 1);
4714 act->act = BITMAP_DISABLE;
4715 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4716 break;
4717 case OPTION_MERGE:
4718 act = g_new0(ImgBitmapAction, 1);
4719 act->act = BITMAP_MERGE;
4720 act->src = optarg;
4721 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4722 merge = true;
4723 break;
4724 case OPTION_OBJECT:
4725 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4726 if (!opts) {
4727 goto out;
4729 break;
4730 case OPTION_IMAGE_OPTS:
4731 image_opts = true;
4732 break;
4736 if (qemu_opts_foreach(&qemu_object_opts,
4737 user_creatable_add_opts_foreach,
4738 qemu_img_object_print_help, &error_fatal)) {
4739 goto out;
4742 if (QSIMPLEQ_EMPTY(&actions)) {
4743 error_report("Need at least one of --add, --remove, --clear, "
4744 "--enable, --disable, or --merge");
4745 goto out;
4748 if (granularity && !add) {
4749 error_report("granularity only supported with --add");
4750 goto out;
4752 if (src_fmt && !src_filename) {
4753 error_report("-F only supported with -b");
4754 goto out;
4756 if (src_filename && !merge) {
4757 error_report("Merge bitmap source file only supported with "
4758 "--merge");
4759 goto out;
4762 if (optind != argc - 2) {
4763 error_report("Expecting filename and bitmap name");
4764 goto out;
4767 filename = argv[optind];
4768 bitmap = argv[optind + 1];
4770 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4771 false);
4772 if (!blk) {
4773 goto out;
4775 bs = blk_bs(blk);
4776 if (src_filename) {
4777 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4778 if (!src) {
4779 goto out;
4781 src_bs = blk_bs(src);
4782 } else {
4783 src_bs = bs;
4786 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4787 switch (act->act) {
4788 case BITMAP_ADD:
4789 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4790 !!granularity, granularity, true, true,
4791 false, false, &err);
4792 op = "add";
4793 break;
4794 case BITMAP_REMOVE:
4795 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4796 op = "remove";
4797 break;
4798 case BITMAP_CLEAR:
4799 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4800 op = "clear";
4801 break;
4802 case BITMAP_ENABLE:
4803 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4804 op = "enable";
4805 break;
4806 case BITMAP_DISABLE:
4807 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4808 op = "disable";
4809 break;
4810 case BITMAP_MERGE:
4811 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4812 act->src, &err);
4813 op = "merge";
4814 break;
4815 default:
4816 g_assert_not_reached();
4819 if (err) {
4820 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4821 op, bitmap);
4822 goto out;
4824 g_free(act);
4827 ret = 0;
4829 out:
4830 blk_unref(src);
4831 blk_unref(blk);
4832 qemu_opts_del(opts);
4833 return ret;
4836 #define C_BS 01
4837 #define C_COUNT 02
4838 #define C_IF 04
4839 #define C_OF 010
4840 #define C_SKIP 020
4842 struct DdInfo {
4843 unsigned int flags;
4844 int64_t count;
4847 struct DdIo {
4848 int bsz; /* Block size */
4849 char *filename;
4850 uint8_t *buf;
4851 int64_t offset;
4854 struct DdOpts {
4855 const char *name;
4856 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4857 unsigned int flag;
4860 static int img_dd_bs(const char *arg,
4861 struct DdIo *in, struct DdIo *out,
4862 struct DdInfo *dd)
4864 int64_t res;
4866 res = cvtnum_full("bs", arg, 1, INT_MAX);
4868 if (res < 0) {
4869 return 1;
4871 in->bsz = out->bsz = res;
4873 return 0;
4876 static int img_dd_count(const char *arg,
4877 struct DdIo *in, struct DdIo *out,
4878 struct DdInfo *dd)
4880 dd->count = cvtnum("count", arg);
4882 if (dd->count < 0) {
4883 return 1;
4886 return 0;
4889 static int img_dd_if(const char *arg,
4890 struct DdIo *in, struct DdIo *out,
4891 struct DdInfo *dd)
4893 in->filename = g_strdup(arg);
4895 return 0;
4898 static int img_dd_of(const char *arg,
4899 struct DdIo *in, struct DdIo *out,
4900 struct DdInfo *dd)
4902 out->filename = g_strdup(arg);
4904 return 0;
4907 static int img_dd_skip(const char *arg,
4908 struct DdIo *in, struct DdIo *out,
4909 struct DdInfo *dd)
4911 in->offset = cvtnum("skip", arg);
4913 if (in->offset < 0) {
4914 return 1;
4917 return 0;
4920 static int img_dd(int argc, char **argv)
4922 int ret = 0;
4923 char *arg = NULL;
4924 char *tmp;
4925 BlockDriver *drv = NULL, *proto_drv = NULL;
4926 BlockBackend *blk1 = NULL, *blk2 = NULL;
4927 QemuOpts *opts = NULL;
4928 QemuOptsList *create_opts = NULL;
4929 Error *local_err = NULL;
4930 bool image_opts = false;
4931 int c, i;
4932 const char *out_fmt = "raw";
4933 const char *fmt = NULL;
4934 int64_t size = 0;
4935 int64_t block_count = 0, out_pos, in_pos;
4936 bool force_share = false;
4937 struct DdInfo dd = {
4938 .flags = 0,
4939 .count = 0,
4941 struct DdIo in = {
4942 .bsz = 512, /* Block size is by default 512 bytes */
4943 .filename = NULL,
4944 .buf = NULL,
4945 .offset = 0
4947 struct DdIo out = {
4948 .bsz = 512,
4949 .filename = NULL,
4950 .buf = NULL,
4951 .offset = 0
4954 const struct DdOpts options[] = {
4955 { "bs", img_dd_bs, C_BS },
4956 { "count", img_dd_count, C_COUNT },
4957 { "if", img_dd_if, C_IF },
4958 { "of", img_dd_of, C_OF },
4959 { "skip", img_dd_skip, C_SKIP },
4960 { NULL, NULL, 0 }
4962 const struct option long_options[] = {
4963 { "help", no_argument, 0, 'h'},
4964 { "object", required_argument, 0, OPTION_OBJECT},
4965 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4966 { "force-share", no_argument, 0, 'U'},
4967 { 0, 0, 0, 0 }
4970 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4971 if (c == EOF) {
4972 break;
4974 switch (c) {
4975 case 'O':
4976 out_fmt = optarg;
4977 break;
4978 case 'f':
4979 fmt = optarg;
4980 break;
4981 case ':':
4982 missing_argument(argv[optind - 1]);
4983 break;
4984 case '?':
4985 unrecognized_option(argv[optind - 1]);
4986 break;
4987 case 'h':
4988 help();
4989 break;
4990 case 'U':
4991 force_share = true;
4992 break;
4993 case OPTION_OBJECT:
4994 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4995 ret = -1;
4996 goto out;
4998 break;
4999 case OPTION_IMAGE_OPTS:
5000 image_opts = true;
5001 break;
5005 for (i = optind; i < argc; i++) {
5006 int j;
5007 arg = g_strdup(argv[i]);
5009 tmp = strchr(arg, '=');
5010 if (tmp == NULL) {
5011 error_report("unrecognized operand %s", arg);
5012 ret = -1;
5013 goto out;
5016 *tmp++ = '\0';
5018 for (j = 0; options[j].name != NULL; j++) {
5019 if (!strcmp(arg, options[j].name)) {
5020 break;
5023 if (options[j].name == NULL) {
5024 error_report("unrecognized operand %s", arg);
5025 ret = -1;
5026 goto out;
5029 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5030 ret = -1;
5031 goto out;
5033 dd.flags |= options[j].flag;
5034 g_free(arg);
5035 arg = NULL;
5038 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5039 error_report("Must specify both input and output files");
5040 ret = -1;
5041 goto out;
5044 if (qemu_opts_foreach(&qemu_object_opts,
5045 user_creatable_add_opts_foreach,
5046 qemu_img_object_print_help, &error_fatal)) {
5047 ret = -1;
5048 goto out;
5051 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5052 force_share);
5054 if (!blk1) {
5055 ret = -1;
5056 goto out;
5059 drv = bdrv_find_format(out_fmt);
5060 if (!drv) {
5061 error_report("Unknown file format");
5062 ret = -1;
5063 goto out;
5065 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5067 if (!proto_drv) {
5068 error_report_err(local_err);
5069 ret = -1;
5070 goto out;
5072 if (!drv->create_opts) {
5073 error_report("Format driver '%s' does not support image creation",
5074 drv->format_name);
5075 ret = -1;
5076 goto out;
5078 if (!proto_drv->create_opts) {
5079 error_report("Protocol driver '%s' does not support image creation",
5080 proto_drv->format_name);
5081 ret = -1;
5082 goto out;
5084 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5085 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5087 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5089 size = blk_getlength(blk1);
5090 if (size < 0) {
5091 error_report("Failed to get size for '%s'", in.filename);
5092 ret = -1;
5093 goto out;
5096 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5097 dd.count * in.bsz < size) {
5098 size = dd.count * in.bsz;
5101 /* Overflow means the specified offset is beyond input image's size */
5102 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5103 size < in.bsz * in.offset)) {
5104 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5105 } else {
5106 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5107 size - in.bsz * in.offset, &error_abort);
5110 ret = bdrv_create(drv, out.filename, opts, &local_err);
5111 if (ret < 0) {
5112 error_reportf_err(local_err,
5113 "%s: error while creating output image: ",
5114 out.filename);
5115 ret = -1;
5116 goto out;
5119 /* TODO, we can't honour --image-opts for the target,
5120 * since it needs to be given in a format compatible
5121 * with the bdrv_create() call above which does not
5122 * support image-opts style.
5124 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5125 false, false, false);
5127 if (!blk2) {
5128 ret = -1;
5129 goto out;
5132 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5133 size < in.offset * in.bsz)) {
5134 /* We give a warning if the skip option is bigger than the input
5135 * size and create an empty output disk image (i.e. like dd(1)).
5137 error_report("%s: cannot skip to specified offset", in.filename);
5138 in_pos = size;
5139 } else {
5140 in_pos = in.offset * in.bsz;
5143 in.buf = g_new(uint8_t, in.bsz);
5145 for (out_pos = 0; in_pos < size; block_count++) {
5146 int in_ret, out_ret;
5148 if (in_pos + in.bsz > size) {
5149 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5150 } else {
5151 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5153 if (in_ret < 0) {
5154 error_report("error while reading from input image file: %s",
5155 strerror(-in_ret));
5156 ret = -1;
5157 goto out;
5159 in_pos += in_ret;
5161 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5163 if (out_ret < 0) {
5164 error_report("error while writing to output image file: %s",
5165 strerror(-out_ret));
5166 ret = -1;
5167 goto out;
5169 out_pos += out_ret;
5172 out:
5173 g_free(arg);
5174 qemu_opts_del(opts);
5175 qemu_opts_free(create_opts);
5176 blk_unref(blk1);
5177 blk_unref(blk2);
5178 g_free(in.filename);
5179 g_free(out.filename);
5180 g_free(in.buf);
5181 g_free(out.buf);
5183 if (ret) {
5184 return 1;
5186 return 0;
5189 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5191 QString *str;
5192 QObject *obj;
5193 Visitor *v = qobject_output_visitor_new(&obj);
5195 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5196 visit_complete(v, &obj);
5197 str = qobject_to_json_pretty(obj);
5198 assert(str != NULL);
5199 printf("%s\n", qstring_get_str(str));
5200 qobject_unref(obj);
5201 visit_free(v);
5202 qobject_unref(str);
5205 static int img_measure(int argc, char **argv)
5207 static const struct option long_options[] = {
5208 {"help", no_argument, 0, 'h'},
5209 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5210 {"object", required_argument, 0, OPTION_OBJECT},
5211 {"output", required_argument, 0, OPTION_OUTPUT},
5212 {"size", required_argument, 0, OPTION_SIZE},
5213 {"force-share", no_argument, 0, 'U'},
5214 {0, 0, 0, 0}
5216 OutputFormat output_format = OFORMAT_HUMAN;
5217 BlockBackend *in_blk = NULL;
5218 BlockDriver *drv;
5219 const char *filename = NULL;
5220 const char *fmt = NULL;
5221 const char *out_fmt = "raw";
5222 char *options = NULL;
5223 char *snapshot_name = NULL;
5224 bool force_share = false;
5225 QemuOpts *opts = NULL;
5226 QemuOpts *object_opts = NULL;
5227 QemuOpts *sn_opts = NULL;
5228 QemuOptsList *create_opts = NULL;
5229 bool image_opts = false;
5230 uint64_t img_size = UINT64_MAX;
5231 BlockMeasureInfo *info = NULL;
5232 Error *local_err = NULL;
5233 int ret = 1;
5234 int c;
5236 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5237 long_options, NULL)) != -1) {
5238 switch (c) {
5239 case '?':
5240 case 'h':
5241 help();
5242 break;
5243 case 'f':
5244 fmt = optarg;
5245 break;
5246 case 'O':
5247 out_fmt = optarg;
5248 break;
5249 case 'o':
5250 if (accumulate_options(&options, optarg) < 0) {
5251 goto out;
5253 break;
5254 case 'l':
5255 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5256 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5257 optarg, false);
5258 if (!sn_opts) {
5259 error_report("Failed in parsing snapshot param '%s'",
5260 optarg);
5261 goto out;
5263 } else {
5264 snapshot_name = optarg;
5266 break;
5267 case 'U':
5268 force_share = true;
5269 break;
5270 case OPTION_OBJECT:
5271 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5272 optarg, true);
5273 if (!object_opts) {
5274 goto out;
5276 break;
5277 case OPTION_IMAGE_OPTS:
5278 image_opts = true;
5279 break;
5280 case OPTION_OUTPUT:
5281 if (!strcmp(optarg, "json")) {
5282 output_format = OFORMAT_JSON;
5283 } else if (!strcmp(optarg, "human")) {
5284 output_format = OFORMAT_HUMAN;
5285 } else {
5286 error_report("--output must be used with human or json "
5287 "as argument.");
5288 goto out;
5290 break;
5291 case OPTION_SIZE:
5293 int64_t sval;
5295 sval = cvtnum("image size", optarg);
5296 if (sval < 0) {
5297 goto out;
5299 img_size = (uint64_t)sval;
5301 break;
5305 if (qemu_opts_foreach(&qemu_object_opts,
5306 user_creatable_add_opts_foreach,
5307 qemu_img_object_print_help, &error_fatal)) {
5308 goto out;
5311 if (argc - optind > 1) {
5312 error_report("At most one filename argument is allowed.");
5313 goto out;
5314 } else if (argc - optind == 1) {
5315 filename = argv[optind];
5318 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5319 error_report("--image-opts, -f, and -l require a filename argument.");
5320 goto out;
5322 if (filename && img_size != UINT64_MAX) {
5323 error_report("--size N cannot be used together with a filename.");
5324 goto out;
5326 if (!filename && img_size == UINT64_MAX) {
5327 error_report("Either --size N or one filename must be specified.");
5328 goto out;
5331 if (filename) {
5332 in_blk = img_open(image_opts, filename, fmt, 0,
5333 false, false, force_share);
5334 if (!in_blk) {
5335 goto out;
5338 if (sn_opts) {
5339 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5340 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5341 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5342 &local_err);
5343 } else if (snapshot_name != NULL) {
5344 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5345 snapshot_name, &local_err);
5347 if (local_err) {
5348 error_reportf_err(local_err, "Failed to load snapshot: ");
5349 goto out;
5353 drv = bdrv_find_format(out_fmt);
5354 if (!drv) {
5355 error_report("Unknown file format '%s'", out_fmt);
5356 goto out;
5358 if (!drv->create_opts) {
5359 error_report("Format driver '%s' does not support image creation",
5360 drv->format_name);
5361 goto out;
5364 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5365 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5366 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5367 if (options) {
5368 qemu_opts_do_parse(opts, options, NULL, &local_err);
5369 if (local_err) {
5370 error_report_err(local_err);
5371 error_report("Invalid options for file format '%s'", out_fmt);
5372 goto out;
5375 if (img_size != UINT64_MAX) {
5376 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5379 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5380 if (local_err) {
5381 error_report_err(local_err);
5382 goto out;
5385 if (output_format == OFORMAT_HUMAN) {
5386 printf("required size: %" PRIu64 "\n", info->required);
5387 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5388 if (info->has_bitmaps) {
5389 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5391 } else {
5392 dump_json_block_measure_info(info);
5395 ret = 0;
5397 out:
5398 qapi_free_BlockMeasureInfo(info);
5399 qemu_opts_del(object_opts);
5400 qemu_opts_del(opts);
5401 qemu_opts_del(sn_opts);
5402 qemu_opts_free(create_opts);
5403 g_free(options);
5404 blk_unref(in_blk);
5405 return ret;
5408 static const img_cmd_t img_cmds[] = {
5409 #define DEF(option, callback, arg_string) \
5410 { option, callback },
5411 #include "qemu-img-cmds.h"
5412 #undef DEF
5413 { NULL, NULL, },
5416 int main(int argc, char **argv)
5418 const img_cmd_t *cmd;
5419 const char *cmdname;
5420 Error *local_error = NULL;
5421 char *trace_file = NULL;
5422 int c;
5423 static const struct option long_options[] = {
5424 {"help", no_argument, 0, 'h'},
5425 {"version", no_argument, 0, 'V'},
5426 {"trace", required_argument, NULL, 'T'},
5427 {0, 0, 0, 0}
5430 #ifdef CONFIG_POSIX
5431 signal(SIGPIPE, SIG_IGN);
5432 #endif
5434 error_init(argv[0]);
5435 module_call_init(MODULE_INIT_TRACE);
5436 qemu_init_exec_dir(argv[0]);
5438 if (qemu_init_main_loop(&local_error)) {
5439 error_report_err(local_error);
5440 exit(EXIT_FAILURE);
5443 qcrypto_init(&error_fatal);
5445 module_call_init(MODULE_INIT_QOM);
5446 bdrv_init();
5447 if (argc < 2) {
5448 error_exit("Not enough arguments");
5451 qemu_add_opts(&qemu_object_opts);
5452 qemu_add_opts(&qemu_source_opts);
5453 qemu_add_opts(&qemu_trace_opts);
5455 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5456 switch (c) {
5457 case ':':
5458 missing_argument(argv[optind - 1]);
5459 return 0;
5460 case '?':
5461 unrecognized_option(argv[optind - 1]);
5462 return 0;
5463 case 'h':
5464 help();
5465 return 0;
5466 case 'V':
5467 printf(QEMU_IMG_VERSION);
5468 return 0;
5469 case 'T':
5470 g_free(trace_file);
5471 trace_file = trace_opt_parse(optarg);
5472 break;
5476 cmdname = argv[optind];
5478 /* reset getopt_long scanning */
5479 argc -= optind;
5480 if (argc < 1) {
5481 return 0;
5483 argv += optind;
5484 qemu_reset_optind();
5486 if (!trace_init_backends()) {
5487 exit(1);
5489 trace_init_file(trace_file);
5490 qemu_set_log(LOG_TRACE);
5492 /* find the command */
5493 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5494 if (!strcmp(cmdname, cmd->name)) {
5495 return cmd->handler(argc, argv);
5499 /* not found */
5500 error_exit("Command not found: %s", cmdname);