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