OSDN Git Service

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