xref: /openbmc/qemu/qemu-img.c (revision be99a9a0)
1 /*
2  * QEMU disk image utility
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include <getopt.h>
27 
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"
52 
53 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
54                           "\n" QEMU_COPYRIGHT "\n"
55 
56 typedef struct img_cmd_t {
57     const char *name;
58     int (*handler)(int argc, char **argv);
59 } img_cmd_t;
60 
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 };
83 
84 typedef enum OutputFormat {
85     OFORMAT_JSON,
86     OFORMAT_HUMAN,
87 } OutputFormat;
88 
89 /* Default to cache=writeback as data integrity is not important for qemu-img */
90 #define BDRV_DEFAULT_CACHE "writeback"
91 
92 static void format_print(void *opaque, const char *name)
93 {
94     printf(" %s", name);
95 }
96 
97 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
98 {
99     va_list ap;
100 
101     va_start(ap, fmt);
102     error_vreport(fmt, ap);
103     va_end(ap);
104 
105     error_printf("Try 'qemu-img --help' for more information\n");
106     exit(EXIT_FAILURE);
107 }
108 
109 static void QEMU_NORETURN missing_argument(const char *option)
110 {
111     error_exit("missing argument for option '%s'", option);
112 }
113 
114 static void QEMU_NORETURN unrecognized_option(const char *option)
115 {
116     error_exit("unrecognized option '%s'", option);
117 }
118 
119 /* Please keep in synch with docs/tools/qemu-img.rst */
120 static void QEMU_NORETURN help(void)
121 {
122     const char *help_msg =
123            QEMU_IMG_VERSION
124            "usage: qemu-img [standard options] command [command options]\n"
125            "QEMU disk image utility\n"
126            "\n"
127            "    '-h', '--help'       display this help and exit\n"
128            "    '-V', '--version'    output version information and exit\n"
129            "    '-T', '--trace'      [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
130            "                         specify tracing options\n"
131            "\n"
132            "Command syntax:\n"
133 #define DEF(option, callback, arg_string)        \
134            "  " arg_string "\n"
135 #include "qemu-img-cmds.h"
136 #undef DEF
137            "\n"
138            "Command parameters:\n"
139            "  'filename' is a disk image filename\n"
140            "  'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
141            "    manual page for a description of the object properties. The most common\n"
142            "    object type is a 'secret', which is used to supply passwords and/or\n"
143            "    encryption keys.\n"
144            "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
145            "  'cache' is the cache mode used to write the output disk image, the valid\n"
146            "    options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
147            "    'directsync' and 'unsafe' (default for convert)\n"
148            "  'src_cache' is the cache mode used to read input disk images, the valid\n"
149            "    options are the same as for the 'cache' option\n"
150            "  'size' is the disk image size in bytes. Optional suffixes\n"
151            "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
152            "    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are\n"
153            "    supported. 'b' is ignored.\n"
154            "  'output_filename' is the destination disk image filename\n"
155            "  'output_fmt' is the destination format\n"
156            "  'options' is a comma separated list of format specific options in a\n"
157            "    name=value format. Use -o ? for an overview of the options supported by the\n"
158            "    used format\n"
159            "  'snapshot_param' is param used for internal snapshot, format\n"
160            "    is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
161            "    '[ID_OR_NAME]'\n"
162            "  '-c' indicates that target image must be compressed (qcow format only)\n"
163            "  '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
164            "       new backing file match exactly. The image doesn't need a working\n"
165            "       backing file before rebasing in this case (useful for renaming the\n"
166            "       backing file). For image creation, allow creating without attempting\n"
167            "       to open the backing file.\n"
168            "  '-h' with or without a command shows this help and lists the supported formats\n"
169            "  '-p' show progress of command (only certain commands)\n"
170            "  '-q' use Quiet mode - do not print any output (except errors)\n"
171            "  '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
172            "       contain only zeros for qemu-img to create a sparse image during\n"
173            "       conversion. If the number of bytes is 0, the source will not be scanned for\n"
174            "       unallocated or zero sectors, and the destination image will always be\n"
175            "       fully allocated\n"
176            "  '--output' takes the format in which the output must be done (human or json)\n"
177            "  '-n' skips the target volume creation (useful if the volume is created\n"
178            "       prior to running qemu-img)\n"
179            "\n"
180            "Parameters to bitmap subcommand:\n"
181            "  'bitmap' is the name of the bitmap to manipulate, through one or more\n"
182            "       actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
183            "       or '--merge source'\n"
184            "  '-g granularity' sets the granularity for '--add' actions\n"
185            "  '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
186            "       bitmaps from an alternative file\n"
187            "\n"
188            "Parameters to check subcommand:\n"
189            "  '-r' tries to repair any inconsistencies that are found during the check.\n"
190            "       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
191            "       kinds of errors, with a higher risk of choosing the wrong fix or\n"
192            "       hiding corruption that has already occurred.\n"
193            "\n"
194            "Parameters to convert subcommand:\n"
195            "  '--bitmaps' copies all top-level persistent bitmaps to destination\n"
196            "  '-m' specifies how many coroutines work in parallel during the convert\n"
197            "       process (defaults to 8)\n"
198            "  '-W' allow to write to the target out of order rather than sequential\n"
199            "\n"
200            "Parameters to snapshot subcommand:\n"
201            "  'snapshot' is the name of the snapshot to create, apply or delete\n"
202            "  '-a' applies a snapshot (revert disk to saved state)\n"
203            "  '-c' creates a snapshot\n"
204            "  '-d' deletes a snapshot\n"
205            "  '-l' lists all snapshots in the given image\n"
206            "\n"
207            "Parameters to compare subcommand:\n"
208            "  '-f' first image format\n"
209            "  '-F' second image format\n"
210            "  '-s' run in Strict mode - fail on different image size or sector allocation\n"
211            "\n"
212            "Parameters to dd subcommand:\n"
213            "  'bs=BYTES' read and write up to BYTES bytes at a time "
214            "(default: 512)\n"
215            "  'count=N' copy only N input blocks\n"
216            "  'if=FILE' read from FILE\n"
217            "  'of=FILE' write to FILE\n"
218            "  'skip=N' skip N bs-sized blocks at the start of input\n";
219 
220     printf("%s\nSupported formats:", help_msg);
221     bdrv_iterate_format(format_print, NULL, false);
222     printf("\n\n" QEMU_HELP_BOTTOM "\n");
223     exit(EXIT_SUCCESS);
224 }
225 
226 static QemuOptsList qemu_object_opts = {
227     .name = "object",
228     .implied_opt_name = "qom-type",
229     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
230     .desc = {
231         { }
232     },
233 };
234 
235 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
236 {
237     if (user_creatable_print_help(type, opts)) {
238         exit(0);
239     }
240     return true;
241 }
242 
243 /*
244  * Is @optarg safe for accumulate_options()?
245  * It is when multiple of them can be joined together separated by ','.
246  * To make that work, @optarg must not start with ',' (or else a
247  * separating ',' preceding it gets escaped), and it must not end with
248  * an odd number of ',' (or else a separating ',' following it gets
249  * escaped), or be empty (or else a separating ',' preceding it can
250  * escape a separating ',' following it).
251  *
252  */
253 static bool is_valid_option_list(const char *optarg)
254 {
255     size_t len = strlen(optarg);
256     size_t i;
257 
258     if (!optarg[0] || optarg[0] == ',') {
259         return false;
260     }
261 
262     for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
263     }
264     if ((len - i) % 2) {
265         return false;
266     }
267 
268     return true;
269 }
270 
271 static int accumulate_options(char **options, char *optarg)
272 {
273     char *new_options;
274 
275     if (!is_valid_option_list(optarg)) {
276         error_report("Invalid option list: %s", optarg);
277         return -1;
278     }
279 
280     if (!*options) {
281         *options = g_strdup(optarg);
282     } else {
283         new_options = g_strdup_printf("%s,%s", *options, optarg);
284         g_free(*options);
285         *options = new_options;
286     }
287     return 0;
288 }
289 
290 static QemuOptsList qemu_source_opts = {
291     .name = "source",
292     .implied_opt_name = "file",
293     .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
294     .desc = {
295         { }
296     },
297 };
298 
299 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
300 {
301     int ret = 0;
302     if (!quiet) {
303         va_list args;
304         va_start(args, fmt);
305         ret = vprintf(fmt, args);
306         va_end(args);
307     }
308     return ret;
309 }
310 
311 
312 static int print_block_option_help(const char *filename, const char *fmt)
313 {
314     BlockDriver *drv, *proto_drv;
315     QemuOptsList *create_opts = NULL;
316     Error *local_err = NULL;
317 
318     /* Find driver and parse its options */
319     drv = bdrv_find_format(fmt);
320     if (!drv) {
321         error_report("Unknown file format '%s'", fmt);
322         return 1;
323     }
324 
325     if (!drv->create_opts) {
326         error_report("Format driver '%s' does not support image creation", fmt);
327         return 1;
328     }
329 
330     create_opts = qemu_opts_append(create_opts, drv->create_opts);
331     if (filename) {
332         proto_drv = bdrv_find_protocol(filename, true, &local_err);
333         if (!proto_drv) {
334             error_report_err(local_err);
335             qemu_opts_free(create_opts);
336             return 1;
337         }
338         if (!proto_drv->create_opts) {
339             error_report("Protocol driver '%s' does not support image creation",
340                          proto_drv->format_name);
341             qemu_opts_free(create_opts);
342             return 1;
343         }
344         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
345     }
346 
347     if (filename) {
348         printf("Supported options:\n");
349     } else {
350         printf("Supported %s options:\n", fmt);
351     }
352     qemu_opts_print_help(create_opts, false);
353     qemu_opts_free(create_opts);
354 
355     if (!filename) {
356         printf("\n"
357                "The protocol level may support further options.\n"
358                "Specify the target filename to include those options.\n");
359     }
360 
361     return 0;
362 }
363 
364 
365 static BlockBackend *img_open_opts(const char *optstr,
366                                    QemuOpts *opts, int flags, bool writethrough,
367                                    bool quiet, bool force_share)
368 {
369     QDict *options;
370     Error *local_err = NULL;
371     BlockBackend *blk;
372     options = qemu_opts_to_qdict(opts, NULL);
373     if (force_share) {
374         if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
375             && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
376             error_report("--force-share/-U conflicts with image options");
377             qobject_unref(options);
378             return NULL;
379         }
380         qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
381     }
382     blk = blk_new_open(NULL, NULL, options, flags, &local_err);
383     if (!blk) {
384         error_reportf_err(local_err, "Could not open '%s': ", optstr);
385         return NULL;
386     }
387     blk_set_enable_write_cache(blk, !writethrough);
388 
389     return blk;
390 }
391 
392 static BlockBackend *img_open_file(const char *filename,
393                                    QDict *options,
394                                    const char *fmt, int flags,
395                                    bool writethrough, bool quiet,
396                                    bool force_share)
397 {
398     BlockBackend *blk;
399     Error *local_err = NULL;
400 
401     if (!options) {
402         options = qdict_new();
403     }
404     if (fmt) {
405         qdict_put_str(options, "driver", fmt);
406     }
407 
408     if (force_share) {
409         qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
410     }
411     blk = blk_new_open(filename, NULL, options, flags, &local_err);
412     if (!blk) {
413         error_reportf_err(local_err, "Could not open '%s': ", filename);
414         return NULL;
415     }
416     blk_set_enable_write_cache(blk, !writethrough);
417 
418     return blk;
419 }
420 
421 
422 static int img_add_key_secrets(void *opaque,
423                                const char *name, const char *value,
424                                Error **errp)
425 {
426     QDict *options = opaque;
427 
428     if (g_str_has_suffix(name, "key-secret")) {
429         qdict_put_str(options, name, value);
430     }
431 
432     return 0;
433 }
434 
435 
436 static BlockBackend *img_open(bool image_opts,
437                               const char *filename,
438                               const char *fmt, int flags, bool writethrough,
439                               bool quiet, bool force_share)
440 {
441     BlockBackend *blk;
442     if (image_opts) {
443         QemuOpts *opts;
444         if (fmt) {
445             error_report("--image-opts and --format are mutually exclusive");
446             return NULL;
447         }
448         opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
449                                        filename, true);
450         if (!opts) {
451             return NULL;
452         }
453         blk = img_open_opts(filename, opts, flags, writethrough, quiet,
454                             force_share);
455     } else {
456         blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
457                             force_share);
458     }
459     return blk;
460 }
461 
462 
463 static int add_old_style_options(const char *fmt, QemuOpts *opts,
464                                  const char *base_filename,
465                                  const char *base_fmt)
466 {
467     Error *err = NULL;
468 
469     if (base_filename) {
470         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
471         if (err) {
472             error_report("Backing file not supported for file format '%s'",
473                          fmt);
474             error_free(err);
475             return -1;
476         }
477     }
478     if (base_fmt) {
479         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
480         if (err) {
481             error_report("Backing file format not supported for file "
482                          "format '%s'", fmt);
483             error_free(err);
484             return -1;
485         }
486     }
487     return 0;
488 }
489 
490 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
491                            int64_t max)
492 {
493     int err;
494     uint64_t res;
495 
496     err = qemu_strtosz(value, NULL, &res);
497     if (err < 0 && err != -ERANGE) {
498         error_report("Invalid %s specified. You may use "
499                      "k, M, G, T, P or E suffixes for", name);
500         error_report("kilobytes, megabytes, gigabytes, terabytes, "
501                      "petabytes and exabytes.");
502         return err;
503     }
504     if (err == -ERANGE || res > max || res < min) {
505         error_report("Invalid %s specified. Must be between %" PRId64
506                      " and %" PRId64 ".", name, min, max);
507         return -ERANGE;
508     }
509     return res;
510 }
511 
512 static int64_t cvtnum(const char *name, const char *value)
513 {
514     return cvtnum_full(name, value, 0, INT64_MAX);
515 }
516 
517 static int img_create(int argc, char **argv)
518 {
519     int c;
520     uint64_t img_size = -1;
521     const char *fmt = "raw";
522     const char *base_fmt = NULL;
523     const char *filename;
524     const char *base_filename = NULL;
525     char *options = NULL;
526     Error *local_err = NULL;
527     bool quiet = false;
528     int flags = 0;
529 
530     for(;;) {
531         static const struct option long_options[] = {
532             {"help", no_argument, 0, 'h'},
533             {"object", required_argument, 0, OPTION_OBJECT},
534             {0, 0, 0, 0}
535         };
536         c = getopt_long(argc, argv, ":F:b:f:ho:qu",
537                         long_options, NULL);
538         if (c == -1) {
539             break;
540         }
541         switch(c) {
542         case ':':
543             missing_argument(argv[optind - 1]);
544             break;
545         case '?':
546             unrecognized_option(argv[optind - 1]);
547             break;
548         case 'h':
549             help();
550             break;
551         case 'F':
552             base_fmt = optarg;
553             break;
554         case 'b':
555             base_filename = optarg;
556             break;
557         case 'f':
558             fmt = optarg;
559             break;
560         case 'o':
561             if (accumulate_options(&options, optarg) < 0) {
562                 goto fail;
563             }
564             break;
565         case 'q':
566             quiet = true;
567             break;
568         case 'u':
569             flags |= BDRV_O_NO_BACKING;
570             break;
571         case OPTION_OBJECT: {
572             QemuOpts *opts;
573             opts = qemu_opts_parse_noisily(&qemu_object_opts,
574                                            optarg, true);
575             if (!opts) {
576                 goto fail;
577             }
578         }   break;
579         }
580     }
581 
582     /* Get the filename */
583     filename = (optind < argc) ? argv[optind] : NULL;
584     if (options && has_help_option(options)) {
585         g_free(options);
586         return print_block_option_help(filename, fmt);
587     }
588 
589     if (optind >= argc) {
590         error_exit("Expecting image file name");
591     }
592     optind++;
593 
594     if (qemu_opts_foreach(&qemu_object_opts,
595                           user_creatable_add_opts_foreach,
596                           qemu_img_object_print_help, &error_fatal)) {
597         goto fail;
598     }
599 
600     /* Get image size, if specified */
601     if (optind < argc) {
602         int64_t sval;
603 
604         sval = cvtnum("image size", argv[optind++]);
605         if (sval < 0) {
606             goto fail;
607         }
608         img_size = (uint64_t)sval;
609     }
610     if (optind != argc) {
611         error_exit("Unexpected argument: %s", argv[optind]);
612     }
613 
614     bdrv_img_create(filename, fmt, base_filename, base_fmt,
615                     options, img_size, flags, quiet, &local_err);
616     if (local_err) {
617         error_reportf_err(local_err, "%s: ", filename);
618         goto fail;
619     }
620 
621     g_free(options);
622     return 0;
623 
624 fail:
625     g_free(options);
626     return 1;
627 }
628 
629 static void dump_json_image_check(ImageCheck *check, bool quiet)
630 {
631     QString *str;
632     QObject *obj;
633     Visitor *v = qobject_output_visitor_new(&obj);
634 
635     visit_type_ImageCheck(v, NULL, &check, &error_abort);
636     visit_complete(v, &obj);
637     str = qobject_to_json_pretty(obj);
638     assert(str != NULL);
639     qprintf(quiet, "%s\n", qstring_get_str(str));
640     qobject_unref(obj);
641     visit_free(v);
642     qobject_unref(str);
643 }
644 
645 static void dump_human_image_check(ImageCheck *check, bool quiet)
646 {
647     if (!(check->corruptions || check->leaks || check->check_errors)) {
648         qprintf(quiet, "No errors were found on the image.\n");
649     } else {
650         if (check->corruptions) {
651             qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
652                     "Data may be corrupted, or further writes to the image "
653                     "may corrupt it.\n",
654                     check->corruptions);
655         }
656 
657         if (check->leaks) {
658             qprintf(quiet,
659                     "\n%" PRId64 " leaked clusters were found on the image.\n"
660                     "This means waste of disk space, but no harm to data.\n",
661                     check->leaks);
662         }
663 
664         if (check->check_errors) {
665             qprintf(quiet,
666                     "\n%" PRId64
667                     " internal errors have occurred during the check.\n",
668                     check->check_errors);
669         }
670     }
671 
672     if (check->total_clusters != 0 && check->allocated_clusters != 0) {
673         qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
674                 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
675                 check->allocated_clusters, check->total_clusters,
676                 check->allocated_clusters * 100.0 / check->total_clusters,
677                 check->fragmented_clusters * 100.0 / check->allocated_clusters,
678                 check->compressed_clusters * 100.0 /
679                 check->allocated_clusters);
680     }
681 
682     if (check->image_end_offset) {
683         qprintf(quiet,
684                 "Image end offset: %" PRId64 "\n", check->image_end_offset);
685     }
686 }
687 
688 static int collect_image_check(BlockDriverState *bs,
689                    ImageCheck *check,
690                    const char *filename,
691                    const char *fmt,
692                    int fix)
693 {
694     int ret;
695     BdrvCheckResult result;
696 
697     ret = bdrv_check(bs, &result, fix);
698     if (ret < 0) {
699         return ret;
700     }
701 
702     check->filename                 = g_strdup(filename);
703     check->format                   = g_strdup(bdrv_get_format_name(bs));
704     check->check_errors             = result.check_errors;
705     check->corruptions              = result.corruptions;
706     check->has_corruptions          = result.corruptions != 0;
707     check->leaks                    = result.leaks;
708     check->has_leaks                = result.leaks != 0;
709     check->corruptions_fixed        = result.corruptions_fixed;
710     check->has_corruptions_fixed    = result.corruptions_fixed != 0;
711     check->leaks_fixed              = result.leaks_fixed;
712     check->has_leaks_fixed          = result.leaks_fixed != 0;
713     check->image_end_offset         = result.image_end_offset;
714     check->has_image_end_offset     = result.image_end_offset != 0;
715     check->total_clusters           = result.bfi.total_clusters;
716     check->has_total_clusters       = result.bfi.total_clusters != 0;
717     check->allocated_clusters       = result.bfi.allocated_clusters;
718     check->has_allocated_clusters   = result.bfi.allocated_clusters != 0;
719     check->fragmented_clusters      = result.bfi.fragmented_clusters;
720     check->has_fragmented_clusters  = result.bfi.fragmented_clusters != 0;
721     check->compressed_clusters      = result.bfi.compressed_clusters;
722     check->has_compressed_clusters  = result.bfi.compressed_clusters != 0;
723 
724     return 0;
725 }
726 
727 /*
728  * Checks an image for consistency. Exit codes:
729  *
730  *  0 - Check completed, image is good
731  *  1 - Check not completed because of internal errors
732  *  2 - Check completed, image is corrupted
733  *  3 - Check completed, image has leaked clusters, but is good otherwise
734  * 63 - Checks are not supported by the image format
735  */
736 static int img_check(int argc, char **argv)
737 {
738     int c, ret;
739     OutputFormat output_format = OFORMAT_HUMAN;
740     const char *filename, *fmt, *output, *cache;
741     BlockBackend *blk;
742     BlockDriverState *bs;
743     int fix = 0;
744     int flags = BDRV_O_CHECK;
745     bool writethrough;
746     ImageCheck *check;
747     bool quiet = false;
748     bool image_opts = false;
749     bool force_share = false;
750 
751     fmt = NULL;
752     output = NULL;
753     cache = BDRV_DEFAULT_CACHE;
754 
755     for(;;) {
756         int option_index = 0;
757         static const struct option long_options[] = {
758             {"help", no_argument, 0, 'h'},
759             {"format", required_argument, 0, 'f'},
760             {"repair", required_argument, 0, 'r'},
761             {"output", required_argument, 0, OPTION_OUTPUT},
762             {"object", required_argument, 0, OPTION_OBJECT},
763             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
764             {"force-share", no_argument, 0, 'U'},
765             {0, 0, 0, 0}
766         };
767         c = getopt_long(argc, argv, ":hf:r:T:qU",
768                         long_options, &option_index);
769         if (c == -1) {
770             break;
771         }
772         switch(c) {
773         case ':':
774             missing_argument(argv[optind - 1]);
775             break;
776         case '?':
777             unrecognized_option(argv[optind - 1]);
778             break;
779         case 'h':
780             help();
781             break;
782         case 'f':
783             fmt = optarg;
784             break;
785         case 'r':
786             flags |= BDRV_O_RDWR;
787 
788             if (!strcmp(optarg, "leaks")) {
789                 fix = BDRV_FIX_LEAKS;
790             } else if (!strcmp(optarg, "all")) {
791                 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
792             } else {
793                 error_exit("Unknown option value for -r "
794                            "(expecting 'leaks' or 'all'): %s", optarg);
795             }
796             break;
797         case OPTION_OUTPUT:
798             output = optarg;
799             break;
800         case 'T':
801             cache = optarg;
802             break;
803         case 'q':
804             quiet = true;
805             break;
806         case 'U':
807             force_share = true;
808             break;
809         case OPTION_OBJECT: {
810             QemuOpts *opts;
811             opts = qemu_opts_parse_noisily(&qemu_object_opts,
812                                            optarg, true);
813             if (!opts) {
814                 return 1;
815             }
816         }   break;
817         case OPTION_IMAGE_OPTS:
818             image_opts = true;
819             break;
820         }
821     }
822     if (optind != argc - 1) {
823         error_exit("Expecting one image file name");
824     }
825     filename = argv[optind++];
826 
827     if (output && !strcmp(output, "json")) {
828         output_format = OFORMAT_JSON;
829     } else if (output && !strcmp(output, "human")) {
830         output_format = OFORMAT_HUMAN;
831     } else if (output) {
832         error_report("--output must be used with human or json as argument.");
833         return 1;
834     }
835 
836     if (qemu_opts_foreach(&qemu_object_opts,
837                           user_creatable_add_opts_foreach,
838                           qemu_img_object_print_help, &error_fatal)) {
839         return 1;
840     }
841 
842     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
843     if (ret < 0) {
844         error_report("Invalid source cache option: %s", cache);
845         return 1;
846     }
847 
848     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
849                    force_share);
850     if (!blk) {
851         return 1;
852     }
853     bs = blk_bs(blk);
854 
855     check = g_new0(ImageCheck, 1);
856     ret = collect_image_check(bs, check, filename, fmt, fix);
857 
858     if (ret == -ENOTSUP) {
859         error_report("This image format does not support checks");
860         ret = 63;
861         goto fail;
862     }
863 
864     if (check->corruptions_fixed || check->leaks_fixed) {
865         int corruptions_fixed, leaks_fixed;
866         bool has_leaks_fixed, has_corruptions_fixed;
867 
868         leaks_fixed         = check->leaks_fixed;
869         has_leaks_fixed     = check->has_leaks_fixed;
870         corruptions_fixed   = check->corruptions_fixed;
871         has_corruptions_fixed = check->has_corruptions_fixed;
872 
873         if (output_format == OFORMAT_HUMAN) {
874             qprintf(quiet,
875                     "The following inconsistencies were found and repaired:\n\n"
876                     "    %" PRId64 " leaked clusters\n"
877                     "    %" PRId64 " corruptions\n\n"
878                     "Double checking the fixed image now...\n",
879                     check->leaks_fixed,
880                     check->corruptions_fixed);
881         }
882 
883         qapi_free_ImageCheck(check);
884         check = g_new0(ImageCheck, 1);
885         ret = collect_image_check(bs, check, filename, fmt, 0);
886 
887         check->leaks_fixed          = leaks_fixed;
888         check->has_leaks_fixed      = has_leaks_fixed;
889         check->corruptions_fixed    = corruptions_fixed;
890         check->has_corruptions_fixed = has_corruptions_fixed;
891     }
892 
893     if (!ret) {
894         switch (output_format) {
895         case OFORMAT_HUMAN:
896             dump_human_image_check(check, quiet);
897             break;
898         case OFORMAT_JSON:
899             dump_json_image_check(check, quiet);
900             break;
901         }
902     }
903 
904     if (ret || check->check_errors) {
905         if (ret) {
906             error_report("Check failed: %s", strerror(-ret));
907         } else {
908             error_report("Check failed");
909         }
910         ret = 1;
911         goto fail;
912     }
913 
914     if (check->corruptions) {
915         ret = 2;
916     } else if (check->leaks) {
917         ret = 3;
918     } else {
919         ret = 0;
920     }
921 
922 fail:
923     qapi_free_ImageCheck(check);
924     blk_unref(blk);
925     return ret;
926 }
927 
928 typedef struct CommonBlockJobCBInfo {
929     BlockDriverState *bs;
930     Error **errp;
931 } CommonBlockJobCBInfo;
932 
933 static void common_block_job_cb(void *opaque, int ret)
934 {
935     CommonBlockJobCBInfo *cbi = opaque;
936 
937     if (ret < 0) {
938         error_setg_errno(cbi->errp, -ret, "Block job failed");
939     }
940 }
941 
942 static void run_block_job(BlockJob *job, Error **errp)
943 {
944     AioContext *aio_context = blk_get_aio_context(job->blk);
945     int ret = 0;
946 
947     aio_context_acquire(aio_context);
948     job_ref(&job->job);
949     do {
950         float progress = 0.0f;
951         aio_poll(aio_context, true);
952         if (job->job.progress.total) {
953             progress = (float)job->job.progress.current /
954                        job->job.progress.total * 100.f;
955         }
956         qemu_progress_print(progress, 0);
957     } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
958 
959     if (!job_is_completed(&job->job)) {
960         ret = job_complete_sync(&job->job, errp);
961     } else {
962         ret = job->job.ret;
963     }
964     job_unref(&job->job);
965     aio_context_release(aio_context);
966 
967     /* publish completion progress only when success */
968     if (!ret) {
969         qemu_progress_print(100.f, 0);
970     }
971 }
972 
973 static int img_commit(int argc, char **argv)
974 {
975     int c, ret, flags;
976     const char *filename, *fmt, *cache, *base;
977     BlockBackend *blk;
978     BlockDriverState *bs, *base_bs;
979     BlockJob *job;
980     bool progress = false, quiet = false, drop = false;
981     bool writethrough;
982     Error *local_err = NULL;
983     CommonBlockJobCBInfo cbi;
984     bool image_opts = false;
985     AioContext *aio_context;
986 
987     fmt = NULL;
988     cache = BDRV_DEFAULT_CACHE;
989     base = NULL;
990     for(;;) {
991         static const struct option long_options[] = {
992             {"help", no_argument, 0, 'h'},
993             {"object", required_argument, 0, OPTION_OBJECT},
994             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
995             {0, 0, 0, 0}
996         };
997         c = getopt_long(argc, argv, ":f:ht:b:dpq",
998                         long_options, NULL);
999         if (c == -1) {
1000             break;
1001         }
1002         switch(c) {
1003         case ':':
1004             missing_argument(argv[optind - 1]);
1005             break;
1006         case '?':
1007             unrecognized_option(argv[optind - 1]);
1008             break;
1009         case 'h':
1010             help();
1011             break;
1012         case 'f':
1013             fmt = optarg;
1014             break;
1015         case 't':
1016             cache = optarg;
1017             break;
1018         case 'b':
1019             base = optarg;
1020             /* -b implies -d */
1021             drop = true;
1022             break;
1023         case 'd':
1024             drop = true;
1025             break;
1026         case 'p':
1027             progress = true;
1028             break;
1029         case 'q':
1030             quiet = true;
1031             break;
1032         case OPTION_OBJECT: {
1033             QemuOpts *opts;
1034             opts = qemu_opts_parse_noisily(&qemu_object_opts,
1035                                            optarg, true);
1036             if (!opts) {
1037                 return 1;
1038             }
1039         }   break;
1040         case OPTION_IMAGE_OPTS:
1041             image_opts = true;
1042             break;
1043         }
1044     }
1045 
1046     /* Progress is not shown in Quiet mode */
1047     if (quiet) {
1048         progress = false;
1049     }
1050 
1051     if (optind != argc - 1) {
1052         error_exit("Expecting one image file name");
1053     }
1054     filename = argv[optind++];
1055 
1056     if (qemu_opts_foreach(&qemu_object_opts,
1057                           user_creatable_add_opts_foreach,
1058                           qemu_img_object_print_help, &error_fatal)) {
1059         return 1;
1060     }
1061 
1062     flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1063     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1064     if (ret < 0) {
1065         error_report("Invalid cache option: %s", cache);
1066         return 1;
1067     }
1068 
1069     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1070                    false);
1071     if (!blk) {
1072         return 1;
1073     }
1074     bs = blk_bs(blk);
1075 
1076     qemu_progress_init(progress, 1.f);
1077     qemu_progress_print(0.f, 100);
1078 
1079     if (base) {
1080         base_bs = bdrv_find_backing_image(bs, base);
1081         if (!base_bs) {
1082             error_setg(&local_err,
1083                        "Did not find '%s' in the backing chain of '%s'",
1084                        base, filename);
1085             goto done;
1086         }
1087     } else {
1088         /* This is different from QMP, which by default uses the deepest file in
1089          * the backing chain (i.e., the very base); however, the traditional
1090          * behavior of qemu-img commit is using the immediate backing file. */
1091         base_bs = backing_bs(bs);
1092         if (!base_bs) {
1093             error_setg(&local_err, "Image does not have a backing file");
1094             goto done;
1095         }
1096     }
1097 
1098     cbi = (CommonBlockJobCBInfo){
1099         .errp = &local_err,
1100         .bs   = bs,
1101     };
1102 
1103     aio_context = bdrv_get_aio_context(bs);
1104     aio_context_acquire(aio_context);
1105     commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1106                         BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1107                         &cbi, false, &local_err);
1108     aio_context_release(aio_context);
1109     if (local_err) {
1110         goto done;
1111     }
1112 
1113     /* When the block job completes, the BlockBackend reference will point to
1114      * the old backing file. In order to avoid that the top image is already
1115      * deleted, so we can still empty it afterwards, increment the reference
1116      * counter here preemptively. */
1117     if (!drop) {
1118         bdrv_ref(bs);
1119     }
1120 
1121     job = block_job_get("commit");
1122     assert(job);
1123     run_block_job(job, &local_err);
1124     if (local_err) {
1125         goto unref_backing;
1126     }
1127 
1128     if (!drop) {
1129         BlockBackend *old_backing_blk;
1130 
1131         old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1132                                           &local_err);
1133         if (!old_backing_blk) {
1134             goto unref_backing;
1135         }
1136         ret = blk_make_empty(old_backing_blk, &local_err);
1137         blk_unref(old_backing_blk);
1138         if (ret == -ENOTSUP) {
1139             error_free(local_err);
1140             local_err = NULL;
1141         } else if (ret < 0) {
1142             goto unref_backing;
1143         }
1144     }
1145 
1146 unref_backing:
1147     if (!drop) {
1148         bdrv_unref(bs);
1149     }
1150 
1151 done:
1152     qemu_progress_end();
1153 
1154     blk_unref(blk);
1155 
1156     if (local_err) {
1157         error_report_err(local_err);
1158         return 1;
1159     }
1160 
1161     qprintf(quiet, "Image committed.\n");
1162     return 0;
1163 }
1164 
1165 /*
1166  * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1167  * of the first sector boundary within buf where the sector contains a
1168  * non-zero byte.  This function is robust to a buffer that is not
1169  * sector-aligned.
1170  */
1171 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1172 {
1173     int64_t i;
1174     int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1175 
1176     for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1177         if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1178             return i;
1179         }
1180     }
1181     if (i < n && !buffer_is_zero(buf + i, n - end)) {
1182         return i;
1183     }
1184     return -1;
1185 }
1186 
1187 /*
1188  * Returns true iff the first sector pointed to by 'buf' contains at least
1189  * a non-NUL byte.
1190  *
1191  * 'pnum' is set to the number of sectors (including and immediately following
1192  * the first one) that are known to be in the same allocated/unallocated state.
1193  * The function will try to align the end offset to alignment boundaries so
1194  * that the request will at least end aligned and consequtive requests will
1195  * also start at an aligned offset.
1196  */
1197 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1198                                 int64_t sector_num, int alignment)
1199 {
1200     bool is_zero;
1201     int i, tail;
1202 
1203     if (n <= 0) {
1204         *pnum = 0;
1205         return 0;
1206     }
1207     is_zero = buffer_is_zero(buf, 512);
1208     for(i = 1; i < n; i++) {
1209         buf += 512;
1210         if (is_zero != buffer_is_zero(buf, 512)) {
1211             break;
1212         }
1213     }
1214 
1215     tail = (sector_num + i) & (alignment - 1);
1216     if (tail) {
1217         if (is_zero && i <= tail) {
1218             /* treat unallocated areas which only consist
1219              * of a small tail as allocated. */
1220             is_zero = false;
1221         }
1222         if (!is_zero) {
1223             /* align up end offset of allocated areas. */
1224             i += alignment - tail;
1225             i = MIN(i, n);
1226         } else {
1227             /* align down end offset of zero areas. */
1228             i -= tail;
1229         }
1230     }
1231     *pnum = i;
1232     return !is_zero;
1233 }
1234 
1235 /*
1236  * Like is_allocated_sectors, but if the buffer starts with a used sector,
1237  * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1238  * breaking up write requests for only small sparse areas.
1239  */
1240 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1241     int min, int64_t sector_num, int alignment)
1242 {
1243     int ret;
1244     int num_checked, num_used;
1245 
1246     if (n < min) {
1247         min = n;
1248     }
1249 
1250     ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1251     if (!ret) {
1252         return ret;
1253     }
1254 
1255     num_used = *pnum;
1256     buf += BDRV_SECTOR_SIZE * *pnum;
1257     n -= *pnum;
1258     sector_num += *pnum;
1259     num_checked = num_used;
1260 
1261     while (n > 0) {
1262         ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1263 
1264         buf += BDRV_SECTOR_SIZE * *pnum;
1265         n -= *pnum;
1266         sector_num += *pnum;
1267         num_checked += *pnum;
1268         if (ret) {
1269             num_used = num_checked;
1270         } else if (*pnum >= min) {
1271             break;
1272         }
1273     }
1274 
1275     *pnum = num_used;
1276     return 1;
1277 }
1278 
1279 /*
1280  * Compares two buffers sector by sector. Returns 0 if the first
1281  * sector of each buffer matches, non-zero otherwise.
1282  *
1283  * pnum is set to the sector-aligned size of the buffer prefix that
1284  * has the same matching status as the first sector.
1285  */
1286 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1287                            int64_t bytes, int64_t *pnum)
1288 {
1289     bool res;
1290     int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1291 
1292     assert(bytes > 0);
1293 
1294     res = !!memcmp(buf1, buf2, i);
1295     while (i < bytes) {
1296         int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1297 
1298         if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1299             break;
1300         }
1301         i += len;
1302     }
1303 
1304     *pnum = i;
1305     return res;
1306 }
1307 
1308 #define IO_BUF_SIZE (2 * MiB)
1309 
1310 /*
1311  * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1312  *
1313  * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1314  * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1315  * failure), and 4 on error (the exit status for read errors), after emitting
1316  * an error message.
1317  *
1318  * @param blk:  BlockBackend for the image
1319  * @param offset: Starting offset to check
1320  * @param bytes: Number of bytes to check
1321  * @param filename: Name of disk file we are checking (logging purpose)
1322  * @param buffer: Allocated buffer for storing read data
1323  * @param quiet: Flag for quiet mode
1324  */
1325 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1326                                int64_t bytes, const char *filename,
1327                                uint8_t *buffer, bool quiet)
1328 {
1329     int ret = 0;
1330     int64_t idx;
1331 
1332     ret = blk_pread(blk, offset, buffer, bytes);
1333     if (ret < 0) {
1334         error_report("Error while reading offset %" PRId64 " of %s: %s",
1335                      offset, filename, strerror(-ret));
1336         return 4;
1337     }
1338     idx = find_nonzero(buffer, bytes);
1339     if (idx >= 0) {
1340         qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1341                 offset + idx);
1342         return 1;
1343     }
1344 
1345     return 0;
1346 }
1347 
1348 /*
1349  * Compares two images. Exit codes:
1350  *
1351  * 0 - Images are identical
1352  * 1 - Images differ
1353  * >1 - Error occurred
1354  */
1355 static int img_compare(int argc, char **argv)
1356 {
1357     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1358     BlockBackend *blk1, *blk2;
1359     BlockDriverState *bs1, *bs2;
1360     int64_t total_size1, total_size2;
1361     uint8_t *buf1 = NULL, *buf2 = NULL;
1362     int64_t pnum1, pnum2;
1363     int allocated1, allocated2;
1364     int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1365     bool progress = false, quiet = false, strict = false;
1366     int flags;
1367     bool writethrough;
1368     int64_t total_size;
1369     int64_t offset = 0;
1370     int64_t chunk;
1371     int c;
1372     uint64_t progress_base;
1373     bool image_opts = false;
1374     bool force_share = false;
1375 
1376     cache = BDRV_DEFAULT_CACHE;
1377     for (;;) {
1378         static const struct option long_options[] = {
1379             {"help", no_argument, 0, 'h'},
1380             {"object", required_argument, 0, OPTION_OBJECT},
1381             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1382             {"force-share", no_argument, 0, 'U'},
1383             {0, 0, 0, 0}
1384         };
1385         c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1386                         long_options, NULL);
1387         if (c == -1) {
1388             break;
1389         }
1390         switch (c) {
1391         case ':':
1392             missing_argument(argv[optind - 1]);
1393             break;
1394         case '?':
1395             unrecognized_option(argv[optind - 1]);
1396             break;
1397         case 'h':
1398             help();
1399             break;
1400         case 'f':
1401             fmt1 = optarg;
1402             break;
1403         case 'F':
1404             fmt2 = optarg;
1405             break;
1406         case 'T':
1407             cache = optarg;
1408             break;
1409         case 'p':
1410             progress = true;
1411             break;
1412         case 'q':
1413             quiet = true;
1414             break;
1415         case 's':
1416             strict = true;
1417             break;
1418         case 'U':
1419             force_share = true;
1420             break;
1421         case OPTION_OBJECT: {
1422             QemuOpts *opts;
1423             opts = qemu_opts_parse_noisily(&qemu_object_opts,
1424                                            optarg, true);
1425             if (!opts) {
1426                 ret = 2;
1427                 goto out4;
1428             }
1429         }   break;
1430         case OPTION_IMAGE_OPTS:
1431             image_opts = true;
1432             break;
1433         }
1434     }
1435 
1436     /* Progress is not shown in Quiet mode */
1437     if (quiet) {
1438         progress = false;
1439     }
1440 
1441 
1442     if (optind != argc - 2) {
1443         error_exit("Expecting two image file names");
1444     }
1445     filename1 = argv[optind++];
1446     filename2 = argv[optind++];
1447 
1448     if (qemu_opts_foreach(&qemu_object_opts,
1449                           user_creatable_add_opts_foreach,
1450                           qemu_img_object_print_help, &error_fatal)) {
1451         ret = 2;
1452         goto out4;
1453     }
1454 
1455     /* Initialize before goto out */
1456     qemu_progress_init(progress, 2.0);
1457 
1458     flags = 0;
1459     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1460     if (ret < 0) {
1461         error_report("Invalid source cache option: %s", cache);
1462         ret = 2;
1463         goto out3;
1464     }
1465 
1466     blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1467                     force_share);
1468     if (!blk1) {
1469         ret = 2;
1470         goto out3;
1471     }
1472 
1473     blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1474                     force_share);
1475     if (!blk2) {
1476         ret = 2;
1477         goto out2;
1478     }
1479     bs1 = blk_bs(blk1);
1480     bs2 = blk_bs(blk2);
1481 
1482     buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1483     buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1484     total_size1 = blk_getlength(blk1);
1485     if (total_size1 < 0) {
1486         error_report("Can't get size of %s: %s",
1487                      filename1, strerror(-total_size1));
1488         ret = 4;
1489         goto out;
1490     }
1491     total_size2 = blk_getlength(blk2);
1492     if (total_size2 < 0) {
1493         error_report("Can't get size of %s: %s",
1494                      filename2, strerror(-total_size2));
1495         ret = 4;
1496         goto out;
1497     }
1498     total_size = MIN(total_size1, total_size2);
1499     progress_base = MAX(total_size1, total_size2);
1500 
1501     qemu_progress_print(0, 100);
1502 
1503     if (strict && total_size1 != total_size2) {
1504         ret = 1;
1505         qprintf(quiet, "Strict mode: Image size mismatch!\n");
1506         goto out;
1507     }
1508 
1509     while (offset < total_size) {
1510         int status1, status2;
1511 
1512         status1 = bdrv_block_status_above(bs1, NULL, offset,
1513                                           total_size1 - offset, &pnum1, NULL,
1514                                           NULL);
1515         if (status1 < 0) {
1516             ret = 3;
1517             error_report("Sector allocation test failed for %s", filename1);
1518             goto out;
1519         }
1520         allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1521 
1522         status2 = bdrv_block_status_above(bs2, NULL, offset,
1523                                           total_size2 - offset, &pnum2, NULL,
1524                                           NULL);
1525         if (status2 < 0) {
1526             ret = 3;
1527             error_report("Sector allocation test failed for %s", filename2);
1528             goto out;
1529         }
1530         allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1531 
1532         assert(pnum1 && pnum2);
1533         chunk = MIN(pnum1, pnum2);
1534 
1535         if (strict) {
1536             if (status1 != status2) {
1537                 ret = 1;
1538                 qprintf(quiet, "Strict mode: Offset %" PRId64
1539                         " block status mismatch!\n", offset);
1540                 goto out;
1541             }
1542         }
1543         if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1544             /* nothing to do */
1545         } else if (allocated1 == allocated2) {
1546             if (allocated1) {
1547                 int64_t pnum;
1548 
1549                 chunk = MIN(chunk, IO_BUF_SIZE);
1550                 ret = blk_pread(blk1, offset, buf1, chunk);
1551                 if (ret < 0) {
1552                     error_report("Error while reading offset %" PRId64
1553                                  " of %s: %s",
1554                                  offset, filename1, strerror(-ret));
1555                     ret = 4;
1556                     goto out;
1557                 }
1558                 ret = blk_pread(blk2, offset, buf2, chunk);
1559                 if (ret < 0) {
1560                     error_report("Error while reading offset %" PRId64
1561                                  " of %s: %s",
1562                                  offset, filename2, strerror(-ret));
1563                     ret = 4;
1564                     goto out;
1565                 }
1566                 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1567                 if (ret || pnum != chunk) {
1568                     qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1569                             offset + (ret ? 0 : pnum));
1570                     ret = 1;
1571                     goto out;
1572                 }
1573             }
1574         } else {
1575             chunk = MIN(chunk, IO_BUF_SIZE);
1576             if (allocated1) {
1577                 ret = check_empty_sectors(blk1, offset, chunk,
1578                                           filename1, buf1, quiet);
1579             } else {
1580                 ret = check_empty_sectors(blk2, offset, chunk,
1581                                           filename2, buf1, quiet);
1582             }
1583             if (ret) {
1584                 goto out;
1585             }
1586         }
1587         offset += chunk;
1588         qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1589     }
1590 
1591     if (total_size1 != total_size2) {
1592         BlockBackend *blk_over;
1593         const char *filename_over;
1594 
1595         qprintf(quiet, "Warning: Image size mismatch!\n");
1596         if (total_size1 > total_size2) {
1597             blk_over = blk1;
1598             filename_over = filename1;
1599         } else {
1600             blk_over = blk2;
1601             filename_over = filename2;
1602         }
1603 
1604         while (offset < progress_base) {
1605             ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1606                                           progress_base - offset, &chunk,
1607                                           NULL, NULL);
1608             if (ret < 0) {
1609                 ret = 3;
1610                 error_report("Sector allocation test failed for %s",
1611                              filename_over);
1612                 goto out;
1613 
1614             }
1615             if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1616                 chunk = MIN(chunk, IO_BUF_SIZE);
1617                 ret = check_empty_sectors(blk_over, offset, chunk,
1618                                           filename_over, buf1, quiet);
1619                 if (ret) {
1620                     goto out;
1621                 }
1622             }
1623             offset += chunk;
1624             qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1625         }
1626     }
1627 
1628     qprintf(quiet, "Images are identical.\n");
1629     ret = 0;
1630 
1631 out:
1632     qemu_vfree(buf1);
1633     qemu_vfree(buf2);
1634     blk_unref(blk2);
1635 out2:
1636     blk_unref(blk1);
1637 out3:
1638     qemu_progress_end();
1639 out4:
1640     return ret;
1641 }
1642 
1643 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1644 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1645                                   const char *src_node, const char *src_name,
1646                                   Error **errp)
1647 {
1648     BlockDirtyBitmapMergeSource *merge_src;
1649     BlockDirtyBitmapMergeSourceList *list;
1650 
1651     merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1652     merge_src->type = QTYPE_QDICT;
1653     merge_src->u.external.node = g_strdup(src_node);
1654     merge_src->u.external.name = g_strdup(src_name);
1655     list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1656     list->value = merge_src;
1657     qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1658     qapi_free_BlockDirtyBitmapMergeSourceList(list);
1659 }
1660 
1661 enum ImgConvertBlockStatus {
1662     BLK_DATA,
1663     BLK_ZERO,
1664     BLK_BACKING_FILE,
1665 };
1666 
1667 #define MAX_COROUTINES 16
1668 
1669 typedef struct ImgConvertState {
1670     BlockBackend **src;
1671     int64_t *src_sectors;
1672     int src_num;
1673     int64_t total_sectors;
1674     int64_t allocated_sectors;
1675     int64_t allocated_done;
1676     int64_t sector_num;
1677     int64_t wr_offs;
1678     enum ImgConvertBlockStatus status;
1679     int64_t sector_next_status;
1680     BlockBackend *target;
1681     bool has_zero_init;
1682     bool compressed;
1683     bool unallocated_blocks_are_zero;
1684     bool target_is_new;
1685     bool target_has_backing;
1686     int64_t target_backing_sectors; /* negative if unknown */
1687     bool wr_in_order;
1688     bool copy_range;
1689     bool salvage;
1690     bool quiet;
1691     int min_sparse;
1692     int alignment;
1693     size_t cluster_sectors;
1694     size_t buf_sectors;
1695     long num_coroutines;
1696     int running_coroutines;
1697     Coroutine *co[MAX_COROUTINES];
1698     int64_t wait_sector_num[MAX_COROUTINES];
1699     CoMutex lock;
1700     int ret;
1701 } ImgConvertState;
1702 
1703 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1704                                 int *src_cur, int64_t *src_cur_offset)
1705 {
1706     *src_cur = 0;
1707     *src_cur_offset = 0;
1708     while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1709         *src_cur_offset += s->src_sectors[*src_cur];
1710         (*src_cur)++;
1711         assert(*src_cur < s->src_num);
1712     }
1713 }
1714 
1715 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1716 {
1717     int64_t src_cur_offset;
1718     int ret, n, src_cur;
1719     bool post_backing_zero = false;
1720 
1721     convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1722 
1723     assert(s->total_sectors > sector_num);
1724     n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1725 
1726     if (s->target_backing_sectors >= 0) {
1727         if (sector_num >= s->target_backing_sectors) {
1728             post_backing_zero = s->unallocated_blocks_are_zero;
1729         } else if (sector_num + n > s->target_backing_sectors) {
1730             /* Split requests around target_backing_sectors (because
1731              * starting from there, zeros are handled differently) */
1732             n = s->target_backing_sectors - sector_num;
1733         }
1734     }
1735 
1736     if (s->sector_next_status <= sector_num) {
1737         uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1738         int64_t count;
1739 
1740         do {
1741             count = n * BDRV_SECTOR_SIZE;
1742 
1743             if (s->target_has_backing) {
1744                 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1745                                         count, &count, NULL, NULL);
1746             } else {
1747                 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1748                                               offset, count, &count, NULL,
1749                                               NULL);
1750             }
1751 
1752             if (ret < 0) {
1753                 if (s->salvage) {
1754                     if (n == 1) {
1755                         if (!s->quiet) {
1756                             warn_report("error while reading block status at "
1757                                         "offset %" PRIu64 ": %s", offset,
1758                                         strerror(-ret));
1759                         }
1760                         /* Just try to read the data, then */
1761                         ret = BDRV_BLOCK_DATA;
1762                         count = BDRV_SECTOR_SIZE;
1763                     } else {
1764                         /* Retry on a shorter range */
1765                         n = DIV_ROUND_UP(n, 4);
1766                     }
1767                 } else {
1768                     error_report("error while reading block status at offset "
1769                                  "%" PRIu64 ": %s", offset, strerror(-ret));
1770                     return ret;
1771                 }
1772             }
1773         } while (ret < 0);
1774 
1775         n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1776 
1777         if (ret & BDRV_BLOCK_ZERO) {
1778             s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1779         } else if (ret & BDRV_BLOCK_DATA) {
1780             s->status = BLK_DATA;
1781         } else {
1782             s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1783         }
1784 
1785         s->sector_next_status = sector_num + n;
1786     }
1787 
1788     n = MIN(n, s->sector_next_status - sector_num);
1789     if (s->status == BLK_DATA) {
1790         n = MIN(n, s->buf_sectors);
1791     }
1792 
1793     /* We need to write complete clusters for compressed images, so if an
1794      * unallocated area is shorter than that, we must consider the whole
1795      * cluster allocated. */
1796     if (s->compressed) {
1797         if (n < s->cluster_sectors) {
1798             n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1799             s->status = BLK_DATA;
1800         } else {
1801             n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1802         }
1803     }
1804 
1805     return n;
1806 }
1807 
1808 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1809                                         int nb_sectors, uint8_t *buf)
1810 {
1811     uint64_t single_read_until = 0;
1812     int n, ret;
1813 
1814     assert(nb_sectors <= s->buf_sectors);
1815     while (nb_sectors > 0) {
1816         BlockBackend *blk;
1817         int src_cur;
1818         int64_t bs_sectors, src_cur_offset;
1819         uint64_t offset;
1820 
1821         /* In the case of compression with multiple source files, we can get a
1822          * nb_sectors that spreads into the next part. So we must be able to
1823          * read across multiple BDSes for one convert_read() call. */
1824         convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1825         blk = s->src[src_cur];
1826         bs_sectors = s->src_sectors[src_cur];
1827 
1828         offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1829 
1830         n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1831         if (single_read_until > offset) {
1832             n = 1;
1833         }
1834 
1835         ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1836         if (ret < 0) {
1837             if (s->salvage) {
1838                 if (n > 1) {
1839                     single_read_until = offset + (n << BDRV_SECTOR_BITS);
1840                     continue;
1841                 } else {
1842                     if (!s->quiet) {
1843                         warn_report("error while reading offset %" PRIu64
1844                                     ": %s", offset, strerror(-ret));
1845                     }
1846                     memset(buf, 0, BDRV_SECTOR_SIZE);
1847                 }
1848             } else {
1849                 return ret;
1850             }
1851         }
1852 
1853         sector_num += n;
1854         nb_sectors -= n;
1855         buf += n * BDRV_SECTOR_SIZE;
1856     }
1857 
1858     return 0;
1859 }
1860 
1861 
1862 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1863                                          int nb_sectors, uint8_t *buf,
1864                                          enum ImgConvertBlockStatus status)
1865 {
1866     int ret;
1867 
1868     while (nb_sectors > 0) {
1869         int n = nb_sectors;
1870         BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1871 
1872         switch (status) {
1873         case BLK_BACKING_FILE:
1874             /* If we have a backing file, leave clusters unallocated that are
1875              * unallocated in the source image, so that the backing file is
1876              * visible at the respective offset. */
1877             assert(s->target_has_backing);
1878             break;
1879 
1880         case BLK_DATA:
1881             /* If we're told to keep the target fully allocated (-S 0) or there
1882              * is real non-zero data, we must write it. Otherwise we can treat
1883              * it as zero sectors.
1884              * Compressed clusters need to be written as a whole, so in that
1885              * case we can only save the write if the buffer is completely
1886              * zeroed. */
1887             if (!s->min_sparse ||
1888                 (!s->compressed &&
1889                  is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1890                                           sector_num, s->alignment)) ||
1891                 (s->compressed &&
1892                  !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1893             {
1894                 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1895                                     n << BDRV_SECTOR_BITS, buf, flags);
1896                 if (ret < 0) {
1897                     return ret;
1898                 }
1899                 break;
1900             }
1901             /* fall-through */
1902 
1903         case BLK_ZERO:
1904             if (s->has_zero_init) {
1905                 assert(!s->target_has_backing);
1906                 break;
1907             }
1908             ret = blk_co_pwrite_zeroes(s->target,
1909                                        sector_num << BDRV_SECTOR_BITS,
1910                                        n << BDRV_SECTOR_BITS,
1911                                        BDRV_REQ_MAY_UNMAP);
1912             if (ret < 0) {
1913                 return ret;
1914             }
1915             break;
1916         }
1917 
1918         sector_num += n;
1919         nb_sectors -= n;
1920         buf += n * BDRV_SECTOR_SIZE;
1921     }
1922 
1923     return 0;
1924 }
1925 
1926 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1927                                               int nb_sectors)
1928 {
1929     int n, ret;
1930 
1931     while (nb_sectors > 0) {
1932         BlockBackend *blk;
1933         int src_cur;
1934         int64_t bs_sectors, src_cur_offset;
1935         int64_t offset;
1936 
1937         convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1938         offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1939         blk = s->src[src_cur];
1940         bs_sectors = s->src_sectors[src_cur];
1941 
1942         n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1943 
1944         ret = blk_co_copy_range(blk, offset, s->target,
1945                                 sector_num << BDRV_SECTOR_BITS,
1946                                 n << BDRV_SECTOR_BITS, 0, 0);
1947         if (ret < 0) {
1948             return ret;
1949         }
1950 
1951         sector_num += n;
1952         nb_sectors -= n;
1953     }
1954     return 0;
1955 }
1956 
1957 static void coroutine_fn convert_co_do_copy(void *opaque)
1958 {
1959     ImgConvertState *s = opaque;
1960     uint8_t *buf = NULL;
1961     int ret, i;
1962     int index = -1;
1963 
1964     for (i = 0; i < s->num_coroutines; i++) {
1965         if (s->co[i] == qemu_coroutine_self()) {
1966             index = i;
1967             break;
1968         }
1969     }
1970     assert(index >= 0);
1971 
1972     s->running_coroutines++;
1973     buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1974 
1975     while (1) {
1976         int n;
1977         int64_t sector_num;
1978         enum ImgConvertBlockStatus status;
1979         bool copy_range;
1980 
1981         qemu_co_mutex_lock(&s->lock);
1982         if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1983             qemu_co_mutex_unlock(&s->lock);
1984             break;
1985         }
1986         n = convert_iteration_sectors(s, s->sector_num);
1987         if (n < 0) {
1988             qemu_co_mutex_unlock(&s->lock);
1989             s->ret = n;
1990             break;
1991         }
1992         /* save current sector and allocation status to local variables */
1993         sector_num = s->sector_num;
1994         status = s->status;
1995         if (!s->min_sparse && s->status == BLK_ZERO) {
1996             n = MIN(n, s->buf_sectors);
1997         }
1998         /* increment global sector counter so that other coroutines can
1999          * already continue reading beyond this request */
2000         s->sector_num += n;
2001         qemu_co_mutex_unlock(&s->lock);
2002 
2003         if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2004             s->allocated_done += n;
2005             qemu_progress_print(100.0 * s->allocated_done /
2006                                         s->allocated_sectors, 0);
2007         }
2008 
2009 retry:
2010         copy_range = s->copy_range && s->status == BLK_DATA;
2011         if (status == BLK_DATA && !copy_range) {
2012             ret = convert_co_read(s, sector_num, n, buf);
2013             if (ret < 0) {
2014                 error_report("error while reading at byte %lld: %s",
2015                              sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2016                 s->ret = ret;
2017             }
2018         } else if (!s->min_sparse && status == BLK_ZERO) {
2019             status = BLK_DATA;
2020             memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2021         }
2022 
2023         if (s->wr_in_order) {
2024             /* keep writes in order */
2025             while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2026                 s->wait_sector_num[index] = sector_num;
2027                 qemu_coroutine_yield();
2028             }
2029             s->wait_sector_num[index] = -1;
2030         }
2031 
2032         if (s->ret == -EINPROGRESS) {
2033             if (copy_range) {
2034                 ret = convert_co_copy_range(s, sector_num, n);
2035                 if (ret) {
2036                     s->copy_range = false;
2037                     goto retry;
2038                 }
2039             } else {
2040                 ret = convert_co_write(s, sector_num, n, buf, status);
2041             }
2042             if (ret < 0) {
2043                 error_report("error while writing at byte %lld: %s",
2044                              sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2045                 s->ret = ret;
2046             }
2047         }
2048 
2049         if (s->wr_in_order) {
2050             /* reenter the coroutine that might have waited
2051              * for this write to complete */
2052             s->wr_offs = sector_num + n;
2053             for (i = 0; i < s->num_coroutines; i++) {
2054                 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2055                     /*
2056                      * A -> B -> A cannot occur because A has
2057                      * s->wait_sector_num[i] == -1 during A -> B.  Therefore
2058                      * B will never enter A during this time window.
2059                      */
2060                     qemu_coroutine_enter(s->co[i]);
2061                     break;
2062                 }
2063             }
2064         }
2065     }
2066 
2067     qemu_vfree(buf);
2068     s->co[index] = NULL;
2069     s->running_coroutines--;
2070     if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2071         /* the convert job finished successfully */
2072         s->ret = 0;
2073     }
2074 }
2075 
2076 static int convert_do_copy(ImgConvertState *s)
2077 {
2078     int ret, i, n;
2079     int64_t sector_num = 0;
2080 
2081     /* Check whether we have zero initialisation or can get it efficiently */
2082     if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2083         !s->target_has_backing) {
2084         s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2085     }
2086 
2087     /* Allocate buffer for copied data. For compressed images, only one cluster
2088      * can be copied at a time. */
2089     if (s->compressed) {
2090         if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2091             error_report("invalid cluster size");
2092             return -EINVAL;
2093         }
2094         s->buf_sectors = s->cluster_sectors;
2095     }
2096 
2097     while (sector_num < s->total_sectors) {
2098         n = convert_iteration_sectors(s, sector_num);
2099         if (n < 0) {
2100             return n;
2101         }
2102         if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2103         {
2104             s->allocated_sectors += n;
2105         }
2106         sector_num += n;
2107     }
2108 
2109     /* Do the copy */
2110     s->sector_next_status = 0;
2111     s->ret = -EINPROGRESS;
2112 
2113     qemu_co_mutex_init(&s->lock);
2114     for (i = 0; i < s->num_coroutines; i++) {
2115         s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2116         s->wait_sector_num[i] = -1;
2117         qemu_coroutine_enter(s->co[i]);
2118     }
2119 
2120     while (s->running_coroutines) {
2121         main_loop_wait(false);
2122     }
2123 
2124     if (s->compressed && !s->ret) {
2125         /* signal EOF to align */
2126         ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2127         if (ret < 0) {
2128             return ret;
2129         }
2130     }
2131 
2132     return s->ret;
2133 }
2134 
2135 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2136 {
2137     BdrvDirtyBitmap *bm;
2138     Error *err = NULL;
2139 
2140     FOR_EACH_DIRTY_BITMAP(src, bm) {
2141         const char *name;
2142 
2143         if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2144             continue;
2145         }
2146         name = bdrv_dirty_bitmap_name(bm);
2147         qmp_block_dirty_bitmap_add(dst->node_name, name,
2148                                    true, bdrv_dirty_bitmap_granularity(bm),
2149                                    true, true,
2150                                    true, !bdrv_dirty_bitmap_enabled(bm),
2151                                    &err);
2152         if (err) {
2153             error_reportf_err(err, "Failed to create bitmap %s: ", name);
2154             return -1;
2155         }
2156 
2157         do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2158                               &err);
2159         if (err) {
2160             error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2161             return -1;
2162         }
2163     }
2164 
2165     return 0;
2166 }
2167 
2168 #define MAX_BUF_SECTORS 32768
2169 
2170 static int img_convert(int argc, char **argv)
2171 {
2172     int c, bs_i, flags, src_flags = 0;
2173     const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2174                *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2175                *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2176     BlockDriver *drv = NULL, *proto_drv = NULL;
2177     BlockDriverInfo bdi;
2178     BlockDriverState *out_bs;
2179     QemuOpts *opts = NULL, *sn_opts = NULL;
2180     QemuOptsList *create_opts = NULL;
2181     QDict *open_opts = NULL;
2182     char *options = NULL;
2183     Error *local_err = NULL;
2184     bool writethrough, src_writethrough, image_opts = false,
2185          skip_create = false, progress = false, tgt_image_opts = false;
2186     int64_t ret = -EINVAL;
2187     bool force_share = false;
2188     bool explict_min_sparse = false;
2189     bool bitmaps = false;
2190 
2191     ImgConvertState s = (ImgConvertState) {
2192         /* Need at least 4k of zeros for sparse detection */
2193         .min_sparse         = 8,
2194         .copy_range         = false,
2195         .buf_sectors        = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2196         .wr_in_order        = true,
2197         .num_coroutines     = 8,
2198     };
2199 
2200     for(;;) {
2201         static const struct option long_options[] = {
2202             {"help", no_argument, 0, 'h'},
2203             {"object", required_argument, 0, OPTION_OBJECT},
2204             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2205             {"force-share", no_argument, 0, 'U'},
2206             {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2207             {"salvage", no_argument, 0, OPTION_SALVAGE},
2208             {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2209             {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2210             {0, 0, 0, 0}
2211         };
2212         c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2213                         long_options, NULL);
2214         if (c == -1) {
2215             break;
2216         }
2217         switch(c) {
2218         case ':':
2219             missing_argument(argv[optind - 1]);
2220             break;
2221         case '?':
2222             unrecognized_option(argv[optind - 1]);
2223             break;
2224         case 'h':
2225             help();
2226             break;
2227         case 'f':
2228             fmt = optarg;
2229             break;
2230         case 'O':
2231             out_fmt = optarg;
2232             break;
2233         case 'B':
2234             out_baseimg = optarg;
2235             break;
2236         case 'C':
2237             s.copy_range = true;
2238             break;
2239         case 'c':
2240             s.compressed = true;
2241             break;
2242         case 'o':
2243             if (accumulate_options(&options, optarg) < 0) {
2244                 goto fail_getopt;
2245             }
2246             break;
2247         case 'l':
2248             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2249                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2250                                                   optarg, false);
2251                 if (!sn_opts) {
2252                     error_report("Failed in parsing snapshot param '%s'",
2253                                  optarg);
2254                     goto fail_getopt;
2255                 }
2256             } else {
2257                 snapshot_name = optarg;
2258             }
2259             break;
2260         case 'S':
2261         {
2262             int64_t sval;
2263 
2264             sval = cvtnum("buffer size for sparse output", optarg);
2265             if (sval < 0) {
2266                 goto fail_getopt;
2267             } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2268                 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2269                 error_report("Invalid buffer size for sparse output specified. "
2270                     "Valid sizes are multiples of %llu up to %llu. Select "
2271                     "0 to disable sparse detection (fully allocates output).",
2272                     BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2273                 goto fail_getopt;
2274             }
2275 
2276             s.min_sparse = sval / BDRV_SECTOR_SIZE;
2277             explict_min_sparse = true;
2278             break;
2279         }
2280         case 'p':
2281             progress = true;
2282             break;
2283         case 't':
2284             cache = optarg;
2285             break;
2286         case 'T':
2287             src_cache = optarg;
2288             break;
2289         case 'q':
2290             s.quiet = true;
2291             break;
2292         case 'n':
2293             skip_create = true;
2294             break;
2295         case 'm':
2296             if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2297                 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2298                 error_report("Invalid number of coroutines. Allowed number of"
2299                              " coroutines is between 1 and %d", MAX_COROUTINES);
2300                 goto fail_getopt;
2301             }
2302             break;
2303         case 'W':
2304             s.wr_in_order = false;
2305             break;
2306         case 'U':
2307             force_share = true;
2308             break;
2309         case OPTION_OBJECT: {
2310             QemuOpts *object_opts;
2311             object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2312                                                   optarg, true);
2313             if (!object_opts) {
2314                 goto fail_getopt;
2315             }
2316             break;
2317         }
2318         case OPTION_IMAGE_OPTS:
2319             image_opts = true;
2320             break;
2321         case OPTION_SALVAGE:
2322             s.salvage = true;
2323             break;
2324         case OPTION_TARGET_IMAGE_OPTS:
2325             tgt_image_opts = true;
2326             break;
2327         case OPTION_TARGET_IS_ZERO:
2328             /*
2329              * The user asserting that the target is blank has the
2330              * same effect as the target driver supporting zero
2331              * initialisation.
2332              */
2333             s.has_zero_init = true;
2334             break;
2335         case OPTION_BITMAPS:
2336             bitmaps = true;
2337             break;
2338         }
2339     }
2340 
2341     if (!out_fmt && !tgt_image_opts) {
2342         out_fmt = "raw";
2343     }
2344 
2345     if (qemu_opts_foreach(&qemu_object_opts,
2346                           user_creatable_add_opts_foreach,
2347                           qemu_img_object_print_help, &error_fatal)) {
2348         goto fail_getopt;
2349     }
2350 
2351     if (s.compressed && s.copy_range) {
2352         error_report("Cannot enable copy offloading when -c is used");
2353         goto fail_getopt;
2354     }
2355 
2356     if (explict_min_sparse && s.copy_range) {
2357         error_report("Cannot enable copy offloading when -S is used");
2358         goto fail_getopt;
2359     }
2360 
2361     if (s.copy_range && s.salvage) {
2362         error_report("Cannot use copy offloading in salvaging mode");
2363         goto fail_getopt;
2364     }
2365 
2366     if (tgt_image_opts && !skip_create) {
2367         error_report("--target-image-opts requires use of -n flag");
2368         goto fail_getopt;
2369     }
2370 
2371     if (skip_create && options) {
2372         warn_report("-o has no effect when skipping image creation");
2373         warn_report("This will become an error in future QEMU versions.");
2374     }
2375 
2376     if (s.has_zero_init && !skip_create) {
2377         error_report("--target-is-zero requires use of -n flag");
2378         goto fail_getopt;
2379     }
2380 
2381     s.src_num = argc - optind - 1;
2382     out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2383 
2384     if (options && has_help_option(options)) {
2385         if (out_fmt) {
2386             ret = print_block_option_help(out_filename, out_fmt);
2387             goto fail_getopt;
2388         } else {
2389             error_report("Option help requires a format be specified");
2390             goto fail_getopt;
2391         }
2392     }
2393 
2394     if (s.src_num < 1) {
2395         error_report("Must specify image file name");
2396         goto fail_getopt;
2397     }
2398 
2399     /* ret is still -EINVAL until here */
2400     ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2401     if (ret < 0) {
2402         error_report("Invalid source cache option: %s", src_cache);
2403         goto fail_getopt;
2404     }
2405 
2406     /* Initialize before goto out */
2407     if (s.quiet) {
2408         progress = false;
2409     }
2410     qemu_progress_init(progress, 1.0);
2411     qemu_progress_print(0, 100);
2412 
2413     s.src = g_new0(BlockBackend *, s.src_num);
2414     s.src_sectors = g_new(int64_t, s.src_num);
2415 
2416     for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2417         s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2418                                fmt, src_flags, src_writethrough, s.quiet,
2419                                force_share);
2420         if (!s.src[bs_i]) {
2421             ret = -1;
2422             goto out;
2423         }
2424         s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2425         if (s.src_sectors[bs_i] < 0) {
2426             error_report("Could not get size of %s: %s",
2427                          argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2428             ret = -1;
2429             goto out;
2430         }
2431         s.total_sectors += s.src_sectors[bs_i];
2432     }
2433 
2434     if (sn_opts) {
2435         bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2436                                qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2437                                qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2438                                &local_err);
2439     } else if (snapshot_name != NULL) {
2440         if (s.src_num > 1) {
2441             error_report("No support for concatenating multiple snapshot");
2442             ret = -1;
2443             goto out;
2444         }
2445 
2446         bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2447                                              &local_err);
2448     }
2449     if (local_err) {
2450         error_reportf_err(local_err, "Failed to load snapshot: ");
2451         ret = -1;
2452         goto out;
2453     }
2454 
2455     if (!skip_create) {
2456         /* Find driver and parse its options */
2457         drv = bdrv_find_format(out_fmt);
2458         if (!drv) {
2459             error_report("Unknown file format '%s'", out_fmt);
2460             ret = -1;
2461             goto out;
2462         }
2463 
2464         proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2465         if (!proto_drv) {
2466             error_report_err(local_err);
2467             ret = -1;
2468             goto out;
2469         }
2470 
2471         if (!drv->create_opts) {
2472             error_report("Format driver '%s' does not support image creation",
2473                          drv->format_name);
2474             ret = -1;
2475             goto out;
2476         }
2477 
2478         if (!proto_drv->create_opts) {
2479             error_report("Protocol driver '%s' does not support image creation",
2480                          proto_drv->format_name);
2481             ret = -1;
2482             goto out;
2483         }
2484 
2485         create_opts = qemu_opts_append(create_opts, drv->create_opts);
2486         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2487 
2488         opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2489         if (options) {
2490             qemu_opts_do_parse(opts, options, NULL, &local_err);
2491             if (local_err) {
2492                 error_report_err(local_err);
2493                 ret = -1;
2494                 goto out;
2495             }
2496         }
2497 
2498         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2499                             &error_abort);
2500         ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2501         if (ret < 0) {
2502             goto out;
2503         }
2504     }
2505 
2506     /* Get backing file name if -o backing_file was used */
2507     out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2508     if (out_baseimg_param) {
2509         out_baseimg = out_baseimg_param;
2510     }
2511     s.target_has_backing = (bool) out_baseimg;
2512 
2513     if (s.has_zero_init && s.target_has_backing) {
2514         error_report("Cannot use --target-is-zero when the destination "
2515                      "image has a backing file");
2516         goto out;
2517     }
2518 
2519     if (s.src_num > 1 && out_baseimg) {
2520         error_report("Having a backing file for the target makes no sense when "
2521                      "concatenating multiple input images");
2522         ret = -1;
2523         goto out;
2524     }
2525 
2526     /* Check if compression is supported */
2527     if (s.compressed) {
2528         bool encryption =
2529             qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2530         const char *encryptfmt =
2531             qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2532         const char *preallocation =
2533             qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2534 
2535         if (drv && !block_driver_can_compress(drv)) {
2536             error_report("Compression not supported for this file format");
2537             ret = -1;
2538             goto out;
2539         }
2540 
2541         if (encryption || encryptfmt) {
2542             error_report("Compression and encryption not supported at "
2543                          "the same time");
2544             ret = -1;
2545             goto out;
2546         }
2547 
2548         if (preallocation
2549             && strcmp(preallocation, "off"))
2550         {
2551             error_report("Compression and preallocation not supported at "
2552                          "the same time");
2553             ret = -1;
2554             goto out;
2555         }
2556     }
2557 
2558     /* Determine if bitmaps need copying */
2559     if (bitmaps) {
2560         if (s.src_num > 1) {
2561             error_report("Copying bitmaps only possible with single source");
2562             ret = -1;
2563             goto out;
2564         }
2565         if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2566             error_report("Source lacks bitmap support");
2567             ret = -1;
2568             goto out;
2569         }
2570     }
2571 
2572     /*
2573      * The later open call will need any decryption secrets, and
2574      * bdrv_create() will purge "opts", so extract them now before
2575      * they are lost.
2576      */
2577     if (!skip_create) {
2578         open_opts = qdict_new();
2579         qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2580 
2581         /* Create the new image */
2582         ret = bdrv_create(drv, out_filename, opts, &local_err);
2583         if (ret < 0) {
2584             error_reportf_err(local_err, "%s: error while converting %s: ",
2585                               out_filename, out_fmt);
2586             goto out;
2587         }
2588     }
2589 
2590     s.target_is_new = !skip_create;
2591 
2592     flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2593     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2594     if (ret < 0) {
2595         error_report("Invalid cache option: %s", cache);
2596         goto out;
2597     }
2598 
2599     if (skip_create) {
2600         s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2601                             flags, writethrough, s.quiet, false);
2602     } else {
2603         /* TODO ultimately we should allow --target-image-opts
2604          * to be used even when -n is not given.
2605          * That has to wait for bdrv_create to be improved
2606          * to allow filenames in option syntax
2607          */
2608         s.target = img_open_file(out_filename, open_opts, out_fmt,
2609                                  flags, writethrough, s.quiet, false);
2610         open_opts = NULL; /* blk_new_open will have freed it */
2611     }
2612     if (!s.target) {
2613         ret = -1;
2614         goto out;
2615     }
2616     out_bs = blk_bs(s.target);
2617 
2618     if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2619         error_report("Format driver '%s' does not support bitmaps",
2620                      out_bs->drv->format_name);
2621         ret = -1;
2622         goto out;
2623     }
2624 
2625     if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2626         error_report("Compression not supported for this file format");
2627         ret = -1;
2628         goto out;
2629     }
2630 
2631     /* increase bufsectors from the default 4096 (2M) if opt_transfer
2632      * or discard_alignment of the out_bs is greater. Limit to
2633      * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2634     s.buf_sectors = MIN(MAX_BUF_SECTORS,
2635                         MAX(s.buf_sectors,
2636                             MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2637                                 out_bs->bl.pdiscard_alignment >>
2638                                 BDRV_SECTOR_BITS)));
2639 
2640     /* try to align the write requests to the destination to avoid unnecessary
2641      * RMW cycles. */
2642     s.alignment = MAX(pow2floor(s.min_sparse),
2643                       DIV_ROUND_UP(out_bs->bl.request_alignment,
2644                                    BDRV_SECTOR_SIZE));
2645     assert(is_power_of_2(s.alignment));
2646 
2647     if (skip_create) {
2648         int64_t output_sectors = blk_nb_sectors(s.target);
2649         if (output_sectors < 0) {
2650             error_report("unable to get output image length: %s",
2651                          strerror(-output_sectors));
2652             ret = -1;
2653             goto out;
2654         } else if (output_sectors < s.total_sectors) {
2655             error_report("output file is smaller than input file");
2656             ret = -1;
2657             goto out;
2658         }
2659     }
2660 
2661     if (s.target_has_backing && s.target_is_new) {
2662         /* Errors are treated as "backing length unknown" (which means
2663          * s.target_backing_sectors has to be negative, which it will
2664          * be automatically).  The backing file length is used only
2665          * for optimizations, so such a case is not fatal. */
2666         s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2667     } else {
2668         s.target_backing_sectors = -1;
2669     }
2670 
2671     ret = bdrv_get_info(out_bs, &bdi);
2672     if (ret < 0) {
2673         if (s.compressed) {
2674             error_report("could not get block driver info");
2675             goto out;
2676         }
2677     } else {
2678         s.compressed = s.compressed || bdi.needs_compressed_writes;
2679         s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2680         s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2681     }
2682 
2683     ret = convert_do_copy(&s);
2684 
2685     /* Now copy the bitmaps */
2686     if (bitmaps && ret == 0) {
2687         ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2688     }
2689 
2690 out:
2691     if (!ret) {
2692         qemu_progress_print(100, 0);
2693     }
2694     qemu_progress_end();
2695     qemu_opts_del(opts);
2696     qemu_opts_free(create_opts);
2697     qemu_opts_del(sn_opts);
2698     qobject_unref(open_opts);
2699     blk_unref(s.target);
2700     if (s.src) {
2701         for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2702             blk_unref(s.src[bs_i]);
2703         }
2704         g_free(s.src);
2705     }
2706     g_free(s.src_sectors);
2707 fail_getopt:
2708     g_free(options);
2709 
2710     return !!ret;
2711 }
2712 
2713 
2714 static void dump_snapshots(BlockDriverState *bs)
2715 {
2716     QEMUSnapshotInfo *sn_tab, *sn;
2717     int nb_sns, i;
2718 
2719     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2720     if (nb_sns <= 0)
2721         return;
2722     printf("Snapshot list:\n");
2723     bdrv_snapshot_dump(NULL);
2724     printf("\n");
2725     for(i = 0; i < nb_sns; i++) {
2726         sn = &sn_tab[i];
2727         bdrv_snapshot_dump(sn);
2728         printf("\n");
2729     }
2730     g_free(sn_tab);
2731 }
2732 
2733 static void dump_json_image_info_list(ImageInfoList *list)
2734 {
2735     QString *str;
2736     QObject *obj;
2737     Visitor *v = qobject_output_visitor_new(&obj);
2738 
2739     visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2740     visit_complete(v, &obj);
2741     str = qobject_to_json_pretty(obj);
2742     assert(str != NULL);
2743     printf("%s\n", qstring_get_str(str));
2744     qobject_unref(obj);
2745     visit_free(v);
2746     qobject_unref(str);
2747 }
2748 
2749 static void dump_json_image_info(ImageInfo *info)
2750 {
2751     QString *str;
2752     QObject *obj;
2753     Visitor *v = qobject_output_visitor_new(&obj);
2754 
2755     visit_type_ImageInfo(v, NULL, &info, &error_abort);
2756     visit_complete(v, &obj);
2757     str = qobject_to_json_pretty(obj);
2758     assert(str != NULL);
2759     printf("%s\n", qstring_get_str(str));
2760     qobject_unref(obj);
2761     visit_free(v);
2762     qobject_unref(str);
2763 }
2764 
2765 static void dump_human_image_info_list(ImageInfoList *list)
2766 {
2767     ImageInfoList *elem;
2768     bool delim = false;
2769 
2770     for (elem = list; elem; elem = elem->next) {
2771         if (delim) {
2772             printf("\n");
2773         }
2774         delim = true;
2775 
2776         bdrv_image_info_dump(elem->value);
2777     }
2778 }
2779 
2780 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2781 {
2782     return strcmp(a, b) == 0;
2783 }
2784 
2785 /**
2786  * Open an image file chain and return an ImageInfoList
2787  *
2788  * @filename: topmost image filename
2789  * @fmt: topmost image format (may be NULL to autodetect)
2790  * @chain: true  - enumerate entire backing file chain
2791  *         false - only topmost image file
2792  *
2793  * Returns a list of ImageInfo objects or NULL if there was an error opening an
2794  * image file.  If there was an error a message will have been printed to
2795  * stderr.
2796  */
2797 static ImageInfoList *collect_image_info_list(bool image_opts,
2798                                               const char *filename,
2799                                               const char *fmt,
2800                                               bool chain, bool force_share)
2801 {
2802     ImageInfoList *head = NULL;
2803     ImageInfoList **last = &head;
2804     GHashTable *filenames;
2805     Error *err = NULL;
2806 
2807     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2808 
2809     while (filename) {
2810         BlockBackend *blk;
2811         BlockDriverState *bs;
2812         ImageInfo *info;
2813         ImageInfoList *elem;
2814 
2815         if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2816             error_report("Backing file '%s' creates an infinite loop.",
2817                          filename);
2818             goto err;
2819         }
2820         g_hash_table_insert(filenames, (gpointer)filename, NULL);
2821 
2822         blk = img_open(image_opts, filename, fmt,
2823                        BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2824                        force_share);
2825         if (!blk) {
2826             goto err;
2827         }
2828         bs = blk_bs(blk);
2829 
2830         bdrv_query_image_info(bs, &info, &err);
2831         if (err) {
2832             error_report_err(err);
2833             blk_unref(blk);
2834             goto err;
2835         }
2836 
2837         elem = g_new0(ImageInfoList, 1);
2838         elem->value = info;
2839         *last = elem;
2840         last = &elem->next;
2841 
2842         blk_unref(blk);
2843 
2844         /* Clear parameters that only apply to the topmost image */
2845         filename = fmt = NULL;
2846         image_opts = false;
2847 
2848         if (chain) {
2849             if (info->has_full_backing_filename) {
2850                 filename = info->full_backing_filename;
2851             } else if (info->has_backing_filename) {
2852                 error_report("Could not determine absolute backing filename,"
2853                              " but backing filename '%s' present",
2854                              info->backing_filename);
2855                 goto err;
2856             }
2857             if (info->has_backing_filename_format) {
2858                 fmt = info->backing_filename_format;
2859             }
2860         }
2861     }
2862     g_hash_table_destroy(filenames);
2863     return head;
2864 
2865 err:
2866     qapi_free_ImageInfoList(head);
2867     g_hash_table_destroy(filenames);
2868     return NULL;
2869 }
2870 
2871 static int img_info(int argc, char **argv)
2872 {
2873     int c;
2874     OutputFormat output_format = OFORMAT_HUMAN;
2875     bool chain = false;
2876     const char *filename, *fmt, *output;
2877     ImageInfoList *list;
2878     bool image_opts = false;
2879     bool force_share = false;
2880 
2881     fmt = NULL;
2882     output = NULL;
2883     for(;;) {
2884         int option_index = 0;
2885         static const struct option long_options[] = {
2886             {"help", no_argument, 0, 'h'},
2887             {"format", required_argument, 0, 'f'},
2888             {"output", required_argument, 0, OPTION_OUTPUT},
2889             {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2890             {"object", required_argument, 0, OPTION_OBJECT},
2891             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2892             {"force-share", no_argument, 0, 'U'},
2893             {0, 0, 0, 0}
2894         };
2895         c = getopt_long(argc, argv, ":f:hU",
2896                         long_options, &option_index);
2897         if (c == -1) {
2898             break;
2899         }
2900         switch(c) {
2901         case ':':
2902             missing_argument(argv[optind - 1]);
2903             break;
2904         case '?':
2905             unrecognized_option(argv[optind - 1]);
2906             break;
2907         case 'h':
2908             help();
2909             break;
2910         case 'f':
2911             fmt = optarg;
2912             break;
2913         case 'U':
2914             force_share = true;
2915             break;
2916         case OPTION_OUTPUT:
2917             output = optarg;
2918             break;
2919         case OPTION_BACKING_CHAIN:
2920             chain = true;
2921             break;
2922         case OPTION_OBJECT: {
2923             QemuOpts *opts;
2924             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2925                                            optarg, true);
2926             if (!opts) {
2927                 return 1;
2928             }
2929         }   break;
2930         case OPTION_IMAGE_OPTS:
2931             image_opts = true;
2932             break;
2933         }
2934     }
2935     if (optind != argc - 1) {
2936         error_exit("Expecting one image file name");
2937     }
2938     filename = argv[optind++];
2939 
2940     if (output && !strcmp(output, "json")) {
2941         output_format = OFORMAT_JSON;
2942     } else if (output && !strcmp(output, "human")) {
2943         output_format = OFORMAT_HUMAN;
2944     } else if (output) {
2945         error_report("--output must be used with human or json as argument.");
2946         return 1;
2947     }
2948 
2949     if (qemu_opts_foreach(&qemu_object_opts,
2950                           user_creatable_add_opts_foreach,
2951                           qemu_img_object_print_help, &error_fatal)) {
2952         return 1;
2953     }
2954 
2955     list = collect_image_info_list(image_opts, filename, fmt, chain,
2956                                    force_share);
2957     if (!list) {
2958         return 1;
2959     }
2960 
2961     switch (output_format) {
2962     case OFORMAT_HUMAN:
2963         dump_human_image_info_list(list);
2964         break;
2965     case OFORMAT_JSON:
2966         if (chain) {
2967             dump_json_image_info_list(list);
2968         } else {
2969             dump_json_image_info(list->value);
2970         }
2971         break;
2972     }
2973 
2974     qapi_free_ImageInfoList(list);
2975     return 0;
2976 }
2977 
2978 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2979                           MapEntry *next)
2980 {
2981     switch (output_format) {
2982     case OFORMAT_HUMAN:
2983         if (e->data && !e->has_offset) {
2984             error_report("File contains external, encrypted or compressed clusters.");
2985             return -1;
2986         }
2987         if (e->data && !e->zero) {
2988             printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2989                    e->start, e->length,
2990                    e->has_offset ? e->offset : 0,
2991                    e->has_filename ? e->filename : "");
2992         }
2993         /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2994          * Modify the flags here to allow more coalescing.
2995          */
2996         if (next && (!next->data || next->zero)) {
2997             next->data = false;
2998             next->zero = true;
2999         }
3000         break;
3001     case OFORMAT_JSON:
3002         printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3003                " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3004                e->start, e->length, e->depth,
3005                e->zero ? "true" : "false",
3006                e->data ? "true" : "false");
3007         if (e->has_offset) {
3008             printf(", \"offset\": %"PRId64"", e->offset);
3009         }
3010         putchar('}');
3011 
3012         if (next) {
3013             puts(",");
3014         }
3015         break;
3016     }
3017     return 0;
3018 }
3019 
3020 static int get_block_status(BlockDriverState *bs, int64_t offset,
3021                             int64_t bytes, MapEntry *e)
3022 {
3023     int ret;
3024     int depth;
3025     BlockDriverState *file;
3026     bool has_offset;
3027     int64_t map;
3028     char *filename = NULL;
3029 
3030     /* As an optimization, we could cache the current range of unallocated
3031      * clusters in each file of the chain, and avoid querying the same
3032      * range repeatedly.
3033      */
3034 
3035     depth = 0;
3036     for (;;) {
3037         ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3038         if (ret < 0) {
3039             return ret;
3040         }
3041         assert(bytes);
3042         if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3043             break;
3044         }
3045         bs = backing_bs(bs);
3046         if (bs == NULL) {
3047             ret = 0;
3048             break;
3049         }
3050 
3051         depth++;
3052     }
3053 
3054     has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3055 
3056     if (file && has_offset) {
3057         bdrv_refresh_filename(file);
3058         filename = file->filename;
3059     }
3060 
3061     *e = (MapEntry) {
3062         .start = offset,
3063         .length = bytes,
3064         .data = !!(ret & BDRV_BLOCK_DATA),
3065         .zero = !!(ret & BDRV_BLOCK_ZERO),
3066         .offset = map,
3067         .has_offset = has_offset,
3068         .depth = depth,
3069         .has_filename = filename,
3070         .filename = filename,
3071     };
3072 
3073     return 0;
3074 }
3075 
3076 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3077 {
3078     if (curr->length == 0) {
3079         return false;
3080     }
3081     if (curr->zero != next->zero ||
3082         curr->data != next->data ||
3083         curr->depth != next->depth ||
3084         curr->has_filename != next->has_filename ||
3085         curr->has_offset != next->has_offset) {
3086         return false;
3087     }
3088     if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3089         return false;
3090     }
3091     if (curr->has_offset && curr->offset + curr->length != next->offset) {
3092         return false;
3093     }
3094     return true;
3095 }
3096 
3097 static int img_map(int argc, char **argv)
3098 {
3099     int c;
3100     OutputFormat output_format = OFORMAT_HUMAN;
3101     BlockBackend *blk;
3102     BlockDriverState *bs;
3103     const char *filename, *fmt, *output;
3104     int64_t length;
3105     MapEntry curr = { .length = 0 }, next;
3106     int ret = 0;
3107     bool image_opts = false;
3108     bool force_share = false;
3109     int64_t start_offset = 0;
3110     int64_t max_length = -1;
3111 
3112     fmt = NULL;
3113     output = NULL;
3114     for (;;) {
3115         int option_index = 0;
3116         static const struct option long_options[] = {
3117             {"help", no_argument, 0, 'h'},
3118             {"format", required_argument, 0, 'f'},
3119             {"output", required_argument, 0, OPTION_OUTPUT},
3120             {"object", required_argument, 0, OPTION_OBJECT},
3121             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3122             {"force-share", no_argument, 0, 'U'},
3123             {"start-offset", required_argument, 0, 's'},
3124             {"max-length", required_argument, 0, 'l'},
3125             {0, 0, 0, 0}
3126         };
3127         c = getopt_long(argc, argv, ":f:s:l:hU",
3128                         long_options, &option_index);
3129         if (c == -1) {
3130             break;
3131         }
3132         switch (c) {
3133         case ':':
3134             missing_argument(argv[optind - 1]);
3135             break;
3136         case '?':
3137             unrecognized_option(argv[optind - 1]);
3138             break;
3139         case 'h':
3140             help();
3141             break;
3142         case 'f':
3143             fmt = optarg;
3144             break;
3145         case 'U':
3146             force_share = true;
3147             break;
3148         case OPTION_OUTPUT:
3149             output = optarg;
3150             break;
3151         case 's':
3152             start_offset = cvtnum("start offset", optarg);
3153             if (start_offset < 0) {
3154                 return 1;
3155             }
3156             break;
3157         case 'l':
3158             max_length = cvtnum("max length", optarg);
3159             if (max_length < 0) {
3160                 return 1;
3161             }
3162             break;
3163         case OPTION_OBJECT: {
3164             QemuOpts *opts;
3165             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3166                                            optarg, true);
3167             if (!opts) {
3168                 return 1;
3169             }
3170         }   break;
3171         case OPTION_IMAGE_OPTS:
3172             image_opts = true;
3173             break;
3174         }
3175     }
3176     if (optind != argc - 1) {
3177         error_exit("Expecting one image file name");
3178     }
3179     filename = argv[optind];
3180 
3181     if (output && !strcmp(output, "json")) {
3182         output_format = OFORMAT_JSON;
3183     } else if (output && !strcmp(output, "human")) {
3184         output_format = OFORMAT_HUMAN;
3185     } else if (output) {
3186         error_report("--output must be used with human or json as argument.");
3187         return 1;
3188     }
3189 
3190     if (qemu_opts_foreach(&qemu_object_opts,
3191                           user_creatable_add_opts_foreach,
3192                           qemu_img_object_print_help, &error_fatal)) {
3193         return 1;
3194     }
3195 
3196     blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3197     if (!blk) {
3198         return 1;
3199     }
3200     bs = blk_bs(blk);
3201 
3202     if (output_format == OFORMAT_HUMAN) {
3203         printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3204     } else if (output_format == OFORMAT_JSON) {
3205         putchar('[');
3206     }
3207 
3208     length = blk_getlength(blk);
3209     if (length < 0) {
3210         error_report("Failed to get size for '%s'", filename);
3211         return 1;
3212     }
3213     if (max_length != -1) {
3214         length = MIN(start_offset + max_length, length);
3215     }
3216 
3217     curr.start = start_offset;
3218     while (curr.start + curr.length < length) {
3219         int64_t offset = curr.start + curr.length;
3220         int64_t n;
3221 
3222         /* Probe up to 1 GiB at a time.  */
3223         n = MIN(1 * GiB, length - offset);
3224         ret = get_block_status(bs, offset, n, &next);
3225 
3226         if (ret < 0) {
3227             error_report("Could not read file metadata: %s", strerror(-ret));
3228             goto out;
3229         }
3230 
3231         if (entry_mergeable(&curr, &next)) {
3232             curr.length += next.length;
3233             continue;
3234         }
3235 
3236         if (curr.length > 0) {
3237             ret = dump_map_entry(output_format, &curr, &next);
3238             if (ret < 0) {
3239                 goto out;
3240             }
3241         }
3242         curr = next;
3243     }
3244 
3245     ret = dump_map_entry(output_format, &curr, NULL);
3246     if (output_format == OFORMAT_JSON) {
3247         puts("]");
3248     }
3249 
3250 out:
3251     blk_unref(blk);
3252     return ret < 0;
3253 }
3254 
3255 #define SNAPSHOT_LIST   1
3256 #define SNAPSHOT_CREATE 2
3257 #define SNAPSHOT_APPLY  3
3258 #define SNAPSHOT_DELETE 4
3259 
3260 static int img_snapshot(int argc, char **argv)
3261 {
3262     BlockBackend *blk;
3263     BlockDriverState *bs;
3264     QEMUSnapshotInfo sn;
3265     char *filename, *snapshot_name = NULL;
3266     int c, ret = 0, bdrv_oflags;
3267     int action = 0;
3268     qemu_timeval tv;
3269     bool quiet = false;
3270     Error *err = NULL;
3271     bool image_opts = false;
3272     bool force_share = false;
3273 
3274     bdrv_oflags = BDRV_O_RDWR;
3275     /* Parse commandline parameters */
3276     for(;;) {
3277         static const struct option long_options[] = {
3278             {"help", no_argument, 0, 'h'},
3279             {"object", required_argument, 0, OPTION_OBJECT},
3280             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3281             {"force-share", no_argument, 0, 'U'},
3282             {0, 0, 0, 0}
3283         };
3284         c = getopt_long(argc, argv, ":la:c:d:hqU",
3285                         long_options, NULL);
3286         if (c == -1) {
3287             break;
3288         }
3289         switch(c) {
3290         case ':':
3291             missing_argument(argv[optind - 1]);
3292             break;
3293         case '?':
3294             unrecognized_option(argv[optind - 1]);
3295             break;
3296         case 'h':
3297             help();
3298             return 0;
3299         case 'l':
3300             if (action) {
3301                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3302                 return 0;
3303             }
3304             action = SNAPSHOT_LIST;
3305             bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3306             break;
3307         case 'a':
3308             if (action) {
3309                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3310                 return 0;
3311             }
3312             action = SNAPSHOT_APPLY;
3313             snapshot_name = optarg;
3314             break;
3315         case 'c':
3316             if (action) {
3317                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3318                 return 0;
3319             }
3320             action = SNAPSHOT_CREATE;
3321             snapshot_name = optarg;
3322             break;
3323         case 'd':
3324             if (action) {
3325                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3326                 return 0;
3327             }
3328             action = SNAPSHOT_DELETE;
3329             snapshot_name = optarg;
3330             break;
3331         case 'q':
3332             quiet = true;
3333             break;
3334         case 'U':
3335             force_share = true;
3336             break;
3337         case OPTION_OBJECT: {
3338             QemuOpts *opts;
3339             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3340                                            optarg, true);
3341             if (!opts) {
3342                 return 1;
3343             }
3344         }   break;
3345         case OPTION_IMAGE_OPTS:
3346             image_opts = true;
3347             break;
3348         }
3349     }
3350 
3351     if (optind != argc - 1) {
3352         error_exit("Expecting one image file name");
3353     }
3354     filename = argv[optind++];
3355 
3356     if (qemu_opts_foreach(&qemu_object_opts,
3357                           user_creatable_add_opts_foreach,
3358                           qemu_img_object_print_help, &error_fatal)) {
3359         return 1;
3360     }
3361 
3362     /* Open the image */
3363     blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3364                    force_share);
3365     if (!blk) {
3366         return 1;
3367     }
3368     bs = blk_bs(blk);
3369 
3370     /* Perform the requested action */
3371     switch(action) {
3372     case SNAPSHOT_LIST:
3373         dump_snapshots(bs);
3374         break;
3375 
3376     case SNAPSHOT_CREATE:
3377         memset(&sn, 0, sizeof(sn));
3378         pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3379 
3380         qemu_gettimeofday(&tv);
3381         sn.date_sec = tv.tv_sec;
3382         sn.date_nsec = tv.tv_usec * 1000;
3383 
3384         ret = bdrv_snapshot_create(bs, &sn);
3385         if (ret) {
3386             error_report("Could not create snapshot '%s': %d (%s)",
3387                 snapshot_name, ret, strerror(-ret));
3388         }
3389         break;
3390 
3391     case SNAPSHOT_APPLY:
3392         ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3393         if (ret) {
3394             error_reportf_err(err, "Could not apply snapshot '%s': ",
3395                               snapshot_name);
3396         }
3397         break;
3398 
3399     case SNAPSHOT_DELETE:
3400         ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3401         if (ret < 0) {
3402             error_report("Could not delete snapshot '%s': snapshot not "
3403                          "found", snapshot_name);
3404             ret = 1;
3405         } else {
3406             ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3407             if (ret < 0) {
3408                 error_reportf_err(err, "Could not delete snapshot '%s': ",
3409                                   snapshot_name);
3410                 ret = 1;
3411             }
3412         }
3413         break;
3414     }
3415 
3416     /* Cleanup */
3417     blk_unref(blk);
3418     if (ret) {
3419         return 1;
3420     }
3421     return 0;
3422 }
3423 
3424 static int img_rebase(int argc, char **argv)
3425 {
3426     BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3427     uint8_t *buf_old = NULL;
3428     uint8_t *buf_new = NULL;
3429     BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3430     char *filename;
3431     const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3432     int c, flags, src_flags, ret;
3433     bool writethrough, src_writethrough;
3434     int unsafe = 0;
3435     bool force_share = false;
3436     int progress = 0;
3437     bool quiet = false;
3438     Error *local_err = NULL;
3439     bool image_opts = false;
3440 
3441     /* Parse commandline parameters */
3442     fmt = NULL;
3443     cache = BDRV_DEFAULT_CACHE;
3444     src_cache = BDRV_DEFAULT_CACHE;
3445     out_baseimg = NULL;
3446     out_basefmt = NULL;
3447     for(;;) {
3448         static const struct option long_options[] = {
3449             {"help", no_argument, 0, 'h'},
3450             {"object", required_argument, 0, OPTION_OBJECT},
3451             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3452             {"force-share", no_argument, 0, 'U'},
3453             {0, 0, 0, 0}
3454         };
3455         c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3456                         long_options, NULL);
3457         if (c == -1) {
3458             break;
3459         }
3460         switch(c) {
3461         case ':':
3462             missing_argument(argv[optind - 1]);
3463             break;
3464         case '?':
3465             unrecognized_option(argv[optind - 1]);
3466             break;
3467         case 'h':
3468             help();
3469             return 0;
3470         case 'f':
3471             fmt = optarg;
3472             break;
3473         case 'F':
3474             out_basefmt = optarg;
3475             break;
3476         case 'b':
3477             out_baseimg = optarg;
3478             break;
3479         case 'u':
3480             unsafe = 1;
3481             break;
3482         case 'p':
3483             progress = 1;
3484             break;
3485         case 't':
3486             cache = optarg;
3487             break;
3488         case 'T':
3489             src_cache = optarg;
3490             break;
3491         case 'q':
3492             quiet = true;
3493             break;
3494         case OPTION_OBJECT: {
3495             QemuOpts *opts;
3496             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3497                                            optarg, true);
3498             if (!opts) {
3499                 return 1;
3500             }
3501         }   break;
3502         case OPTION_IMAGE_OPTS:
3503             image_opts = true;
3504             break;
3505         case 'U':
3506             force_share = true;
3507             break;
3508         }
3509     }
3510 
3511     if (quiet) {
3512         progress = 0;
3513     }
3514 
3515     if (optind != argc - 1) {
3516         error_exit("Expecting one image file name");
3517     }
3518     if (!unsafe && !out_baseimg) {
3519         error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3520     }
3521     filename = argv[optind++];
3522 
3523     if (qemu_opts_foreach(&qemu_object_opts,
3524                           user_creatable_add_opts_foreach,
3525                           qemu_img_object_print_help, &error_fatal)) {
3526         return 1;
3527     }
3528 
3529     qemu_progress_init(progress, 2.0);
3530     qemu_progress_print(0, 100);
3531 
3532     flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3533     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3534     if (ret < 0) {
3535         error_report("Invalid cache option: %s", cache);
3536         goto out;
3537     }
3538 
3539     src_flags = 0;
3540     ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3541     if (ret < 0) {
3542         error_report("Invalid source cache option: %s", src_cache);
3543         goto out;
3544     }
3545 
3546     /* The source files are opened read-only, don't care about WCE */
3547     assert((src_flags & BDRV_O_RDWR) == 0);
3548     (void) src_writethrough;
3549 
3550     /*
3551      * Open the images.
3552      *
3553      * Ignore the old backing file for unsafe rebase in case we want to correct
3554      * the reference to a renamed or moved backing file.
3555      */
3556     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3557                    false);
3558     if (!blk) {
3559         ret = -1;
3560         goto out;
3561     }
3562     bs = blk_bs(blk);
3563 
3564     if (out_basefmt != NULL) {
3565         if (bdrv_find_format(out_basefmt) == NULL) {
3566             error_report("Invalid format name: '%s'", out_basefmt);
3567             ret = -1;
3568             goto out;
3569         }
3570     }
3571 
3572     /* For safe rebasing we need to compare old and new backing file */
3573     if (!unsafe) {
3574         QDict *options = NULL;
3575         BlockDriverState *base_bs = backing_bs(bs);
3576 
3577         if (base_bs) {
3578             blk_old_backing = blk_new(qemu_get_aio_context(),
3579                                       BLK_PERM_CONSISTENT_READ,
3580                                       BLK_PERM_ALL);
3581             ret = blk_insert_bs(blk_old_backing, base_bs,
3582                                 &local_err);
3583             if (ret < 0) {
3584                 error_reportf_err(local_err,
3585                                   "Could not reuse old backing file '%s': ",
3586                                   base_bs->filename);
3587                 goto out;
3588             }
3589         } else {
3590             blk_old_backing = NULL;
3591         }
3592 
3593         if (out_baseimg[0]) {
3594             const char *overlay_filename;
3595             char *out_real_path;
3596 
3597             options = qdict_new();
3598             if (out_basefmt) {
3599                 qdict_put_str(options, "driver", out_basefmt);
3600             }
3601             if (force_share) {
3602                 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3603             }
3604 
3605             bdrv_refresh_filename(bs);
3606             overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3607                                                      : bs->filename;
3608             out_real_path =
3609                 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3610                                                              out_baseimg,
3611                                                              &local_err);
3612             if (local_err) {
3613                 qobject_unref(options);
3614                 error_reportf_err(local_err,
3615                                   "Could not resolve backing filename: ");
3616                 ret = -1;
3617                 goto out;
3618             }
3619 
3620             /*
3621              * Find out whether we rebase an image on top of a previous image
3622              * in its chain.
3623              */
3624             prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3625             if (prefix_chain_bs) {
3626                 qobject_unref(options);
3627                 g_free(out_real_path);
3628 
3629                 blk_new_backing = blk_new(qemu_get_aio_context(),
3630                                           BLK_PERM_CONSISTENT_READ,
3631                                           BLK_PERM_ALL);
3632                 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3633                                     &local_err);
3634                 if (ret < 0) {
3635                     error_reportf_err(local_err,
3636                                       "Could not reuse backing file '%s': ",
3637                                       out_baseimg);
3638                     goto out;
3639                 }
3640             } else {
3641                 blk_new_backing = blk_new_open(out_real_path, NULL,
3642                                                options, src_flags, &local_err);
3643                 g_free(out_real_path);
3644                 if (!blk_new_backing) {
3645                     error_reportf_err(local_err,
3646                                       "Could not open new backing file '%s': ",
3647                                       out_baseimg);
3648                     ret = -1;
3649                     goto out;
3650                 }
3651             }
3652         }
3653     }
3654 
3655     /*
3656      * Check each unallocated cluster in the COW file. If it is unallocated,
3657      * accesses go to the backing file. We must therefore compare this cluster
3658      * in the old and new backing file, and if they differ we need to copy it
3659      * from the old backing file into the COW file.
3660      *
3661      * If qemu-img crashes during this step, no harm is done. The content of
3662      * the image is the same as the original one at any time.
3663      */
3664     if (!unsafe) {
3665         int64_t size;
3666         int64_t old_backing_size = 0;
3667         int64_t new_backing_size = 0;
3668         uint64_t offset;
3669         int64_t n;
3670         float local_progress = 0;
3671 
3672         buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3673         buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3674 
3675         size = blk_getlength(blk);
3676         if (size < 0) {
3677             error_report("Could not get size of '%s': %s",
3678                          filename, strerror(-size));
3679             ret = -1;
3680             goto out;
3681         }
3682         if (blk_old_backing) {
3683             old_backing_size = blk_getlength(blk_old_backing);
3684             if (old_backing_size < 0) {
3685                 char backing_name[PATH_MAX];
3686 
3687                 bdrv_get_backing_filename(bs, backing_name,
3688                                           sizeof(backing_name));
3689                 error_report("Could not get size of '%s': %s",
3690                              backing_name, strerror(-old_backing_size));
3691                 ret = -1;
3692                 goto out;
3693             }
3694         }
3695         if (blk_new_backing) {
3696             new_backing_size = blk_getlength(blk_new_backing);
3697             if (new_backing_size < 0) {
3698                 error_report("Could not get size of '%s': %s",
3699                              out_baseimg, strerror(-new_backing_size));
3700                 ret = -1;
3701                 goto out;
3702             }
3703         }
3704 
3705         if (size != 0) {
3706             local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3707         }
3708 
3709         for (offset = 0; offset < size; offset += n) {
3710             bool buf_old_is_zero = false;
3711 
3712             /* How many bytes can we handle with the next read? */
3713             n = MIN(IO_BUF_SIZE, size - offset);
3714 
3715             /* If the cluster is allocated, we don't need to take action */
3716             ret = bdrv_is_allocated(bs, offset, n, &n);
3717             if (ret < 0) {
3718                 error_report("error while reading image metadata: %s",
3719                              strerror(-ret));
3720                 goto out;
3721             }
3722             if (ret) {
3723                 continue;
3724             }
3725 
3726             if (prefix_chain_bs) {
3727                 /*
3728                  * If cluster wasn't changed since prefix_chain, we don't need
3729                  * to take action
3730                  */
3731                 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3732                                               false, offset, n, &n);
3733                 if (ret < 0) {
3734                     error_report("error while reading image metadata: %s",
3735                                  strerror(-ret));
3736                     goto out;
3737                 }
3738                 if (!ret) {
3739                     continue;
3740                 }
3741             }
3742 
3743             /*
3744              * Read old and new backing file and take into consideration that
3745              * backing files may be smaller than the COW image.
3746              */
3747             if (offset >= old_backing_size) {
3748                 memset(buf_old, 0, n);
3749                 buf_old_is_zero = true;
3750             } else {
3751                 if (offset + n > old_backing_size) {
3752                     n = old_backing_size - offset;
3753                 }
3754 
3755                 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3756                 if (ret < 0) {
3757                     error_report("error while reading from old backing file");
3758                     goto out;
3759                 }
3760             }
3761 
3762             if (offset >= new_backing_size || !blk_new_backing) {
3763                 memset(buf_new, 0, n);
3764             } else {
3765                 if (offset + n > new_backing_size) {
3766                     n = new_backing_size - offset;
3767                 }
3768 
3769                 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3770                 if (ret < 0) {
3771                     error_report("error while reading from new backing file");
3772                     goto out;
3773                 }
3774             }
3775 
3776             /* If they differ, we need to write to the COW file */
3777             uint64_t written = 0;
3778 
3779             while (written < n) {
3780                 int64_t pnum;
3781 
3782                 if (compare_buffers(buf_old + written, buf_new + written,
3783                                     n - written, &pnum))
3784                 {
3785                     if (buf_old_is_zero) {
3786                         ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3787                     } else {
3788                         ret = blk_pwrite(blk, offset + written,
3789                                          buf_old + written, pnum, 0);
3790                     }
3791                     if (ret < 0) {
3792                         error_report("Error while writing to COW image: %s",
3793                             strerror(-ret));
3794                         goto out;
3795                     }
3796                 }
3797 
3798                 written += pnum;
3799             }
3800             qemu_progress_print(local_progress, 100);
3801         }
3802     }
3803 
3804     /*
3805      * Change the backing file. All clusters that are different from the old
3806      * backing file are overwritten in the COW file now, so the visible content
3807      * doesn't change when we switch the backing file.
3808      */
3809     if (out_baseimg && *out_baseimg) {
3810         ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3811     } else {
3812         ret = bdrv_change_backing_file(bs, NULL, NULL);
3813     }
3814 
3815     if (ret == -ENOSPC) {
3816         error_report("Could not change the backing file to '%s': No "
3817                      "space left in the file header", out_baseimg);
3818     } else if (ret < 0) {
3819         error_report("Could not change the backing file to '%s': %s",
3820             out_baseimg, strerror(-ret));
3821     }
3822 
3823     qemu_progress_print(100, 0);
3824     /*
3825      * TODO At this point it is possible to check if any clusters that are
3826      * allocated in the COW file are the same in the backing file. If so, they
3827      * could be dropped from the COW file. Don't do this before switching the
3828      * backing file, in case of a crash this would lead to corruption.
3829      */
3830 out:
3831     qemu_progress_end();
3832     /* Cleanup */
3833     if (!unsafe) {
3834         blk_unref(blk_old_backing);
3835         blk_unref(blk_new_backing);
3836     }
3837     qemu_vfree(buf_old);
3838     qemu_vfree(buf_new);
3839 
3840     blk_unref(blk);
3841     if (ret) {
3842         return 1;
3843     }
3844     return 0;
3845 }
3846 
3847 static int img_resize(int argc, char **argv)
3848 {
3849     Error *err = NULL;
3850     int c, ret, relative;
3851     const char *filename, *fmt, *size;
3852     int64_t n, total_size, current_size;
3853     bool quiet = false;
3854     BlockBackend *blk = NULL;
3855     PreallocMode prealloc = PREALLOC_MODE_OFF;
3856     QemuOpts *param;
3857 
3858     static QemuOptsList resize_options = {
3859         .name = "resize_options",
3860         .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3861         .desc = {
3862             {
3863                 .name = BLOCK_OPT_SIZE,
3864                 .type = QEMU_OPT_SIZE,
3865                 .help = "Virtual disk size"
3866             }, {
3867                 /* end of list */
3868             }
3869         },
3870     };
3871     bool image_opts = false;
3872     bool shrink = false;
3873 
3874     /* Remove size from argv manually so that negative numbers are not treated
3875      * as options by getopt. */
3876     if (argc < 3) {
3877         error_exit("Not enough arguments");
3878         return 1;
3879     }
3880 
3881     size = argv[--argc];
3882 
3883     /* Parse getopt arguments */
3884     fmt = NULL;
3885     for(;;) {
3886         static const struct option long_options[] = {
3887             {"help", no_argument, 0, 'h'},
3888             {"object", required_argument, 0, OPTION_OBJECT},
3889             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3890             {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3891             {"shrink", no_argument, 0, OPTION_SHRINK},
3892             {0, 0, 0, 0}
3893         };
3894         c = getopt_long(argc, argv, ":f:hq",
3895                         long_options, NULL);
3896         if (c == -1) {
3897             break;
3898         }
3899         switch(c) {
3900         case ':':
3901             missing_argument(argv[optind - 1]);
3902             break;
3903         case '?':
3904             unrecognized_option(argv[optind - 1]);
3905             break;
3906         case 'h':
3907             help();
3908             break;
3909         case 'f':
3910             fmt = optarg;
3911             break;
3912         case 'q':
3913             quiet = true;
3914             break;
3915         case OPTION_OBJECT: {
3916             QemuOpts *opts;
3917             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3918                                            optarg, true);
3919             if (!opts) {
3920                 return 1;
3921             }
3922         }   break;
3923         case OPTION_IMAGE_OPTS:
3924             image_opts = true;
3925             break;
3926         case OPTION_PREALLOCATION:
3927             prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3928                                        PREALLOC_MODE__MAX, NULL);
3929             if (prealloc == PREALLOC_MODE__MAX) {
3930                 error_report("Invalid preallocation mode '%s'", optarg);
3931                 return 1;
3932             }
3933             break;
3934         case OPTION_SHRINK:
3935             shrink = true;
3936             break;
3937         }
3938     }
3939     if (optind != argc - 1) {
3940         error_exit("Expecting image file name and size");
3941     }
3942     filename = argv[optind++];
3943 
3944     if (qemu_opts_foreach(&qemu_object_opts,
3945                           user_creatable_add_opts_foreach,
3946                           qemu_img_object_print_help, &error_fatal)) {
3947         return 1;
3948     }
3949 
3950     /* Choose grow, shrink, or absolute resize mode */
3951     switch (size[0]) {
3952     case '+':
3953         relative = 1;
3954         size++;
3955         break;
3956     case '-':
3957         relative = -1;
3958         size++;
3959         break;
3960     default:
3961         relative = 0;
3962         break;
3963     }
3964 
3965     /* Parse size */
3966     param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3967     qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3968     if (err) {
3969         error_report_err(err);
3970         ret = -1;
3971         qemu_opts_del(param);
3972         goto out;
3973     }
3974     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3975     qemu_opts_del(param);
3976 
3977     blk = img_open(image_opts, filename, fmt,
3978                    BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3979                    false);
3980     if (!blk) {
3981         ret = -1;
3982         goto out;
3983     }
3984 
3985     current_size = blk_getlength(blk);
3986     if (current_size < 0) {
3987         error_report("Failed to inquire current image length: %s",
3988                      strerror(-current_size));
3989         ret = -1;
3990         goto out;
3991     }
3992 
3993     if (relative) {
3994         total_size = current_size + n * relative;
3995     } else {
3996         total_size = n;
3997     }
3998     if (total_size <= 0) {
3999         error_report("New image size must be positive");
4000         ret = -1;
4001         goto out;
4002     }
4003 
4004     if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4005         error_report("Preallocation can only be used for growing images");
4006         ret = -1;
4007         goto out;
4008     }
4009 
4010     if (total_size < current_size && !shrink) {
4011         warn_report("Shrinking an image will delete all data beyond the "
4012                     "shrunken image's end. Before performing such an "
4013                     "operation, make sure there is no important data there.");
4014 
4015         if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4016             error_report(
4017               "Use the --shrink option to perform a shrink operation.");
4018             ret = -1;
4019             goto out;
4020         } else {
4021             warn_report("Using the --shrink option will suppress this message. "
4022                         "Note that future versions of qemu-img may refuse to "
4023                         "shrink images without this option.");
4024         }
4025     }
4026 
4027     /*
4028      * The user expects the image to have the desired size after
4029      * resizing, so pass @exact=true.  It is of no use to report
4030      * success when the image has not actually been resized.
4031      */
4032     ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4033     if (!ret) {
4034         qprintf(quiet, "Image resized.\n");
4035     } else {
4036         error_report_err(err);
4037     }
4038 out:
4039     blk_unref(blk);
4040     if (ret) {
4041         return 1;
4042     }
4043     return 0;
4044 }
4045 
4046 static void amend_status_cb(BlockDriverState *bs,
4047                             int64_t offset, int64_t total_work_size,
4048                             void *opaque)
4049 {
4050     qemu_progress_print(100.f * offset / total_work_size, 0);
4051 }
4052 
4053 static int print_amend_option_help(const char *format)
4054 {
4055     BlockDriver *drv;
4056 
4057     /* Find driver and parse its options */
4058     drv = bdrv_find_format(format);
4059     if (!drv) {
4060         error_report("Unknown file format '%s'", format);
4061         return 1;
4062     }
4063 
4064     if (!drv->bdrv_amend_options) {
4065         error_report("Format driver '%s' does not support option amendment",
4066                      format);
4067         return 1;
4068     }
4069 
4070     /* Every driver supporting amendment must have create_opts */
4071     assert(drv->create_opts);
4072 
4073     printf("Creation options for '%s':\n", format);
4074     qemu_opts_print_help(drv->create_opts, false);
4075     printf("\nNote that not all of these options may be amendable.\n");
4076     return 0;
4077 }
4078 
4079 static int img_amend(int argc, char **argv)
4080 {
4081     Error *err = NULL;
4082     int c, ret = 0;
4083     char *options = NULL;
4084     QemuOptsList *create_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 
4094     cache = BDRV_DEFAULT_CACHE;
4095     for (;;) {
4096         static const struct option long_options[] = {
4097             {"help", no_argument, 0, 'h'},
4098             {"object", required_argument, 0, OPTION_OBJECT},
4099             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4100             {0, 0, 0, 0}
4101         };
4102         c = getopt_long(argc, argv, ":ho:f:t:pq",
4103                         long_options, NULL);
4104         if (c == -1) {
4105             break;
4106         }
4107 
4108         switch (c) {
4109         case ':':
4110             missing_argument(argv[optind - 1]);
4111             break;
4112         case '?':
4113             unrecognized_option(argv[optind - 1]);
4114             break;
4115         case 'h':
4116             help();
4117             break;
4118         case 'o':
4119             if (accumulate_options(&options, optarg) < 0) {
4120                 ret = -1;
4121                 goto out_no_progress;
4122             }
4123             break;
4124         case 'f':
4125             fmt = optarg;
4126             break;
4127         case 't':
4128             cache = optarg;
4129             break;
4130         case 'p':
4131             progress = true;
4132             break;
4133         case 'q':
4134             quiet = true;
4135             break;
4136         case OPTION_OBJECT:
4137             opts = qemu_opts_parse_noisily(&qemu_object_opts,
4138                                            optarg, true);
4139             if (!opts) {
4140                 ret = -1;
4141                 goto out_no_progress;
4142             }
4143             break;
4144         case OPTION_IMAGE_OPTS:
4145             image_opts = true;
4146             break;
4147         }
4148     }
4149 
4150     if (!options) {
4151         error_exit("Must specify options (-o)");
4152     }
4153 
4154     if (qemu_opts_foreach(&qemu_object_opts,
4155                           user_creatable_add_opts_foreach,
4156                           qemu_img_object_print_help, &error_fatal)) {
4157         ret = -1;
4158         goto out_no_progress;
4159     }
4160 
4161     if (quiet) {
4162         progress = false;
4163     }
4164     qemu_progress_init(progress, 1.0);
4165 
4166     filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4167     if (fmt && has_help_option(options)) {
4168         /* If a format is explicitly specified (and possibly no filename is
4169          * given), print option help here */
4170         ret = print_amend_option_help(fmt);
4171         goto out;
4172     }
4173 
4174     if (optind != argc - 1) {
4175         error_report("Expecting one image file name");
4176         ret = -1;
4177         goto out;
4178     }
4179 
4180     flags = BDRV_O_RDWR;
4181     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4182     if (ret < 0) {
4183         error_report("Invalid cache option: %s", cache);
4184         goto out;
4185     }
4186 
4187     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4188                    false);
4189     if (!blk) {
4190         ret = -1;
4191         goto out;
4192     }
4193     bs = blk_bs(blk);
4194 
4195     fmt = bs->drv->format_name;
4196 
4197     if (has_help_option(options)) {
4198         /* If the format was auto-detected, print option help here */
4199         ret = print_amend_option_help(fmt);
4200         goto out;
4201     }
4202 
4203     if (!bs->drv->bdrv_amend_options) {
4204         error_report("Format driver '%s' does not support option amendment",
4205                      fmt);
4206         ret = -1;
4207         goto out;
4208     }
4209 
4210     /* Every driver supporting amendment must have create_opts */
4211     assert(bs->drv->create_opts);
4212 
4213     create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
4214     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4215     qemu_opts_do_parse(opts, options, NULL, &err);
4216     if (err) {
4217         error_report_err(err);
4218         ret = -1;
4219         goto out;
4220     }
4221 
4222     /* In case the driver does not call amend_status_cb() */
4223     qemu_progress_print(0.f, 0);
4224     ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
4225     qemu_progress_print(100.f, 0);
4226     if (ret < 0) {
4227         error_report_err(err);
4228         goto out;
4229     }
4230 
4231 out:
4232     qemu_progress_end();
4233 
4234 out_no_progress:
4235     blk_unref(blk);
4236     qemu_opts_del(opts);
4237     qemu_opts_free(create_opts);
4238     g_free(options);
4239 
4240     if (ret) {
4241         return 1;
4242     }
4243     return 0;
4244 }
4245 
4246 typedef struct BenchData {
4247     BlockBackend *blk;
4248     uint64_t image_size;
4249     bool write;
4250     int bufsize;
4251     int step;
4252     int nrreq;
4253     int n;
4254     int flush_interval;
4255     bool drain_on_flush;
4256     uint8_t *buf;
4257     QEMUIOVector *qiov;
4258 
4259     int in_flight;
4260     bool in_flush;
4261     uint64_t offset;
4262 } BenchData;
4263 
4264 static void bench_undrained_flush_cb(void *opaque, int ret)
4265 {
4266     if (ret < 0) {
4267         error_report("Failed flush request: %s", strerror(-ret));
4268         exit(EXIT_FAILURE);
4269     }
4270 }
4271 
4272 static void bench_cb(void *opaque, int ret)
4273 {
4274     BenchData *b = opaque;
4275     BlockAIOCB *acb;
4276 
4277     if (ret < 0) {
4278         error_report("Failed request: %s", strerror(-ret));
4279         exit(EXIT_FAILURE);
4280     }
4281 
4282     if (b->in_flush) {
4283         /* Just finished a flush with drained queue: Start next requests */
4284         assert(b->in_flight == 0);
4285         b->in_flush = false;
4286     } else if (b->in_flight > 0) {
4287         int remaining = b->n - b->in_flight;
4288 
4289         b->n--;
4290         b->in_flight--;
4291 
4292         /* Time for flush? Drain queue if requested, then flush */
4293         if (b->flush_interval && remaining % b->flush_interval == 0) {
4294             if (!b->in_flight || !b->drain_on_flush) {
4295                 BlockCompletionFunc *cb;
4296 
4297                 if (b->drain_on_flush) {
4298                     b->in_flush = true;
4299                     cb = bench_cb;
4300                 } else {
4301                     cb = bench_undrained_flush_cb;
4302                 }
4303 
4304                 acb = blk_aio_flush(b->blk, cb, b);
4305                 if (!acb) {
4306                     error_report("Failed to issue flush request");
4307                     exit(EXIT_FAILURE);
4308                 }
4309             }
4310             if (b->drain_on_flush) {
4311                 return;
4312             }
4313         }
4314     }
4315 
4316     while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4317         int64_t offset = b->offset;
4318         /* blk_aio_* might look for completed I/Os and kick bench_cb
4319          * again, so make sure this operation is counted by in_flight
4320          * and b->offset is ready for the next submission.
4321          */
4322         b->in_flight++;
4323         b->offset += b->step;
4324         b->offset %= b->image_size;
4325         if (b->write) {
4326             acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4327         } else {
4328             acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4329         }
4330         if (!acb) {
4331             error_report("Failed to issue request");
4332             exit(EXIT_FAILURE);
4333         }
4334     }
4335 }
4336 
4337 static int img_bench(int argc, char **argv)
4338 {
4339     int c, ret = 0;
4340     const char *fmt = NULL, *filename;
4341     bool quiet = false;
4342     bool image_opts = false;
4343     bool is_write = false;
4344     int count = 75000;
4345     int depth = 64;
4346     int64_t offset = 0;
4347     size_t bufsize = 4096;
4348     int pattern = 0;
4349     size_t step = 0;
4350     int flush_interval = 0;
4351     bool drain_on_flush = true;
4352     int64_t image_size;
4353     BlockBackend *blk = NULL;
4354     BenchData data = {};
4355     int flags = 0;
4356     bool writethrough = false;
4357     struct timeval t1, t2;
4358     int i;
4359     bool force_share = false;
4360     size_t buf_size;
4361 
4362     for (;;) {
4363         static const struct option long_options[] = {
4364             {"help", no_argument, 0, 'h'},
4365             {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4366             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4367             {"pattern", required_argument, 0, OPTION_PATTERN},
4368             {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4369             {"force-share", no_argument, 0, 'U'},
4370             {0, 0, 0, 0}
4371         };
4372         c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4373                         NULL);
4374         if (c == -1) {
4375             break;
4376         }
4377 
4378         switch (c) {
4379         case ':':
4380             missing_argument(argv[optind - 1]);
4381             break;
4382         case '?':
4383             unrecognized_option(argv[optind - 1]);
4384             break;
4385         case 'h':
4386             help();
4387             break;
4388         case 'c':
4389         {
4390             unsigned long res;
4391 
4392             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4393                 error_report("Invalid request count specified");
4394                 return 1;
4395             }
4396             count = res;
4397             break;
4398         }
4399         case 'd':
4400         {
4401             unsigned long res;
4402 
4403             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4404                 error_report("Invalid queue depth specified");
4405                 return 1;
4406             }
4407             depth = res;
4408             break;
4409         }
4410         case 'f':
4411             fmt = optarg;
4412             break;
4413         case 'n':
4414             flags |= BDRV_O_NATIVE_AIO;
4415             break;
4416         case 'i':
4417             ret = bdrv_parse_aio(optarg, &flags);
4418             if (ret < 0) {
4419                 error_report("Invalid aio option: %s", optarg);
4420                 ret = -1;
4421                 goto out;
4422             }
4423             break;
4424         case 'o':
4425         {
4426             offset = cvtnum("offset", optarg);
4427             if (offset < 0) {
4428                 return 1;
4429             }
4430             break;
4431         }
4432             break;
4433         case 'q':
4434             quiet = true;
4435             break;
4436         case 's':
4437         {
4438             int64_t sval;
4439 
4440             sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4441             if (sval < 0) {
4442                 return 1;
4443             }
4444 
4445             bufsize = sval;
4446             break;
4447         }
4448         case 'S':
4449         {
4450             int64_t sval;
4451 
4452             sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4453             if (sval < 0) {
4454                 return 1;
4455             }
4456 
4457             step = sval;
4458             break;
4459         }
4460         case 't':
4461             ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4462             if (ret < 0) {
4463                 error_report("Invalid cache mode");
4464                 ret = -1;
4465                 goto out;
4466             }
4467             break;
4468         case 'w':
4469             flags |= BDRV_O_RDWR;
4470             is_write = true;
4471             break;
4472         case 'U':
4473             force_share = true;
4474             break;
4475         case OPTION_PATTERN:
4476         {
4477             unsigned long res;
4478 
4479             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4480                 error_report("Invalid pattern byte specified");
4481                 return 1;
4482             }
4483             pattern = res;
4484             break;
4485         }
4486         case OPTION_FLUSH_INTERVAL:
4487         {
4488             unsigned long res;
4489 
4490             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4491                 error_report("Invalid flush interval specified");
4492                 return 1;
4493             }
4494             flush_interval = res;
4495             break;
4496         }
4497         case OPTION_NO_DRAIN:
4498             drain_on_flush = false;
4499             break;
4500         case OPTION_IMAGE_OPTS:
4501             image_opts = true;
4502             break;
4503         }
4504     }
4505 
4506     if (optind != argc - 1) {
4507         error_exit("Expecting one image file name");
4508     }
4509     filename = argv[argc - 1];
4510 
4511     if (!is_write && flush_interval) {
4512         error_report("--flush-interval is only available in write tests");
4513         ret = -1;
4514         goto out;
4515     }
4516     if (flush_interval && flush_interval < depth) {
4517         error_report("Flush interval can't be smaller than depth");
4518         ret = -1;
4519         goto out;
4520     }
4521 
4522     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4523                    force_share);
4524     if (!blk) {
4525         ret = -1;
4526         goto out;
4527     }
4528 
4529     image_size = blk_getlength(blk);
4530     if (image_size < 0) {
4531         ret = image_size;
4532         goto out;
4533     }
4534 
4535     data = (BenchData) {
4536         .blk            = blk,
4537         .image_size     = image_size,
4538         .bufsize        = bufsize,
4539         .step           = step ?: bufsize,
4540         .nrreq          = depth,
4541         .n              = count,
4542         .offset         = offset,
4543         .write          = is_write,
4544         .flush_interval = flush_interval,
4545         .drain_on_flush = drain_on_flush,
4546     };
4547     printf("Sending %d %s requests, %d bytes each, %d in parallel "
4548            "(starting at offset %" PRId64 ", step size %d)\n",
4549            data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4550            data.offset, data.step);
4551     if (flush_interval) {
4552         printf("Sending flush every %d requests\n", flush_interval);
4553     }
4554 
4555     buf_size = data.nrreq * data.bufsize;
4556     data.buf = blk_blockalign(blk, buf_size);
4557     memset(data.buf, pattern, data.nrreq * data.bufsize);
4558 
4559     blk_register_buf(blk, data.buf, buf_size);
4560 
4561     data.qiov = g_new(QEMUIOVector, data.nrreq);
4562     for (i = 0; i < data.nrreq; i++) {
4563         qemu_iovec_init(&data.qiov[i], 1);
4564         qemu_iovec_add(&data.qiov[i],
4565                        data.buf + i * data.bufsize, data.bufsize);
4566     }
4567 
4568     gettimeofday(&t1, NULL);
4569     bench_cb(&data, 0);
4570 
4571     while (data.n > 0) {
4572         main_loop_wait(false);
4573     }
4574     gettimeofday(&t2, NULL);
4575 
4576     printf("Run completed in %3.3f seconds.\n",
4577            (t2.tv_sec - t1.tv_sec)
4578            + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4579 
4580 out:
4581     if (data.buf) {
4582         blk_unregister_buf(blk, data.buf);
4583     }
4584     qemu_vfree(data.buf);
4585     blk_unref(blk);
4586 
4587     if (ret) {
4588         return 1;
4589     }
4590     return 0;
4591 }
4592 
4593 enum ImgBitmapAct {
4594     BITMAP_ADD,
4595     BITMAP_REMOVE,
4596     BITMAP_CLEAR,
4597     BITMAP_ENABLE,
4598     BITMAP_DISABLE,
4599     BITMAP_MERGE,
4600 };
4601 typedef struct ImgBitmapAction {
4602     enum ImgBitmapAct act;
4603     const char *src; /* only used for merge */
4604     QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4605 } ImgBitmapAction;
4606 
4607 static int img_bitmap(int argc, char **argv)
4608 {
4609     Error *err = NULL;
4610     int c, ret = 1;
4611     QemuOpts *opts = NULL;
4612     const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4613     const char *filename, *bitmap;
4614     BlockBackend *blk = NULL, *src = NULL;
4615     BlockDriverState *bs = NULL, *src_bs = NULL;
4616     bool image_opts = false;
4617     int64_t granularity = 0;
4618     bool add = false, merge = false;
4619     QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4620     ImgBitmapAction *act, *act_next;
4621     const char *op;
4622 
4623     QSIMPLEQ_INIT(&actions);
4624 
4625     for (;;) {
4626         static const struct option long_options[] = {
4627             {"help", no_argument, 0, 'h'},
4628             {"object", required_argument, 0, OPTION_OBJECT},
4629             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4630             {"add", no_argument, 0, OPTION_ADD},
4631             {"remove", no_argument, 0, OPTION_REMOVE},
4632             {"clear", no_argument, 0, OPTION_CLEAR},
4633             {"enable", no_argument, 0, OPTION_ENABLE},
4634             {"disable", no_argument, 0, OPTION_DISABLE},
4635             {"merge", required_argument, 0, OPTION_MERGE},
4636             {"granularity", required_argument, 0, 'g'},
4637             {"source-file", required_argument, 0, 'b'},
4638             {"source-format", required_argument, 0, 'F'},
4639             {0, 0, 0, 0}
4640         };
4641         c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4642         if (c == -1) {
4643             break;
4644         }
4645 
4646         switch (c) {
4647         case ':':
4648             missing_argument(argv[optind - 1]);
4649             break;
4650         case '?':
4651             unrecognized_option(argv[optind - 1]);
4652             break;
4653         case 'h':
4654             help();
4655             break;
4656         case 'b':
4657             src_filename = optarg;
4658             break;
4659         case 'f':
4660             fmt = optarg;
4661             break;
4662         case 'F':
4663             src_fmt = optarg;
4664             break;
4665         case 'g':
4666             granularity = cvtnum("granularity", optarg);
4667             if (granularity < 0) {
4668                 return 1;
4669             }
4670             break;
4671         case OPTION_ADD:
4672             act = g_new0(ImgBitmapAction, 1);
4673             act->act = BITMAP_ADD;
4674             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4675             add = true;
4676             break;
4677         case OPTION_REMOVE:
4678             act = g_new0(ImgBitmapAction, 1);
4679             act->act = BITMAP_REMOVE;
4680             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4681             break;
4682         case OPTION_CLEAR:
4683             act = g_new0(ImgBitmapAction, 1);
4684             act->act = BITMAP_CLEAR;
4685             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4686             break;
4687         case OPTION_ENABLE:
4688             act = g_new0(ImgBitmapAction, 1);
4689             act->act = BITMAP_ENABLE;
4690             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4691             break;
4692         case OPTION_DISABLE:
4693             act = g_new0(ImgBitmapAction, 1);
4694             act->act = BITMAP_DISABLE;
4695             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4696             break;
4697         case OPTION_MERGE:
4698             act = g_new0(ImgBitmapAction, 1);
4699             act->act = BITMAP_MERGE;
4700             act->src = optarg;
4701             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4702             merge = true;
4703             break;
4704         case OPTION_OBJECT:
4705             opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4706             if (!opts) {
4707                 goto out;
4708             }
4709             break;
4710         case OPTION_IMAGE_OPTS:
4711             image_opts = true;
4712             break;
4713         }
4714     }
4715 
4716     if (qemu_opts_foreach(&qemu_object_opts,
4717                           user_creatable_add_opts_foreach,
4718                           qemu_img_object_print_help, &error_fatal)) {
4719         goto out;
4720     }
4721 
4722     if (QSIMPLEQ_EMPTY(&actions)) {
4723         error_report("Need at least one of --add, --remove, --clear, "
4724                      "--enable, --disable, or --merge");
4725         goto out;
4726     }
4727 
4728     if (granularity && !add) {
4729         error_report("granularity only supported with --add");
4730         goto out;
4731     }
4732     if (src_fmt && !src_filename) {
4733         error_report("-F only supported with -b");
4734         goto out;
4735     }
4736     if (src_filename && !merge) {
4737         error_report("Merge bitmap source file only supported with "
4738                      "--merge");
4739         goto out;
4740     }
4741 
4742     if (optind != argc - 2) {
4743         error_report("Expecting filename and bitmap name");
4744         goto out;
4745     }
4746 
4747     filename = argv[optind];
4748     bitmap = argv[optind + 1];
4749 
4750     blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4751                    false);
4752     if (!blk) {
4753         goto out;
4754     }
4755     bs = blk_bs(blk);
4756     if (src_filename) {
4757         src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4758         if (!src) {
4759             goto out;
4760         }
4761         src_bs = blk_bs(src);
4762     } else {
4763         src_bs = bs;
4764     }
4765 
4766     QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4767         switch (act->act) {
4768         case BITMAP_ADD:
4769             qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4770                                        !!granularity, granularity, true, true,
4771                                        false, false, &err);
4772             op = "add";
4773             break;
4774         case BITMAP_REMOVE:
4775             qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4776             op = "remove";
4777             break;
4778         case BITMAP_CLEAR:
4779             qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4780             op = "clear";
4781             break;
4782         case BITMAP_ENABLE:
4783             qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4784             op = "enable";
4785             break;
4786         case BITMAP_DISABLE:
4787             qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4788             op = "disable";
4789             break;
4790         case BITMAP_MERGE:
4791             do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4792                                   act->src, &err);
4793             op = "merge";
4794             break;
4795         default:
4796             g_assert_not_reached();
4797         }
4798 
4799         if (err) {
4800             error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4801                               op, bitmap);
4802             goto out;
4803         }
4804         g_free(act);
4805     }
4806 
4807     ret = 0;
4808 
4809  out:
4810     blk_unref(src);
4811     blk_unref(blk);
4812     qemu_opts_del(opts);
4813     return ret;
4814 }
4815 
4816 #define C_BS      01
4817 #define C_COUNT   02
4818 #define C_IF      04
4819 #define C_OF      010
4820 #define C_SKIP    020
4821 
4822 struct DdInfo {
4823     unsigned int flags;
4824     int64_t count;
4825 };
4826 
4827 struct DdIo {
4828     int bsz;    /* Block size */
4829     char *filename;
4830     uint8_t *buf;
4831     int64_t offset;
4832 };
4833 
4834 struct DdOpts {
4835     const char *name;
4836     int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4837     unsigned int flag;
4838 };
4839 
4840 static int img_dd_bs(const char *arg,
4841                      struct DdIo *in, struct DdIo *out,
4842                      struct DdInfo *dd)
4843 {
4844     int64_t res;
4845 
4846     res = cvtnum_full("bs", arg, 1, INT_MAX);
4847 
4848     if (res < 0) {
4849         return 1;
4850     }
4851     in->bsz = out->bsz = res;
4852 
4853     return 0;
4854 }
4855 
4856 static int img_dd_count(const char *arg,
4857                         struct DdIo *in, struct DdIo *out,
4858                         struct DdInfo *dd)
4859 {
4860     dd->count = cvtnum("count", arg);
4861 
4862     if (dd->count < 0) {
4863         return 1;
4864     }
4865 
4866     return 0;
4867 }
4868 
4869 static int img_dd_if(const char *arg,
4870                      struct DdIo *in, struct DdIo *out,
4871                      struct DdInfo *dd)
4872 {
4873     in->filename = g_strdup(arg);
4874 
4875     return 0;
4876 }
4877 
4878 static int img_dd_of(const char *arg,
4879                      struct DdIo *in, struct DdIo *out,
4880                      struct DdInfo *dd)
4881 {
4882     out->filename = g_strdup(arg);
4883 
4884     return 0;
4885 }
4886 
4887 static int img_dd_skip(const char *arg,
4888                        struct DdIo *in, struct DdIo *out,
4889                        struct DdInfo *dd)
4890 {
4891     in->offset = cvtnum("skip", arg);
4892 
4893     if (in->offset < 0) {
4894         return 1;
4895     }
4896 
4897     return 0;
4898 }
4899 
4900 static int img_dd(int argc, char **argv)
4901 {
4902     int ret = 0;
4903     char *arg = NULL;
4904     char *tmp;
4905     BlockDriver *drv = NULL, *proto_drv = NULL;
4906     BlockBackend *blk1 = NULL, *blk2 = NULL;
4907     QemuOpts *opts = NULL;
4908     QemuOptsList *create_opts = NULL;
4909     Error *local_err = NULL;
4910     bool image_opts = false;
4911     int c, i;
4912     const char *out_fmt = "raw";
4913     const char *fmt = NULL;
4914     int64_t size = 0;
4915     int64_t block_count = 0, out_pos, in_pos;
4916     bool force_share = false;
4917     struct DdInfo dd = {
4918         .flags = 0,
4919         .count = 0,
4920     };
4921     struct DdIo in = {
4922         .bsz = 512, /* Block size is by default 512 bytes */
4923         .filename = NULL,
4924         .buf = NULL,
4925         .offset = 0
4926     };
4927     struct DdIo out = {
4928         .bsz = 512,
4929         .filename = NULL,
4930         .buf = NULL,
4931         .offset = 0
4932     };
4933 
4934     const struct DdOpts options[] = {
4935         { "bs", img_dd_bs, C_BS },
4936         { "count", img_dd_count, C_COUNT },
4937         { "if", img_dd_if, C_IF },
4938         { "of", img_dd_of, C_OF },
4939         { "skip", img_dd_skip, C_SKIP },
4940         { NULL, NULL, 0 }
4941     };
4942     const struct option long_options[] = {
4943         { "help", no_argument, 0, 'h'},
4944         { "object", required_argument, 0, OPTION_OBJECT},
4945         { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4946         { "force-share", no_argument, 0, 'U'},
4947         { 0, 0, 0, 0 }
4948     };
4949 
4950     while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4951         if (c == EOF) {
4952             break;
4953         }
4954         switch (c) {
4955         case 'O':
4956             out_fmt = optarg;
4957             break;
4958         case 'f':
4959             fmt = optarg;
4960             break;
4961         case ':':
4962             missing_argument(argv[optind - 1]);
4963             break;
4964         case '?':
4965             unrecognized_option(argv[optind - 1]);
4966             break;
4967         case 'h':
4968             help();
4969             break;
4970         case 'U':
4971             force_share = true;
4972             break;
4973         case OPTION_OBJECT:
4974             if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4975                 ret = -1;
4976                 goto out;
4977             }
4978             break;
4979         case OPTION_IMAGE_OPTS:
4980             image_opts = true;
4981             break;
4982         }
4983     }
4984 
4985     for (i = optind; i < argc; i++) {
4986         int j;
4987         arg = g_strdup(argv[i]);
4988 
4989         tmp = strchr(arg, '=');
4990         if (tmp == NULL) {
4991             error_report("unrecognized operand %s", arg);
4992             ret = -1;
4993             goto out;
4994         }
4995 
4996         *tmp++ = '\0';
4997 
4998         for (j = 0; options[j].name != NULL; j++) {
4999             if (!strcmp(arg, options[j].name)) {
5000                 break;
5001             }
5002         }
5003         if (options[j].name == NULL) {
5004             error_report("unrecognized operand %s", arg);
5005             ret = -1;
5006             goto out;
5007         }
5008 
5009         if (options[j].f(tmp, &in, &out, &dd) != 0) {
5010             ret = -1;
5011             goto out;
5012         }
5013         dd.flags |= options[j].flag;
5014         g_free(arg);
5015         arg = NULL;
5016     }
5017 
5018     if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5019         error_report("Must specify both input and output files");
5020         ret = -1;
5021         goto out;
5022     }
5023 
5024     if (qemu_opts_foreach(&qemu_object_opts,
5025                           user_creatable_add_opts_foreach,
5026                           qemu_img_object_print_help, &error_fatal)) {
5027         ret = -1;
5028         goto out;
5029     }
5030 
5031     blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5032                     force_share);
5033 
5034     if (!blk1) {
5035         ret = -1;
5036         goto out;
5037     }
5038 
5039     drv = bdrv_find_format(out_fmt);
5040     if (!drv) {
5041         error_report("Unknown file format");
5042         ret = -1;
5043         goto out;
5044     }
5045     proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5046 
5047     if (!proto_drv) {
5048         error_report_err(local_err);
5049         ret = -1;
5050         goto out;
5051     }
5052     if (!drv->create_opts) {
5053         error_report("Format driver '%s' does not support image creation",
5054                      drv->format_name);
5055         ret = -1;
5056         goto out;
5057     }
5058     if (!proto_drv->create_opts) {
5059         error_report("Protocol driver '%s' does not support image creation",
5060                      proto_drv->format_name);
5061         ret = -1;
5062         goto out;
5063     }
5064     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5065     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5066 
5067     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5068 
5069     size = blk_getlength(blk1);
5070     if (size < 0) {
5071         error_report("Failed to get size for '%s'", in.filename);
5072         ret = -1;
5073         goto out;
5074     }
5075 
5076     if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5077         dd.count * in.bsz < size) {
5078         size = dd.count * in.bsz;
5079     }
5080 
5081     /* Overflow means the specified offset is beyond input image's size */
5082     if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5083                               size < in.bsz * in.offset)) {
5084         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5085     } else {
5086         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5087                             size - in.bsz * in.offset, &error_abort);
5088     }
5089 
5090     ret = bdrv_create(drv, out.filename, opts, &local_err);
5091     if (ret < 0) {
5092         error_reportf_err(local_err,
5093                           "%s: error while creating output image: ",
5094                           out.filename);
5095         ret = -1;
5096         goto out;
5097     }
5098 
5099     /* TODO, we can't honour --image-opts for the target,
5100      * since it needs to be given in a format compatible
5101      * with the bdrv_create() call above which does not
5102      * support image-opts style.
5103      */
5104     blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5105                          false, false, false);
5106 
5107     if (!blk2) {
5108         ret = -1;
5109         goto out;
5110     }
5111 
5112     if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5113                               size < in.offset * in.bsz)) {
5114         /* We give a warning if the skip option is bigger than the input
5115          * size and create an empty output disk image (i.e. like dd(1)).
5116          */
5117         error_report("%s: cannot skip to specified offset", in.filename);
5118         in_pos = size;
5119     } else {
5120         in_pos = in.offset * in.bsz;
5121     }
5122 
5123     in.buf = g_new(uint8_t, in.bsz);
5124 
5125     for (out_pos = 0; in_pos < size; block_count++) {
5126         int in_ret, out_ret;
5127 
5128         if (in_pos + in.bsz > size) {
5129             in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5130         } else {
5131             in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5132         }
5133         if (in_ret < 0) {
5134             error_report("error while reading from input image file: %s",
5135                          strerror(-in_ret));
5136             ret = -1;
5137             goto out;
5138         }
5139         in_pos += in_ret;
5140 
5141         out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5142 
5143         if (out_ret < 0) {
5144             error_report("error while writing to output image file: %s",
5145                          strerror(-out_ret));
5146             ret = -1;
5147             goto out;
5148         }
5149         out_pos += out_ret;
5150     }
5151 
5152 out:
5153     g_free(arg);
5154     qemu_opts_del(opts);
5155     qemu_opts_free(create_opts);
5156     blk_unref(blk1);
5157     blk_unref(blk2);
5158     g_free(in.filename);
5159     g_free(out.filename);
5160     g_free(in.buf);
5161     g_free(out.buf);
5162 
5163     if (ret) {
5164         return 1;
5165     }
5166     return 0;
5167 }
5168 
5169 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5170 {
5171     QString *str;
5172     QObject *obj;
5173     Visitor *v = qobject_output_visitor_new(&obj);
5174 
5175     visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5176     visit_complete(v, &obj);
5177     str = qobject_to_json_pretty(obj);
5178     assert(str != NULL);
5179     printf("%s\n", qstring_get_str(str));
5180     qobject_unref(obj);
5181     visit_free(v);
5182     qobject_unref(str);
5183 }
5184 
5185 static int img_measure(int argc, char **argv)
5186 {
5187     static const struct option long_options[] = {
5188         {"help", no_argument, 0, 'h'},
5189         {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5190         {"object", required_argument, 0, OPTION_OBJECT},
5191         {"output", required_argument, 0, OPTION_OUTPUT},
5192         {"size", required_argument, 0, OPTION_SIZE},
5193         {"force-share", no_argument, 0, 'U'},
5194         {0, 0, 0, 0}
5195     };
5196     OutputFormat output_format = OFORMAT_HUMAN;
5197     BlockBackend *in_blk = NULL;
5198     BlockDriver *drv;
5199     const char *filename = NULL;
5200     const char *fmt = NULL;
5201     const char *out_fmt = "raw";
5202     char *options = NULL;
5203     char *snapshot_name = NULL;
5204     bool force_share = false;
5205     QemuOpts *opts = NULL;
5206     QemuOpts *object_opts = NULL;
5207     QemuOpts *sn_opts = NULL;
5208     QemuOptsList *create_opts = NULL;
5209     bool image_opts = false;
5210     uint64_t img_size = UINT64_MAX;
5211     BlockMeasureInfo *info = NULL;
5212     Error *local_err = NULL;
5213     int ret = 1;
5214     int c;
5215 
5216     while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5217                             long_options, NULL)) != -1) {
5218         switch (c) {
5219         case '?':
5220         case 'h':
5221             help();
5222             break;
5223         case 'f':
5224             fmt = optarg;
5225             break;
5226         case 'O':
5227             out_fmt = optarg;
5228             break;
5229         case 'o':
5230             if (accumulate_options(&options, optarg) < 0) {
5231                 goto out;
5232             }
5233             break;
5234         case 'l':
5235             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5236                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5237                                                   optarg, false);
5238                 if (!sn_opts) {
5239                     error_report("Failed in parsing snapshot param '%s'",
5240                                  optarg);
5241                     goto out;
5242                 }
5243             } else {
5244                 snapshot_name = optarg;
5245             }
5246             break;
5247         case 'U':
5248             force_share = true;
5249             break;
5250         case OPTION_OBJECT:
5251             object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5252                                                   optarg, true);
5253             if (!object_opts) {
5254                 goto out;
5255             }
5256             break;
5257         case OPTION_IMAGE_OPTS:
5258             image_opts = true;
5259             break;
5260         case OPTION_OUTPUT:
5261             if (!strcmp(optarg, "json")) {
5262                 output_format = OFORMAT_JSON;
5263             } else if (!strcmp(optarg, "human")) {
5264                 output_format = OFORMAT_HUMAN;
5265             } else {
5266                 error_report("--output must be used with human or json "
5267                              "as argument.");
5268                 goto out;
5269             }
5270             break;
5271         case OPTION_SIZE:
5272         {
5273             int64_t sval;
5274 
5275             sval = cvtnum("image size", optarg);
5276             if (sval < 0) {
5277                 goto out;
5278             }
5279             img_size = (uint64_t)sval;
5280         }
5281         break;
5282         }
5283     }
5284 
5285     if (qemu_opts_foreach(&qemu_object_opts,
5286                           user_creatable_add_opts_foreach,
5287                           qemu_img_object_print_help, &error_fatal)) {
5288         goto out;
5289     }
5290 
5291     if (argc - optind > 1) {
5292         error_report("At most one filename argument is allowed.");
5293         goto out;
5294     } else if (argc - optind == 1) {
5295         filename = argv[optind];
5296     }
5297 
5298     if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5299         error_report("--image-opts, -f, and -l require a filename argument.");
5300         goto out;
5301     }
5302     if (filename && img_size != UINT64_MAX) {
5303         error_report("--size N cannot be used together with a filename.");
5304         goto out;
5305     }
5306     if (!filename && img_size == UINT64_MAX) {
5307         error_report("Either --size N or one filename must be specified.");
5308         goto out;
5309     }
5310 
5311     if (filename) {
5312         in_blk = img_open(image_opts, filename, fmt, 0,
5313                           false, false, force_share);
5314         if (!in_blk) {
5315             goto out;
5316         }
5317 
5318         if (sn_opts) {
5319             bdrv_snapshot_load_tmp(blk_bs(in_blk),
5320                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5321                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5322                     &local_err);
5323         } else if (snapshot_name != NULL) {
5324             bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5325                     snapshot_name, &local_err);
5326         }
5327         if (local_err) {
5328             error_reportf_err(local_err, "Failed to load snapshot: ");
5329             goto out;
5330         }
5331     }
5332 
5333     drv = bdrv_find_format(out_fmt);
5334     if (!drv) {
5335         error_report("Unknown file format '%s'", out_fmt);
5336         goto out;
5337     }
5338     if (!drv->create_opts) {
5339         error_report("Format driver '%s' does not support image creation",
5340                      drv->format_name);
5341         goto out;
5342     }
5343 
5344     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5345     create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5346     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5347     if (options) {
5348         qemu_opts_do_parse(opts, options, NULL, &local_err);
5349         if (local_err) {
5350             error_report_err(local_err);
5351             error_report("Invalid options for file format '%s'", out_fmt);
5352             goto out;
5353         }
5354     }
5355     if (img_size != UINT64_MAX) {
5356         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5357     }
5358 
5359     info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5360     if (local_err) {
5361         error_report_err(local_err);
5362         goto out;
5363     }
5364 
5365     if (output_format == OFORMAT_HUMAN) {
5366         printf("required size: %" PRIu64 "\n", info->required);
5367         printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5368         if (info->has_bitmaps) {
5369             printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5370         }
5371     } else {
5372         dump_json_block_measure_info(info);
5373     }
5374 
5375     ret = 0;
5376 
5377 out:
5378     qapi_free_BlockMeasureInfo(info);
5379     qemu_opts_del(object_opts);
5380     qemu_opts_del(opts);
5381     qemu_opts_del(sn_opts);
5382     qemu_opts_free(create_opts);
5383     g_free(options);
5384     blk_unref(in_blk);
5385     return ret;
5386 }
5387 
5388 static const img_cmd_t img_cmds[] = {
5389 #define DEF(option, callback, arg_string)        \
5390     { option, callback },
5391 #include "qemu-img-cmds.h"
5392 #undef DEF
5393     { NULL, NULL, },
5394 };
5395 
5396 int main(int argc, char **argv)
5397 {
5398     const img_cmd_t *cmd;
5399     const char *cmdname;
5400     Error *local_error = NULL;
5401     char *trace_file = NULL;
5402     int c;
5403     static const struct option long_options[] = {
5404         {"help", no_argument, 0, 'h'},
5405         {"version", no_argument, 0, 'V'},
5406         {"trace", required_argument, NULL, 'T'},
5407         {0, 0, 0, 0}
5408     };
5409 
5410 #ifdef CONFIG_POSIX
5411     signal(SIGPIPE, SIG_IGN);
5412 #endif
5413 
5414     error_init(argv[0]);
5415     module_call_init(MODULE_INIT_TRACE);
5416     qemu_init_exec_dir(argv[0]);
5417 
5418     if (qemu_init_main_loop(&local_error)) {
5419         error_report_err(local_error);
5420         exit(EXIT_FAILURE);
5421     }
5422 
5423     qcrypto_init(&error_fatal);
5424 
5425     module_call_init(MODULE_INIT_QOM);
5426     bdrv_init();
5427     if (argc < 2) {
5428         error_exit("Not enough arguments");
5429     }
5430 
5431     qemu_add_opts(&qemu_object_opts);
5432     qemu_add_opts(&qemu_source_opts);
5433     qemu_add_opts(&qemu_trace_opts);
5434 
5435     while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5436         switch (c) {
5437         case ':':
5438             missing_argument(argv[optind - 1]);
5439             return 0;
5440         case '?':
5441             unrecognized_option(argv[optind - 1]);
5442             return 0;
5443         case 'h':
5444             help();
5445             return 0;
5446         case 'V':
5447             printf(QEMU_IMG_VERSION);
5448             return 0;
5449         case 'T':
5450             g_free(trace_file);
5451             trace_file = trace_opt_parse(optarg);
5452             break;
5453         }
5454     }
5455 
5456     cmdname = argv[optind];
5457 
5458     /* reset getopt_long scanning */
5459     argc -= optind;
5460     if (argc < 1) {
5461         return 0;
5462     }
5463     argv += optind;
5464     qemu_reset_optind();
5465 
5466     if (!trace_init_backends()) {
5467         exit(1);
5468     }
5469     trace_init_file(trace_file);
5470     qemu_set_log(LOG_TRACE);
5471 
5472     /* find the command */
5473     for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5474         if (!strcmp(cmdname, cmd->name)) {
5475             return cmd->handler(argc, argv);
5476         }
5477     }
5478 
5479     /* not found */
5480     error_exit("Command not found: %s", cmdname);
5481 }
5482