]> Git Repo - qemu.git/blob - qemu-img.c
qemu-option: Use returned bool to check for failure
[qemu.git] / qemu-img.c
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     OPTION_FORCE = 276,
83 };
84
85 typedef enum OutputFormat {
86     OFORMAT_JSON,
87     OFORMAT_HUMAN,
88 } OutputFormat;
89
90 /* Default to cache=writeback as data integrity is not important for qemu-img */
91 #define BDRV_DEFAULT_CACHE "writeback"
92
93 static void format_print(void *opaque, const char *name)
94 {
95     printf(" %s", name);
96 }
97
98 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
99 {
100     va_list ap;
101
102     va_start(ap, fmt);
103     error_vreport(fmt, ap);
104     va_end(ap);
105
106     error_printf("Try 'qemu-img --help' for more information\n");
107     exit(EXIT_FAILURE);
108 }
109
110 static void QEMU_NORETURN missing_argument(const char *option)
111 {
112     error_exit("missing argument for option '%s'", option);
113 }
114
115 static void QEMU_NORETURN unrecognized_option(const char *option)
116 {
117     error_exit("unrecognized option '%s'", option);
118 }
119
120 /* Please keep in synch with docs/tools/qemu-img.rst */
121 static void QEMU_NORETURN help(void)
122 {
123     const char *help_msg =
124            QEMU_IMG_VERSION
125            "usage: qemu-img [standard options] command [command options]\n"
126            "QEMU disk image utility\n"
127            "\n"
128            "    '-h', '--help'       display this help and exit\n"
129            "    '-V', '--version'    output version information and exit\n"
130            "    '-T', '--trace'      [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
131            "                         specify tracing options\n"
132            "\n"
133            "Command syntax:\n"
134 #define DEF(option, callback, arg_string)        \
135            "  " arg_string "\n"
136 #include "qemu-img-cmds.h"
137 #undef DEF
138            "\n"
139            "Command parameters:\n"
140            "  'filename' is a disk image filename\n"
141            "  'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
142            "    manual page for a description of the object properties. The most common\n"
143            "    object type is a 'secret', which is used to supply passwords and/or\n"
144            "    encryption keys.\n"
145            "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
146            "  'cache' is the cache mode used to write the output disk image, the valid\n"
147            "    options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
148            "    'directsync' and 'unsafe' (default for convert)\n"
149            "  'src_cache' is the cache mode used to read input disk images, the valid\n"
150            "    options are the same as for the 'cache' option\n"
151            "  'size' is the disk image size in bytes. Optional suffixes\n"
152            "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
153            "    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are\n"
154            "    supported. 'b' is ignored.\n"
155            "  'output_filename' is the destination disk image filename\n"
156            "  'output_fmt' is the destination format\n"
157            "  'options' is a comma separated list of format specific options in a\n"
158            "    name=value format. Use -o ? for an overview of the options supported by the\n"
159            "    used format\n"
160            "  'snapshot_param' is param used for internal snapshot, format\n"
161            "    is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
162            "    '[ID_OR_NAME]'\n"
163            "  '-c' indicates that target image must be compressed (qcow format only)\n"
164            "  '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
165            "       new backing file match exactly. The image doesn't need a working\n"
166            "       backing file before rebasing in this case (useful for renaming the\n"
167            "       backing file). For image creation, allow creating without attempting\n"
168            "       to open the backing file.\n"
169            "  '-h' with or without a command shows this help and lists the supported formats\n"
170            "  '-p' show progress of command (only certain commands)\n"
171            "  '-q' use Quiet mode - do not print any output (except errors)\n"
172            "  '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
173            "       contain only zeros for qemu-img to create a sparse image during\n"
174            "       conversion. If the number of bytes is 0, the source will not be scanned for\n"
175            "       unallocated or zero sectors, and the destination image will always be\n"
176            "       fully allocated\n"
177            "  '--output' takes the format in which the output must be done (human or json)\n"
178            "  '-n' skips the target volume creation (useful if the volume is created\n"
179            "       prior to running qemu-img)\n"
180            "\n"
181            "Parameters to bitmap subcommand:\n"
182            "  'bitmap' is the name of the bitmap to manipulate, through one or more\n"
183            "       actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
184            "       or '--merge source'\n"
185            "  '-g granularity' sets the granularity for '--add' actions\n"
186            "  '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
187            "       bitmaps from an alternative file\n"
188            "\n"
189            "Parameters to check subcommand:\n"
190            "  '-r' tries to repair any inconsistencies that are found during the check.\n"
191            "       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
192            "       kinds of errors, with a higher risk of choosing the wrong fix or\n"
193            "       hiding corruption that has already occurred.\n"
194            "\n"
195            "Parameters to convert subcommand:\n"
196            "  '--bitmaps' copies all top-level persistent bitmaps to destination\n"
197            "  '-m' specifies how many coroutines work in parallel during the convert\n"
198            "       process (defaults to 8)\n"
199            "  '-W' allow to write to the target out of order rather than sequential\n"
200            "\n"
201            "Parameters to snapshot subcommand:\n"
202            "  'snapshot' is the name of the snapshot to create, apply or delete\n"
203            "  '-a' applies a snapshot (revert disk to saved state)\n"
204            "  '-c' creates a snapshot\n"
205            "  '-d' deletes a snapshot\n"
206            "  '-l' lists all snapshots in the given image\n"
207            "\n"
208            "Parameters to compare subcommand:\n"
209            "  '-f' first image format\n"
210            "  '-F' second image format\n"
211            "  '-s' run in Strict mode - fail on different image size or sector allocation\n"
212            "\n"
213            "Parameters to dd subcommand:\n"
214            "  'bs=BYTES' read and write up to BYTES bytes at a time "
215            "(default: 512)\n"
216            "  'count=N' copy only N input blocks\n"
217            "  'if=FILE' read from FILE\n"
218            "  'of=FILE' write to FILE\n"
219            "  'skip=N' skip N bs-sized blocks at the start of input\n";
220
221     printf("%s\nSupported formats:", help_msg);
222     bdrv_iterate_format(format_print, NULL, false);
223     printf("\n\n" QEMU_HELP_BOTTOM "\n");
224     exit(EXIT_SUCCESS);
225 }
226
227 static QemuOptsList qemu_object_opts = {
228     .name = "object",
229     .implied_opt_name = "qom-type",
230     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
231     .desc = {
232         { }
233     },
234 };
235
236 static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
237 {
238     if (user_creatable_print_help(type, opts)) {
239         exit(0);
240     }
241     return true;
242 }
243
244 /*
245  * Is @optarg safe for accumulate_options()?
246  * It is when multiple of them can be joined together separated by ','.
247  * To make that work, @optarg must not start with ',' (or else a
248  * separating ',' preceding it gets escaped), and it must not end with
249  * an odd number of ',' (or else a separating ',' following it gets
250  * escaped), or be empty (or else a separating ',' preceding it can
251  * escape a separating ',' following it).
252  * 
253  */
254 static bool is_valid_option_list(const char *optarg)
255 {
256     size_t len = strlen(optarg);
257     size_t i;
258
259     if (!optarg[0] || optarg[0] == ',') {
260         return false;
261     }
262
263     for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
264     }
265     if ((len - i) % 2) {
266         return false;
267     }
268
269     return true;
270 }
271
272 static int accumulate_options(char **options, char *optarg)
273 {
274     char *new_options;
275
276     if (!is_valid_option_list(optarg)) {
277         error_report("Invalid option list: %s", optarg);
278         return -1;
279     }
280
281     if (!*options) {
282         *options = g_strdup(optarg);
283     } else {
284         new_options = g_strdup_printf("%s,%s", *options, optarg);
285         g_free(*options);
286         *options = new_options;
287     }
288     return 0;
289 }
290
291 static QemuOptsList qemu_source_opts = {
292     .name = "source",
293     .implied_opt_name = "file",
294     .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
295     .desc = {
296         { }
297     },
298 };
299
300 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
301 {
302     int ret = 0;
303     if (!quiet) {
304         va_list args;
305         va_start(args, fmt);
306         ret = vprintf(fmt, args);
307         va_end(args);
308     }
309     return ret;
310 }
311
312
313 static int print_block_option_help(const char *filename, const char *fmt)
314 {
315     BlockDriver *drv, *proto_drv;
316     QemuOptsList *create_opts = NULL;
317     Error *local_err = NULL;
318
319     /* Find driver and parse its options */
320     drv = bdrv_find_format(fmt);
321     if (!drv) {
322         error_report("Unknown file format '%s'", fmt);
323         return 1;
324     }
325
326     if (!drv->create_opts) {
327         error_report("Format driver '%s' does not support image creation", fmt);
328         return 1;
329     }
330
331     create_opts = qemu_opts_append(create_opts, drv->create_opts);
332     if (filename) {
333         proto_drv = bdrv_find_protocol(filename, true, &local_err);
334         if (!proto_drv) {
335             error_report_err(local_err);
336             qemu_opts_free(create_opts);
337             return 1;
338         }
339         if (!proto_drv->create_opts) {
340             error_report("Protocol driver '%s' does not support image creation",
341                          proto_drv->format_name);
342             qemu_opts_free(create_opts);
343             return 1;
344         }
345         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
346     }
347
348     if (filename) {
349         printf("Supported options:\n");
350     } else {
351         printf("Supported %s options:\n", fmt);
352     }
353     qemu_opts_print_help(create_opts, false);
354     qemu_opts_free(create_opts);
355
356     if (!filename) {
357         printf("\n"
358                "The protocol level may support further options.\n"
359                "Specify the target filename to include those options.\n");
360     }
361
362     return 0;
363 }
364
365
366 static BlockBackend *img_open_opts(const char *optstr,
367                                    QemuOpts *opts, int flags, bool writethrough,
368                                    bool quiet, bool force_share)
369 {
370     QDict *options;
371     Error *local_err = NULL;
372     BlockBackend *blk;
373     options = qemu_opts_to_qdict(opts, NULL);
374     if (force_share) {
375         if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
376             && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
377             error_report("--force-share/-U conflicts with image options");
378             qobject_unref(options);
379             return NULL;
380         }
381         qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
382     }
383     blk = blk_new_open(NULL, NULL, options, flags, &local_err);
384     if (!blk) {
385         error_reportf_err(local_err, "Could not open '%s': ", optstr);
386         return NULL;
387     }
388     blk_set_enable_write_cache(blk, !writethrough);
389
390     return blk;
391 }
392
393 static BlockBackend *img_open_file(const char *filename,
394                                    QDict *options,
395                                    const char *fmt, int flags,
396                                    bool writethrough, bool quiet,
397                                    bool force_share)
398 {
399     BlockBackend *blk;
400     Error *local_err = NULL;
401
402     if (!options) {
403         options = qdict_new();
404     }
405     if (fmt) {
406         qdict_put_str(options, "driver", fmt);
407     }
408
409     if (force_share) {
410         qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
411     }
412     blk = blk_new_open(filename, NULL, options, flags, &local_err);
413     if (!blk) {
414         error_reportf_err(local_err, "Could not open '%s': ", filename);
415         return NULL;
416     }
417     blk_set_enable_write_cache(blk, !writethrough);
418
419     return blk;
420 }
421
422
423 static int img_add_key_secrets(void *opaque,
424                                const char *name, const char *value,
425                                Error **errp)
426 {
427     QDict *options = opaque;
428
429     if (g_str_has_suffix(name, "key-secret")) {
430         qdict_put_str(options, name, value);
431     }
432
433     return 0;
434 }
435
436
437 static BlockBackend *img_open(bool image_opts,
438                               const char *filename,
439                               const char *fmt, int flags, bool writethrough,
440                               bool quiet, bool force_share)
441 {
442     BlockBackend *blk;
443     if (image_opts) {
444         QemuOpts *opts;
445         if (fmt) {
446             error_report("--image-opts and --format are mutually exclusive");
447             return NULL;
448         }
449         opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
450                                        filename, true);
451         if (!opts) {
452             return NULL;
453         }
454         blk = img_open_opts(filename, opts, flags, writethrough, quiet,
455                             force_share);
456     } else {
457         blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
458                             force_share);
459     }
460     return blk;
461 }
462
463
464 static int add_old_style_options(const char *fmt, QemuOpts *opts,
465                                  const char *base_filename,
466                                  const char *base_fmt)
467 {
468     Error *err = NULL;
469
470     if (base_filename) {
471         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
472                           &err)) {
473             error_report("Backing file not supported for file format '%s'",
474                          fmt);
475             error_free(err);
476             return -1;
477         }
478     }
479     if (base_fmt) {
480         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &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 target_is_new;
1684     bool target_has_backing;
1685     int64_t target_backing_sectors; /* negative if unknown */
1686     bool wr_in_order;
1687     bool copy_range;
1688     bool salvage;
1689     bool quiet;
1690     int min_sparse;
1691     int alignment;
1692     size_t cluster_sectors;
1693     size_t buf_sectors;
1694     long num_coroutines;
1695     int running_coroutines;
1696     Coroutine *co[MAX_COROUTINES];
1697     int64_t wait_sector_num[MAX_COROUTINES];
1698     CoMutex lock;
1699     int ret;
1700 } ImgConvertState;
1701
1702 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1703                                 int *src_cur, int64_t *src_cur_offset)
1704 {
1705     *src_cur = 0;
1706     *src_cur_offset = 0;
1707     while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1708         *src_cur_offset += s->src_sectors[*src_cur];
1709         (*src_cur)++;
1710         assert(*src_cur < s->src_num);
1711     }
1712 }
1713
1714 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1715 {
1716     int64_t src_cur_offset;
1717     int ret, n, src_cur;
1718     bool post_backing_zero = false;
1719
1720     convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1721
1722     assert(s->total_sectors > sector_num);
1723     n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1724
1725     if (s->target_backing_sectors >= 0) {
1726         if (sector_num >= s->target_backing_sectors) {
1727             post_backing_zero = true;
1728         } else if (sector_num + n > s->target_backing_sectors) {
1729             /* Split requests around target_backing_sectors (because
1730              * starting from there, zeros are handled differently) */
1731             n = s->target_backing_sectors - sector_num;
1732         }
1733     }
1734
1735     if (s->sector_next_status <= sector_num) {
1736         uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1737         int64_t count;
1738
1739         do {
1740             count = n * BDRV_SECTOR_SIZE;
1741
1742             if (s->target_has_backing) {
1743                 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1744                                         count, &count, NULL, NULL);
1745             } else {
1746                 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1747                                               offset, count, &count, NULL,
1748                                               NULL);
1749             }
1750
1751             if (ret < 0) {
1752                 if (s->salvage) {
1753                     if (n == 1) {
1754                         if (!s->quiet) {
1755                             warn_report("error while reading block status at "
1756                                         "offset %" PRIu64 ": %s", offset,
1757                                         strerror(-ret));
1758                         }
1759                         /* Just try to read the data, then */
1760                         ret = BDRV_BLOCK_DATA;
1761                         count = BDRV_SECTOR_SIZE;
1762                     } else {
1763                         /* Retry on a shorter range */
1764                         n = DIV_ROUND_UP(n, 4);
1765                     }
1766                 } else {
1767                     error_report("error while reading block status at offset "
1768                                  "%" PRIu64 ": %s", offset, strerror(-ret));
1769                     return ret;
1770                 }
1771             }
1772         } while (ret < 0);
1773
1774         n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1775
1776         if (ret & BDRV_BLOCK_ZERO) {
1777             s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1778         } else if (ret & BDRV_BLOCK_DATA) {
1779             s->status = BLK_DATA;
1780         } else {
1781             s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1782         }
1783
1784         s->sector_next_status = sector_num + n;
1785     }
1786
1787     n = MIN(n, s->sector_next_status - sector_num);
1788     if (s->status == BLK_DATA) {
1789         n = MIN(n, s->buf_sectors);
1790     }
1791
1792     /* We need to write complete clusters for compressed images, so if an
1793      * unallocated area is shorter than that, we must consider the whole
1794      * cluster allocated. */
1795     if (s->compressed) {
1796         if (n < s->cluster_sectors) {
1797             n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1798             s->status = BLK_DATA;
1799         } else {
1800             n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1801         }
1802     }
1803
1804     return n;
1805 }
1806
1807 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1808                                         int nb_sectors, uint8_t *buf)
1809 {
1810     uint64_t single_read_until = 0;
1811     int n, ret;
1812
1813     assert(nb_sectors <= s->buf_sectors);
1814     while (nb_sectors > 0) {
1815         BlockBackend *blk;
1816         int src_cur;
1817         int64_t bs_sectors, src_cur_offset;
1818         uint64_t offset;
1819
1820         /* In the case of compression with multiple source files, we can get a
1821          * nb_sectors that spreads into the next part. So we must be able to
1822          * read across multiple BDSes for one convert_read() call. */
1823         convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1824         blk = s->src[src_cur];
1825         bs_sectors = s->src_sectors[src_cur];
1826
1827         offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1828
1829         n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1830         if (single_read_until > offset) {
1831             n = 1;
1832         }
1833
1834         ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1835         if (ret < 0) {
1836             if (s->salvage) {
1837                 if (n > 1) {
1838                     single_read_until = offset + (n << BDRV_SECTOR_BITS);
1839                     continue;
1840                 } else {
1841                     if (!s->quiet) {
1842                         warn_report("error while reading offset %" PRIu64
1843                                     ": %s", offset, strerror(-ret));
1844                     }
1845                     memset(buf, 0, BDRV_SECTOR_SIZE);
1846                 }
1847             } else {
1848                 return ret;
1849             }
1850         }
1851
1852         sector_num += n;
1853         nb_sectors -= n;
1854         buf += n * BDRV_SECTOR_SIZE;
1855     }
1856
1857     return 0;
1858 }
1859
1860
1861 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1862                                          int nb_sectors, uint8_t *buf,
1863                                          enum ImgConvertBlockStatus status)
1864 {
1865     int ret;
1866
1867     while (nb_sectors > 0) {
1868         int n = nb_sectors;
1869         BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1870
1871         switch (status) {
1872         case BLK_BACKING_FILE:
1873             /* If we have a backing file, leave clusters unallocated that are
1874              * unallocated in the source image, so that the backing file is
1875              * visible at the respective offset. */
1876             assert(s->target_has_backing);
1877             break;
1878
1879         case BLK_DATA:
1880             /* If we're told to keep the target fully allocated (-S 0) or there
1881              * is real non-zero data, we must write it. Otherwise we can treat
1882              * it as zero sectors.
1883              * Compressed clusters need to be written as a whole, so in that
1884              * case we can only save the write if the buffer is completely
1885              * zeroed. */
1886             if (!s->min_sparse ||
1887                 (!s->compressed &&
1888                  is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1889                                           sector_num, s->alignment)) ||
1890                 (s->compressed &&
1891                  !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1892             {
1893                 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1894                                     n << BDRV_SECTOR_BITS, buf, flags);
1895                 if (ret < 0) {
1896                     return ret;
1897                 }
1898                 break;
1899             }
1900             /* fall-through */
1901
1902         case BLK_ZERO:
1903             if (s->has_zero_init) {
1904                 assert(!s->target_has_backing);
1905                 break;
1906             }
1907             ret = blk_co_pwrite_zeroes(s->target,
1908                                        sector_num << BDRV_SECTOR_BITS,
1909                                        n << BDRV_SECTOR_BITS,
1910                                        BDRV_REQ_MAY_UNMAP);
1911             if (ret < 0) {
1912                 return ret;
1913             }
1914             break;
1915         }
1916
1917         sector_num += n;
1918         nb_sectors -= n;
1919         buf += n * BDRV_SECTOR_SIZE;
1920     }
1921
1922     return 0;
1923 }
1924
1925 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1926                                               int nb_sectors)
1927 {
1928     int n, ret;
1929
1930     while (nb_sectors > 0) {
1931         BlockBackend *blk;
1932         int src_cur;
1933         int64_t bs_sectors, src_cur_offset;
1934         int64_t offset;
1935
1936         convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1937         offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1938         blk = s->src[src_cur];
1939         bs_sectors = s->src_sectors[src_cur];
1940
1941         n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1942
1943         ret = blk_co_copy_range(blk, offset, s->target,
1944                                 sector_num << BDRV_SECTOR_BITS,
1945                                 n << BDRV_SECTOR_BITS, 0, 0);
1946         if (ret < 0) {
1947             return ret;
1948         }
1949
1950         sector_num += n;
1951         nb_sectors -= n;
1952     }
1953     return 0;
1954 }
1955
1956 static void coroutine_fn convert_co_do_copy(void *opaque)
1957 {
1958     ImgConvertState *s = opaque;
1959     uint8_t *buf = NULL;
1960     int ret, i;
1961     int index = -1;
1962
1963     for (i = 0; i < s->num_coroutines; i++) {
1964         if (s->co[i] == qemu_coroutine_self()) {
1965             index = i;
1966             break;
1967         }
1968     }
1969     assert(index >= 0);
1970
1971     s->running_coroutines++;
1972     buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1973
1974     while (1) {
1975         int n;
1976         int64_t sector_num;
1977         enum ImgConvertBlockStatus status;
1978         bool copy_range;
1979
1980         qemu_co_mutex_lock(&s->lock);
1981         if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1982             qemu_co_mutex_unlock(&s->lock);
1983             break;
1984         }
1985         n = convert_iteration_sectors(s, s->sector_num);
1986         if (n < 0) {
1987             qemu_co_mutex_unlock(&s->lock);
1988             s->ret = n;
1989             break;
1990         }
1991         /* save current sector and allocation status to local variables */
1992         sector_num = s->sector_num;
1993         status = s->status;
1994         if (!s->min_sparse && s->status == BLK_ZERO) {
1995             n = MIN(n, s->buf_sectors);
1996         }
1997         /* increment global sector counter so that other coroutines can
1998          * already continue reading beyond this request */
1999         s->sector_num += n;
2000         qemu_co_mutex_unlock(&s->lock);
2001
2002         if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2003             s->allocated_done += n;
2004             qemu_progress_print(100.0 * s->allocated_done /
2005                                         s->allocated_sectors, 0);
2006         }
2007
2008 retry:
2009         copy_range = s->copy_range && s->status == BLK_DATA;
2010         if (status == BLK_DATA && !copy_range) {
2011             ret = convert_co_read(s, sector_num, n, buf);
2012             if (ret < 0) {
2013                 error_report("error while reading at byte %lld: %s",
2014                              sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2015                 s->ret = ret;
2016             }
2017         } else if (!s->min_sparse && status == BLK_ZERO) {
2018             status = BLK_DATA;
2019             memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2020         }
2021
2022         if (s->wr_in_order) {
2023             /* keep writes in order */
2024             while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2025                 s->wait_sector_num[index] = sector_num;
2026                 qemu_coroutine_yield();
2027             }
2028             s->wait_sector_num[index] = -1;
2029         }
2030
2031         if (s->ret == -EINPROGRESS) {
2032             if (copy_range) {
2033                 ret = convert_co_copy_range(s, sector_num, n);
2034                 if (ret) {
2035                     s->copy_range = false;
2036                     goto retry;
2037                 }
2038             } else {
2039                 ret = convert_co_write(s, sector_num, n, buf, status);
2040             }
2041             if (ret < 0) {
2042                 error_report("error while writing at byte %lld: %s",
2043                              sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2044                 s->ret = ret;
2045             }
2046         }
2047
2048         if (s->wr_in_order) {
2049             /* reenter the coroutine that might have waited
2050              * for this write to complete */
2051             s->wr_offs = sector_num + n;
2052             for (i = 0; i < s->num_coroutines; i++) {
2053                 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2054                     /*
2055                      * A -> B -> A cannot occur because A has
2056                      * s->wait_sector_num[i] == -1 during A -> B.  Therefore
2057                      * B will never enter A during this time window.
2058                      */
2059                     qemu_coroutine_enter(s->co[i]);
2060                     break;
2061                 }
2062             }
2063         }
2064     }
2065
2066     qemu_vfree(buf);
2067     s->co[index] = NULL;
2068     s->running_coroutines--;
2069     if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2070         /* the convert job finished successfully */
2071         s->ret = 0;
2072     }
2073 }
2074
2075 static int convert_do_copy(ImgConvertState *s)
2076 {
2077     int ret, i, n;
2078     int64_t sector_num = 0;
2079
2080     /* Check whether we have zero initialisation or can get it efficiently */
2081     if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2082         !s->target_has_backing) {
2083         s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2084     }
2085
2086     /* Allocate buffer for copied data. For compressed images, only one cluster
2087      * can be copied at a time. */
2088     if (s->compressed) {
2089         if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2090             error_report("invalid cluster size");
2091             return -EINVAL;
2092         }
2093         s->buf_sectors = s->cluster_sectors;
2094     }
2095
2096     while (sector_num < s->total_sectors) {
2097         n = convert_iteration_sectors(s, sector_num);
2098         if (n < 0) {
2099             return n;
2100         }
2101         if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2102         {
2103             s->allocated_sectors += n;
2104         }
2105         sector_num += n;
2106     }
2107
2108     /* Do the copy */
2109     s->sector_next_status = 0;
2110     s->ret = -EINPROGRESS;
2111
2112     qemu_co_mutex_init(&s->lock);
2113     for (i = 0; i < s->num_coroutines; i++) {
2114         s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2115         s->wait_sector_num[i] = -1;
2116         qemu_coroutine_enter(s->co[i]);
2117     }
2118
2119     while (s->running_coroutines) {
2120         main_loop_wait(false);
2121     }
2122
2123     if (s->compressed && !s->ret) {
2124         /* signal EOF to align */
2125         ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2126         if (ret < 0) {
2127             return ret;
2128         }
2129     }
2130
2131     return s->ret;
2132 }
2133
2134 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2135 {
2136     BdrvDirtyBitmap *bm;
2137     Error *err = NULL;
2138
2139     FOR_EACH_DIRTY_BITMAP(src, bm) {
2140         const char *name;
2141
2142         if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2143             continue;
2144         }
2145         name = bdrv_dirty_bitmap_name(bm);
2146         qmp_block_dirty_bitmap_add(dst->node_name, name,
2147                                    true, bdrv_dirty_bitmap_granularity(bm),
2148                                    true, true,
2149                                    true, !bdrv_dirty_bitmap_enabled(bm),
2150                                    &err);
2151         if (err) {
2152             error_reportf_err(err, "Failed to create bitmap %s: ", name);
2153             return -1;
2154         }
2155
2156         do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2157                               &err);
2158         if (err) {
2159             error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2160             return -1;
2161         }
2162     }
2163
2164     return 0;
2165 }
2166
2167 #define MAX_BUF_SECTORS 32768
2168
2169 static int img_convert(int argc, char **argv)
2170 {
2171     int c, bs_i, flags, src_flags = 0;
2172     const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2173                *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2174                *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2175     BlockDriver *drv = NULL, *proto_drv = NULL;
2176     BlockDriverInfo bdi;
2177     BlockDriverState *out_bs;
2178     QemuOpts *opts = NULL, *sn_opts = NULL;
2179     QemuOptsList *create_opts = NULL;
2180     QDict *open_opts = NULL;
2181     char *options = NULL;
2182     Error *local_err = NULL;
2183     bool writethrough, src_writethrough, image_opts = false,
2184          skip_create = false, progress = false, tgt_image_opts = false;
2185     int64_t ret = -EINVAL;
2186     bool force_share = false;
2187     bool explict_min_sparse = false;
2188     bool bitmaps = false;
2189
2190     ImgConvertState s = (ImgConvertState) {
2191         /* Need at least 4k of zeros for sparse detection */
2192         .min_sparse         = 8,
2193         .copy_range         = false,
2194         .buf_sectors        = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2195         .wr_in_order        = true,
2196         .num_coroutines     = 8,
2197     };
2198
2199     for(;;) {
2200         static const struct option long_options[] = {
2201             {"help", no_argument, 0, 'h'},
2202             {"object", required_argument, 0, OPTION_OBJECT},
2203             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2204             {"force-share", no_argument, 0, 'U'},
2205             {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2206             {"salvage", no_argument, 0, OPTION_SALVAGE},
2207             {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2208             {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2209             {0, 0, 0, 0}
2210         };
2211         c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2212                         long_options, NULL);
2213         if (c == -1) {
2214             break;
2215         }
2216         switch(c) {
2217         case ':':
2218             missing_argument(argv[optind - 1]);
2219             break;
2220         case '?':
2221             unrecognized_option(argv[optind - 1]);
2222             break;
2223         case 'h':
2224             help();
2225             break;
2226         case 'f':
2227             fmt = optarg;
2228             break;
2229         case 'O':
2230             out_fmt = optarg;
2231             break;
2232         case 'B':
2233             out_baseimg = optarg;
2234             break;
2235         case 'C':
2236             s.copy_range = true;
2237             break;
2238         case 'c':
2239             s.compressed = true;
2240             break;
2241         case 'o':
2242             if (accumulate_options(&options, optarg) < 0) {
2243                 goto fail_getopt;
2244             }
2245             break;
2246         case 'l':
2247             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2248                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2249                                                   optarg, false);
2250                 if (!sn_opts) {
2251                     error_report("Failed in parsing snapshot param '%s'",
2252                                  optarg);
2253                     goto fail_getopt;
2254                 }
2255             } else {
2256                 snapshot_name = optarg;
2257             }
2258             break;
2259         case 'S':
2260         {
2261             int64_t sval;
2262
2263             sval = cvtnum("buffer size for sparse output", optarg);
2264             if (sval < 0) {
2265                 goto fail_getopt;
2266             } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2267                 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2268                 error_report("Invalid buffer size for sparse output specified. "
2269                     "Valid sizes are multiples of %llu up to %llu. Select "
2270                     "0 to disable sparse detection (fully allocates output).",
2271                     BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2272                 goto fail_getopt;
2273             }
2274
2275             s.min_sparse = sval / BDRV_SECTOR_SIZE;
2276             explict_min_sparse = true;
2277             break;
2278         }
2279         case 'p':
2280             progress = true;
2281             break;
2282         case 't':
2283             cache = optarg;
2284             break;
2285         case 'T':
2286             src_cache = optarg;
2287             break;
2288         case 'q':
2289             s.quiet = true;
2290             break;
2291         case 'n':
2292             skip_create = true;
2293             break;
2294         case 'm':
2295             if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2296                 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2297                 error_report("Invalid number of coroutines. Allowed number of"
2298                              " coroutines is between 1 and %d", MAX_COROUTINES);
2299                 goto fail_getopt;
2300             }
2301             break;
2302         case 'W':
2303             s.wr_in_order = false;
2304             break;
2305         case 'U':
2306             force_share = true;
2307             break;
2308         case OPTION_OBJECT: {
2309             QemuOpts *object_opts;
2310             object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2311                                                   optarg, true);
2312             if (!object_opts) {
2313                 goto fail_getopt;
2314             }
2315             break;
2316         }
2317         case OPTION_IMAGE_OPTS:
2318             image_opts = true;
2319             break;
2320         case OPTION_SALVAGE:
2321             s.salvage = true;
2322             break;
2323         case OPTION_TARGET_IMAGE_OPTS:
2324             tgt_image_opts = true;
2325             break;
2326         case OPTION_TARGET_IS_ZERO:
2327             /*
2328              * The user asserting that the target is blank has the
2329              * same effect as the target driver supporting zero
2330              * initialisation.
2331              */
2332             s.has_zero_init = true;
2333             break;
2334         case OPTION_BITMAPS:
2335             bitmaps = true;
2336             break;
2337         }
2338     }
2339
2340     if (!out_fmt && !tgt_image_opts) {
2341         out_fmt = "raw";
2342     }
2343
2344     if (qemu_opts_foreach(&qemu_object_opts,
2345                           user_creatable_add_opts_foreach,
2346                           qemu_img_object_print_help, &error_fatal)) {
2347         goto fail_getopt;
2348     }
2349
2350     if (s.compressed && s.copy_range) {
2351         error_report("Cannot enable copy offloading when -c is used");
2352         goto fail_getopt;
2353     }
2354
2355     if (explict_min_sparse && s.copy_range) {
2356         error_report("Cannot enable copy offloading when -S is used");
2357         goto fail_getopt;
2358     }
2359
2360     if (s.copy_range && s.salvage) {
2361         error_report("Cannot use copy offloading in salvaging mode");
2362         goto fail_getopt;
2363     }
2364
2365     if (tgt_image_opts && !skip_create) {
2366         error_report("--target-image-opts requires use of -n flag");
2367         goto fail_getopt;
2368     }
2369
2370     if (skip_create && options) {
2371         warn_report("-o has no effect when skipping image creation");
2372         warn_report("This will become an error in future QEMU versions.");
2373     }
2374
2375     if (s.has_zero_init && !skip_create) {
2376         error_report("--target-is-zero requires use of -n flag");
2377         goto fail_getopt;
2378     }
2379
2380     s.src_num = argc - optind - 1;
2381     out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2382
2383     if (options && has_help_option(options)) {
2384         if (out_fmt) {
2385             ret = print_block_option_help(out_filename, out_fmt);
2386             goto fail_getopt;
2387         } else {
2388             error_report("Option help requires a format be specified");
2389             goto fail_getopt;
2390         }
2391     }
2392
2393     if (s.src_num < 1) {
2394         error_report("Must specify image file name");
2395         goto fail_getopt;
2396     }
2397
2398     /* ret is still -EINVAL until here */
2399     ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2400     if (ret < 0) {
2401         error_report("Invalid source cache option: %s", src_cache);
2402         goto fail_getopt;
2403     }
2404
2405     /* Initialize before goto out */
2406     if (s.quiet) {
2407         progress = false;
2408     }
2409     qemu_progress_init(progress, 1.0);
2410     qemu_progress_print(0, 100);
2411
2412     s.src = g_new0(BlockBackend *, s.src_num);
2413     s.src_sectors = g_new(int64_t, s.src_num);
2414
2415     for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2416         s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2417                                fmt, src_flags, src_writethrough, s.quiet,
2418                                force_share);
2419         if (!s.src[bs_i]) {
2420             ret = -1;
2421             goto out;
2422         }
2423         s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2424         if (s.src_sectors[bs_i] < 0) {
2425             error_report("Could not get size of %s: %s",
2426                          argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2427             ret = -1;
2428             goto out;
2429         }
2430         s.total_sectors += s.src_sectors[bs_i];
2431     }
2432
2433     if (sn_opts) {
2434         bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2435                                qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2436                                qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2437                                &local_err);
2438     } else if (snapshot_name != NULL) {
2439         if (s.src_num > 1) {
2440             error_report("No support for concatenating multiple snapshot");
2441             ret = -1;
2442             goto out;
2443         }
2444
2445         bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2446                                              &local_err);
2447     }
2448     if (local_err) {
2449         error_reportf_err(local_err, "Failed to load snapshot: ");
2450         ret = -1;
2451         goto out;
2452     }
2453
2454     if (!skip_create) {
2455         /* Find driver and parse its options */
2456         drv = bdrv_find_format(out_fmt);
2457         if (!drv) {
2458             error_report("Unknown file format '%s'", out_fmt);
2459             ret = -1;
2460             goto out;
2461         }
2462
2463         proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2464         if (!proto_drv) {
2465             error_report_err(local_err);
2466             ret = -1;
2467             goto out;
2468         }
2469
2470         if (!drv->create_opts) {
2471             error_report("Format driver '%s' does not support image creation",
2472                          drv->format_name);
2473             ret = -1;
2474             goto out;
2475         }
2476
2477         if (!proto_drv->create_opts) {
2478             error_report("Protocol driver '%s' does not support image creation",
2479                          proto_drv->format_name);
2480             ret = -1;
2481             goto out;
2482         }
2483
2484         create_opts = qemu_opts_append(create_opts, drv->create_opts);
2485         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2486
2487         opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2488         if (options) {
2489             if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
2490                 error_report_err(local_err);
2491                 ret = -1;
2492                 goto out;
2493             }
2494         }
2495
2496         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2497                             &error_abort);
2498         ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2499         if (ret < 0) {
2500             goto out;
2501         }
2502     }
2503
2504     /* Get backing file name if -o backing_file was used */
2505     out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2506     if (out_baseimg_param) {
2507         out_baseimg = out_baseimg_param;
2508     }
2509     s.target_has_backing = (bool) out_baseimg;
2510
2511     if (s.has_zero_init && s.target_has_backing) {
2512         error_report("Cannot use --target-is-zero when the destination "
2513                      "image has a backing file");
2514         goto out;
2515     }
2516
2517     if (s.src_num > 1 && out_baseimg) {
2518         error_report("Having a backing file for the target makes no sense when "
2519                      "concatenating multiple input images");
2520         ret = -1;
2521         goto out;
2522     }
2523
2524     /* Check if compression is supported */
2525     if (s.compressed) {
2526         bool encryption =
2527             qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2528         const char *encryptfmt =
2529             qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2530         const char *preallocation =
2531             qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2532
2533         if (drv && !block_driver_can_compress(drv)) {
2534             error_report("Compression not supported for this file format");
2535             ret = -1;
2536             goto out;
2537         }
2538
2539         if (encryption || encryptfmt) {
2540             error_report("Compression and encryption not supported at "
2541                          "the same time");
2542             ret = -1;
2543             goto out;
2544         }
2545
2546         if (preallocation
2547             && strcmp(preallocation, "off"))
2548         {
2549             error_report("Compression and preallocation not supported at "
2550                          "the same time");
2551             ret = -1;
2552             goto out;
2553         }
2554     }
2555
2556     /* Determine if bitmaps need copying */
2557     if (bitmaps) {
2558         if (s.src_num > 1) {
2559             error_report("Copying bitmaps only possible with single source");
2560             ret = -1;
2561             goto out;
2562         }
2563         if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2564             error_report("Source lacks bitmap support");
2565             ret = -1;
2566             goto out;
2567         }
2568     }
2569
2570     /*
2571      * The later open call will need any decryption secrets, and
2572      * bdrv_create() will purge "opts", so extract them now before
2573      * they are lost.
2574      */
2575     if (!skip_create) {
2576         open_opts = qdict_new();
2577         qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2578
2579         /* Create the new image */
2580         ret = bdrv_create(drv, out_filename, opts, &local_err);
2581         if (ret < 0) {
2582             error_reportf_err(local_err, "%s: error while converting %s: ",
2583                               out_filename, out_fmt);
2584             goto out;
2585         }
2586     }
2587
2588     s.target_is_new = !skip_create;
2589
2590     flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2591     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2592     if (ret < 0) {
2593         error_report("Invalid cache option: %s", cache);
2594         goto out;
2595     }
2596
2597     if (skip_create) {
2598         s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2599                             flags, writethrough, s.quiet, false);
2600     } else {
2601         /* TODO ultimately we should allow --target-image-opts
2602          * to be used even when -n is not given.
2603          * That has to wait for bdrv_create to be improved
2604          * to allow filenames in option syntax
2605          */
2606         s.target = img_open_file(out_filename, open_opts, out_fmt,
2607                                  flags, writethrough, s.quiet, false);
2608         open_opts = NULL; /* blk_new_open will have freed it */
2609     }
2610     if (!s.target) {
2611         ret = -1;
2612         goto out;
2613     }
2614     out_bs = blk_bs(s.target);
2615
2616     if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2617         error_report("Format driver '%s' does not support bitmaps",
2618                      out_bs->drv->format_name);
2619         ret = -1;
2620         goto out;
2621     }
2622
2623     if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2624         error_report("Compression not supported for this file format");
2625         ret = -1;
2626         goto out;
2627     }
2628
2629     /* increase bufsectors from the default 4096 (2M) if opt_transfer
2630      * or discard_alignment of the out_bs is greater. Limit to
2631      * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2632     s.buf_sectors = MIN(MAX_BUF_SECTORS,
2633                         MAX(s.buf_sectors,
2634                             MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2635                                 out_bs->bl.pdiscard_alignment >>
2636                                 BDRV_SECTOR_BITS)));
2637
2638     /* try to align the write requests to the destination to avoid unnecessary
2639      * RMW cycles. */
2640     s.alignment = MAX(pow2floor(s.min_sparse),
2641                       DIV_ROUND_UP(out_bs->bl.request_alignment,
2642                                    BDRV_SECTOR_SIZE));
2643     assert(is_power_of_2(s.alignment));
2644
2645     if (skip_create) {
2646         int64_t output_sectors = blk_nb_sectors(s.target);
2647         if (output_sectors < 0) {
2648             error_report("unable to get output image length: %s",
2649                          strerror(-output_sectors));
2650             ret = -1;
2651             goto out;
2652         } else if (output_sectors < s.total_sectors) {
2653             error_report("output file is smaller than input file");
2654             ret = -1;
2655             goto out;
2656         }
2657     }
2658
2659     if (s.target_has_backing && s.target_is_new) {
2660         /* Errors are treated as "backing length unknown" (which means
2661          * s.target_backing_sectors has to be negative, which it will
2662          * be automatically).  The backing file length is used only
2663          * for optimizations, so such a case is not fatal. */
2664         s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2665     } else {
2666         s.target_backing_sectors = -1;
2667     }
2668
2669     ret = bdrv_get_info(out_bs, &bdi);
2670     if (ret < 0) {
2671         if (s.compressed) {
2672             error_report("could not get block driver info");
2673             goto out;
2674         }
2675     } else {
2676         s.compressed = s.compressed || bdi.needs_compressed_writes;
2677         s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2678     }
2679
2680     ret = convert_do_copy(&s);
2681
2682     /* Now copy the bitmaps */
2683     if (bitmaps && ret == 0) {
2684         ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2685     }
2686
2687 out:
2688     if (!ret) {
2689         qemu_progress_print(100, 0);
2690     }
2691     qemu_progress_end();
2692     qemu_opts_del(opts);
2693     qemu_opts_free(create_opts);
2694     qemu_opts_del(sn_opts);
2695     qobject_unref(open_opts);
2696     blk_unref(s.target);
2697     if (s.src) {
2698         for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2699             blk_unref(s.src[bs_i]);
2700         }
2701         g_free(s.src);
2702     }
2703     g_free(s.src_sectors);
2704 fail_getopt:
2705     g_free(options);
2706
2707     return !!ret;
2708 }
2709
2710
2711 static void dump_snapshots(BlockDriverState *bs)
2712 {
2713     QEMUSnapshotInfo *sn_tab, *sn;
2714     int nb_sns, i;
2715
2716     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2717     if (nb_sns <= 0)
2718         return;
2719     printf("Snapshot list:\n");
2720     bdrv_snapshot_dump(NULL);
2721     printf("\n");
2722     for(i = 0; i < nb_sns; i++) {
2723         sn = &sn_tab[i];
2724         bdrv_snapshot_dump(sn);
2725         printf("\n");
2726     }
2727     g_free(sn_tab);
2728 }
2729
2730 static void dump_json_image_info_list(ImageInfoList *list)
2731 {
2732     QString *str;
2733     QObject *obj;
2734     Visitor *v = qobject_output_visitor_new(&obj);
2735
2736     visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2737     visit_complete(v, &obj);
2738     str = qobject_to_json_pretty(obj);
2739     assert(str != NULL);
2740     printf("%s\n", qstring_get_str(str));
2741     qobject_unref(obj);
2742     visit_free(v);
2743     qobject_unref(str);
2744 }
2745
2746 static void dump_json_image_info(ImageInfo *info)
2747 {
2748     QString *str;
2749     QObject *obj;
2750     Visitor *v = qobject_output_visitor_new(&obj);
2751
2752     visit_type_ImageInfo(v, NULL, &info, &error_abort);
2753     visit_complete(v, &obj);
2754     str = qobject_to_json_pretty(obj);
2755     assert(str != NULL);
2756     printf("%s\n", qstring_get_str(str));
2757     qobject_unref(obj);
2758     visit_free(v);
2759     qobject_unref(str);
2760 }
2761
2762 static void dump_human_image_info_list(ImageInfoList *list)
2763 {
2764     ImageInfoList *elem;
2765     bool delim = false;
2766
2767     for (elem = list; elem; elem = elem->next) {
2768         if (delim) {
2769             printf("\n");
2770         }
2771         delim = true;
2772
2773         bdrv_image_info_dump(elem->value);
2774     }
2775 }
2776
2777 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2778 {
2779     return strcmp(a, b) == 0;
2780 }
2781
2782 /**
2783  * Open an image file chain and return an ImageInfoList
2784  *
2785  * @filename: topmost image filename
2786  * @fmt: topmost image format (may be NULL to autodetect)
2787  * @chain: true  - enumerate entire backing file chain
2788  *         false - only topmost image file
2789  *
2790  * Returns a list of ImageInfo objects or NULL if there was an error opening an
2791  * image file.  If there was an error a message will have been printed to
2792  * stderr.
2793  */
2794 static ImageInfoList *collect_image_info_list(bool image_opts,
2795                                               const char *filename,
2796                                               const char *fmt,
2797                                               bool chain, bool force_share)
2798 {
2799     ImageInfoList *head = NULL;
2800     ImageInfoList **last = &head;
2801     GHashTable *filenames;
2802     Error *err = NULL;
2803
2804     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2805
2806     while (filename) {
2807         BlockBackend *blk;
2808         BlockDriverState *bs;
2809         ImageInfo *info;
2810         ImageInfoList *elem;
2811
2812         if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2813             error_report("Backing file '%s' creates an infinite loop.",
2814                          filename);
2815             goto err;
2816         }
2817         g_hash_table_insert(filenames, (gpointer)filename, NULL);
2818
2819         blk = img_open(image_opts, filename, fmt,
2820                        BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2821                        force_share);
2822         if (!blk) {
2823             goto err;
2824         }
2825         bs = blk_bs(blk);
2826
2827         bdrv_query_image_info(bs, &info, &err);
2828         if (err) {
2829             error_report_err(err);
2830             blk_unref(blk);
2831             goto err;
2832         }
2833
2834         elem = g_new0(ImageInfoList, 1);
2835         elem->value = info;
2836         *last = elem;
2837         last = &elem->next;
2838
2839         blk_unref(blk);
2840
2841         /* Clear parameters that only apply to the topmost image */
2842         filename = fmt = NULL;
2843         image_opts = false;
2844
2845         if (chain) {
2846             if (info->has_full_backing_filename) {
2847                 filename = info->full_backing_filename;
2848             } else if (info->has_backing_filename) {
2849                 error_report("Could not determine absolute backing filename,"
2850                              " but backing filename '%s' present",
2851                              info->backing_filename);
2852                 goto err;
2853             }
2854             if (info->has_backing_filename_format) {
2855                 fmt = info->backing_filename_format;
2856             }
2857         }
2858     }
2859     g_hash_table_destroy(filenames);
2860     return head;
2861
2862 err:
2863     qapi_free_ImageInfoList(head);
2864     g_hash_table_destroy(filenames);
2865     return NULL;
2866 }
2867
2868 static int img_info(int argc, char **argv)
2869 {
2870     int c;
2871     OutputFormat output_format = OFORMAT_HUMAN;
2872     bool chain = false;
2873     const char *filename, *fmt, *output;
2874     ImageInfoList *list;
2875     bool image_opts = false;
2876     bool force_share = false;
2877
2878     fmt = NULL;
2879     output = NULL;
2880     for(;;) {
2881         int option_index = 0;
2882         static const struct option long_options[] = {
2883             {"help", no_argument, 0, 'h'},
2884             {"format", required_argument, 0, 'f'},
2885             {"output", required_argument, 0, OPTION_OUTPUT},
2886             {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2887             {"object", required_argument, 0, OPTION_OBJECT},
2888             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2889             {"force-share", no_argument, 0, 'U'},
2890             {0, 0, 0, 0}
2891         };
2892         c = getopt_long(argc, argv, ":f:hU",
2893                         long_options, &option_index);
2894         if (c == -1) {
2895             break;
2896         }
2897         switch(c) {
2898         case ':':
2899             missing_argument(argv[optind - 1]);
2900             break;
2901         case '?':
2902             unrecognized_option(argv[optind - 1]);
2903             break;
2904         case 'h':
2905             help();
2906             break;
2907         case 'f':
2908             fmt = optarg;
2909             break;
2910         case 'U':
2911             force_share = true;
2912             break;
2913         case OPTION_OUTPUT:
2914             output = optarg;
2915             break;
2916         case OPTION_BACKING_CHAIN:
2917             chain = true;
2918             break;
2919         case OPTION_OBJECT: {
2920             QemuOpts *opts;
2921             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2922                                            optarg, true);
2923             if (!opts) {
2924                 return 1;
2925             }
2926         }   break;
2927         case OPTION_IMAGE_OPTS:
2928             image_opts = true;
2929             break;
2930         }
2931     }
2932     if (optind != argc - 1) {
2933         error_exit("Expecting one image file name");
2934     }
2935     filename = argv[optind++];
2936
2937     if (output && !strcmp(output, "json")) {
2938         output_format = OFORMAT_JSON;
2939     } else if (output && !strcmp(output, "human")) {
2940         output_format = OFORMAT_HUMAN;
2941     } else if (output) {
2942         error_report("--output must be used with human or json as argument.");
2943         return 1;
2944     }
2945
2946     if (qemu_opts_foreach(&qemu_object_opts,
2947                           user_creatable_add_opts_foreach,
2948                           qemu_img_object_print_help, &error_fatal)) {
2949         return 1;
2950     }
2951
2952     list = collect_image_info_list(image_opts, filename, fmt, chain,
2953                                    force_share);
2954     if (!list) {
2955         return 1;
2956     }
2957
2958     switch (output_format) {
2959     case OFORMAT_HUMAN:
2960         dump_human_image_info_list(list);
2961         break;
2962     case OFORMAT_JSON:
2963         if (chain) {
2964             dump_json_image_info_list(list);
2965         } else {
2966             dump_json_image_info(list->value);
2967         }
2968         break;
2969     }
2970
2971     qapi_free_ImageInfoList(list);
2972     return 0;
2973 }
2974
2975 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2976                           MapEntry *next)
2977 {
2978     switch (output_format) {
2979     case OFORMAT_HUMAN:
2980         if (e->data && !e->has_offset) {
2981             error_report("File contains external, encrypted or compressed clusters.");
2982             return -1;
2983         }
2984         if (e->data && !e->zero) {
2985             printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2986                    e->start, e->length,
2987                    e->has_offset ? e->offset : 0,
2988                    e->has_filename ? e->filename : "");
2989         }
2990         /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2991          * Modify the flags here to allow more coalescing.
2992          */
2993         if (next && (!next->data || next->zero)) {
2994             next->data = false;
2995             next->zero = true;
2996         }
2997         break;
2998     case OFORMAT_JSON:
2999         printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3000                " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
3001                e->start, e->length, e->depth,
3002                e->zero ? "true" : "false",
3003                e->data ? "true" : "false");
3004         if (e->has_offset) {
3005             printf(", \"offset\": %"PRId64"", e->offset);
3006         }
3007         putchar('}');
3008
3009         if (next) {
3010             puts(",");
3011         }
3012         break;
3013     }
3014     return 0;
3015 }
3016
3017 static int get_block_status(BlockDriverState *bs, int64_t offset,
3018                             int64_t bytes, MapEntry *e)
3019 {
3020     int ret;
3021     int depth;
3022     BlockDriverState *file;
3023     bool has_offset;
3024     int64_t map;
3025     char *filename = NULL;
3026
3027     /* As an optimization, we could cache the current range of unallocated
3028      * clusters in each file of the chain, and avoid querying the same
3029      * range repeatedly.
3030      */
3031
3032     depth = 0;
3033     for (;;) {
3034         ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3035         if (ret < 0) {
3036             return ret;
3037         }
3038         assert(bytes);
3039         if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3040             break;
3041         }
3042         bs = backing_bs(bs);
3043         if (bs == NULL) {
3044             ret = 0;
3045             break;
3046         }
3047
3048         depth++;
3049     }
3050
3051     has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3052
3053     if (file && has_offset) {
3054         bdrv_refresh_filename(file);
3055         filename = file->filename;
3056     }
3057
3058     *e = (MapEntry) {
3059         .start = offset,
3060         .length = bytes,
3061         .data = !!(ret & BDRV_BLOCK_DATA),
3062         .zero = !!(ret & BDRV_BLOCK_ZERO),
3063         .offset = map,
3064         .has_offset = has_offset,
3065         .depth = depth,
3066         .has_filename = filename,
3067         .filename = filename,
3068     };
3069
3070     return 0;
3071 }
3072
3073 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3074 {
3075     if (curr->length == 0) {
3076         return false;
3077     }
3078     if (curr->zero != next->zero ||
3079         curr->data != next->data ||
3080         curr->depth != next->depth ||
3081         curr->has_filename != next->has_filename ||
3082         curr->has_offset != next->has_offset) {
3083         return false;
3084     }
3085     if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3086         return false;
3087     }
3088     if (curr->has_offset && curr->offset + curr->length != next->offset) {
3089         return false;
3090     }
3091     return true;
3092 }
3093
3094 static int img_map(int argc, char **argv)
3095 {
3096     int c;
3097     OutputFormat output_format = OFORMAT_HUMAN;
3098     BlockBackend *blk;
3099     BlockDriverState *bs;
3100     const char *filename, *fmt, *output;
3101     int64_t length;
3102     MapEntry curr = { .length = 0 }, next;
3103     int ret = 0;
3104     bool image_opts = false;
3105     bool force_share = false;
3106     int64_t start_offset = 0;
3107     int64_t max_length = -1;
3108
3109     fmt = NULL;
3110     output = NULL;
3111     for (;;) {
3112         int option_index = 0;
3113         static const struct option long_options[] = {
3114             {"help", no_argument, 0, 'h'},
3115             {"format", required_argument, 0, 'f'},
3116             {"output", required_argument, 0, OPTION_OUTPUT},
3117             {"object", required_argument, 0, OPTION_OBJECT},
3118             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3119             {"force-share", no_argument, 0, 'U'},
3120             {"start-offset", required_argument, 0, 's'},
3121             {"max-length", required_argument, 0, 'l'},
3122             {0, 0, 0, 0}
3123         };
3124         c = getopt_long(argc, argv, ":f:s:l:hU",
3125                         long_options, &option_index);
3126         if (c == -1) {
3127             break;
3128         }
3129         switch (c) {
3130         case ':':
3131             missing_argument(argv[optind - 1]);
3132             break;
3133         case '?':
3134             unrecognized_option(argv[optind - 1]);
3135             break;
3136         case 'h':
3137             help();
3138             break;
3139         case 'f':
3140             fmt = optarg;
3141             break;
3142         case 'U':
3143             force_share = true;
3144             break;
3145         case OPTION_OUTPUT:
3146             output = optarg;
3147             break;
3148         case 's':
3149             start_offset = cvtnum("start offset", optarg);
3150             if (start_offset < 0) {
3151                 return 1;
3152             }
3153             break;
3154         case 'l':
3155             max_length = cvtnum("max length", optarg);
3156             if (max_length < 0) {
3157                 return 1;
3158             }
3159             break;
3160         case OPTION_OBJECT: {
3161             QemuOpts *opts;
3162             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3163                                            optarg, true);
3164             if (!opts) {
3165                 return 1;
3166             }
3167         }   break;
3168         case OPTION_IMAGE_OPTS:
3169             image_opts = true;
3170             break;
3171         }
3172     }
3173     if (optind != argc - 1) {
3174         error_exit("Expecting one image file name");
3175     }
3176     filename = argv[optind];
3177
3178     if (output && !strcmp(output, "json")) {
3179         output_format = OFORMAT_JSON;
3180     } else if (output && !strcmp(output, "human")) {
3181         output_format = OFORMAT_HUMAN;
3182     } else if (output) {
3183         error_report("--output must be used with human or json as argument.");
3184         return 1;
3185     }
3186
3187     if (qemu_opts_foreach(&qemu_object_opts,
3188                           user_creatable_add_opts_foreach,
3189                           qemu_img_object_print_help, &error_fatal)) {
3190         return 1;
3191     }
3192
3193     blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3194     if (!blk) {
3195         return 1;
3196     }
3197     bs = blk_bs(blk);
3198
3199     if (output_format == OFORMAT_HUMAN) {
3200         printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3201     } else if (output_format == OFORMAT_JSON) {
3202         putchar('[');
3203     }
3204
3205     length = blk_getlength(blk);
3206     if (length < 0) {
3207         error_report("Failed to get size for '%s'", filename);
3208         return 1;
3209     }
3210     if (max_length != -1) {
3211         length = MIN(start_offset + max_length, length);
3212     }
3213
3214     curr.start = start_offset;
3215     while (curr.start + curr.length < length) {
3216         int64_t offset = curr.start + curr.length;
3217         int64_t n;
3218
3219         /* Probe up to 1 GiB at a time.  */
3220         n = MIN(1 * GiB, length - offset);
3221         ret = get_block_status(bs, offset, n, &next);
3222
3223         if (ret < 0) {
3224             error_report("Could not read file metadata: %s", strerror(-ret));
3225             goto out;
3226         }
3227
3228         if (entry_mergeable(&curr, &next)) {
3229             curr.length += next.length;
3230             continue;
3231         }
3232
3233         if (curr.length > 0) {
3234             ret = dump_map_entry(output_format, &curr, &next);
3235             if (ret < 0) {
3236                 goto out;
3237             }
3238         }
3239         curr = next;
3240     }
3241
3242     ret = dump_map_entry(output_format, &curr, NULL);
3243     if (output_format == OFORMAT_JSON) {
3244         puts("]");
3245     }
3246
3247 out:
3248     blk_unref(blk);
3249     return ret < 0;
3250 }
3251
3252 #define SNAPSHOT_LIST   1
3253 #define SNAPSHOT_CREATE 2
3254 #define SNAPSHOT_APPLY  3
3255 #define SNAPSHOT_DELETE 4
3256
3257 static int img_snapshot(int argc, char **argv)
3258 {
3259     BlockBackend *blk;
3260     BlockDriverState *bs;
3261     QEMUSnapshotInfo sn;
3262     char *filename, *snapshot_name = NULL;
3263     int c, ret = 0, bdrv_oflags;
3264     int action = 0;
3265     qemu_timeval tv;
3266     bool quiet = false;
3267     Error *err = NULL;
3268     bool image_opts = false;
3269     bool force_share = false;
3270
3271     bdrv_oflags = BDRV_O_RDWR;
3272     /* Parse commandline parameters */
3273     for(;;) {
3274         static const struct option long_options[] = {
3275             {"help", no_argument, 0, 'h'},
3276             {"object", required_argument, 0, OPTION_OBJECT},
3277             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3278             {"force-share", no_argument, 0, 'U'},
3279             {0, 0, 0, 0}
3280         };
3281         c = getopt_long(argc, argv, ":la:c:d:hqU",
3282                         long_options, NULL);
3283         if (c == -1) {
3284             break;
3285         }
3286         switch(c) {
3287         case ':':
3288             missing_argument(argv[optind - 1]);
3289             break;
3290         case '?':
3291             unrecognized_option(argv[optind - 1]);
3292             break;
3293         case 'h':
3294             help();
3295             return 0;
3296         case 'l':
3297             if (action) {
3298                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3299                 return 0;
3300             }
3301             action = SNAPSHOT_LIST;
3302             bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3303             break;
3304         case 'a':
3305             if (action) {
3306                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3307                 return 0;
3308             }
3309             action = SNAPSHOT_APPLY;
3310             snapshot_name = optarg;
3311             break;
3312         case 'c':
3313             if (action) {
3314                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3315                 return 0;
3316             }
3317             action = SNAPSHOT_CREATE;
3318             snapshot_name = optarg;
3319             break;
3320         case 'd':
3321             if (action) {
3322                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3323                 return 0;
3324             }
3325             action = SNAPSHOT_DELETE;
3326             snapshot_name = optarg;
3327             break;
3328         case 'q':
3329             quiet = true;
3330             break;
3331         case 'U':
3332             force_share = true;
3333             break;
3334         case OPTION_OBJECT: {
3335             QemuOpts *opts;
3336             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3337                                            optarg, true);
3338             if (!opts) {
3339                 return 1;
3340             }
3341         }   break;
3342         case OPTION_IMAGE_OPTS:
3343             image_opts = true;
3344             break;
3345         }
3346     }
3347
3348     if (optind != argc - 1) {
3349         error_exit("Expecting one image file name");
3350     }
3351     filename = argv[optind++];
3352
3353     if (qemu_opts_foreach(&qemu_object_opts,
3354                           user_creatable_add_opts_foreach,
3355                           qemu_img_object_print_help, &error_fatal)) {
3356         return 1;
3357     }
3358
3359     /* Open the image */
3360     blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3361                    force_share);
3362     if (!blk) {
3363         return 1;
3364     }
3365     bs = blk_bs(blk);
3366
3367     /* Perform the requested action */
3368     switch(action) {
3369     case SNAPSHOT_LIST:
3370         dump_snapshots(bs);
3371         break;
3372
3373     case SNAPSHOT_CREATE:
3374         memset(&sn, 0, sizeof(sn));
3375         pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3376
3377         qemu_gettimeofday(&tv);
3378         sn.date_sec = tv.tv_sec;
3379         sn.date_nsec = tv.tv_usec * 1000;
3380
3381         ret = bdrv_snapshot_create(bs, &sn);
3382         if (ret) {
3383             error_report("Could not create snapshot '%s': %d (%s)",
3384                 snapshot_name, ret, strerror(-ret));
3385         }
3386         break;
3387
3388     case SNAPSHOT_APPLY:
3389         ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3390         if (ret) {
3391             error_reportf_err(err, "Could not apply snapshot '%s': ",
3392                               snapshot_name);
3393         }
3394         break;
3395
3396     case SNAPSHOT_DELETE:
3397         ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3398         if (ret < 0) {
3399             error_report("Could not delete snapshot '%s': snapshot not "
3400                          "found", snapshot_name);
3401             ret = 1;
3402         } else {
3403             ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3404             if (ret < 0) {
3405                 error_reportf_err(err, "Could not delete snapshot '%s': ",
3406                                   snapshot_name);
3407                 ret = 1;
3408             }
3409         }
3410         break;
3411     }
3412
3413     /* Cleanup */
3414     blk_unref(blk);
3415     if (ret) {
3416         return 1;
3417     }
3418     return 0;
3419 }
3420
3421 static int img_rebase(int argc, char **argv)
3422 {
3423     BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3424     uint8_t *buf_old = NULL;
3425     uint8_t *buf_new = NULL;
3426     BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3427     char *filename;
3428     const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3429     int c, flags, src_flags, ret;
3430     bool writethrough, src_writethrough;
3431     int unsafe = 0;
3432     bool force_share = false;
3433     int progress = 0;
3434     bool quiet = false;
3435     Error *local_err = NULL;
3436     bool image_opts = false;
3437
3438     /* Parse commandline parameters */
3439     fmt = NULL;
3440     cache = BDRV_DEFAULT_CACHE;
3441     src_cache = BDRV_DEFAULT_CACHE;
3442     out_baseimg = NULL;
3443     out_basefmt = NULL;
3444     for(;;) {
3445         static const struct option long_options[] = {
3446             {"help", no_argument, 0, 'h'},
3447             {"object", required_argument, 0, OPTION_OBJECT},
3448             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3449             {"force-share", no_argument, 0, 'U'},
3450             {0, 0, 0, 0}
3451         };
3452         c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3453                         long_options, NULL);
3454         if (c == -1) {
3455             break;
3456         }
3457         switch(c) {
3458         case ':':
3459             missing_argument(argv[optind - 1]);
3460             break;
3461         case '?':
3462             unrecognized_option(argv[optind - 1]);
3463             break;
3464         case 'h':
3465             help();
3466             return 0;
3467         case 'f':
3468             fmt = optarg;
3469             break;
3470         case 'F':
3471             out_basefmt = optarg;
3472             break;
3473         case 'b':
3474             out_baseimg = optarg;
3475             break;
3476         case 'u':
3477             unsafe = 1;
3478             break;
3479         case 'p':
3480             progress = 1;
3481             break;
3482         case 't':
3483             cache = optarg;
3484             break;
3485         case 'T':
3486             src_cache = optarg;
3487             break;
3488         case 'q':
3489             quiet = true;
3490             break;
3491         case OPTION_OBJECT: {
3492             QemuOpts *opts;
3493             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3494                                            optarg, true);
3495             if (!opts) {
3496                 return 1;
3497             }
3498         }   break;
3499         case OPTION_IMAGE_OPTS:
3500             image_opts = true;
3501             break;
3502         case 'U':
3503             force_share = true;
3504             break;
3505         }
3506     }
3507
3508     if (quiet) {
3509         progress = 0;
3510     }
3511
3512     if (optind != argc - 1) {
3513         error_exit("Expecting one image file name");
3514     }
3515     if (!unsafe && !out_baseimg) {
3516         error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3517     }
3518     filename = argv[optind++];
3519
3520     if (qemu_opts_foreach(&qemu_object_opts,
3521                           user_creatable_add_opts_foreach,
3522                           qemu_img_object_print_help, &error_fatal)) {
3523         return 1;
3524     }
3525
3526     qemu_progress_init(progress, 2.0);
3527     qemu_progress_print(0, 100);
3528
3529     flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3530     ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3531     if (ret < 0) {
3532         error_report("Invalid cache option: %s", cache);
3533         goto out;
3534     }
3535
3536     src_flags = 0;
3537     ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3538     if (ret < 0) {
3539         error_report("Invalid source cache option: %s", src_cache);
3540         goto out;
3541     }
3542
3543     /* The source files are opened read-only, don't care about WCE */
3544     assert((src_flags & BDRV_O_RDWR) == 0);
3545     (void) src_writethrough;
3546
3547     /*
3548      * Open the images.
3549      *
3550      * Ignore the old backing file for unsafe rebase in case we want to correct
3551      * the reference to a renamed or moved backing file.
3552      */
3553     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3554                    false);
3555     if (!blk) {
3556         ret = -1;
3557         goto out;
3558     }
3559     bs = blk_bs(blk);
3560
3561     if (out_basefmt != NULL) {
3562         if (bdrv_find_format(out_basefmt) == NULL) {
3563             error_report("Invalid format name: '%s'", out_basefmt);
3564             ret = -1;
3565             goto out;
3566         }
3567     }
3568
3569     /* For safe rebasing we need to compare old and new backing file */
3570     if (!unsafe) {
3571         QDict *options = NULL;
3572         BlockDriverState *base_bs = backing_bs(bs);
3573
3574         if (base_bs) {
3575             blk_old_backing = blk_new(qemu_get_aio_context(),
3576                                       BLK_PERM_CONSISTENT_READ,
3577                                       BLK_PERM_ALL);
3578             ret = blk_insert_bs(blk_old_backing, base_bs,
3579                                 &local_err);
3580             if (ret < 0) {
3581                 error_reportf_err(local_err,
3582                                   "Could not reuse old backing file '%s': ",
3583                                   base_bs->filename);
3584                 goto out;
3585             }
3586         } else {
3587             blk_old_backing = NULL;
3588         }
3589
3590         if (out_baseimg[0]) {
3591             const char *overlay_filename;
3592             char *out_real_path;
3593
3594             options = qdict_new();
3595             if (out_basefmt) {
3596                 qdict_put_str(options, "driver", out_basefmt);
3597             }
3598             if (force_share) {
3599                 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3600             }
3601
3602             bdrv_refresh_filename(bs);
3603             overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3604                                                      : bs->filename;
3605             out_real_path =
3606                 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3607                                                              out_baseimg,
3608                                                              &local_err);
3609             if (local_err) {
3610                 qobject_unref(options);
3611                 error_reportf_err(local_err,
3612                                   "Could not resolve backing filename: ");
3613                 ret = -1;
3614                 goto out;
3615             }
3616
3617             /*
3618              * Find out whether we rebase an image on top of a previous image
3619              * in its chain.
3620              */
3621             prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3622             if (prefix_chain_bs) {
3623                 qobject_unref(options);
3624                 g_free(out_real_path);
3625
3626                 blk_new_backing = blk_new(qemu_get_aio_context(),
3627                                           BLK_PERM_CONSISTENT_READ,
3628                                           BLK_PERM_ALL);
3629                 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3630                                     &local_err);
3631                 if (ret < 0) {
3632                     error_reportf_err(local_err,
3633                                       "Could not reuse backing file '%s': ",
3634                                       out_baseimg);
3635                     goto out;
3636                 }
3637             } else {
3638                 blk_new_backing = blk_new_open(out_real_path, NULL,
3639                                                options, src_flags, &local_err);
3640                 g_free(out_real_path);
3641                 if (!blk_new_backing) {
3642                     error_reportf_err(local_err,
3643                                       "Could not open new backing file '%s': ",
3644                                       out_baseimg);
3645                     ret = -1;
3646                     goto out;
3647                 }
3648             }
3649         }
3650     }
3651
3652     /*
3653      * Check each unallocated cluster in the COW file. If it is unallocated,
3654      * accesses go to the backing file. We must therefore compare this cluster
3655      * in the old and new backing file, and if they differ we need to copy it
3656      * from the old backing file into the COW file.
3657      *
3658      * If qemu-img crashes during this step, no harm is done. The content of
3659      * the image is the same as the original one at any time.
3660      */
3661     if (!unsafe) {
3662         int64_t size;
3663         int64_t old_backing_size = 0;
3664         int64_t new_backing_size = 0;
3665         uint64_t offset;
3666         int64_t n;
3667         float local_progress = 0;
3668
3669         buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3670         buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3671
3672         size = blk_getlength(blk);
3673         if (size < 0) {
3674             error_report("Could not get size of '%s': %s",
3675                          filename, strerror(-size));
3676             ret = -1;
3677             goto out;
3678         }
3679         if (blk_old_backing) {
3680             old_backing_size = blk_getlength(blk_old_backing);
3681             if (old_backing_size < 0) {
3682                 char backing_name[PATH_MAX];
3683
3684                 bdrv_get_backing_filename(bs, backing_name,
3685                                           sizeof(backing_name));
3686                 error_report("Could not get size of '%s': %s",
3687                              backing_name, strerror(-old_backing_size));
3688                 ret = -1;
3689                 goto out;
3690             }
3691         }
3692         if (blk_new_backing) {
3693             new_backing_size = blk_getlength(blk_new_backing);
3694             if (new_backing_size < 0) {
3695                 error_report("Could not get size of '%s': %s",
3696                              out_baseimg, strerror(-new_backing_size));
3697                 ret = -1;
3698                 goto out;
3699             }
3700         }
3701
3702         if (size != 0) {
3703             local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3704         }
3705
3706         for (offset = 0; offset < size; offset += n) {
3707             bool buf_old_is_zero = false;
3708
3709             /* How many bytes can we handle with the next read? */
3710             n = MIN(IO_BUF_SIZE, size - offset);
3711
3712             /* If the cluster is allocated, we don't need to take action */
3713             ret = bdrv_is_allocated(bs, offset, n, &n);
3714             if (ret < 0) {
3715                 error_report("error while reading image metadata: %s",
3716                              strerror(-ret));
3717                 goto out;
3718             }
3719             if (ret) {
3720                 continue;
3721             }
3722
3723             if (prefix_chain_bs) {
3724                 /*
3725                  * If cluster wasn't changed since prefix_chain, we don't need
3726                  * to take action
3727                  */
3728                 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3729                                               false, offset, n, &n);
3730                 if (ret < 0) {
3731                     error_report("error while reading image metadata: %s",
3732                                  strerror(-ret));
3733                     goto out;
3734                 }
3735                 if (!ret) {
3736                     continue;
3737                 }
3738             }
3739
3740             /*
3741              * Read old and new backing file and take into consideration that
3742              * backing files may be smaller than the COW image.
3743              */
3744             if (offset >= old_backing_size) {
3745                 memset(buf_old, 0, n);
3746                 buf_old_is_zero = true;
3747             } else {
3748                 if (offset + n > old_backing_size) {
3749                     n = old_backing_size - offset;
3750                 }
3751
3752                 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3753                 if (ret < 0) {
3754                     error_report("error while reading from old backing file");
3755                     goto out;
3756                 }
3757             }
3758
3759             if (offset >= new_backing_size || !blk_new_backing) {
3760                 memset(buf_new, 0, n);
3761             } else {
3762                 if (offset + n > new_backing_size) {
3763                     n = new_backing_size - offset;
3764                 }
3765
3766                 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3767                 if (ret < 0) {
3768                     error_report("error while reading from new backing file");
3769                     goto out;
3770                 }
3771             }
3772
3773             /* If they differ, we need to write to the COW file */
3774             uint64_t written = 0;
3775
3776             while (written < n) {
3777                 int64_t pnum;
3778
3779                 if (compare_buffers(buf_old + written, buf_new + written,
3780                                     n - written, &pnum))
3781                 {
3782                     if (buf_old_is_zero) {
3783                         ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3784                     } else {
3785                         ret = blk_pwrite(blk, offset + written,
3786                                          buf_old + written, pnum, 0);
3787                     }
3788                     if (ret < 0) {
3789                         error_report("Error while writing to COW image: %s",
3790                             strerror(-ret));
3791                         goto out;
3792                     }
3793                 }
3794
3795                 written += pnum;
3796             }
3797             qemu_progress_print(local_progress, 100);
3798         }
3799     }
3800
3801     /*
3802      * Change the backing file. All clusters that are different from the old
3803      * backing file are overwritten in the COW file now, so the visible content
3804      * doesn't change when we switch the backing file.
3805      */
3806     if (out_baseimg && *out_baseimg) {
3807         ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3808     } else {
3809         ret = bdrv_change_backing_file(bs, NULL, NULL);
3810     }
3811
3812     if (ret == -ENOSPC) {
3813         error_report("Could not change the backing file to '%s': No "
3814                      "space left in the file header", out_baseimg);
3815     } else if (ret < 0) {
3816         error_report("Could not change the backing file to '%s': %s",
3817             out_baseimg, strerror(-ret));
3818     }
3819
3820     qemu_progress_print(100, 0);
3821     /*
3822      * TODO At this point it is possible to check if any clusters that are
3823      * allocated in the COW file are the same in the backing file. If so, they
3824      * could be dropped from the COW file. Don't do this before switching the
3825      * backing file, in case of a crash this would lead to corruption.
3826      */
3827 out:
3828     qemu_progress_end();
3829     /* Cleanup */
3830     if (!unsafe) {
3831         blk_unref(blk_old_backing);
3832         blk_unref(blk_new_backing);
3833     }
3834     qemu_vfree(buf_old);
3835     qemu_vfree(buf_new);
3836
3837     blk_unref(blk);
3838     if (ret) {
3839         return 1;
3840     }
3841     return 0;
3842 }
3843
3844 static int img_resize(int argc, char **argv)
3845 {
3846     Error *err = NULL;
3847     int c, ret, relative;
3848     const char *filename, *fmt, *size;
3849     int64_t n, total_size, current_size;
3850     bool quiet = false;
3851     BlockBackend *blk = NULL;
3852     PreallocMode prealloc = PREALLOC_MODE_OFF;
3853     QemuOpts *param;
3854
3855     static QemuOptsList resize_options = {
3856         .name = "resize_options",
3857         .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3858         .desc = {
3859             {
3860                 .name = BLOCK_OPT_SIZE,
3861                 .type = QEMU_OPT_SIZE,
3862                 .help = "Virtual disk size"
3863             }, {
3864                 /* end of list */
3865             }
3866         },
3867     };
3868     bool image_opts = false;
3869     bool shrink = false;
3870
3871     /* Remove size from argv manually so that negative numbers are not treated
3872      * as options by getopt. */
3873     if (argc < 3) {
3874         error_exit("Not enough arguments");
3875         return 1;
3876     }
3877
3878     size = argv[--argc];
3879
3880     /* Parse getopt arguments */
3881     fmt = NULL;
3882     for(;;) {
3883         static const struct option long_options[] = {
3884             {"help", no_argument, 0, 'h'},
3885             {"object", required_argument, 0, OPTION_OBJECT},
3886             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3887             {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3888             {"shrink", no_argument, 0, OPTION_SHRINK},
3889             {0, 0, 0, 0}
3890         };
3891         c = getopt_long(argc, argv, ":f:hq",
3892                         long_options, NULL);
3893         if (c == -1) {
3894             break;
3895         }
3896         switch(c) {
3897         case ':':
3898             missing_argument(argv[optind - 1]);
3899             break;
3900         case '?':
3901             unrecognized_option(argv[optind - 1]);
3902             break;
3903         case 'h':
3904             help();
3905             break;
3906         case 'f':
3907             fmt = optarg;
3908             break;
3909         case 'q':
3910             quiet = true;
3911             break;
3912         case OPTION_OBJECT: {
3913             QemuOpts *opts;
3914             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3915                                            optarg, true);
3916             if (!opts) {
3917                 return 1;
3918             }
3919         }   break;
3920         case OPTION_IMAGE_OPTS:
3921             image_opts = true;
3922             break;
3923         case OPTION_PREALLOCATION:
3924             prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3925                                        PREALLOC_MODE__MAX, NULL);
3926             if (prealloc == PREALLOC_MODE__MAX) {
3927                 error_report("Invalid preallocation mode '%s'", optarg);
3928                 return 1;
3929             }
3930             break;
3931         case OPTION_SHRINK:
3932             shrink = true;
3933             break;
3934         }
3935     }
3936     if (optind != argc - 1) {
3937         error_exit("Expecting image file name and size");
3938     }
3939     filename = argv[optind++];
3940
3941     if (qemu_opts_foreach(&qemu_object_opts,
3942                           user_creatable_add_opts_foreach,
3943                           qemu_img_object_print_help, &error_fatal)) {
3944         return 1;
3945     }
3946
3947     /* Choose grow, shrink, or absolute resize mode */
3948     switch (size[0]) {
3949     case '+':
3950         relative = 1;
3951         size++;
3952         break;
3953     case '-':
3954         relative = -1;
3955         size++;
3956         break;
3957     default:
3958         relative = 0;
3959         break;
3960     }
3961
3962     /* Parse size */
3963     param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3964     if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
3965         error_report_err(err);
3966         ret = -1;
3967         qemu_opts_del(param);
3968         goto out;
3969     }
3970     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3971     qemu_opts_del(param);
3972
3973     blk = img_open(image_opts, filename, fmt,
3974                    BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3975                    false);
3976     if (!blk) {
3977         ret = -1;
3978         goto out;
3979     }
3980
3981     current_size = blk_getlength(blk);
3982     if (current_size < 0) {
3983         error_report("Failed to inquire current image length: %s",
3984                      strerror(-current_size));
3985         ret = -1;
3986         goto out;
3987     }
3988
3989     if (relative) {
3990         total_size = current_size + n * relative;
3991     } else {
3992         total_size = n;
3993     }
3994     if (total_size <= 0) {
3995         error_report("New image size must be positive");
3996         ret = -1;
3997         goto out;
3998     }
3999
4000     if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4001         error_report("Preallocation can only be used for growing images");
4002         ret = -1;
4003         goto out;
4004     }
4005
4006     if (total_size < current_size && !shrink) {
4007         warn_report("Shrinking an image will delete all data beyond the "
4008                     "shrunken image's end. Before performing such an "
4009                     "operation, make sure there is no important data there.");
4010
4011         if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4012             error_report(
4013               "Use the --shrink option to perform a shrink operation.");
4014             ret = -1;
4015             goto out;
4016         } else {
4017             warn_report("Using the --shrink option will suppress this message. "
4018                         "Note that future versions of qemu-img may refuse to "
4019                         "shrink images without this option.");
4020         }
4021     }
4022
4023     /*
4024      * The user expects the image to have the desired size after
4025      * resizing, so pass @exact=true.  It is of no use to report
4026      * success when the image has not actually been resized.
4027      */
4028     ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
4029     if (!ret) {
4030         qprintf(quiet, "Image resized.\n");
4031     } else {
4032         error_report_err(err);
4033     }
4034 out:
4035     blk_unref(blk);
4036     if (ret) {
4037         return 1;
4038     }
4039     return 0;
4040 }
4041
4042 static void amend_status_cb(BlockDriverState *bs,
4043                             int64_t offset, int64_t total_work_size,
4044                             void *opaque)
4045 {
4046     qemu_progress_print(100.f * offset / total_work_size, 0);
4047 }
4048
4049 static int print_amend_option_help(const char *format)
4050 {
4051     BlockDriver *drv;
4052
4053     /* Find driver and parse its options */
4054     drv = bdrv_find_format(format);
4055     if (!drv) {
4056         error_report("Unknown file format '%s'", format);
4057         return 1;
4058     }
4059
4060     if (!drv->bdrv_amend_options) {
4061         error_report("Format driver '%s' does not support option amendment",
4062                      format);
4063         return 1;
4064     }
4065
4066     /* Every driver supporting amendment must have amend_opts */
4067     assert(drv->amend_opts);
4068
4069     printf("Amend options for '%s':\n", format);
4070     qemu_opts_print_help(drv->amend_opts, false);
4071     return 0;
4072 }
4073
4074 static int img_amend(int argc, char **argv)
4075 {
4076     Error *err = NULL;
4077     int c, ret = 0;
4078     char *options = NULL;
4079     QemuOptsList *amend_opts = NULL;
4080     QemuOpts *opts = NULL;
4081     const char *fmt = NULL, *filename, *cache;
4082     int flags;
4083     bool writethrough;
4084     bool quiet = false, progress = false;
4085     BlockBackend *blk = NULL;
4086     BlockDriverState *bs = NULL;
4087     bool image_opts = false;
4088     bool force = false;
4089
4090     cache = BDRV_DEFAULT_CACHE;
4091     for (;;) {
4092         static const struct option long_options[] = {
4093             {"help", no_argument, 0, 'h'},
4094             {"object", required_argument, 0, OPTION_OBJECT},
4095             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4096             {"force", no_argument, 0, OPTION_FORCE},
4097             {0, 0, 0, 0}
4098         };
4099         c = getopt_long(argc, argv, ":ho:f:t:pq",
4100                         long_options, NULL);
4101         if (c == -1) {
4102             break;
4103         }
4104
4105         switch (c) {
4106         case ':':
4107             missing_argument(argv[optind - 1]);
4108             break;
4109         case '?':
4110             unrecognized_option(argv[optind - 1]);
4111             break;
4112         case 'h':
4113             help();
4114             break;
4115         case 'o':
4116             if (accumulate_options(&options, optarg) < 0) {
4117                 ret = -1;
4118                 goto out_no_progress;
4119             }
4120             break;
4121         case 'f':
4122             fmt = optarg;
4123             break;
4124         case 't':
4125             cache = optarg;
4126             break;
4127         case 'p':
4128             progress = true;
4129             break;
4130         case 'q':
4131             quiet = true;
4132             break;
4133         case OPTION_OBJECT:
4134             opts = qemu_opts_parse_noisily(&qemu_object_opts,
4135                                            optarg, true);
4136             if (!opts) {
4137                 ret = -1;
4138                 goto out_no_progress;
4139             }
4140             break;
4141         case OPTION_IMAGE_OPTS:
4142             image_opts = true;
4143             break;
4144         case OPTION_FORCE:
4145             force = 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 amend_opts */
4211     assert(bs->drv->amend_opts);
4212
4213     amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4214     opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4215     if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
4216         /* Try to parse options using the create options */
4217         Error *err1 = NULL;
4218         amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4219         qemu_opts_del(opts);
4220         opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4221         qemu_opts_do_parse(opts, options, NULL, &err1);
4222
4223         if (!err1) {
4224             error_append_hint(&err,
4225                               "This option is only supported for image creation\n");
4226         } else {
4227             error_free(err1);
4228         }
4229
4230         error_report_err(err);
4231         ret = -1;
4232         goto out;
4233     }
4234
4235     /* In case the driver does not call amend_status_cb() */
4236     qemu_progress_print(0.f, 0);
4237     ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4238     qemu_progress_print(100.f, 0);
4239     if (ret < 0) {
4240         error_report_err(err);
4241         goto out;
4242     }
4243
4244 out:
4245     qemu_progress_end();
4246
4247 out_no_progress:
4248     blk_unref(blk);
4249     qemu_opts_del(opts);
4250     qemu_opts_free(amend_opts);
4251     g_free(options);
4252
4253     if (ret) {
4254         return 1;
4255     }
4256     return 0;
4257 }
4258
4259 typedef struct BenchData {
4260     BlockBackend *blk;
4261     uint64_t image_size;
4262     bool write;
4263     int bufsize;
4264     int step;
4265     int nrreq;
4266     int n;
4267     int flush_interval;
4268     bool drain_on_flush;
4269     uint8_t *buf;
4270     QEMUIOVector *qiov;
4271
4272     int in_flight;
4273     bool in_flush;
4274     uint64_t offset;
4275 } BenchData;
4276
4277 static void bench_undrained_flush_cb(void *opaque, int ret)
4278 {
4279     if (ret < 0) {
4280         error_report("Failed flush request: %s", strerror(-ret));
4281         exit(EXIT_FAILURE);
4282     }
4283 }
4284
4285 static void bench_cb(void *opaque, int ret)
4286 {
4287     BenchData *b = opaque;
4288     BlockAIOCB *acb;
4289
4290     if (ret < 0) {
4291         error_report("Failed request: %s", strerror(-ret));
4292         exit(EXIT_FAILURE);
4293     }
4294
4295     if (b->in_flush) {
4296         /* Just finished a flush with drained queue: Start next requests */
4297         assert(b->in_flight == 0);
4298         b->in_flush = false;
4299     } else if (b->in_flight > 0) {
4300         int remaining = b->n - b->in_flight;
4301
4302         b->n--;
4303         b->in_flight--;
4304
4305         /* Time for flush? Drain queue if requested, then flush */
4306         if (b->flush_interval && remaining % b->flush_interval == 0) {
4307             if (!b->in_flight || !b->drain_on_flush) {
4308                 BlockCompletionFunc *cb;
4309
4310                 if (b->drain_on_flush) {
4311                     b->in_flush = true;
4312                     cb = bench_cb;
4313                 } else {
4314                     cb = bench_undrained_flush_cb;
4315                 }
4316
4317                 acb = blk_aio_flush(b->blk, cb, b);
4318                 if (!acb) {
4319                     error_report("Failed to issue flush request");
4320                     exit(EXIT_FAILURE);
4321                 }
4322             }
4323             if (b->drain_on_flush) {
4324                 return;
4325             }
4326         }
4327     }
4328
4329     while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4330         int64_t offset = b->offset;
4331         /* blk_aio_* might look for completed I/Os and kick bench_cb
4332          * again, so make sure this operation is counted by in_flight
4333          * and b->offset is ready for the next submission.
4334          */
4335         b->in_flight++;
4336         b->offset += b->step;
4337         b->offset %= b->image_size;
4338         if (b->write) {
4339             acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4340         } else {
4341             acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4342         }
4343         if (!acb) {
4344             error_report("Failed to issue request");
4345             exit(EXIT_FAILURE);
4346         }
4347     }
4348 }
4349
4350 static int img_bench(int argc, char **argv)
4351 {
4352     int c, ret = 0;
4353     const char *fmt = NULL, *filename;
4354     bool quiet = false;
4355     bool image_opts = false;
4356     bool is_write = false;
4357     int count = 75000;
4358     int depth = 64;
4359     int64_t offset = 0;
4360     size_t bufsize = 4096;
4361     int pattern = 0;
4362     size_t step = 0;
4363     int flush_interval = 0;
4364     bool drain_on_flush = true;
4365     int64_t image_size;
4366     BlockBackend *blk = NULL;
4367     BenchData data = {};
4368     int flags = 0;
4369     bool writethrough = false;
4370     struct timeval t1, t2;
4371     int i;
4372     bool force_share = false;
4373     size_t buf_size;
4374
4375     for (;;) {
4376         static const struct option long_options[] = {
4377             {"help", no_argument, 0, 'h'},
4378             {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4379             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4380             {"pattern", required_argument, 0, OPTION_PATTERN},
4381             {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4382             {"force-share", no_argument, 0, 'U'},
4383             {0, 0, 0, 0}
4384         };
4385         c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4386                         NULL);
4387         if (c == -1) {
4388             break;
4389         }
4390
4391         switch (c) {
4392         case ':':
4393             missing_argument(argv[optind - 1]);
4394             break;
4395         case '?':
4396             unrecognized_option(argv[optind - 1]);
4397             break;
4398         case 'h':
4399             help();
4400             break;
4401         case 'c':
4402         {
4403             unsigned long res;
4404
4405             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4406                 error_report("Invalid request count specified");
4407                 return 1;
4408             }
4409             count = res;
4410             break;
4411         }
4412         case 'd':
4413         {
4414             unsigned long res;
4415
4416             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4417                 error_report("Invalid queue depth specified");
4418                 return 1;
4419             }
4420             depth = res;
4421             break;
4422         }
4423         case 'f':
4424             fmt = optarg;
4425             break;
4426         case 'n':
4427             flags |= BDRV_O_NATIVE_AIO;
4428             break;
4429         case 'i':
4430             ret = bdrv_parse_aio(optarg, &flags);
4431             if (ret < 0) {
4432                 error_report("Invalid aio option: %s", optarg);
4433                 ret = -1;
4434                 goto out;
4435             }
4436             break;
4437         case 'o':
4438         {
4439             offset = cvtnum("offset", optarg);
4440             if (offset < 0) {
4441                 return 1;
4442             }
4443             break;
4444         }
4445             break;
4446         case 'q':
4447             quiet = true;
4448             break;
4449         case 's':
4450         {
4451             int64_t sval;
4452
4453             sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4454             if (sval < 0) {
4455                 return 1;
4456             }
4457
4458             bufsize = sval;
4459             break;
4460         }
4461         case 'S':
4462         {
4463             int64_t sval;
4464
4465             sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4466             if (sval < 0) {
4467                 return 1;
4468             }
4469
4470             step = sval;
4471             break;
4472         }
4473         case 't':
4474             ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4475             if (ret < 0) {
4476                 error_report("Invalid cache mode");
4477                 ret = -1;
4478                 goto out;
4479             }
4480             break;
4481         case 'w':
4482             flags |= BDRV_O_RDWR;
4483             is_write = true;
4484             break;
4485         case 'U':
4486             force_share = true;
4487             break;
4488         case OPTION_PATTERN:
4489         {
4490             unsigned long res;
4491
4492             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4493                 error_report("Invalid pattern byte specified");
4494                 return 1;
4495             }
4496             pattern = res;
4497             break;
4498         }
4499         case OPTION_FLUSH_INTERVAL:
4500         {
4501             unsigned long res;
4502
4503             if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4504                 error_report("Invalid flush interval specified");
4505                 return 1;
4506             }
4507             flush_interval = res;
4508             break;
4509         }
4510         case OPTION_NO_DRAIN:
4511             drain_on_flush = false;
4512             break;
4513         case OPTION_IMAGE_OPTS:
4514             image_opts = true;
4515             break;
4516         }
4517     }
4518
4519     if (optind != argc - 1) {
4520         error_exit("Expecting one image file name");
4521     }
4522     filename = argv[argc - 1];
4523
4524     if (!is_write && flush_interval) {
4525         error_report("--flush-interval is only available in write tests");
4526         ret = -1;
4527         goto out;
4528     }
4529     if (flush_interval && flush_interval < depth) {
4530         error_report("Flush interval can't be smaller than depth");
4531         ret = -1;
4532         goto out;
4533     }
4534
4535     blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4536                    force_share);
4537     if (!blk) {
4538         ret = -1;
4539         goto out;
4540     }
4541
4542     image_size = blk_getlength(blk);
4543     if (image_size < 0) {
4544         ret = image_size;
4545         goto out;
4546     }
4547
4548     data = (BenchData) {
4549         .blk            = blk,
4550         .image_size     = image_size,
4551         .bufsize        = bufsize,
4552         .step           = step ?: bufsize,
4553         .nrreq          = depth,
4554         .n              = count,
4555         .offset         = offset,
4556         .write          = is_write,
4557         .flush_interval = flush_interval,
4558         .drain_on_flush = drain_on_flush,
4559     };
4560     printf("Sending %d %s requests, %d bytes each, %d in parallel "
4561            "(starting at offset %" PRId64 ", step size %d)\n",
4562            data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4563            data.offset, data.step);
4564     if (flush_interval) {
4565         printf("Sending flush every %d requests\n", flush_interval);
4566     }
4567
4568     buf_size = data.nrreq * data.bufsize;
4569     data.buf = blk_blockalign(blk, buf_size);
4570     memset(data.buf, pattern, data.nrreq * data.bufsize);
4571
4572     blk_register_buf(blk, data.buf, buf_size);
4573
4574     data.qiov = g_new(QEMUIOVector, data.nrreq);
4575     for (i = 0; i < data.nrreq; i++) {
4576         qemu_iovec_init(&data.qiov[i], 1);
4577         qemu_iovec_add(&data.qiov[i],
4578                        data.buf + i * data.bufsize, data.bufsize);
4579     }
4580
4581     gettimeofday(&t1, NULL);
4582     bench_cb(&data, 0);
4583
4584     while (data.n > 0) {
4585         main_loop_wait(false);
4586     }
4587     gettimeofday(&t2, NULL);
4588
4589     printf("Run completed in %3.3f seconds.\n",
4590            (t2.tv_sec - t1.tv_sec)
4591            + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4592
4593 out:
4594     if (data.buf) {
4595         blk_unregister_buf(blk, data.buf);
4596     }
4597     qemu_vfree(data.buf);
4598     blk_unref(blk);
4599
4600     if (ret) {
4601         return 1;
4602     }
4603     return 0;
4604 }
4605
4606 enum ImgBitmapAct {
4607     BITMAP_ADD,
4608     BITMAP_REMOVE,
4609     BITMAP_CLEAR,
4610     BITMAP_ENABLE,
4611     BITMAP_DISABLE,
4612     BITMAP_MERGE,
4613 };
4614 typedef struct ImgBitmapAction {
4615     enum ImgBitmapAct act;
4616     const char *src; /* only used for merge */
4617     QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4618 } ImgBitmapAction;
4619
4620 static int img_bitmap(int argc, char **argv)
4621 {
4622     Error *err = NULL;
4623     int c, ret = 1;
4624     QemuOpts *opts = NULL;
4625     const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4626     const char *filename, *bitmap;
4627     BlockBackend *blk = NULL, *src = NULL;
4628     BlockDriverState *bs = NULL, *src_bs = NULL;
4629     bool image_opts = false;
4630     int64_t granularity = 0;
4631     bool add = false, merge = false;
4632     QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4633     ImgBitmapAction *act, *act_next;
4634     const char *op;
4635
4636     QSIMPLEQ_INIT(&actions);
4637
4638     for (;;) {
4639         static const struct option long_options[] = {
4640             {"help", no_argument, 0, 'h'},
4641             {"object", required_argument, 0, OPTION_OBJECT},
4642             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4643             {"add", no_argument, 0, OPTION_ADD},
4644             {"remove", no_argument, 0, OPTION_REMOVE},
4645             {"clear", no_argument, 0, OPTION_CLEAR},
4646             {"enable", no_argument, 0, OPTION_ENABLE},
4647             {"disable", no_argument, 0, OPTION_DISABLE},
4648             {"merge", required_argument, 0, OPTION_MERGE},
4649             {"granularity", required_argument, 0, 'g'},
4650             {"source-file", required_argument, 0, 'b'},
4651             {"source-format", required_argument, 0, 'F'},
4652             {0, 0, 0, 0}
4653         };
4654         c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4655         if (c == -1) {
4656             break;
4657         }
4658
4659         switch (c) {
4660         case ':':
4661             missing_argument(argv[optind - 1]);
4662             break;
4663         case '?':
4664             unrecognized_option(argv[optind - 1]);
4665             break;
4666         case 'h':
4667             help();
4668             break;
4669         case 'b':
4670             src_filename = optarg;
4671             break;
4672         case 'f':
4673             fmt = optarg;
4674             break;
4675         case 'F':
4676             src_fmt = optarg;
4677             break;
4678         case 'g':
4679             granularity = cvtnum("granularity", optarg);
4680             if (granularity < 0) {
4681                 return 1;
4682             }
4683             break;
4684         case OPTION_ADD:
4685             act = g_new0(ImgBitmapAction, 1);
4686             act->act = BITMAP_ADD;
4687             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4688             add = true;
4689             break;
4690         case OPTION_REMOVE:
4691             act = g_new0(ImgBitmapAction, 1);
4692             act->act = BITMAP_REMOVE;
4693             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4694             break;
4695         case OPTION_CLEAR:
4696             act = g_new0(ImgBitmapAction, 1);
4697             act->act = BITMAP_CLEAR;
4698             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4699             break;
4700         case OPTION_ENABLE:
4701             act = g_new0(ImgBitmapAction, 1);
4702             act->act = BITMAP_ENABLE;
4703             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4704             break;
4705         case OPTION_DISABLE:
4706             act = g_new0(ImgBitmapAction, 1);
4707             act->act = BITMAP_DISABLE;
4708             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4709             break;
4710         case OPTION_MERGE:
4711             act = g_new0(ImgBitmapAction, 1);
4712             act->act = BITMAP_MERGE;
4713             act->src = optarg;
4714             QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4715             merge = true;
4716             break;
4717         case OPTION_OBJECT:
4718             opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4719             if (!opts) {
4720                 goto out;
4721             }
4722             break;
4723         case OPTION_IMAGE_OPTS:
4724             image_opts = true;
4725             break;
4726         }
4727     }
4728
4729     if (qemu_opts_foreach(&qemu_object_opts,
4730                           user_creatable_add_opts_foreach,
4731                           qemu_img_object_print_help, &error_fatal)) {
4732         goto out;
4733     }
4734
4735     if (QSIMPLEQ_EMPTY(&actions)) {
4736         error_report("Need at least one of --add, --remove, --clear, "
4737                      "--enable, --disable, or --merge");
4738         goto out;
4739     }
4740
4741     if (granularity && !add) {
4742         error_report("granularity only supported with --add");
4743         goto out;
4744     }
4745     if (src_fmt && !src_filename) {
4746         error_report("-F only supported with -b");
4747         goto out;
4748     }
4749     if (src_filename && !merge) {
4750         error_report("Merge bitmap source file only supported with "
4751                      "--merge");
4752         goto out;
4753     }
4754
4755     if (optind != argc - 2) {
4756         error_report("Expecting filename and bitmap name");
4757         goto out;
4758     }
4759
4760     filename = argv[optind];
4761     bitmap = argv[optind + 1];
4762
4763     blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4764                    false);
4765     if (!blk) {
4766         goto out;
4767     }
4768     bs = blk_bs(blk);
4769     if (src_filename) {
4770         src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4771         if (!src) {
4772             goto out;
4773         }
4774         src_bs = blk_bs(src);
4775     } else {
4776         src_bs = bs;
4777     }
4778
4779     QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4780         switch (act->act) {
4781         case BITMAP_ADD:
4782             qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4783                                        !!granularity, granularity, true, true,
4784                                        false, false, &err);
4785             op = "add";
4786             break;
4787         case BITMAP_REMOVE:
4788             qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4789             op = "remove";
4790             break;
4791         case BITMAP_CLEAR:
4792             qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4793             op = "clear";
4794             break;
4795         case BITMAP_ENABLE:
4796             qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4797             op = "enable";
4798             break;
4799         case BITMAP_DISABLE:
4800             qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4801             op = "disable";
4802             break;
4803         case BITMAP_MERGE:
4804             do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4805                                   act->src, &err);
4806             op = "merge";
4807             break;
4808         default:
4809             g_assert_not_reached();
4810         }
4811
4812         if (err) {
4813             error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4814                               op, bitmap);
4815             goto out;
4816         }
4817         g_free(act);
4818     }
4819
4820     ret = 0;
4821
4822  out:
4823     blk_unref(src);
4824     blk_unref(blk);
4825     qemu_opts_del(opts);
4826     return ret;
4827 }
4828
4829 #define C_BS      01
4830 #define C_COUNT   02
4831 #define C_IF      04
4832 #define C_OF      010
4833 #define C_SKIP    020
4834
4835 struct DdInfo {
4836     unsigned int flags;
4837     int64_t count;
4838 };
4839
4840 struct DdIo {
4841     int bsz;    /* Block size */
4842     char *filename;
4843     uint8_t *buf;
4844     int64_t offset;
4845 };
4846
4847 struct DdOpts {
4848     const char *name;
4849     int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4850     unsigned int flag;
4851 };
4852
4853 static int img_dd_bs(const char *arg,
4854                      struct DdIo *in, struct DdIo *out,
4855                      struct DdInfo *dd)
4856 {
4857     int64_t res;
4858
4859     res = cvtnum_full("bs", arg, 1, INT_MAX);
4860
4861     if (res < 0) {
4862         return 1;
4863     }
4864     in->bsz = out->bsz = res;
4865
4866     return 0;
4867 }
4868
4869 static int img_dd_count(const char *arg,
4870                         struct DdIo *in, struct DdIo *out,
4871                         struct DdInfo *dd)
4872 {
4873     dd->count = cvtnum("count", arg);
4874
4875     if (dd->count < 0) {
4876         return 1;
4877     }
4878
4879     return 0;
4880 }
4881
4882 static int img_dd_if(const char *arg,
4883                      struct DdIo *in, struct DdIo *out,
4884                      struct DdInfo *dd)
4885 {
4886     in->filename = g_strdup(arg);
4887
4888     return 0;
4889 }
4890
4891 static int img_dd_of(const char *arg,
4892                      struct DdIo *in, struct DdIo *out,
4893                      struct DdInfo *dd)
4894 {
4895     out->filename = g_strdup(arg);
4896
4897     return 0;
4898 }
4899
4900 static int img_dd_skip(const char *arg,
4901                        struct DdIo *in, struct DdIo *out,
4902                        struct DdInfo *dd)
4903 {
4904     in->offset = cvtnum("skip", arg);
4905
4906     if (in->offset < 0) {
4907         return 1;
4908     }
4909
4910     return 0;
4911 }
4912
4913 static int img_dd(int argc, char **argv)
4914 {
4915     int ret = 0;
4916     char *arg = NULL;
4917     char *tmp;
4918     BlockDriver *drv = NULL, *proto_drv = NULL;
4919     BlockBackend *blk1 = NULL, *blk2 = NULL;
4920     QemuOpts *opts = NULL;
4921     QemuOptsList *create_opts = NULL;
4922     Error *local_err = NULL;
4923     bool image_opts = false;
4924     int c, i;
4925     const char *out_fmt = "raw";
4926     const char *fmt = NULL;
4927     int64_t size = 0;
4928     int64_t block_count = 0, out_pos, in_pos;
4929     bool force_share = false;
4930     struct DdInfo dd = {
4931         .flags = 0,
4932         .count = 0,
4933     };
4934     struct DdIo in = {
4935         .bsz = 512, /* Block size is by default 512 bytes */
4936         .filename = NULL,
4937         .buf = NULL,
4938         .offset = 0
4939     };
4940     struct DdIo out = {
4941         .bsz = 512,
4942         .filename = NULL,
4943         .buf = NULL,
4944         .offset = 0
4945     };
4946
4947     const struct DdOpts options[] = {
4948         { "bs", img_dd_bs, C_BS },
4949         { "count", img_dd_count, C_COUNT },
4950         { "if", img_dd_if, C_IF },
4951         { "of", img_dd_of, C_OF },
4952         { "skip", img_dd_skip, C_SKIP },
4953         { NULL, NULL, 0 }
4954     };
4955     const struct option long_options[] = {
4956         { "help", no_argument, 0, 'h'},
4957         { "object", required_argument, 0, OPTION_OBJECT},
4958         { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4959         { "force-share", no_argument, 0, 'U'},
4960         { 0, 0, 0, 0 }
4961     };
4962
4963     while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4964         if (c == EOF) {
4965             break;
4966         }
4967         switch (c) {
4968         case 'O':
4969             out_fmt = optarg;
4970             break;
4971         case 'f':
4972             fmt = optarg;
4973             break;
4974         case ':':
4975             missing_argument(argv[optind - 1]);
4976             break;
4977         case '?':
4978             unrecognized_option(argv[optind - 1]);
4979             break;
4980         case 'h':
4981             help();
4982             break;
4983         case 'U':
4984             force_share = true;
4985             break;
4986         case OPTION_OBJECT:
4987             if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4988                 ret = -1;
4989                 goto out;
4990             }
4991             break;
4992         case OPTION_IMAGE_OPTS:
4993             image_opts = true;
4994             break;
4995         }
4996     }
4997
4998     for (i = optind; i < argc; i++) {
4999         int j;
5000         arg = g_strdup(argv[i]);
5001
5002         tmp = strchr(arg, '=');
5003         if (tmp == NULL) {
5004             error_report("unrecognized operand %s", arg);
5005             ret = -1;
5006             goto out;
5007         }
5008
5009         *tmp++ = '\0';
5010
5011         for (j = 0; options[j].name != NULL; j++) {
5012             if (!strcmp(arg, options[j].name)) {
5013                 break;
5014             }
5015         }
5016         if (options[j].name == NULL) {
5017             error_report("unrecognized operand %s", arg);
5018             ret = -1;
5019             goto out;
5020         }
5021
5022         if (options[j].f(tmp, &in, &out, &dd) != 0) {
5023             ret = -1;
5024             goto out;
5025         }
5026         dd.flags |= options[j].flag;
5027         g_free(arg);
5028         arg = NULL;
5029     }
5030
5031     if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5032         error_report("Must specify both input and output files");
5033         ret = -1;
5034         goto out;
5035     }
5036
5037     if (qemu_opts_foreach(&qemu_object_opts,
5038                           user_creatable_add_opts_foreach,
5039                           qemu_img_object_print_help, &error_fatal)) {
5040         ret = -1;
5041         goto out;
5042     }
5043
5044     blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5045                     force_share);
5046
5047     if (!blk1) {
5048         ret = -1;
5049         goto out;
5050     }
5051
5052     drv = bdrv_find_format(out_fmt);
5053     if (!drv) {
5054         error_report("Unknown file format");
5055         ret = -1;
5056         goto out;
5057     }
5058     proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5059
5060     if (!proto_drv) {
5061         error_report_err(local_err);
5062         ret = -1;
5063         goto out;
5064     }
5065     if (!drv->create_opts) {
5066         error_report("Format driver '%s' does not support image creation",
5067                      drv->format_name);
5068         ret = -1;
5069         goto out;
5070     }
5071     if (!proto_drv->create_opts) {
5072         error_report("Protocol driver '%s' does not support image creation",
5073                      proto_drv->format_name);
5074         ret = -1;
5075         goto out;
5076     }
5077     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5078     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5079
5080     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5081
5082     size = blk_getlength(blk1);
5083     if (size < 0) {
5084         error_report("Failed to get size for '%s'", in.filename);
5085         ret = -1;
5086         goto out;
5087     }
5088
5089     if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5090         dd.count * in.bsz < size) {
5091         size = dd.count * in.bsz;
5092     }
5093
5094     /* Overflow means the specified offset is beyond input image's size */
5095     if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5096                               size < in.bsz * in.offset)) {
5097         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5098     } else {
5099         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5100                             size - in.bsz * in.offset, &error_abort);
5101     }
5102
5103     ret = bdrv_create(drv, out.filename, opts, &local_err);
5104     if (ret < 0) {
5105         error_reportf_err(local_err,
5106                           "%s: error while creating output image: ",
5107                           out.filename);
5108         ret = -1;
5109         goto out;
5110     }
5111
5112     /* TODO, we can't honour --image-opts for the target,
5113      * since it needs to be given in a format compatible
5114      * with the bdrv_create() call above which does not
5115      * support image-opts style.
5116      */
5117     blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5118                          false, false, false);
5119
5120     if (!blk2) {
5121         ret = -1;
5122         goto out;
5123     }
5124
5125     if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5126                               size < in.offset * in.bsz)) {
5127         /* We give a warning if the skip option is bigger than the input
5128          * size and create an empty output disk image (i.e. like dd(1)).
5129          */
5130         error_report("%s: cannot skip to specified offset", in.filename);
5131         in_pos = size;
5132     } else {
5133         in_pos = in.offset * in.bsz;
5134     }
5135
5136     in.buf = g_new(uint8_t, in.bsz);
5137
5138     for (out_pos = 0; in_pos < size; block_count++) {
5139         int in_ret, out_ret;
5140
5141         if (in_pos + in.bsz > size) {
5142             in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5143         } else {
5144             in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5145         }
5146         if (in_ret < 0) {
5147             error_report("error while reading from input image file: %s",
5148                          strerror(-in_ret));
5149             ret = -1;
5150             goto out;
5151         }
5152         in_pos += in_ret;
5153
5154         out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5155
5156         if (out_ret < 0) {
5157             error_report("error while writing to output image file: %s",
5158                          strerror(-out_ret));
5159             ret = -1;
5160             goto out;
5161         }
5162         out_pos += out_ret;
5163     }
5164
5165 out:
5166     g_free(arg);
5167     qemu_opts_del(opts);
5168     qemu_opts_free(create_opts);
5169     blk_unref(blk1);
5170     blk_unref(blk2);
5171     g_free(in.filename);
5172     g_free(out.filename);
5173     g_free(in.buf);
5174     g_free(out.buf);
5175
5176     if (ret) {
5177         return 1;
5178     }
5179     return 0;
5180 }
5181
5182 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5183 {
5184     QString *str;
5185     QObject *obj;
5186     Visitor *v = qobject_output_visitor_new(&obj);
5187
5188     visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5189     visit_complete(v, &obj);
5190     str = qobject_to_json_pretty(obj);
5191     assert(str != NULL);
5192     printf("%s\n", qstring_get_str(str));
5193     qobject_unref(obj);
5194     visit_free(v);
5195     qobject_unref(str);
5196 }
5197
5198 static int img_measure(int argc, char **argv)
5199 {
5200     static const struct option long_options[] = {
5201         {"help", no_argument, 0, 'h'},
5202         {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5203         {"object", required_argument, 0, OPTION_OBJECT},
5204         {"output", required_argument, 0, OPTION_OUTPUT},
5205         {"size", required_argument, 0, OPTION_SIZE},
5206         {"force-share", no_argument, 0, 'U'},
5207         {0, 0, 0, 0}
5208     };
5209     OutputFormat output_format = OFORMAT_HUMAN;
5210     BlockBackend *in_blk = NULL;
5211     BlockDriver *drv;
5212     const char *filename = NULL;
5213     const char *fmt = NULL;
5214     const char *out_fmt = "raw";
5215     char *options = NULL;
5216     char *snapshot_name = NULL;
5217     bool force_share = false;
5218     QemuOpts *opts = NULL;
5219     QemuOpts *object_opts = NULL;
5220     QemuOpts *sn_opts = NULL;
5221     QemuOptsList *create_opts = NULL;
5222     bool image_opts = false;
5223     uint64_t img_size = UINT64_MAX;
5224     BlockMeasureInfo *info = NULL;
5225     Error *local_err = NULL;
5226     int ret = 1;
5227     int c;
5228
5229     while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5230                             long_options, NULL)) != -1) {
5231         switch (c) {
5232         case '?':
5233         case 'h':
5234             help();
5235             break;
5236         case 'f':
5237             fmt = optarg;
5238             break;
5239         case 'O':
5240             out_fmt = optarg;
5241             break;
5242         case 'o':
5243             if (accumulate_options(&options, optarg) < 0) {
5244                 goto out;
5245             }
5246             break;
5247         case 'l':
5248             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5249                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5250                                                   optarg, false);
5251                 if (!sn_opts) {
5252                     error_report("Failed in parsing snapshot param '%s'",
5253                                  optarg);
5254                     goto out;
5255                 }
5256             } else {
5257                 snapshot_name = optarg;
5258             }
5259             break;
5260         case 'U':
5261             force_share = true;
5262             break;
5263         case OPTION_OBJECT:
5264             object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5265                                                   optarg, true);
5266             if (!object_opts) {
5267                 goto out;
5268             }
5269             break;
5270         case OPTION_IMAGE_OPTS:
5271             image_opts = true;
5272             break;
5273         case OPTION_OUTPUT:
5274             if (!strcmp(optarg, "json")) {
5275                 output_format = OFORMAT_JSON;
5276             } else if (!strcmp(optarg, "human")) {
5277                 output_format = OFORMAT_HUMAN;
5278             } else {
5279                 error_report("--output must be used with human or json "
5280                              "as argument.");
5281                 goto out;
5282             }
5283             break;
5284         case OPTION_SIZE:
5285         {
5286             int64_t sval;
5287
5288             sval = cvtnum("image size", optarg);
5289             if (sval < 0) {
5290                 goto out;
5291             }
5292             img_size = (uint64_t)sval;
5293         }
5294         break;
5295         }
5296     }
5297
5298     if (qemu_opts_foreach(&qemu_object_opts,
5299                           user_creatable_add_opts_foreach,
5300                           qemu_img_object_print_help, &error_fatal)) {
5301         goto out;
5302     }
5303
5304     if (argc - optind > 1) {
5305         error_report("At most one filename argument is allowed.");
5306         goto out;
5307     } else if (argc - optind == 1) {
5308         filename = argv[optind];
5309     }
5310
5311     if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5312         error_report("--image-opts, -f, and -l require a filename argument.");
5313         goto out;
5314     }
5315     if (filename && img_size != UINT64_MAX) {
5316         error_report("--size N cannot be used together with a filename.");
5317         goto out;
5318     }
5319     if (!filename && img_size == UINT64_MAX) {
5320         error_report("Either --size N or one filename must be specified.");
5321         goto out;
5322     }
5323
5324     if (filename) {
5325         in_blk = img_open(image_opts, filename, fmt, 0,
5326                           false, false, force_share);
5327         if (!in_blk) {
5328             goto out;
5329         }
5330
5331         if (sn_opts) {
5332             bdrv_snapshot_load_tmp(blk_bs(in_blk),
5333                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5334                     qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5335                     &local_err);
5336         } else if (snapshot_name != NULL) {
5337             bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5338                     snapshot_name, &local_err);
5339         }
5340         if (local_err) {
5341             error_reportf_err(local_err, "Failed to load snapshot: ");
5342             goto out;
5343         }
5344     }
5345
5346     drv = bdrv_find_format(out_fmt);
5347     if (!drv) {
5348         error_report("Unknown file format '%s'", out_fmt);
5349         goto out;
5350     }
5351     if (!drv->create_opts) {
5352         error_report("Format driver '%s' does not support image creation",
5353                      drv->format_name);
5354         goto out;
5355     }
5356
5357     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5358     create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5359     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5360     if (options) {
5361         if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
5362             error_report_err(local_err);
5363             error_report("Invalid options for file format '%s'", out_fmt);
5364             goto out;
5365         }
5366     }
5367     if (img_size != UINT64_MAX) {
5368         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5369     }
5370
5371     info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5372     if (local_err) {
5373         error_report_err(local_err);
5374         goto out;
5375     }
5376
5377     if (output_format == OFORMAT_HUMAN) {
5378         printf("required size: %" PRIu64 "\n", info->required);
5379         printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5380         if (info->has_bitmaps) {
5381             printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5382         }
5383     } else {
5384         dump_json_block_measure_info(info);
5385     }
5386
5387     ret = 0;
5388
5389 out:
5390     qapi_free_BlockMeasureInfo(info);
5391     qemu_opts_del(object_opts);
5392     qemu_opts_del(opts);
5393     qemu_opts_del(sn_opts);
5394     qemu_opts_free(create_opts);
5395     g_free(options);
5396     blk_unref(in_blk);
5397     return ret;
5398 }
5399
5400 static const img_cmd_t img_cmds[] = {
5401 #define DEF(option, callback, arg_string)        \
5402     { option, callback },
5403 #include "qemu-img-cmds.h"
5404 #undef DEF
5405     { NULL, NULL, },
5406 };
5407
5408 int main(int argc, char **argv)
5409 {
5410     const img_cmd_t *cmd;
5411     const char *cmdname;
5412     Error *local_error = NULL;
5413     char *trace_file = NULL;
5414     int c;
5415     static const struct option long_options[] = {
5416         {"help", no_argument, 0, 'h'},
5417         {"version", no_argument, 0, 'V'},
5418         {"trace", required_argument, NULL, 'T'},
5419         {0, 0, 0, 0}
5420     };
5421
5422 #ifdef CONFIG_POSIX
5423     signal(SIGPIPE, SIG_IGN);
5424 #endif
5425
5426     error_init(argv[0]);
5427     module_call_init(MODULE_INIT_TRACE);
5428     qemu_init_exec_dir(argv[0]);
5429
5430     if (qemu_init_main_loop(&local_error)) {
5431         error_report_err(local_error);
5432         exit(EXIT_FAILURE);
5433     }
5434
5435     qcrypto_init(&error_fatal);
5436
5437     module_call_init(MODULE_INIT_QOM);
5438     bdrv_init();
5439     if (argc < 2) {
5440         error_exit("Not enough arguments");
5441     }
5442
5443     qemu_add_opts(&qemu_object_opts);
5444     qemu_add_opts(&qemu_source_opts);
5445     qemu_add_opts(&qemu_trace_opts);
5446
5447     while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5448         switch (c) {
5449         case ':':
5450             missing_argument(argv[optind - 1]);
5451             return 0;
5452         case '?':
5453             unrecognized_option(argv[optind - 1]);
5454             return 0;
5455         case 'h':
5456             help();
5457             return 0;
5458         case 'V':
5459             printf(QEMU_IMG_VERSION);
5460             return 0;
5461         case 'T':
5462             g_free(trace_file);
5463             trace_file = trace_opt_parse(optarg);
5464             break;
5465         }
5466     }
5467
5468     cmdname = argv[optind];
5469
5470     /* reset getopt_long scanning */
5471     argc -= optind;
5472     if (argc < 1) {
5473         return 0;
5474     }
5475     argv += optind;
5476     qemu_reset_optind();
5477
5478     if (!trace_init_backends()) {
5479         exit(1);
5480     }
5481     trace_init_file(trace_file);
5482     qemu_set_log(LOG_TRACE);
5483
5484     /* find the command */
5485     for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5486         if (!strcmp(cmdname, cmd->name)) {
5487             return cmd->handler(argc, argv);
5488         }
5489     }
5490
5491     /* not found */
5492     error_exit("Command not found: %s", cmdname);
5493 }
This page took 0.339821 seconds and 4 git commands to generate.