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