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