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