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