OSDN Git Service

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