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