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