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