block: add flag to indicate that no I/O will be performed
[sdk/emulator/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 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qapi-visit.h"
27 #include "qapi/qmp-output-visitor.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qapi/qmp/qjson.h"
30 #include "qemu/cutils.h"
31 #include "qemu/config-file.h"
32 #include "qemu/option.h"
33 #include "qemu/error-report.h"
34 #include "qom/object_interfaces.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/block-backend.h"
37 #include "block/block_int.h"
38 #include "block/blockjob.h"
39 #include "block/qapi.h"
40 #include <getopt.h>
41
42 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
43                           ", Copyright (c) 2004-2008 Fabrice Bellard\n"
44
45 typedef struct img_cmd_t {
46     const char *name;
47     int (*handler)(int argc, char **argv);
48 } img_cmd_t;
49
50 enum {
51     OPTION_OUTPUT = 256,
52     OPTION_BACKING_CHAIN = 257,
53     OPTION_OBJECT = 258,
54     OPTION_IMAGE_OPTS = 259,
55 };
56
57 typedef enum OutputFormat {
58     OFORMAT_JSON,
59     OFORMAT_HUMAN,
60 } OutputFormat;
61
62 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
63 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
64 #define BDRV_DEFAULT_CACHE "writeback"
65
66 static void format_print(void *opaque, const char *name)
67 {
68     printf(" %s", name);
69 }
70
71 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
72 {
73     va_list ap;
74
75     error_printf("qemu-img: ");
76
77     va_start(ap, fmt);
78     error_vprintf(fmt, ap);
79     va_end(ap);
80
81     error_printf("\nTry 'qemu-img --help' for more information\n");
82     exit(EXIT_FAILURE);
83 }
84
85 /* Please keep in synch with qemu-img.texi */
86 static void QEMU_NORETURN help(void)
87 {
88     const char *help_msg =
89            QEMU_IMG_VERSION
90            "usage: qemu-img command [command options]\n"
91            "QEMU disk image utility\n"
92            "\n"
93            "Command syntax:\n"
94 #define DEF(option, callback, arg_string)        \
95            "  " arg_string "\n"
96 #include "qemu-img-cmds.h"
97 #undef DEF
98 #undef GEN_DOCS
99            "\n"
100            "Command parameters:\n"
101            "  'filename' is a disk image filename\n"
102            "  'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
103            "    manual page for a description of the object properties. The most common\n"
104            "    object type is a 'secret', which is used to supply passwords and/or\n"
105            "    encryption keys.\n"
106            "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
107            "  'cache' is the cache mode used to write the output disk image, the valid\n"
108            "    options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
109            "    'directsync' and 'unsafe' (default for convert)\n"
110            "  'src_cache' is the cache mode used to read input disk images, the valid\n"
111            "    options are the same as for the 'cache' option\n"
112            "  'size' is the disk image size in bytes. Optional suffixes\n"
113            "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
114            "    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are\n"
115            "    supported. 'b' is ignored.\n"
116            "  'output_filename' is the destination disk image filename\n"
117            "  'output_fmt' is the destination format\n"
118            "  'options' is a comma separated list of format specific options in a\n"
119            "    name=value format. Use -o ? for an overview of the options supported by the\n"
120            "    used format\n"
121            "  'snapshot_param' is param used for internal snapshot, format\n"
122            "    is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
123            "    '[ID_OR_NAME]'\n"
124            "  'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
125            "    instead\n"
126            "  '-c' indicates that target image must be compressed (qcow format only)\n"
127            "  '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
128            "       match exactly. The image doesn't need a working backing file before\n"
129            "       rebasing in this case (useful for renaming the backing file)\n"
130            "  '-h' with or without a command shows this help and lists the supported formats\n"
131            "  '-p' show progress of command (only certain commands)\n"
132            "  '-q' use Quiet mode - do not print any output (except errors)\n"
133            "  '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
134            "       contain only zeros for qemu-img to create a sparse image during\n"
135            "       conversion. If the number of bytes is 0, the source will not be scanned for\n"
136            "       unallocated or zero sectors, and the destination image will always be\n"
137            "       fully allocated\n"
138            "  '--output' takes the format in which the output must be done (human or json)\n"
139            "  '-n' skips the target volume creation (useful if the volume is created\n"
140            "       prior to running qemu-img)\n"
141            "\n"
142            "Parameters to check subcommand:\n"
143            "  '-r' tries to repair any inconsistencies that are found during the check.\n"
144            "       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
145            "       kinds of errors, with a higher risk of choosing the wrong fix or\n"
146            "       hiding corruption that has already occurred.\n"
147            "\n"
148            "Parameters to snapshot subcommand:\n"
149            "  'snapshot' is the name of the snapshot to create, apply or delete\n"
150            "  '-a' applies a snapshot (revert disk to saved state)\n"
151            "  '-c' creates a snapshot\n"
152            "  '-d' deletes a snapshot\n"
153            "  '-l' lists all snapshots in the given image\n"
154            "\n"
155            "Parameters to compare subcommand:\n"
156            "  '-f' first image format\n"
157            "  '-F' second image format\n"
158            "  '-s' run in Strict mode - fail on different image size or sector allocation\n";
159
160     printf("%s\nSupported formats:", help_msg);
161     bdrv_iterate_format(format_print, NULL);
162     printf("\n");
163     exit(EXIT_SUCCESS);
164 }
165
166 static QemuOptsList qemu_object_opts = {
167     .name = "object",
168     .implied_opt_name = "qom-type",
169     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
170     .desc = {
171         { }
172     },
173 };
174
175 static QemuOptsList qemu_source_opts = {
176     .name = "source",
177     .implied_opt_name = "file",
178     .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
179     .desc = {
180         { }
181     },
182 };
183
184 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
185 {
186     int ret = 0;
187     if (!quiet) {
188         va_list args;
189         va_start(args, fmt);
190         ret = vprintf(fmt, args);
191         va_end(args);
192     }
193     return ret;
194 }
195
196
197 static int print_block_option_help(const char *filename, const char *fmt)
198 {
199     BlockDriver *drv, *proto_drv;
200     QemuOptsList *create_opts = NULL;
201     Error *local_err = NULL;
202
203     /* Find driver and parse its options */
204     drv = bdrv_find_format(fmt);
205     if (!drv) {
206         error_report("Unknown file format '%s'", fmt);
207         return 1;
208     }
209
210     create_opts = qemu_opts_append(create_opts, drv->create_opts);
211     if (filename) {
212         proto_drv = bdrv_find_protocol(filename, true, &local_err);
213         if (!proto_drv) {
214             error_report_err(local_err);
215             qemu_opts_free(create_opts);
216             return 1;
217         }
218         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
219     }
220
221     qemu_opts_print_help(create_opts);
222     qemu_opts_free(create_opts);
223     return 0;
224 }
225
226
227 static int img_open_password(BlockBackend *blk, const char *filename,
228                              int flags, bool quiet)
229 {
230     BlockDriverState *bs;
231     char password[256];
232
233     bs = blk_bs(blk);
234     if (bdrv_is_encrypted(bs) && !(flags & BDRV_O_NO_IO)) {
235         qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
236         if (qemu_read_password(password, sizeof(password)) < 0) {
237             error_report("No password given");
238             return -1;
239         }
240         if (bdrv_set_key(bs, password) < 0) {
241             error_report("invalid password");
242             return -1;
243         }
244     }
245     return 0;
246 }
247
248
249 static BlockBackend *img_open_opts(const char *optstr,
250                                    QemuOpts *opts, int flags,
251                                    bool quiet)
252 {
253     QDict *options;
254     Error *local_err = NULL;
255     BlockBackend *blk;
256     options = qemu_opts_to_qdict(opts, NULL);
257     blk = blk_new_open(NULL, NULL, options, flags, &local_err);
258     if (!blk) {
259         error_reportf_err(local_err, "Could not open '%s'", optstr);
260         return NULL;
261     }
262
263     if (img_open_password(blk, optstr, flags, quiet) < 0) {
264         blk_unref(blk);
265         return NULL;
266     }
267     return blk;
268 }
269
270 static BlockBackend *img_open_file(const char *filename,
271                                    const char *fmt, int flags,
272                                    bool quiet)
273 {
274     BlockBackend *blk;
275     Error *local_err = NULL;
276     QDict *options = NULL;
277
278     if (fmt) {
279         options = qdict_new();
280         qdict_put(options, "driver", qstring_from_str(fmt));
281     }
282
283     blk = blk_new_open(filename, NULL, options, flags, &local_err);
284     if (!blk) {
285         error_reportf_err(local_err, "Could not open '%s': ", filename);
286         return NULL;
287     }
288
289     if (img_open_password(blk, filename, flags, quiet) < 0) {
290         blk_unref(blk);
291         return NULL;
292     }
293     return blk;
294 }
295
296
297 static BlockBackend *img_open(bool image_opts,
298                               const char *filename,
299                               const char *fmt, int flags,
300                               bool quiet)
301 {
302     BlockBackend *blk;
303     if (image_opts) {
304         QemuOpts *opts;
305         if (fmt) {
306             error_report("--image-opts and --format are mutually exclusive");
307             return NULL;
308         }
309         opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
310                                        filename, true);
311         if (!opts) {
312             return NULL;
313         }
314         blk = img_open_opts(filename, opts, flags, quiet);
315     } else {
316         blk = img_open_file(filename, fmt, flags, quiet);
317     }
318     return blk;
319 }
320
321
322 static int add_old_style_options(const char *fmt, QemuOpts *opts,
323                                  const char *base_filename,
324                                  const char *base_fmt)
325 {
326     Error *err = NULL;
327
328     if (base_filename) {
329         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
330         if (err) {
331             error_report("Backing file not supported for file format '%s'",
332                          fmt);
333             error_free(err);
334             return -1;
335         }
336     }
337     if (base_fmt) {
338         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
339         if (err) {
340             error_report("Backing file format not supported for file "
341                          "format '%s'", fmt);
342             error_free(err);
343             return -1;
344         }
345     }
346     return 0;
347 }
348
349 static int img_create(int argc, char **argv)
350 {
351     int c;
352     uint64_t img_size = -1;
353     const char *fmt = "raw";
354     const char *base_fmt = NULL;
355     const char *filename;
356     const char *base_filename = NULL;
357     char *options = NULL;
358     Error *local_err = NULL;
359     bool quiet = false;
360
361     for(;;) {
362         static const struct option long_options[] = {
363             {"help", no_argument, 0, 'h'},
364             {"object", required_argument, 0, OPTION_OBJECT},
365             {0, 0, 0, 0}
366         };
367         c = getopt_long(argc, argv, "F:b:f:he6o:q",
368                         long_options, NULL);
369         if (c == -1) {
370             break;
371         }
372         switch(c) {
373         case '?':
374         case 'h':
375             help();
376             break;
377         case 'F':
378             base_fmt = optarg;
379             break;
380         case 'b':
381             base_filename = optarg;
382             break;
383         case 'f':
384             fmt = optarg;
385             break;
386         case 'e':
387             error_report("option -e is deprecated, please use \'-o "
388                   "encryption\' instead!");
389             goto fail;
390         case '6':
391             error_report("option -6 is deprecated, please use \'-o "
392                   "compat6\' instead!");
393             goto fail;
394         case 'o':
395             if (!is_valid_option_list(optarg)) {
396                 error_report("Invalid option list: %s", optarg);
397                 goto fail;
398             }
399             if (!options) {
400                 options = g_strdup(optarg);
401             } else {
402                 char *old_options = options;
403                 options = g_strdup_printf("%s,%s", options, optarg);
404                 g_free(old_options);
405             }
406             break;
407         case 'q':
408             quiet = true;
409             break;
410         case OPTION_OBJECT: {
411             QemuOpts *opts;
412             opts = qemu_opts_parse_noisily(&qemu_object_opts,
413                                            optarg, true);
414             if (!opts) {
415                 goto fail;
416             }
417         }   break;
418         }
419     }
420
421     /* Get the filename */
422     filename = (optind < argc) ? argv[optind] : NULL;
423     if (options && has_help_option(options)) {
424         g_free(options);
425         return print_block_option_help(filename, fmt);
426     }
427
428     if (optind >= argc) {
429         error_exit("Expecting image file name");
430     }
431     optind++;
432
433     if (qemu_opts_foreach(&qemu_object_opts,
434                           user_creatable_add_opts_foreach,
435                           NULL, &local_err)) {
436         error_report_err(local_err);
437         goto fail;
438     }
439
440     /* Get image size, if specified */
441     if (optind < argc) {
442         int64_t sval;
443         char *end;
444         sval = qemu_strtosz_suffix(argv[optind++], &end,
445                                    QEMU_STRTOSZ_DEFSUFFIX_B);
446         if (sval < 0 || *end) {
447             if (sval == -ERANGE) {
448                 error_report("Image size must be less than 8 EiB!");
449             } else {
450                 error_report("Invalid image size specified! You may use k, M, "
451                       "G, T, P or E suffixes for ");
452                 error_report("kilobytes, megabytes, gigabytes, terabytes, "
453                              "petabytes and exabytes.");
454             }
455             goto fail;
456         }
457         img_size = (uint64_t)sval;
458     }
459     if (optind != argc) {
460         error_exit("Unexpected argument: %s", argv[optind]);
461     }
462
463     bdrv_img_create(filename, fmt, base_filename, base_fmt,
464                     options, img_size, BDRV_O_FLAGS, &local_err, quiet);
465     if (local_err) {
466         error_reportf_err(local_err, "%s: ", filename);
467         goto fail;
468     }
469
470     g_free(options);
471     return 0;
472
473 fail:
474     g_free(options);
475     return 1;
476 }
477
478 static void dump_json_image_check(ImageCheck *check, bool quiet)
479 {
480     Error *local_err = NULL;
481     QString *str;
482     QmpOutputVisitor *ov = qmp_output_visitor_new();
483     QObject *obj;
484     visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
485                           &local_err);
486     obj = qmp_output_get_qobject(ov);
487     str = qobject_to_json_pretty(obj);
488     assert(str != NULL);
489     qprintf(quiet, "%s\n", qstring_get_str(str));
490     qobject_decref(obj);
491     qmp_output_visitor_cleanup(ov);
492     QDECREF(str);
493 }
494
495 static void dump_human_image_check(ImageCheck *check, bool quiet)
496 {
497     if (!(check->corruptions || check->leaks || check->check_errors)) {
498         qprintf(quiet, "No errors were found on the image.\n");
499     } else {
500         if (check->corruptions) {
501             qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
502                     "Data may be corrupted, or further writes to the image "
503                     "may corrupt it.\n",
504                     check->corruptions);
505         }
506
507         if (check->leaks) {
508             qprintf(quiet,
509                     "\n%" PRId64 " leaked clusters were found on the image.\n"
510                     "This means waste of disk space, but no harm to data.\n",
511                     check->leaks);
512         }
513
514         if (check->check_errors) {
515             qprintf(quiet,
516                     "\n%" PRId64
517                     " internal errors have occurred during the check.\n",
518                     check->check_errors);
519         }
520     }
521
522     if (check->total_clusters != 0 && check->allocated_clusters != 0) {
523         qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
524                 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
525                 check->allocated_clusters, check->total_clusters,
526                 check->allocated_clusters * 100.0 / check->total_clusters,
527                 check->fragmented_clusters * 100.0 / check->allocated_clusters,
528                 check->compressed_clusters * 100.0 /
529                 check->allocated_clusters);
530     }
531
532     if (check->image_end_offset) {
533         qprintf(quiet,
534                 "Image end offset: %" PRId64 "\n", check->image_end_offset);
535     }
536 }
537
538 static int collect_image_check(BlockDriverState *bs,
539                    ImageCheck *check,
540                    const char *filename,
541                    const char *fmt,
542                    int fix)
543 {
544     int ret;
545     BdrvCheckResult result;
546
547     ret = bdrv_check(bs, &result, fix);
548     if (ret < 0) {
549         return ret;
550     }
551
552     check->filename                 = g_strdup(filename);
553     check->format                   = g_strdup(bdrv_get_format_name(bs));
554     check->check_errors             = result.check_errors;
555     check->corruptions              = result.corruptions;
556     check->has_corruptions          = result.corruptions != 0;
557     check->leaks                    = result.leaks;
558     check->has_leaks                = result.leaks != 0;
559     check->corruptions_fixed        = result.corruptions_fixed;
560     check->has_corruptions_fixed    = result.corruptions != 0;
561     check->leaks_fixed              = result.leaks_fixed;
562     check->has_leaks_fixed          = result.leaks != 0;
563     check->image_end_offset         = result.image_end_offset;
564     check->has_image_end_offset     = result.image_end_offset != 0;
565     check->total_clusters           = result.bfi.total_clusters;
566     check->has_total_clusters       = result.bfi.total_clusters != 0;
567     check->allocated_clusters       = result.bfi.allocated_clusters;
568     check->has_allocated_clusters   = result.bfi.allocated_clusters != 0;
569     check->fragmented_clusters      = result.bfi.fragmented_clusters;
570     check->has_fragmented_clusters  = result.bfi.fragmented_clusters != 0;
571     check->compressed_clusters      = result.bfi.compressed_clusters;
572     check->has_compressed_clusters  = result.bfi.compressed_clusters != 0;
573
574     return 0;
575 }
576
577 /*
578  * Checks an image for consistency. Exit codes:
579  *
580  *  0 - Check completed, image is good
581  *  1 - Check not completed because of internal errors
582  *  2 - Check completed, image is corrupted
583  *  3 - Check completed, image has leaked clusters, but is good otherwise
584  * 63 - Checks are not supported by the image format
585  */
586 static int img_check(int argc, char **argv)
587 {
588     int c, ret;
589     OutputFormat output_format = OFORMAT_HUMAN;
590     const char *filename, *fmt, *output, *cache;
591     BlockBackend *blk;
592     BlockDriverState *bs;
593     int fix = 0;
594     int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
595     ImageCheck *check;
596     bool quiet = false;
597     Error *local_err = NULL;
598     bool image_opts = false;
599
600     fmt = NULL;
601     output = NULL;
602     cache = BDRV_DEFAULT_CACHE;
603     for(;;) {
604         int option_index = 0;
605         static const struct option long_options[] = {
606             {"help", no_argument, 0, 'h'},
607             {"format", required_argument, 0, 'f'},
608             {"repair", required_argument, 0, 'r'},
609             {"output", required_argument, 0, OPTION_OUTPUT},
610             {"object", required_argument, 0, OPTION_OBJECT},
611             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
612             {0, 0, 0, 0}
613         };
614         c = getopt_long(argc, argv, "hf:r:T:q",
615                         long_options, &option_index);
616         if (c == -1) {
617             break;
618         }
619         switch(c) {
620         case '?':
621         case 'h':
622             help();
623             break;
624         case 'f':
625             fmt = optarg;
626             break;
627         case 'r':
628             flags |= BDRV_O_RDWR;
629
630             if (!strcmp(optarg, "leaks")) {
631                 fix = BDRV_FIX_LEAKS;
632             } else if (!strcmp(optarg, "all")) {
633                 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
634             } else {
635                 error_exit("Unknown option value for -r "
636                            "(expecting 'leaks' or 'all'): %s", optarg);
637             }
638             break;
639         case OPTION_OUTPUT:
640             output = optarg;
641             break;
642         case 'T':
643             cache = optarg;
644             break;
645         case 'q':
646             quiet = true;
647             break;
648         case OPTION_OBJECT: {
649             QemuOpts *opts;
650             opts = qemu_opts_parse_noisily(&qemu_object_opts,
651                                            optarg, true);
652             if (!opts) {
653                 return 1;
654             }
655         }   break;
656         case OPTION_IMAGE_OPTS:
657             image_opts = true;
658             break;
659         }
660     }
661     if (optind != argc - 1) {
662         error_exit("Expecting one image file name");
663     }
664     filename = argv[optind++];
665
666     if (output && !strcmp(output, "json")) {
667         output_format = OFORMAT_JSON;
668     } else if (output && !strcmp(output, "human")) {
669         output_format = OFORMAT_HUMAN;
670     } else if (output) {
671         error_report("--output must be used with human or json as argument.");
672         return 1;
673     }
674
675     if (qemu_opts_foreach(&qemu_object_opts,
676                           user_creatable_add_opts_foreach,
677                           NULL, &local_err)) {
678         error_report_err(local_err);
679         return 1;
680     }
681
682     ret = bdrv_parse_cache_flags(cache, &flags);
683     if (ret < 0) {
684         error_report("Invalid source cache option: %s", cache);
685         return 1;
686     }
687
688     blk = img_open(image_opts, filename, fmt, flags, quiet);
689     if (!blk) {
690         return 1;
691     }
692     bs = blk_bs(blk);
693
694     check = g_new0(ImageCheck, 1);
695     ret = collect_image_check(bs, check, filename, fmt, fix);
696
697     if (ret == -ENOTSUP) {
698         error_report("This image format does not support checks");
699         ret = 63;
700         goto fail;
701     }
702
703     if (check->corruptions_fixed || check->leaks_fixed) {
704         int corruptions_fixed, leaks_fixed;
705
706         leaks_fixed         = check->leaks_fixed;
707         corruptions_fixed   = check->corruptions_fixed;
708
709         if (output_format == OFORMAT_HUMAN) {
710             qprintf(quiet,
711                     "The following inconsistencies were found and repaired:\n\n"
712                     "    %" PRId64 " leaked clusters\n"
713                     "    %" PRId64 " corruptions\n\n"
714                     "Double checking the fixed image now...\n",
715                     check->leaks_fixed,
716                     check->corruptions_fixed);
717         }
718
719         ret = collect_image_check(bs, check, filename, fmt, 0);
720
721         check->leaks_fixed          = leaks_fixed;
722         check->corruptions_fixed    = corruptions_fixed;
723     }
724
725     if (!ret) {
726         switch (output_format) {
727         case OFORMAT_HUMAN:
728             dump_human_image_check(check, quiet);
729             break;
730         case OFORMAT_JSON:
731             dump_json_image_check(check, quiet);
732             break;
733         }
734     }
735
736     if (ret || check->check_errors) {
737         if (ret) {
738             error_report("Check failed: %s", strerror(-ret));
739         } else {
740             error_report("Check failed");
741         }
742         ret = 1;
743         goto fail;
744     }
745
746     if (check->corruptions) {
747         ret = 2;
748     } else if (check->leaks) {
749         ret = 3;
750     } else {
751         ret = 0;
752     }
753
754 fail:
755     qapi_free_ImageCheck(check);
756     blk_unref(blk);
757     return ret;
758 }
759
760 typedef struct CommonBlockJobCBInfo {
761     BlockDriverState *bs;
762     Error **errp;
763 } CommonBlockJobCBInfo;
764
765 static void common_block_job_cb(void *opaque, int ret)
766 {
767     CommonBlockJobCBInfo *cbi = opaque;
768
769     if (ret < 0) {
770         error_setg_errno(cbi->errp, -ret, "Block job failed");
771     }
772 }
773
774 static void run_block_job(BlockJob *job, Error **errp)
775 {
776     AioContext *aio_context = bdrv_get_aio_context(job->bs);
777
778     do {
779         aio_poll(aio_context, true);
780         qemu_progress_print(job->len ?
781                             ((float)job->offset / job->len * 100.f) : 0.0f, 0);
782     } while (!job->ready);
783
784     block_job_complete_sync(job, errp);
785
786     /* A block job may finish instantaneously without publishing any progress,
787      * so just signal completion here */
788     qemu_progress_print(100.f, 0);
789 }
790
791 static int img_commit(int argc, char **argv)
792 {
793     int c, ret, flags;
794     const char *filename, *fmt, *cache, *base;
795     BlockBackend *blk;
796     BlockDriverState *bs, *base_bs;
797     bool progress = false, quiet = false, drop = false;
798     Error *local_err = NULL;
799     CommonBlockJobCBInfo cbi;
800     bool image_opts = false;
801
802     fmt = NULL;
803     cache = BDRV_DEFAULT_CACHE;
804     base = NULL;
805     for(;;) {
806         static const struct option long_options[] = {
807             {"help", no_argument, 0, 'h'},
808             {"object", required_argument, 0, OPTION_OBJECT},
809             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
810             {0, 0, 0, 0}
811         };
812         c = getopt_long(argc, argv, "f:ht:b:dpq",
813                         long_options, NULL);
814         if (c == -1) {
815             break;
816         }
817         switch(c) {
818         case '?':
819         case 'h':
820             help();
821             break;
822         case 'f':
823             fmt = optarg;
824             break;
825         case 't':
826             cache = optarg;
827             break;
828         case 'b':
829             base = optarg;
830             /* -b implies -d */
831             drop = true;
832             break;
833         case 'd':
834             drop = true;
835             break;
836         case 'p':
837             progress = true;
838             break;
839         case 'q':
840             quiet = true;
841             break;
842         case OPTION_OBJECT: {
843             QemuOpts *opts;
844             opts = qemu_opts_parse_noisily(&qemu_object_opts,
845                                            optarg, true);
846             if (!opts) {
847                 return 1;
848             }
849         }   break;
850         case OPTION_IMAGE_OPTS:
851             image_opts = true;
852             break;
853         }
854     }
855
856     /* Progress is not shown in Quiet mode */
857     if (quiet) {
858         progress = false;
859     }
860
861     if (optind != argc - 1) {
862         error_exit("Expecting one image file name");
863     }
864     filename = argv[optind++];
865
866     if (qemu_opts_foreach(&qemu_object_opts,
867                           user_creatable_add_opts_foreach,
868                           NULL, &local_err)) {
869         error_report_err(local_err);
870         return 1;
871     }
872
873     flags = BDRV_O_RDWR | BDRV_O_UNMAP;
874     ret = bdrv_parse_cache_flags(cache, &flags);
875     if (ret < 0) {
876         error_report("Invalid cache option: %s", cache);
877         return 1;
878     }
879
880     blk = img_open(image_opts, filename, fmt, flags, quiet);
881     if (!blk) {
882         return 1;
883     }
884     bs = blk_bs(blk);
885
886     qemu_progress_init(progress, 1.f);
887     qemu_progress_print(0.f, 100);
888
889     if (base) {
890         base_bs = bdrv_find_backing_image(bs, base);
891         if (!base_bs) {
892             error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
893             goto done;
894         }
895     } else {
896         /* This is different from QMP, which by default uses the deepest file in
897          * the backing chain (i.e., the very base); however, the traditional
898          * behavior of qemu-img commit is using the immediate backing file. */
899         base_bs = backing_bs(bs);
900         if (!base_bs) {
901             error_setg(&local_err, "Image does not have a backing file");
902             goto done;
903         }
904     }
905
906     cbi = (CommonBlockJobCBInfo){
907         .errp = &local_err,
908         .bs   = bs,
909     };
910
911     commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
912                         common_block_job_cb, &cbi, &local_err);
913     if (local_err) {
914         goto done;
915     }
916
917     /* When the block job completes, the BlockBackend reference will point to
918      * the old backing file. In order to avoid that the top image is already
919      * deleted, so we can still empty it afterwards, increment the reference
920      * counter here preemptively. */
921     if (!drop) {
922         bdrv_ref(bs);
923     }
924
925     run_block_job(bs->job, &local_err);
926     if (local_err) {
927         goto unref_backing;
928     }
929
930     if (!drop && bs->drv->bdrv_make_empty) {
931         ret = bs->drv->bdrv_make_empty(bs);
932         if (ret) {
933             error_setg_errno(&local_err, -ret, "Could not empty %s",
934                              filename);
935             goto unref_backing;
936         }
937     }
938
939 unref_backing:
940     if (!drop) {
941         bdrv_unref(bs);
942     }
943
944 done:
945     qemu_progress_end();
946
947     blk_unref(blk);
948
949     if (local_err) {
950         error_report_err(local_err);
951         return 1;
952     }
953
954     qprintf(quiet, "Image committed.\n");
955     return 0;
956 }
957
958 /*
959  * Returns true iff the first sector pointed to by 'buf' contains at least
960  * a non-NUL byte.
961  *
962  * 'pnum' is set to the number of sectors (including and immediately following
963  * the first one) that are known to be in the same allocated/unallocated state.
964  */
965 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
966 {
967     bool is_zero;
968     int i;
969
970     if (n <= 0) {
971         *pnum = 0;
972         return 0;
973     }
974     is_zero = buffer_is_zero(buf, 512);
975     for(i = 1; i < n; i++) {
976         buf += 512;
977         if (is_zero != buffer_is_zero(buf, 512)) {
978             break;
979         }
980     }
981     *pnum = i;
982     return !is_zero;
983 }
984
985 /*
986  * Like is_allocated_sectors, but if the buffer starts with a used sector,
987  * up to 'min' consecutive sectors containing zeros are ignored. This avoids
988  * breaking up write requests for only small sparse areas.
989  */
990 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
991     int min)
992 {
993     int ret;
994     int num_checked, num_used;
995
996     if (n < min) {
997         min = n;
998     }
999
1000     ret = is_allocated_sectors(buf, n, pnum);
1001     if (!ret) {
1002         return ret;
1003     }
1004
1005     num_used = *pnum;
1006     buf += BDRV_SECTOR_SIZE * *pnum;
1007     n -= *pnum;
1008     num_checked = num_used;
1009
1010     while (n > 0) {
1011         ret = is_allocated_sectors(buf, n, pnum);
1012
1013         buf += BDRV_SECTOR_SIZE * *pnum;
1014         n -= *pnum;
1015         num_checked += *pnum;
1016         if (ret) {
1017             num_used = num_checked;
1018         } else if (*pnum >= min) {
1019             break;
1020         }
1021     }
1022
1023     *pnum = num_used;
1024     return 1;
1025 }
1026
1027 /*
1028  * Compares two buffers sector by sector. Returns 0 if the first sector of both
1029  * buffers matches, non-zero otherwise.
1030  *
1031  * pnum is set to the number of sectors (including and immediately following
1032  * the first one) that are known to have the same comparison result
1033  */
1034 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1035     int *pnum)
1036 {
1037     bool res;
1038     int i;
1039
1040     if (n <= 0) {
1041         *pnum = 0;
1042         return 0;
1043     }
1044
1045     res = !!memcmp(buf1, buf2, 512);
1046     for(i = 1; i < n; i++) {
1047         buf1 += 512;
1048         buf2 += 512;
1049
1050         if (!!memcmp(buf1, buf2, 512) != res) {
1051             break;
1052         }
1053     }
1054
1055     *pnum = i;
1056     return res;
1057 }
1058
1059 #define IO_BUF_SIZE (2 * 1024 * 1024)
1060
1061 static int64_t sectors_to_bytes(int64_t sectors)
1062 {
1063     return sectors << BDRV_SECTOR_BITS;
1064 }
1065
1066 static int64_t sectors_to_process(int64_t total, int64_t from)
1067 {
1068     return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1069 }
1070
1071 /*
1072  * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1073  *
1074  * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1075  * data and negative value on error.
1076  *
1077  * @param blk:  BlockBackend for the image
1078  * @param sect_num: Number of first sector to check
1079  * @param sect_count: Number of sectors to check
1080  * @param filename: Name of disk file we are checking (logging purpose)
1081  * @param buffer: Allocated buffer for storing read data
1082  * @param quiet: Flag for quiet mode
1083  */
1084 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1085                                int sect_count, const char *filename,
1086                                uint8_t *buffer, bool quiet)
1087 {
1088     int pnum, ret = 0;
1089     ret = blk_read(blk, sect_num, buffer, sect_count);
1090     if (ret < 0) {
1091         error_report("Error while reading offset %" PRId64 " of %s: %s",
1092                      sectors_to_bytes(sect_num), filename, strerror(-ret));
1093         return ret;
1094     }
1095     ret = is_allocated_sectors(buffer, sect_count, &pnum);
1096     if (ret || pnum != sect_count) {
1097         qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1098                 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1099         return 1;
1100     }
1101
1102     return 0;
1103 }
1104
1105 /*
1106  * Compares two images. Exit codes:
1107  *
1108  * 0 - Images are identical
1109  * 1 - Images differ
1110  * >1 - Error occurred
1111  */
1112 static int img_compare(int argc, char **argv)
1113 {
1114     const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1115     BlockBackend *blk1, *blk2;
1116     BlockDriverState *bs1, *bs2;
1117     int64_t total_sectors1, total_sectors2;
1118     uint8_t *buf1 = NULL, *buf2 = NULL;
1119     int pnum1, pnum2;
1120     int allocated1, allocated2;
1121     int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1122     bool progress = false, quiet = false, strict = false;
1123     int flags;
1124     int64_t total_sectors;
1125     int64_t sector_num = 0;
1126     int64_t nb_sectors;
1127     int c, pnum;
1128     uint64_t progress_base;
1129     Error *local_err = NULL;
1130     bool image_opts = false;
1131
1132     cache = BDRV_DEFAULT_CACHE;
1133     for (;;) {
1134         static const struct option long_options[] = {
1135             {"help", no_argument, 0, 'h'},
1136             {"object", required_argument, 0, OPTION_OBJECT},
1137             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1138             {0, 0, 0, 0}
1139         };
1140         c = getopt_long(argc, argv, "hf:F:T:pqs",
1141                         long_options, NULL);
1142         if (c == -1) {
1143             break;
1144         }
1145         switch (c) {
1146         case '?':
1147         case 'h':
1148             help();
1149             break;
1150         case 'f':
1151             fmt1 = optarg;
1152             break;
1153         case 'F':
1154             fmt2 = optarg;
1155             break;
1156         case 'T':
1157             cache = optarg;
1158             break;
1159         case 'p':
1160             progress = true;
1161             break;
1162         case 'q':
1163             quiet = true;
1164             break;
1165         case 's':
1166             strict = true;
1167             break;
1168         case OPTION_OBJECT: {
1169             QemuOpts *opts;
1170             opts = qemu_opts_parse_noisily(&qemu_object_opts,
1171                                            optarg, true);
1172             if (!opts) {
1173                 ret = 2;
1174                 goto out4;
1175             }
1176         }   break;
1177         case OPTION_IMAGE_OPTS:
1178             image_opts = true;
1179             break;
1180         }
1181     }
1182
1183     /* Progress is not shown in Quiet mode */
1184     if (quiet) {
1185         progress = false;
1186     }
1187
1188
1189     if (optind != argc - 2) {
1190         error_exit("Expecting two image file names");
1191     }
1192     filename1 = argv[optind++];
1193     filename2 = argv[optind++];
1194
1195     if (qemu_opts_foreach(&qemu_object_opts,
1196                           user_creatable_add_opts_foreach,
1197                           NULL, &local_err)) {
1198         error_report_err(local_err);
1199         ret = 2;
1200         goto out4;
1201     }
1202
1203     /* Initialize before goto out */
1204     qemu_progress_init(progress, 2.0);
1205
1206     flags = BDRV_O_FLAGS;
1207     ret = bdrv_parse_cache_flags(cache, &flags);
1208     if (ret < 0) {
1209         error_report("Invalid source cache option: %s", cache);
1210         ret = 2;
1211         goto out3;
1212     }
1213
1214     blk1 = img_open(image_opts, filename1, fmt1, flags, quiet);
1215     if (!blk1) {
1216         ret = 2;
1217         goto out3;
1218     }
1219
1220     blk2 = img_open(image_opts, filename2, fmt2, flags, quiet);
1221     if (!blk2) {
1222         ret = 2;
1223         goto out2;
1224     }
1225     bs1 = blk_bs(blk1);
1226     bs2 = blk_bs(blk2);
1227
1228     buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1229     buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1230     total_sectors1 = blk_nb_sectors(blk1);
1231     if (total_sectors1 < 0) {
1232         error_report("Can't get size of %s: %s",
1233                      filename1, strerror(-total_sectors1));
1234         ret = 4;
1235         goto out;
1236     }
1237     total_sectors2 = blk_nb_sectors(blk2);
1238     if (total_sectors2 < 0) {
1239         error_report("Can't get size of %s: %s",
1240                      filename2, strerror(-total_sectors2));
1241         ret = 4;
1242         goto out;
1243     }
1244     total_sectors = MIN(total_sectors1, total_sectors2);
1245     progress_base = MAX(total_sectors1, total_sectors2);
1246
1247     qemu_progress_print(0, 100);
1248
1249     if (strict && total_sectors1 != total_sectors2) {
1250         ret = 1;
1251         qprintf(quiet, "Strict mode: Image size mismatch!\n");
1252         goto out;
1253     }
1254
1255     for (;;) {
1256         int64_t status1, status2;
1257         BlockDriverState *file;
1258
1259         nb_sectors = sectors_to_process(total_sectors, sector_num);
1260         if (nb_sectors <= 0) {
1261             break;
1262         }
1263         status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1264                                               total_sectors1 - sector_num,
1265                                               &pnum1, &file);
1266         if (status1 < 0) {
1267             ret = 3;
1268             error_report("Sector allocation test failed for %s", filename1);
1269             goto out;
1270         }
1271         allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1272
1273         status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1274                                               total_sectors2 - sector_num,
1275                                               &pnum2, &file);
1276         if (status2 < 0) {
1277             ret = 3;
1278             error_report("Sector allocation test failed for %s", filename2);
1279             goto out;
1280         }
1281         allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1282         if (pnum1) {
1283             nb_sectors = MIN(nb_sectors, pnum1);
1284         }
1285         if (pnum2) {
1286             nb_sectors = MIN(nb_sectors, pnum2);
1287         }
1288
1289         if (strict) {
1290             if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1291                 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1292                 ret = 1;
1293                 qprintf(quiet, "Strict mode: Offset %" PRId64
1294                         " block status mismatch!\n",
1295                         sectors_to_bytes(sector_num));
1296                 goto out;
1297             }
1298         }
1299         if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1300             nb_sectors = MIN(pnum1, pnum2);
1301         } else if (allocated1 == allocated2) {
1302             if (allocated1) {
1303                 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1304                 if (ret < 0) {
1305                     error_report("Error while reading offset %" PRId64 " of %s:"
1306                                  " %s", sectors_to_bytes(sector_num), filename1,
1307                                  strerror(-ret));
1308                     ret = 4;
1309                     goto out;
1310                 }
1311                 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1312                 if (ret < 0) {
1313                     error_report("Error while reading offset %" PRId64
1314                                  " of %s: %s", sectors_to_bytes(sector_num),
1315                                  filename2, strerror(-ret));
1316                     ret = 4;
1317                     goto out;
1318                 }
1319                 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1320                 if (ret || pnum != nb_sectors) {
1321                     qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1322                             sectors_to_bytes(
1323                                 ret ? sector_num : sector_num + pnum));
1324                     ret = 1;
1325                     goto out;
1326                 }
1327             }
1328         } else {
1329
1330             if (allocated1) {
1331                 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1332                                           filename1, buf1, quiet);
1333             } else {
1334                 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1335                                           filename2, buf1, quiet);
1336             }
1337             if (ret) {
1338                 if (ret < 0) {
1339                     error_report("Error while reading offset %" PRId64 ": %s",
1340                                  sectors_to_bytes(sector_num), strerror(-ret));
1341                     ret = 4;
1342                 }
1343                 goto out;
1344             }
1345         }
1346         sector_num += nb_sectors;
1347         qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1348     }
1349
1350     if (total_sectors1 != total_sectors2) {
1351         BlockBackend *blk_over;
1352         int64_t total_sectors_over;
1353         const char *filename_over;
1354
1355         qprintf(quiet, "Warning: Image size mismatch!\n");
1356         if (total_sectors1 > total_sectors2) {
1357             total_sectors_over = total_sectors1;
1358             blk_over = blk1;
1359             filename_over = filename1;
1360         } else {
1361             total_sectors_over = total_sectors2;
1362             blk_over = blk2;
1363             filename_over = filename2;
1364         }
1365
1366         for (;;) {
1367             nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1368             if (nb_sectors <= 0) {
1369                 break;
1370             }
1371             ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1372                                           nb_sectors, &pnum);
1373             if (ret < 0) {
1374                 ret = 3;
1375                 error_report("Sector allocation test failed for %s",
1376                              filename_over);
1377                 goto out;
1378
1379             }
1380             nb_sectors = pnum;
1381             if (ret) {
1382                 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1383                                           filename_over, buf1, quiet);
1384                 if (ret) {
1385                     if (ret < 0) {
1386                         error_report("Error while reading offset %" PRId64
1387                                      " of %s: %s", sectors_to_bytes(sector_num),
1388                                      filename_over, strerror(-ret));
1389                         ret = 4;
1390                     }
1391                     goto out;
1392                 }
1393             }
1394             sector_num += nb_sectors;
1395             qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1396         }
1397     }
1398
1399     qprintf(quiet, "Images are identical.\n");
1400     ret = 0;
1401
1402 out:
1403     qemu_vfree(buf1);
1404     qemu_vfree(buf2);
1405     blk_unref(blk2);
1406 out2:
1407     blk_unref(blk1);
1408 out3:
1409     qemu_progress_end();
1410 out4:
1411     return ret;
1412 }
1413
1414 enum ImgConvertBlockStatus {
1415     BLK_DATA,
1416     BLK_ZERO,
1417     BLK_BACKING_FILE,
1418 };
1419
1420 typedef struct ImgConvertState {
1421     BlockBackend **src;
1422     int64_t *src_sectors;
1423     int src_cur, src_num;
1424     int64_t src_cur_offset;
1425     int64_t total_sectors;
1426     int64_t allocated_sectors;
1427     enum ImgConvertBlockStatus status;
1428     int64_t sector_next_status;
1429     BlockBackend *target;
1430     bool has_zero_init;
1431     bool compressed;
1432     bool target_has_backing;
1433     int min_sparse;
1434     size_t cluster_sectors;
1435     size_t buf_sectors;
1436 } ImgConvertState;
1437
1438 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1439 {
1440     assert(sector_num >= s->src_cur_offset);
1441     while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1442         s->src_cur_offset += s->src_sectors[s->src_cur];
1443         s->src_cur++;
1444         assert(s->src_cur < s->src_num);
1445     }
1446 }
1447
1448 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1449 {
1450     int64_t ret;
1451     int n;
1452
1453     convert_select_part(s, sector_num);
1454
1455     assert(s->total_sectors > sector_num);
1456     n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1457
1458     if (s->sector_next_status <= sector_num) {
1459         BlockDriverState *file;
1460         ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1461                                     sector_num - s->src_cur_offset,
1462                                     n, &n, &file);
1463         if (ret < 0) {
1464             return ret;
1465         }
1466
1467         if (ret & BDRV_BLOCK_ZERO) {
1468             s->status = BLK_ZERO;
1469         } else if (ret & BDRV_BLOCK_DATA) {
1470             s->status = BLK_DATA;
1471         } else if (!s->target_has_backing) {
1472             /* Without a target backing file we must copy over the contents of
1473              * the backing file as well. */
1474             /* TODO Check block status of the backing file chain to avoid
1475              * needlessly reading zeroes and limiting the iteration to the
1476              * buffer size */
1477             s->status = BLK_DATA;
1478         } else {
1479             s->status = BLK_BACKING_FILE;
1480         }
1481
1482         s->sector_next_status = sector_num + n;
1483     }
1484
1485     n = MIN(n, s->sector_next_status - sector_num);
1486     if (s->status == BLK_DATA) {
1487         n = MIN(n, s->buf_sectors);
1488     }
1489
1490     /* We need to write complete clusters for compressed images, so if an
1491      * unallocated area is shorter than that, we must consider the whole
1492      * cluster allocated. */
1493     if (s->compressed) {
1494         if (n < s->cluster_sectors) {
1495             n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1496             s->status = BLK_DATA;
1497         } else {
1498             n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1499         }
1500     }
1501
1502     return n;
1503 }
1504
1505 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1506                         uint8_t *buf)
1507 {
1508     int n;
1509     int ret;
1510
1511     if (s->status == BLK_ZERO || s->status == BLK_BACKING_FILE) {
1512         return 0;
1513     }
1514
1515     assert(nb_sectors <= s->buf_sectors);
1516     while (nb_sectors > 0) {
1517         BlockBackend *blk;
1518         int64_t bs_sectors;
1519
1520         /* In the case of compression with multiple source files, we can get a
1521          * nb_sectors that spreads into the next part. So we must be able to
1522          * read across multiple BDSes for one convert_read() call. */
1523         convert_select_part(s, sector_num);
1524         blk = s->src[s->src_cur];
1525         bs_sectors = s->src_sectors[s->src_cur];
1526
1527         n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1528         ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1529         if (ret < 0) {
1530             return ret;
1531         }
1532
1533         sector_num += n;
1534         nb_sectors -= n;
1535         buf += n * BDRV_SECTOR_SIZE;
1536     }
1537
1538     return 0;
1539 }
1540
1541 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1542                          const uint8_t *buf)
1543 {
1544     int ret;
1545
1546     while (nb_sectors > 0) {
1547         int n = nb_sectors;
1548
1549         switch (s->status) {
1550         case BLK_BACKING_FILE:
1551             /* If we have a backing file, leave clusters unallocated that are
1552              * unallocated in the source image, so that the backing file is
1553              * visible at the respective offset. */
1554             assert(s->target_has_backing);
1555             break;
1556
1557         case BLK_DATA:
1558             /* We must always write compressed clusters as a whole, so don't
1559              * try to find zeroed parts in the buffer. We can only save the
1560              * write if the buffer is completely zeroed and we're allowed to
1561              * keep the target sparse. */
1562             if (s->compressed) {
1563                 if (s->has_zero_init && s->min_sparse &&
1564                     buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1565                 {
1566                     assert(!s->target_has_backing);
1567                     break;
1568                 }
1569
1570                 ret = blk_write_compressed(s->target, sector_num, buf, n);
1571                 if (ret < 0) {
1572                     return ret;
1573                 }
1574                 break;
1575             }
1576
1577             /* If there is real non-zero data or we're told to keep the target
1578              * fully allocated (-S 0), we must write it. Otherwise we can treat
1579              * it as zero sectors. */
1580             if (!s->min_sparse ||
1581                 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1582             {
1583                 ret = blk_write(s->target, sector_num, buf, n);
1584                 if (ret < 0) {
1585                     return ret;
1586                 }
1587                 break;
1588             }
1589             /* fall-through */
1590
1591         case BLK_ZERO:
1592             if (s->has_zero_init) {
1593                 break;
1594             }
1595             ret = blk_write_zeroes(s->target, sector_num, n, 0);
1596             if (ret < 0) {
1597                 return ret;
1598             }
1599             break;
1600         }
1601
1602         sector_num += n;
1603         nb_sectors -= n;
1604         buf += n * BDRV_SECTOR_SIZE;
1605     }
1606
1607     return 0;
1608 }
1609
1610 static int convert_do_copy(ImgConvertState *s)
1611 {
1612     uint8_t *buf = NULL;
1613     int64_t sector_num, allocated_done;
1614     int ret;
1615     int n;
1616
1617     /* Check whether we have zero initialisation or can get it efficiently */
1618     s->has_zero_init = s->min_sparse && !s->target_has_backing
1619                      ? bdrv_has_zero_init(blk_bs(s->target))
1620                      : false;
1621
1622     if (!s->has_zero_init && !s->target_has_backing &&
1623         bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1624     {
1625         ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1626         if (ret == 0) {
1627             s->has_zero_init = true;
1628         }
1629     }
1630
1631     /* Allocate buffer for copied data. For compressed images, only one cluster
1632      * can be copied at a time. */
1633     if (s->compressed) {
1634         if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1635             error_report("invalid cluster size");
1636             ret = -EINVAL;
1637             goto fail;
1638         }
1639         s->buf_sectors = s->cluster_sectors;
1640     }
1641     buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1642
1643     /* Calculate allocated sectors for progress */
1644     s->allocated_sectors = 0;
1645     sector_num = 0;
1646     while (sector_num < s->total_sectors) {
1647         n = convert_iteration_sectors(s, sector_num);
1648         if (n < 0) {
1649             ret = n;
1650             goto fail;
1651         }
1652         if (s->status == BLK_DATA) {
1653             s->allocated_sectors += n;
1654         }
1655         sector_num += n;
1656     }
1657
1658     /* Do the copy */
1659     s->src_cur = 0;
1660     s->src_cur_offset = 0;
1661     s->sector_next_status = 0;
1662
1663     sector_num = 0;
1664     allocated_done = 0;
1665
1666     while (sector_num < s->total_sectors) {
1667         n = convert_iteration_sectors(s, sector_num);
1668         if (n < 0) {
1669             ret = n;
1670             goto fail;
1671         }
1672         if (s->status == BLK_DATA) {
1673             allocated_done += n;
1674             qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1675                                 0);
1676         }
1677
1678         ret = convert_read(s, sector_num, n, buf);
1679         if (ret < 0) {
1680             error_report("error while reading sector %" PRId64
1681                          ": %s", sector_num, strerror(-ret));
1682             goto fail;
1683         }
1684
1685         ret = convert_write(s, sector_num, n, buf);
1686         if (ret < 0) {
1687             error_report("error while writing sector %" PRId64
1688                          ": %s", sector_num, strerror(-ret));
1689             goto fail;
1690         }
1691
1692         sector_num += n;
1693     }
1694
1695     if (s->compressed) {
1696         /* signal EOF to align */
1697         ret = blk_write_compressed(s->target, 0, NULL, 0);
1698         if (ret < 0) {
1699             goto fail;
1700         }
1701     }
1702
1703     ret = 0;
1704 fail:
1705     qemu_vfree(buf);
1706     return ret;
1707 }
1708
1709 static int img_convert(int argc, char **argv)
1710 {
1711     int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1712     int64_t ret = 0;
1713     int progress = 0, flags, src_flags;
1714     const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1715     BlockDriver *drv, *proto_drv;
1716     BlockBackend **blk = NULL, *out_blk = NULL;
1717     BlockDriverState **bs = NULL, *out_bs = NULL;
1718     int64_t total_sectors;
1719     int64_t *bs_sectors = NULL;
1720     size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1721     BlockDriverInfo bdi;
1722     QemuOpts *opts = NULL;
1723     QemuOptsList *create_opts = NULL;
1724     const char *out_baseimg_param;
1725     char *options = NULL;
1726     const char *snapshot_name = NULL;
1727     int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1728     bool quiet = false;
1729     Error *local_err = NULL;
1730     QemuOpts *sn_opts = NULL;
1731     ImgConvertState state;
1732     bool image_opts = false;
1733
1734     fmt = NULL;
1735     out_fmt = "raw";
1736     cache = "unsafe";
1737     src_cache = BDRV_DEFAULT_CACHE;
1738     out_baseimg = NULL;
1739     compress = 0;
1740     skip_create = 0;
1741     for(;;) {
1742         static const struct option long_options[] = {
1743             {"help", no_argument, 0, 'h'},
1744             {"object", required_argument, 0, OPTION_OBJECT},
1745             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1746             {0, 0, 0, 0}
1747         };
1748         c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1749                         long_options, NULL);
1750         if (c == -1) {
1751             break;
1752         }
1753         switch(c) {
1754         case '?':
1755         case 'h':
1756             help();
1757             break;
1758         case 'f':
1759             fmt = optarg;
1760             break;
1761         case 'O':
1762             out_fmt = optarg;
1763             break;
1764         case 'B':
1765             out_baseimg = optarg;
1766             break;
1767         case 'c':
1768             compress = 1;
1769             break;
1770         case 'e':
1771             error_report("option -e is deprecated, please use \'-o "
1772                   "encryption\' instead!");
1773             ret = -1;
1774             goto fail_getopt;
1775         case '6':
1776             error_report("option -6 is deprecated, please use \'-o "
1777                   "compat6\' instead!");
1778             ret = -1;
1779             goto fail_getopt;
1780         case 'o':
1781             if (!is_valid_option_list(optarg)) {
1782                 error_report("Invalid option list: %s", optarg);
1783                 ret = -1;
1784                 goto fail_getopt;
1785             }
1786             if (!options) {
1787                 options = g_strdup(optarg);
1788             } else {
1789                 char *old_options = options;
1790                 options = g_strdup_printf("%s,%s", options, optarg);
1791                 g_free(old_options);
1792             }
1793             break;
1794         case 's':
1795             snapshot_name = optarg;
1796             break;
1797         case 'l':
1798             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1799                 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1800                                                   optarg, false);
1801                 if (!sn_opts) {
1802                     error_report("Failed in parsing snapshot param '%s'",
1803                                  optarg);
1804                     ret = -1;
1805                     goto fail_getopt;
1806                 }
1807             } else {
1808                 snapshot_name = optarg;
1809             }
1810             break;
1811         case 'S':
1812         {
1813             int64_t sval;
1814             char *end;
1815             sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1816             if (sval < 0 || *end) {
1817                 error_report("Invalid minimum zero buffer size for sparse output specified");
1818                 ret = -1;
1819                 goto fail_getopt;
1820             }
1821
1822             min_sparse = sval / BDRV_SECTOR_SIZE;
1823             break;
1824         }
1825         case 'p':
1826             progress = 1;
1827             break;
1828         case 't':
1829             cache = optarg;
1830             break;
1831         case 'T':
1832             src_cache = optarg;
1833             break;
1834         case 'q':
1835             quiet = true;
1836             break;
1837         case 'n':
1838             skip_create = 1;
1839             break;
1840         case OPTION_OBJECT:
1841             opts = qemu_opts_parse_noisily(&qemu_object_opts,
1842                                            optarg, true);
1843             if (!opts) {
1844                 goto fail_getopt;
1845             }
1846             break;
1847         case OPTION_IMAGE_OPTS:
1848             image_opts = true;
1849             break;
1850         }
1851     }
1852
1853     if (qemu_opts_foreach(&qemu_object_opts,
1854                           user_creatable_add_opts_foreach,
1855                           NULL, &local_err)) {
1856         error_report_err(local_err);
1857         goto fail_getopt;
1858     }
1859
1860     /* Initialize before goto out */
1861     if (quiet) {
1862         progress = 0;
1863     }
1864     qemu_progress_init(progress, 1.0);
1865
1866     bs_n = argc - optind - 1;
1867     out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1868
1869     if (options && has_help_option(options)) {
1870         ret = print_block_option_help(out_filename, out_fmt);
1871         goto out;
1872     }
1873
1874     if (bs_n < 1) {
1875         error_exit("Must specify image file name");
1876     }
1877
1878
1879     if (bs_n > 1 && out_baseimg) {
1880         error_report("-B makes no sense when concatenating multiple input "
1881                      "images");
1882         ret = -1;
1883         goto out;
1884     }
1885
1886     src_flags = BDRV_O_FLAGS;
1887     ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1888     if (ret < 0) {
1889         error_report("Invalid source cache option: %s", src_cache);
1890         goto out;
1891     }
1892
1893     qemu_progress_print(0, 100);
1894
1895     blk = g_new0(BlockBackend *, bs_n);
1896     bs = g_new0(BlockDriverState *, bs_n);
1897     bs_sectors = g_new(int64_t, bs_n);
1898
1899     total_sectors = 0;
1900     for (bs_i = 0; bs_i < bs_n; bs_i++) {
1901         blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1902                              fmt, src_flags, quiet);
1903         if (!blk[bs_i]) {
1904             ret = -1;
1905             goto out;
1906         }
1907         bs[bs_i] = blk_bs(blk[bs_i]);
1908         bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1909         if (bs_sectors[bs_i] < 0) {
1910             error_report("Could not get size of %s: %s",
1911                          argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1912             ret = -1;
1913             goto out;
1914         }
1915         total_sectors += bs_sectors[bs_i];
1916     }
1917
1918     if (sn_opts) {
1919         ret = bdrv_snapshot_load_tmp(bs[0],
1920                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1921                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1922                                      &local_err);
1923     } else if (snapshot_name != NULL) {
1924         if (bs_n > 1) {
1925             error_report("No support for concatenating multiple snapshot");
1926             ret = -1;
1927             goto out;
1928         }
1929
1930         bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1931     }
1932     if (local_err) {
1933         error_reportf_err(local_err, "Failed to load snapshot: ");
1934         ret = -1;
1935         goto out;
1936     }
1937
1938     /* Find driver and parse its options */
1939     drv = bdrv_find_format(out_fmt);
1940     if (!drv) {
1941         error_report("Unknown file format '%s'", out_fmt);
1942         ret = -1;
1943         goto out;
1944     }
1945
1946     proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1947     if (!proto_drv) {
1948         error_report_err(local_err);
1949         ret = -1;
1950         goto out;
1951     }
1952
1953     if (!skip_create) {
1954         if (!drv->create_opts) {
1955             error_report("Format driver '%s' does not support image creation",
1956                          drv->format_name);
1957             ret = -1;
1958             goto out;
1959         }
1960
1961         if (!proto_drv->create_opts) {
1962             error_report("Protocol driver '%s' does not support image creation",
1963                          proto_drv->format_name);
1964             ret = -1;
1965             goto out;
1966         }
1967
1968         create_opts = qemu_opts_append(create_opts, drv->create_opts);
1969         create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1970
1971         opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1972         if (options) {
1973             qemu_opts_do_parse(opts, options, NULL, &local_err);
1974             if (local_err) {
1975                 error_report_err(local_err);
1976                 ret = -1;
1977                 goto out;
1978             }
1979         }
1980
1981         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1982                             &error_abort);
1983         ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1984         if (ret < 0) {
1985             goto out;
1986         }
1987     }
1988
1989     /* Get backing file name if -o backing_file was used */
1990     out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1991     if (out_baseimg_param) {
1992         out_baseimg = out_baseimg_param;
1993     }
1994
1995     /* Check if compression is supported */
1996     if (compress) {
1997         bool encryption =
1998             qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1999         const char *preallocation =
2000             qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2001
2002         if (!drv->bdrv_write_compressed) {
2003             error_report("Compression not supported for this file format");
2004             ret = -1;
2005             goto out;
2006         }
2007
2008         if (encryption) {
2009             error_report("Compression and encryption not supported at "
2010                          "the same time");
2011             ret = -1;
2012             goto out;
2013         }
2014
2015         if (preallocation
2016             && strcmp(preallocation, "off"))
2017         {
2018             error_report("Compression and preallocation not supported at "
2019                          "the same time");
2020             ret = -1;
2021             goto out;
2022         }
2023     }
2024
2025     if (!skip_create) {
2026         /* Create the new image */
2027         ret = bdrv_create(drv, out_filename, opts, &local_err);
2028         if (ret < 0) {
2029             error_reportf_err(local_err, "%s: error while converting %s: ",
2030                               out_filename, out_fmt);
2031             goto out;
2032         }
2033     }
2034
2035     flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2036     ret = bdrv_parse_cache_flags(cache, &flags);
2037     if (ret < 0) {
2038         error_report("Invalid cache option: %s", cache);
2039         goto out;
2040     }
2041
2042     /* XXX we should allow --image-opts to trigger use of
2043      * img_open() here, but then we have trouble with
2044      * the bdrv_create() call which takes different params.
2045      * Not critical right now, so fix can wait...
2046      */
2047     out_blk = img_open_file(out_filename, out_fmt, flags, quiet);
2048     if (!out_blk) {
2049         ret = -1;
2050         goto out;
2051     }
2052     out_bs = blk_bs(out_blk);
2053
2054     /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2055      * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2056      * as maximum. */
2057     bufsectors = MIN(32768,
2058                      MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2059                                          out_bs->bl.discard_alignment))
2060                     );
2061
2062     if (skip_create) {
2063         int64_t output_sectors = blk_nb_sectors(out_blk);
2064         if (output_sectors < 0) {
2065             error_report("unable to get output image length: %s",
2066                          strerror(-output_sectors));
2067             ret = -1;
2068             goto out;
2069         } else if (output_sectors < total_sectors) {
2070             error_report("output file is smaller than input file");
2071             ret = -1;
2072             goto out;
2073         }
2074     }
2075
2076     cluster_sectors = 0;
2077     ret = bdrv_get_info(out_bs, &bdi);
2078     if (ret < 0) {
2079         if (compress) {
2080             error_report("could not get block driver info");
2081             goto out;
2082         }
2083     } else {
2084         compress = compress || bdi.needs_compressed_writes;
2085         cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2086     }
2087
2088     state = (ImgConvertState) {
2089         .src                = blk,
2090         .src_sectors        = bs_sectors,
2091         .src_num            = bs_n,
2092         .total_sectors      = total_sectors,
2093         .target             = out_blk,
2094         .compressed         = compress,
2095         .target_has_backing = (bool) out_baseimg,
2096         .min_sparse         = min_sparse,
2097         .cluster_sectors    = cluster_sectors,
2098         .buf_sectors        = bufsectors,
2099     };
2100     ret = convert_do_copy(&state);
2101
2102 out:
2103     if (!ret) {
2104         qemu_progress_print(100, 0);
2105     }
2106     qemu_progress_end();
2107     qemu_opts_del(opts);
2108     qemu_opts_free(create_opts);
2109     qemu_opts_del(sn_opts);
2110     blk_unref(out_blk);
2111     g_free(bs);
2112     if (blk) {
2113         for (bs_i = 0; bs_i < bs_n; bs_i++) {
2114             blk_unref(blk[bs_i]);
2115         }
2116         g_free(blk);
2117     }
2118     g_free(bs_sectors);
2119 fail_getopt:
2120     g_free(options);
2121
2122     if (ret) {
2123         return 1;
2124     }
2125     return 0;
2126 }
2127
2128
2129 static void dump_snapshots(BlockDriverState *bs)
2130 {
2131     QEMUSnapshotInfo *sn_tab, *sn;
2132     int nb_sns, i;
2133
2134     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2135     if (nb_sns <= 0)
2136         return;
2137     printf("Snapshot list:\n");
2138     bdrv_snapshot_dump(fprintf, stdout, NULL);
2139     printf("\n");
2140     for(i = 0; i < nb_sns; i++) {
2141         sn = &sn_tab[i];
2142         bdrv_snapshot_dump(fprintf, stdout, sn);
2143         printf("\n");
2144     }
2145     g_free(sn_tab);
2146 }
2147
2148 static void dump_json_image_info_list(ImageInfoList *list)
2149 {
2150     Error *local_err = NULL;
2151     QString *str;
2152     QmpOutputVisitor *ov = qmp_output_visitor_new();
2153     QObject *obj;
2154     visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2155                              &local_err);
2156     obj = qmp_output_get_qobject(ov);
2157     str = qobject_to_json_pretty(obj);
2158     assert(str != NULL);
2159     printf("%s\n", qstring_get_str(str));
2160     qobject_decref(obj);
2161     qmp_output_visitor_cleanup(ov);
2162     QDECREF(str);
2163 }
2164
2165 static void dump_json_image_info(ImageInfo *info)
2166 {
2167     Error *local_err = NULL;
2168     QString *str;
2169     QmpOutputVisitor *ov = qmp_output_visitor_new();
2170     QObject *obj;
2171     visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2172     obj = qmp_output_get_qobject(ov);
2173     str = qobject_to_json_pretty(obj);
2174     assert(str != NULL);
2175     printf("%s\n", qstring_get_str(str));
2176     qobject_decref(obj);
2177     qmp_output_visitor_cleanup(ov);
2178     QDECREF(str);
2179 }
2180
2181 static void dump_human_image_info_list(ImageInfoList *list)
2182 {
2183     ImageInfoList *elem;
2184     bool delim = false;
2185
2186     for (elem = list; elem; elem = elem->next) {
2187         if (delim) {
2188             printf("\n");
2189         }
2190         delim = true;
2191
2192         bdrv_image_info_dump(fprintf, stdout, elem->value);
2193     }
2194 }
2195
2196 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2197 {
2198     return strcmp(a, b) == 0;
2199 }
2200
2201 /**
2202  * Open an image file chain and return an ImageInfoList
2203  *
2204  * @filename: topmost image filename
2205  * @fmt: topmost image format (may be NULL to autodetect)
2206  * @chain: true  - enumerate entire backing file chain
2207  *         false - only topmost image file
2208  *
2209  * Returns a list of ImageInfo objects or NULL if there was an error opening an
2210  * image file.  If there was an error a message will have been printed to
2211  * stderr.
2212  */
2213 static ImageInfoList *collect_image_info_list(bool image_opts,
2214                                               const char *filename,
2215                                               const char *fmt,
2216                                               bool chain)
2217 {
2218     ImageInfoList *head = NULL;
2219     ImageInfoList **last = &head;
2220     GHashTable *filenames;
2221     Error *err = NULL;
2222
2223     filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2224
2225     while (filename) {
2226         BlockBackend *blk;
2227         BlockDriverState *bs;
2228         ImageInfo *info;
2229         ImageInfoList *elem;
2230
2231         if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2232             error_report("Backing file '%s' creates an infinite loop.",
2233                          filename);
2234             goto err;
2235         }
2236         g_hash_table_insert(filenames, (gpointer)filename, NULL);
2237
2238         blk = img_open(image_opts, filename, fmt,
2239                        BDRV_O_FLAGS | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
2240                        false);
2241         if (!blk) {
2242             goto err;
2243         }
2244         bs = blk_bs(blk);
2245
2246         bdrv_query_image_info(bs, &info, &err);
2247         if (err) {
2248             error_report_err(err);
2249             blk_unref(blk);
2250             goto err;
2251         }
2252
2253         elem = g_new0(ImageInfoList, 1);
2254         elem->value = info;
2255         *last = elem;
2256         last = &elem->next;
2257
2258         blk_unref(blk);
2259
2260         filename = fmt = NULL;
2261         if (chain) {
2262             if (info->has_full_backing_filename) {
2263                 filename = info->full_backing_filename;
2264             } else if (info->has_backing_filename) {
2265                 error_report("Could not determine absolute backing filename,"
2266                              " but backing filename '%s' present",
2267                              info->backing_filename);
2268                 goto err;
2269             }
2270             if (info->has_backing_filename_format) {
2271                 fmt = info->backing_filename_format;
2272             }
2273         }
2274     }
2275     g_hash_table_destroy(filenames);
2276     return head;
2277
2278 err:
2279     qapi_free_ImageInfoList(head);
2280     g_hash_table_destroy(filenames);
2281     return NULL;
2282 }
2283
2284 static int img_info(int argc, char **argv)
2285 {
2286     int c;
2287     OutputFormat output_format = OFORMAT_HUMAN;
2288     bool chain = false;
2289     const char *filename, *fmt, *output;
2290     ImageInfoList *list;
2291     Error *local_err = NULL;
2292     bool image_opts = false;
2293
2294     fmt = NULL;
2295     output = NULL;
2296     for(;;) {
2297         int option_index = 0;
2298         static const struct option long_options[] = {
2299             {"help", no_argument, 0, 'h'},
2300             {"format", required_argument, 0, 'f'},
2301             {"output", required_argument, 0, OPTION_OUTPUT},
2302             {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2303             {"object", required_argument, 0, OPTION_OBJECT},
2304             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2305             {0, 0, 0, 0}
2306         };
2307         c = getopt_long(argc, argv, "f:h",
2308                         long_options, &option_index);
2309         if (c == -1) {
2310             break;
2311         }
2312         switch(c) {
2313         case '?':
2314         case 'h':
2315             help();
2316             break;
2317         case 'f':
2318             fmt = optarg;
2319             break;
2320         case OPTION_OUTPUT:
2321             output = optarg;
2322             break;
2323         case OPTION_BACKING_CHAIN:
2324             chain = true;
2325             break;
2326         case OPTION_OBJECT: {
2327             QemuOpts *opts;
2328             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2329                                            optarg, true);
2330             if (!opts) {
2331                 return 1;
2332             }
2333         }   break;
2334         case OPTION_IMAGE_OPTS:
2335             image_opts = true;
2336             break;
2337         }
2338     }
2339     if (optind != argc - 1) {
2340         error_exit("Expecting one image file name");
2341     }
2342     filename = argv[optind++];
2343
2344     if (output && !strcmp(output, "json")) {
2345         output_format = OFORMAT_JSON;
2346     } else if (output && !strcmp(output, "human")) {
2347         output_format = OFORMAT_HUMAN;
2348     } else if (output) {
2349         error_report("--output must be used with human or json as argument.");
2350         return 1;
2351     }
2352
2353     if (qemu_opts_foreach(&qemu_object_opts,
2354                           user_creatable_add_opts_foreach,
2355                           NULL, &local_err)) {
2356         error_report_err(local_err);
2357         return 1;
2358     }
2359
2360     list = collect_image_info_list(image_opts, filename, fmt, chain);
2361     if (!list) {
2362         return 1;
2363     }
2364
2365     switch (output_format) {
2366     case OFORMAT_HUMAN:
2367         dump_human_image_info_list(list);
2368         break;
2369     case OFORMAT_JSON:
2370         if (chain) {
2371             dump_json_image_info_list(list);
2372         } else {
2373             dump_json_image_info(list->value);
2374         }
2375         break;
2376     }
2377
2378     qapi_free_ImageInfoList(list);
2379     return 0;
2380 }
2381
2382 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2383                            MapEntry *next)
2384 {
2385     switch (output_format) {
2386     case OFORMAT_HUMAN:
2387         if (e->data && !e->has_offset) {
2388             error_report("File contains external, encrypted or compressed clusters.");
2389             exit(1);
2390         }
2391         if (e->data && !e->zero) {
2392             printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2393                    e->start, e->length,
2394                    e->has_offset ? e->offset : 0,
2395                    e->has_filename ? e->filename : "");
2396         }
2397         /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2398          * Modify the flags here to allow more coalescing.
2399          */
2400         if (next && (!next->data || next->zero)) {
2401             next->data = false;
2402             next->zero = true;
2403         }
2404         break;
2405     case OFORMAT_JSON:
2406         printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2407                " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2408                (e->start == 0 ? "[" : ",\n"),
2409                e->start, e->length, e->depth,
2410                e->zero ? "true" : "false",
2411                e->data ? "true" : "false");
2412         if (e->has_offset) {
2413             printf(", \"offset\": %"PRId64"", e->offset);
2414         }
2415         putchar('}');
2416
2417         if (!next) {
2418             printf("]\n");
2419         }
2420         break;
2421     }
2422 }
2423
2424 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2425                             int nb_sectors, MapEntry *e)
2426 {
2427     int64_t ret;
2428     int depth;
2429     BlockDriverState *file;
2430     bool has_offset;
2431
2432     /* As an optimization, we could cache the current range of unallocated
2433      * clusters in each file of the chain, and avoid querying the same
2434      * range repeatedly.
2435      */
2436
2437     depth = 0;
2438     for (;;) {
2439         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2440                                     &file);
2441         if (ret < 0) {
2442             return ret;
2443         }
2444         assert(nb_sectors);
2445         if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2446             break;
2447         }
2448         bs = backing_bs(bs);
2449         if (bs == NULL) {
2450             ret = 0;
2451             break;
2452         }
2453
2454         depth++;
2455     }
2456
2457     has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2458
2459     *e = (MapEntry) {
2460         .start = sector_num * BDRV_SECTOR_SIZE,
2461         .length = nb_sectors * BDRV_SECTOR_SIZE,
2462         .data = !!(ret & BDRV_BLOCK_DATA),
2463         .zero = !!(ret & BDRV_BLOCK_ZERO),
2464         .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2465         .has_offset = has_offset,
2466         .depth = depth,
2467         .has_filename = file && has_offset,
2468         .filename = file && has_offset ? file->filename : NULL,
2469     };
2470
2471     return 0;
2472 }
2473
2474 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2475 {
2476     if (curr->length == 0) {
2477         return false;
2478     }
2479     if (curr->zero != next->zero ||
2480         curr->data != next->data ||
2481         curr->depth != next->depth ||
2482         curr->has_filename != next->has_filename ||
2483         curr->has_offset != next->has_offset) {
2484         return false;
2485     }
2486     if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2487         return false;
2488     }
2489     if (curr->has_offset && curr->offset + curr->length != next->offset) {
2490         return false;
2491     }
2492     return true;
2493 }
2494
2495 static int img_map(int argc, char **argv)
2496 {
2497     int c;
2498     OutputFormat output_format = OFORMAT_HUMAN;
2499     BlockBackend *blk;
2500     BlockDriverState *bs;
2501     const char *filename, *fmt, *output;
2502     int64_t length;
2503     MapEntry curr = { .length = 0 }, next;
2504     int ret = 0;
2505     Error *local_err = NULL;
2506     bool image_opts = false;
2507
2508     fmt = NULL;
2509     output = NULL;
2510     for (;;) {
2511         int option_index = 0;
2512         static const struct option long_options[] = {
2513             {"help", no_argument, 0, 'h'},
2514             {"format", required_argument, 0, 'f'},
2515             {"output", required_argument, 0, OPTION_OUTPUT},
2516             {"object", required_argument, 0, OPTION_OBJECT},
2517             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2518             {0, 0, 0, 0}
2519         };
2520         c = getopt_long(argc, argv, "f:h",
2521                         long_options, &option_index);
2522         if (c == -1) {
2523             break;
2524         }
2525         switch (c) {
2526         case '?':
2527         case 'h':
2528             help();
2529             break;
2530         case 'f':
2531             fmt = optarg;
2532             break;
2533         case OPTION_OUTPUT:
2534             output = optarg;
2535             break;
2536         case OPTION_OBJECT: {
2537             QemuOpts *opts;
2538             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2539                                            optarg, true);
2540             if (!opts) {
2541                 return 1;
2542             }
2543         }   break;
2544         case OPTION_IMAGE_OPTS:
2545             image_opts = true;
2546             break;
2547         }
2548     }
2549     if (optind != argc - 1) {
2550         error_exit("Expecting one image file name");
2551     }
2552     filename = argv[optind];
2553
2554     if (output && !strcmp(output, "json")) {
2555         output_format = OFORMAT_JSON;
2556     } else if (output && !strcmp(output, "human")) {
2557         output_format = OFORMAT_HUMAN;
2558     } else if (output) {
2559         error_report("--output must be used with human or json as argument.");
2560         return 1;
2561     }
2562
2563     if (qemu_opts_foreach(&qemu_object_opts,
2564                           user_creatable_add_opts_foreach,
2565                           NULL, &local_err)) {
2566         error_report_err(local_err);
2567         return 1;
2568     }
2569
2570     blk = img_open(image_opts, filename, fmt, BDRV_O_FLAGS, false);
2571     if (!blk) {
2572         return 1;
2573     }
2574     bs = blk_bs(blk);
2575
2576     if (output_format == OFORMAT_HUMAN) {
2577         printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2578     }
2579
2580     length = blk_getlength(blk);
2581     while (curr.start + curr.length < length) {
2582         int64_t nsectors_left;
2583         int64_t sector_num;
2584         int n;
2585
2586         sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2587
2588         /* Probe up to 1 GiB at a time.  */
2589         nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2590         n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2591         ret = get_block_status(bs, sector_num, n, &next);
2592
2593         if (ret < 0) {
2594             error_report("Could not read file metadata: %s", strerror(-ret));
2595             goto out;
2596         }
2597
2598         if (entry_mergeable(&curr, &next)) {
2599             curr.length += next.length;
2600             continue;
2601         }
2602
2603         if (curr.length > 0) {
2604             dump_map_entry(output_format, &curr, &next);
2605         }
2606         curr = next;
2607     }
2608
2609     dump_map_entry(output_format, &curr, NULL);
2610
2611 out:
2612     blk_unref(blk);
2613     return ret < 0;
2614 }
2615
2616 #define SNAPSHOT_LIST   1
2617 #define SNAPSHOT_CREATE 2
2618 #define SNAPSHOT_APPLY  3
2619 #define SNAPSHOT_DELETE 4
2620
2621 static int img_snapshot(int argc, char **argv)
2622 {
2623     BlockBackend *blk;
2624     BlockDriverState *bs;
2625     QEMUSnapshotInfo sn;
2626     char *filename, *snapshot_name = NULL;
2627     int c, ret = 0, bdrv_oflags;
2628     int action = 0;
2629     qemu_timeval tv;
2630     bool quiet = false;
2631     Error *err = NULL;
2632     bool image_opts = false;
2633
2634     bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
2635     /* Parse commandline parameters */
2636     for(;;) {
2637         static const struct option long_options[] = {
2638             {"help", no_argument, 0, 'h'},
2639             {"object", required_argument, 0, OPTION_OBJECT},
2640             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2641             {0, 0, 0, 0}
2642         };
2643         c = getopt_long(argc, argv, "la:c:d:hq",
2644                         long_options, NULL);
2645         if (c == -1) {
2646             break;
2647         }
2648         switch(c) {
2649         case '?':
2650         case 'h':
2651             help();
2652             return 0;
2653         case 'l':
2654             if (action) {
2655                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2656                 return 0;
2657             }
2658             action = SNAPSHOT_LIST;
2659             bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2660             break;
2661         case 'a':
2662             if (action) {
2663                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2664                 return 0;
2665             }
2666             action = SNAPSHOT_APPLY;
2667             snapshot_name = optarg;
2668             break;
2669         case 'c':
2670             if (action) {
2671                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2672                 return 0;
2673             }
2674             action = SNAPSHOT_CREATE;
2675             snapshot_name = optarg;
2676             break;
2677         case 'd':
2678             if (action) {
2679                 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2680                 return 0;
2681             }
2682             action = SNAPSHOT_DELETE;
2683             snapshot_name = optarg;
2684             break;
2685         case 'q':
2686             quiet = true;
2687             break;
2688         case OPTION_OBJECT: {
2689             QemuOpts *opts;
2690             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2691                                            optarg, true);
2692             if (!opts) {
2693                 return 1;
2694             }
2695         }   break;
2696         case OPTION_IMAGE_OPTS:
2697             image_opts = true;
2698             break;
2699         }
2700     }
2701
2702     if (optind != argc - 1) {
2703         error_exit("Expecting one image file name");
2704     }
2705     filename = argv[optind++];
2706
2707     if (qemu_opts_foreach(&qemu_object_opts,
2708                           user_creatable_add_opts_foreach,
2709                           NULL, &err)) {
2710         error_report_err(err);
2711         return 1;
2712     }
2713
2714     /* Open the image */
2715     blk = img_open(image_opts, filename, NULL, bdrv_oflags, quiet);
2716     if (!blk) {
2717         return 1;
2718     }
2719     bs = blk_bs(blk);
2720
2721     /* Perform the requested action */
2722     switch(action) {
2723     case SNAPSHOT_LIST:
2724         dump_snapshots(bs);
2725         break;
2726
2727     case SNAPSHOT_CREATE:
2728         memset(&sn, 0, sizeof(sn));
2729         pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2730
2731         qemu_gettimeofday(&tv);
2732         sn.date_sec = tv.tv_sec;
2733         sn.date_nsec = tv.tv_usec * 1000;
2734
2735         ret = bdrv_snapshot_create(bs, &sn);
2736         if (ret) {
2737             error_report("Could not create snapshot '%s': %d (%s)",
2738                 snapshot_name, ret, strerror(-ret));
2739         }
2740         break;
2741
2742     case SNAPSHOT_APPLY:
2743         ret = bdrv_snapshot_goto(bs, snapshot_name);
2744         if (ret) {
2745             error_report("Could not apply snapshot '%s': %d (%s)",
2746                 snapshot_name, ret, strerror(-ret));
2747         }
2748         break;
2749
2750     case SNAPSHOT_DELETE:
2751         bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2752         if (err) {
2753             error_reportf_err(err, "Could not delete snapshot '%s': ",
2754                               snapshot_name);
2755             ret = 1;
2756         }
2757         break;
2758     }
2759
2760     /* Cleanup */
2761     blk_unref(blk);
2762     if (ret) {
2763         return 1;
2764     }
2765     return 0;
2766 }
2767
2768 static int img_rebase(int argc, char **argv)
2769 {
2770     BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2771     uint8_t *buf_old = NULL;
2772     uint8_t *buf_new = NULL;
2773     BlockDriverState *bs = NULL;
2774     char *filename;
2775     const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2776     int c, flags, src_flags, ret;
2777     int unsafe = 0;
2778     int progress = 0;
2779     bool quiet = false;
2780     Error *local_err = NULL;
2781     bool image_opts = false;
2782
2783     /* Parse commandline parameters */
2784     fmt = NULL;
2785     cache = BDRV_DEFAULT_CACHE;
2786     src_cache = BDRV_DEFAULT_CACHE;
2787     out_baseimg = NULL;
2788     out_basefmt = NULL;
2789     for(;;) {
2790         static const struct option long_options[] = {
2791             {"help", no_argument, 0, 'h'},
2792             {"object", required_argument, 0, OPTION_OBJECT},
2793             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2794             {0, 0, 0, 0}
2795         };
2796         c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2797                         long_options, NULL);
2798         if (c == -1) {
2799             break;
2800         }
2801         switch(c) {
2802         case '?':
2803         case 'h':
2804             help();
2805             return 0;
2806         case 'f':
2807             fmt = optarg;
2808             break;
2809         case 'F':
2810             out_basefmt = optarg;
2811             break;
2812         case 'b':
2813             out_baseimg = optarg;
2814             break;
2815         case 'u':
2816             unsafe = 1;
2817             break;
2818         case 'p':
2819             progress = 1;
2820             break;
2821         case 't':
2822             cache = optarg;
2823             break;
2824         case 'T':
2825             src_cache = optarg;
2826             break;
2827         case 'q':
2828             quiet = true;
2829             break;
2830         case OPTION_OBJECT: {
2831             QemuOpts *opts;
2832             opts = qemu_opts_parse_noisily(&qemu_object_opts,
2833                                            optarg, true);
2834             if (!opts) {
2835                 return 1;
2836             }
2837         }   break;
2838         case OPTION_IMAGE_OPTS:
2839             image_opts = true;
2840             break;
2841         }
2842     }
2843
2844     if (quiet) {
2845         progress = 0;
2846     }
2847
2848     if (optind != argc - 1) {
2849         error_exit("Expecting one image file name");
2850     }
2851     if (!unsafe && !out_baseimg) {
2852         error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2853     }
2854     filename = argv[optind++];
2855
2856     if (qemu_opts_foreach(&qemu_object_opts,
2857                           user_creatable_add_opts_foreach,
2858                           NULL, &local_err)) {
2859         error_report_err(local_err);
2860         return 1;
2861     }
2862
2863     qemu_progress_init(progress, 2.0);
2864     qemu_progress_print(0, 100);
2865
2866     flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2867     ret = bdrv_parse_cache_flags(cache, &flags);
2868     if (ret < 0) {
2869         error_report("Invalid cache option: %s", cache);
2870         goto out;
2871     }
2872
2873     src_flags = BDRV_O_FLAGS;
2874     ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2875     if (ret < 0) {
2876         error_report("Invalid source cache option: %s", src_cache);
2877         goto out;
2878     }
2879
2880     /*
2881      * Open the images.
2882      *
2883      * Ignore the old backing file for unsafe rebase in case we want to correct
2884      * the reference to a renamed or moved backing file.
2885      */
2886     blk = img_open(image_opts, filename, fmt, flags, quiet);
2887     if (!blk) {
2888         ret = -1;
2889         goto out;
2890     }
2891     bs = blk_bs(blk);
2892
2893     if (out_basefmt != NULL) {
2894         if (bdrv_find_format(out_basefmt) == NULL) {
2895             error_report("Invalid format name: '%s'", out_basefmt);
2896             ret = -1;
2897             goto out;
2898         }
2899     }
2900
2901     /* For safe rebasing we need to compare old and new backing file */
2902     if (!unsafe) {
2903         char backing_name[PATH_MAX];
2904         QDict *options = NULL;
2905
2906         if (bs->backing_format[0] != '\0') {
2907             options = qdict_new();
2908             qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2909         }
2910
2911         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2912         blk_old_backing = blk_new_open(backing_name, NULL,
2913                                        options, src_flags, &local_err);
2914         if (!blk_old_backing) {
2915             error_reportf_err(local_err,
2916                               "Could not open old backing file '%s': ",
2917                               backing_name);
2918             goto out;
2919         }
2920
2921         if (out_baseimg[0]) {
2922             if (out_basefmt) {
2923                 options = qdict_new();
2924                 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2925             } else {
2926                 options = NULL;
2927             }
2928
2929             blk_new_backing = blk_new_open(out_baseimg, NULL,
2930                                            options, src_flags, &local_err);
2931             if (!blk_new_backing) {
2932                 error_reportf_err(local_err,
2933                                   "Could not open new backing file '%s': ",
2934                                   out_baseimg);
2935                 goto out;
2936             }
2937         }
2938     }
2939
2940     /*
2941      * Check each unallocated cluster in the COW file. If it is unallocated,
2942      * accesses go to the backing file. We must therefore compare this cluster
2943      * in the old and new backing file, and if they differ we need to copy it
2944      * from the old backing file into the COW file.
2945      *
2946      * If qemu-img crashes during this step, no harm is done. The content of
2947      * the image is the same as the original one at any time.
2948      */
2949     if (!unsafe) {
2950         int64_t num_sectors;
2951         int64_t old_backing_num_sectors;
2952         int64_t new_backing_num_sectors = 0;
2953         uint64_t sector;
2954         int n;
2955         float local_progress = 0;
2956
2957         buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2958         buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2959
2960         num_sectors = blk_nb_sectors(blk);
2961         if (num_sectors < 0) {
2962             error_report("Could not get size of '%s': %s",
2963                          filename, strerror(-num_sectors));
2964             ret = -1;
2965             goto out;
2966         }
2967         old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2968         if (old_backing_num_sectors < 0) {
2969             char backing_name[PATH_MAX];
2970
2971             bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2972             error_report("Could not get size of '%s': %s",
2973                          backing_name, strerror(-old_backing_num_sectors));
2974             ret = -1;
2975             goto out;
2976         }
2977         if (blk_new_backing) {
2978             new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2979             if (new_backing_num_sectors < 0) {
2980                 error_report("Could not get size of '%s': %s",
2981                              out_baseimg, strerror(-new_backing_num_sectors));
2982                 ret = -1;
2983                 goto out;
2984             }
2985         }
2986
2987         if (num_sectors != 0) {
2988             local_progress = (float)100 /
2989                 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2990         }
2991
2992         for (sector = 0; sector < num_sectors; sector += n) {
2993
2994             /* How many sectors can we handle with the next read? */
2995             if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2996                 n = (IO_BUF_SIZE / 512);
2997             } else {
2998                 n = num_sectors - sector;
2999             }
3000
3001             /* If the cluster is allocated, we don't need to take action */
3002             ret = bdrv_is_allocated(bs, sector, n, &n);
3003             if (ret < 0) {
3004                 error_report("error while reading image metadata: %s",
3005                              strerror(-ret));
3006                 goto out;
3007             }
3008             if (ret) {
3009                 continue;
3010             }
3011
3012             /*
3013              * Read old and new backing file and take into consideration that
3014              * backing files may be smaller than the COW image.
3015              */
3016             if (sector >= old_backing_num_sectors) {
3017                 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3018             } else {
3019                 if (sector + n > old_backing_num_sectors) {
3020                     n = old_backing_num_sectors - sector;
3021                 }
3022
3023                 ret = blk_read(blk_old_backing, sector, buf_old, n);
3024                 if (ret < 0) {
3025                     error_report("error while reading from old backing file");
3026                     goto out;
3027                 }
3028             }
3029
3030             if (sector >= new_backing_num_sectors || !blk_new_backing) {
3031                 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3032             } else {
3033                 if (sector + n > new_backing_num_sectors) {
3034                     n = new_backing_num_sectors - sector;
3035                 }
3036
3037                 ret = blk_read(blk_new_backing, sector, buf_new, n);
3038                 if (ret < 0) {
3039                     error_report("error while reading from new backing file");
3040                     goto out;
3041                 }
3042             }
3043
3044             /* If they differ, we need to write to the COW file */
3045             uint64_t written = 0;
3046
3047             while (written < n) {
3048                 int pnum;
3049
3050                 if (compare_sectors(buf_old + written * 512,
3051                     buf_new + written * 512, n - written, &pnum))
3052                 {
3053                     ret = blk_write(blk, sector + written,
3054                                     buf_old + written * 512, pnum);
3055                     if (ret < 0) {
3056                         error_report("Error while writing to COW image: %s",
3057                             strerror(-ret));
3058                         goto out;
3059                     }
3060                 }
3061
3062                 written += pnum;
3063             }
3064             qemu_progress_print(local_progress, 100);
3065         }
3066     }
3067
3068     /*
3069      * Change the backing file. All clusters that are different from the old
3070      * backing file are overwritten in the COW file now, so the visible content
3071      * doesn't change when we switch the backing file.
3072      */
3073     if (out_baseimg && *out_baseimg) {
3074         ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3075     } else {
3076         ret = bdrv_change_backing_file(bs, NULL, NULL);
3077     }
3078
3079     if (ret == -ENOSPC) {
3080         error_report("Could not change the backing file to '%s': No "
3081                      "space left in the file header", out_baseimg);
3082     } else if (ret < 0) {
3083         error_report("Could not change the backing file to '%s': %s",
3084             out_baseimg, strerror(-ret));
3085     }
3086
3087     qemu_progress_print(100, 0);
3088     /*
3089      * TODO At this point it is possible to check if any clusters that are
3090      * allocated in the COW file are the same in the backing file. If so, they
3091      * could be dropped from the COW file. Don't do this before switching the
3092      * backing file, in case of a crash this would lead to corruption.
3093      */
3094 out:
3095     qemu_progress_end();
3096     /* Cleanup */
3097     if (!unsafe) {
3098         blk_unref(blk_old_backing);
3099         blk_unref(blk_new_backing);
3100     }
3101     qemu_vfree(buf_old);
3102     qemu_vfree(buf_new);
3103
3104     blk_unref(blk);
3105     if (ret) {
3106         return 1;
3107     }
3108     return 0;
3109 }
3110
3111 static int img_resize(int argc, char **argv)
3112 {
3113     Error *err = NULL;
3114     int c, ret, relative;
3115     const char *filename, *fmt, *size;
3116     int64_t n, total_size;
3117     bool quiet = false;
3118     BlockBackend *blk = NULL;
3119     QemuOpts *param;
3120     Error *local_err = NULL;
3121
3122     static QemuOptsList resize_options = {
3123         .name = "resize_options",
3124         .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3125         .desc = {
3126             {
3127                 .name = BLOCK_OPT_SIZE,
3128                 .type = QEMU_OPT_SIZE,
3129                 .help = "Virtual disk size"
3130             }, {
3131                 /* end of list */
3132             }
3133         },
3134     };
3135     bool image_opts = false;
3136
3137     /* Remove size from argv manually so that negative numbers are not treated
3138      * as options by getopt. */
3139     if (argc < 3) {
3140         error_exit("Not enough arguments");
3141         return 1;
3142     }
3143
3144     size = argv[--argc];
3145
3146     /* Parse getopt arguments */
3147     fmt = NULL;
3148     for(;;) {
3149         static const struct option long_options[] = {
3150             {"help", no_argument, 0, 'h'},
3151             {"object", required_argument, 0, OPTION_OBJECT},
3152             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3153             {0, 0, 0, 0}
3154         };
3155         c = getopt_long(argc, argv, "f:hq",
3156                         long_options, NULL);
3157         if (c == -1) {
3158             break;
3159         }
3160         switch(c) {
3161         case '?':
3162         case 'h':
3163             help();
3164             break;
3165         case 'f':
3166             fmt = optarg;
3167             break;
3168         case 'q':
3169             quiet = true;
3170             break;
3171         case OPTION_OBJECT: {
3172             QemuOpts *opts;
3173             opts = qemu_opts_parse_noisily(&qemu_object_opts,
3174                                            optarg, true);
3175             if (!opts) {
3176                 return 1;
3177             }
3178         }   break;
3179         case OPTION_IMAGE_OPTS:
3180             image_opts = true;
3181             break;
3182         }
3183     }
3184     if (optind != argc - 1) {
3185         error_exit("Expecting one image file name");
3186     }
3187     filename = argv[optind++];
3188
3189     if (qemu_opts_foreach(&qemu_object_opts,
3190                           user_creatable_add_opts_foreach,
3191                           NULL, &local_err)) {
3192         error_report_err(local_err);
3193         return 1;
3194     }
3195
3196     /* Choose grow, shrink, or absolute resize mode */
3197     switch (size[0]) {
3198     case '+':
3199         relative = 1;
3200         size++;
3201         break;
3202     case '-':
3203         relative = -1;
3204         size++;
3205         break;
3206     default:
3207         relative = 0;
3208         break;
3209     }
3210
3211     /* Parse size */
3212     param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3213     qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3214     if (err) {
3215         error_report_err(err);
3216         ret = -1;
3217         qemu_opts_del(param);
3218         goto out;
3219     }
3220     n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3221     qemu_opts_del(param);
3222
3223     blk = img_open(image_opts, filename, fmt,
3224                    BDRV_O_FLAGS | BDRV_O_RDWR, quiet);
3225     if (!blk) {
3226         ret = -1;
3227         goto out;
3228     }
3229
3230     if (relative) {
3231         total_size = blk_getlength(blk) + n * relative;
3232     } else {
3233         total_size = n;
3234     }
3235     if (total_size <= 0) {
3236         error_report("New image size must be positive");
3237         ret = -1;
3238         goto out;
3239     }
3240
3241     ret = blk_truncate(blk, total_size);
3242     switch (ret) {
3243     case 0:
3244         qprintf(quiet, "Image resized.\n");
3245         break;
3246     case -ENOTSUP:
3247         error_report("This image does not support resize");
3248         break;
3249     case -EACCES:
3250         error_report("Image is read-only");
3251         break;
3252     default:
3253         error_report("Error resizing image (%d)", -ret);
3254         break;
3255     }
3256 out:
3257     blk_unref(blk);
3258     if (ret) {
3259         return 1;
3260     }
3261     return 0;
3262 }
3263
3264 static void amend_status_cb(BlockDriverState *bs,
3265                             int64_t offset, int64_t total_work_size,
3266                             void *opaque)
3267 {
3268     qemu_progress_print(100.f * offset / total_work_size, 0);
3269 }
3270
3271 static int img_amend(int argc, char **argv)
3272 {
3273     Error *err = NULL;
3274     int c, ret = 0;
3275     char *options = NULL;
3276     QemuOptsList *create_opts = NULL;
3277     QemuOpts *opts = NULL;
3278     const char *fmt = NULL, *filename, *cache;
3279     int flags;
3280     bool quiet = false, progress = false;
3281     BlockBackend *blk = NULL;
3282     BlockDriverState *bs = NULL;
3283     Error *local_err = NULL;
3284     bool image_opts = false;
3285
3286     cache = BDRV_DEFAULT_CACHE;
3287     for (;;) {
3288         static const struct option long_options[] = {
3289             {"help", no_argument, 0, 'h'},
3290             {"object", required_argument, 0, OPTION_OBJECT},
3291             {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3292             {0, 0, 0, 0}
3293         };
3294         c = getopt_long(argc, argv, "ho:f:t:pq",
3295                         long_options, NULL);
3296         if (c == -1) {
3297             break;
3298         }
3299
3300         switch (c) {
3301             case 'h':
3302             case '?':
3303                 help();
3304                 break;
3305             case 'o':
3306                 if (!is_valid_option_list(optarg)) {
3307                     error_report("Invalid option list: %s", optarg);
3308                     ret = -1;
3309                     goto out_no_progress;
3310                 }
3311                 if (!options) {
3312                     options = g_strdup(optarg);
3313                 } else {
3314                     char *old_options = options;
3315                     options = g_strdup_printf("%s,%s", options, optarg);
3316                     g_free(old_options);
3317                 }
3318                 break;
3319             case 'f':
3320                 fmt = optarg;
3321                 break;
3322             case 't':
3323                 cache = optarg;
3324                 break;
3325             case 'p':
3326                 progress = true;
3327                 break;
3328             case 'q':
3329                 quiet = true;
3330                 break;
3331             case OPTION_OBJECT:
3332                 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3333                                                optarg, true);
3334                 if (!opts) {
3335                     ret = -1;
3336                     goto out_no_progress;
3337                 }
3338                 break;
3339             case OPTION_IMAGE_OPTS:
3340                 image_opts = true;
3341                 break;
3342         }
3343     }
3344
3345     if (!options) {
3346         error_exit("Must specify options (-o)");
3347     }
3348
3349     if (qemu_opts_foreach(&qemu_object_opts,
3350                           user_creatable_add_opts_foreach,
3351                           NULL, &local_err)) {
3352         error_report_err(local_err);
3353         ret = -1;
3354         goto out_no_progress;
3355     }
3356
3357     if (quiet) {
3358         progress = false;
3359     }
3360     qemu_progress_init(progress, 1.0);
3361
3362     filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3363     if (fmt && has_help_option(options)) {
3364         /* If a format is explicitly specified (and possibly no filename is
3365          * given), print option help here */
3366         ret = print_block_option_help(filename, fmt);
3367         goto out;
3368     }
3369
3370     if (optind != argc - 1) {
3371         error_report("Expecting one image file name");
3372         ret = -1;
3373         goto out;
3374     }
3375
3376     flags = BDRV_O_FLAGS | BDRV_O_RDWR;
3377     ret = bdrv_parse_cache_flags(cache, &flags);
3378     if (ret < 0) {
3379         error_report("Invalid cache option: %s", cache);
3380         goto out;
3381     }
3382
3383     blk = img_open(image_opts, filename, fmt, flags, quiet);
3384     if (!blk) {
3385         ret = -1;
3386         goto out;
3387     }
3388     bs = blk_bs(blk);
3389
3390     fmt = bs->drv->format_name;
3391
3392     if (has_help_option(options)) {
3393         /* If the format was auto-detected, print option help here */
3394         ret = print_block_option_help(filename, fmt);
3395         goto out;
3396     }
3397
3398     if (!bs->drv->create_opts) {
3399         error_report("Format driver '%s' does not support any options to amend",
3400                      fmt);
3401         ret = -1;
3402         goto out;
3403     }
3404
3405     create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3406     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3407     if (options) {
3408         qemu_opts_do_parse(opts, options, NULL, &err);
3409         if (err) {
3410             error_report_err(err);
3411             ret = -1;
3412             goto out;
3413         }
3414     }
3415
3416     /* In case the driver does not call amend_status_cb() */
3417     qemu_progress_print(0.f, 0);
3418     ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3419     qemu_progress_print(100.f, 0);
3420     if (ret < 0) {
3421         error_report("Error while amending options: %s", strerror(-ret));
3422         goto out;
3423     }
3424
3425 out:
3426     qemu_progress_end();
3427
3428 out_no_progress:
3429     blk_unref(blk);
3430     qemu_opts_del(opts);
3431     qemu_opts_free(create_opts);
3432     g_free(options);
3433
3434     if (ret) {
3435         return 1;
3436     }
3437     return 0;
3438 }
3439
3440 static const img_cmd_t img_cmds[] = {
3441 #define DEF(option, callback, arg_string)        \
3442     { option, callback },
3443 #include "qemu-img-cmds.h"
3444 #undef DEF
3445 #undef GEN_DOCS
3446     { NULL, NULL, },
3447 };
3448
3449 int main(int argc, char **argv)
3450 {
3451     const img_cmd_t *cmd;
3452     const char *cmdname;
3453     Error *local_error = NULL;
3454     int c;
3455     static const struct option long_options[] = {
3456         {"help", no_argument, 0, 'h'},
3457         {"version", no_argument, 0, 'v'},
3458         {0, 0, 0, 0}
3459     };
3460
3461 #ifdef CONFIG_POSIX
3462     signal(SIGPIPE, SIG_IGN);
3463 #endif
3464
3465     error_set_progname(argv[0]);
3466     qemu_init_exec_dir(argv[0]);
3467
3468     if (qemu_init_main_loop(&local_error)) {
3469         error_report_err(local_error);
3470         exit(EXIT_FAILURE);
3471     }
3472
3473     module_call_init(MODULE_INIT_QOM);
3474     bdrv_init();
3475     if (argc < 2) {
3476         error_exit("Not enough arguments");
3477     }
3478     cmdname = argv[1];
3479
3480     qemu_add_opts(&qemu_object_opts);
3481     qemu_add_opts(&qemu_source_opts);
3482
3483     /* find the command */
3484     for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3485         if (!strcmp(cmdname, cmd->name)) {
3486             return cmd->handler(argc - 1, argv + 1);
3487         }
3488     }
3489
3490     c = getopt_long(argc, argv, "h", long_options, NULL);
3491
3492     if (c == 'h') {
3493         help();
3494     }
3495     if (c == 'v') {
3496         printf(QEMU_IMG_VERSION);
3497         return 0;
3498     }
3499
3500     /* not found */
3501     error_exit("Command not found: %s", cmdname);
3502 }