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