Merge remote branch 'qemu-kvm/uq/master' into staging
[sdk/emulator/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-common.h"
25 #include "qemu-option.h"
26 #include "qemu-error.h"
27 #include "osdep.h"
28 #include "sysemu.h"
29 #include "block_int.h"
30 #include <stdio.h>
31
32 #ifdef _WIN32
33 #include <windows.h>
34 #endif
35
36 typedef struct img_cmd_t {
37     const char *name;
38     int (*handler)(int argc, char **argv);
39 } img_cmd_t;
40
41 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
42 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
43
44 static void format_print(void *opaque, const char *name)
45 {
46     printf(" %s", name);
47 }
48
49 /* Please keep in synch with qemu-img.texi */
50 static void help(void)
51 {
52     const char *help_msg =
53            "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
54            "usage: qemu-img command [command options]\n"
55            "QEMU disk image utility\n"
56            "\n"
57            "Command syntax:\n"
58 #define DEF(option, callback, arg_string)        \
59            "  " arg_string "\n"
60 #include "qemu-img-cmds.h"
61 #undef DEF
62 #undef GEN_DOCS
63            "\n"
64            "Command parameters:\n"
65            "  'filename' is a disk image filename\n"
66            "  'fmt' is the disk image format. It is guessed automatically in most cases\n"
67            "  'size' is the disk image size in bytes. Optional suffixes\n"
68            "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
69            "    and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
70            "  'output_filename' is the destination disk image filename\n"
71            "  'output_fmt' is the destination format\n"
72            "  'options' is a comma separated list of format specific options in a\n"
73            "    name=value format. Use -o ? for an overview of the options supported by the\n"
74            "    used format\n"
75            "  '-c' indicates that target image must be compressed (qcow format only)\n"
76            "  '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
77            "       match exactly. The image doesn't need a working backing file before\n"
78            "       rebasing in this case (useful for renaming the backing file)\n"
79            "  '-h' with or without a command shows this help and lists the supported formats\n"
80            "\n"
81            "Parameters to snapshot subcommand:\n"
82            "  'snapshot' is the name of the snapshot to create, apply or delete\n"
83            "  '-a' applies a snapshot (revert disk to saved state)\n"
84            "  '-c' creates a snapshot\n"
85            "  '-d' deletes a snapshot\n"
86            "  '-l' lists all snapshots in the given image\n";
87
88     printf("%s\nSupported formats:", help_msg);
89     bdrv_iterate_format(format_print, NULL);
90     printf("\n");
91     exit(1);
92 }
93
94 #if defined(WIN32)
95 /* XXX: put correct support for win32 */
96 static int read_password(char *buf, int buf_size)
97 {
98     int c, i;
99     printf("Password: ");
100     fflush(stdout);
101     i = 0;
102     for(;;) {
103         c = getchar();
104         if (c == '\n')
105             break;
106         if (i < (buf_size - 1))
107             buf[i++] = c;
108     }
109     buf[i] = '\0';
110     return 0;
111 }
112
113 #else
114
115 #include <termios.h>
116
117 static struct termios oldtty;
118
119 static void term_exit(void)
120 {
121     tcsetattr (0, TCSANOW, &oldtty);
122 }
123
124 static void term_init(void)
125 {
126     struct termios tty;
127
128     tcgetattr (0, &tty);
129     oldtty = tty;
130
131     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
132                           |INLCR|IGNCR|ICRNL|IXON);
133     tty.c_oflag |= OPOST;
134     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
135     tty.c_cflag &= ~(CSIZE|PARENB);
136     tty.c_cflag |= CS8;
137     tty.c_cc[VMIN] = 1;
138     tty.c_cc[VTIME] = 0;
139
140     tcsetattr (0, TCSANOW, &tty);
141
142     atexit(term_exit);
143 }
144
145 static int read_password(char *buf, int buf_size)
146 {
147     uint8_t ch;
148     int i, ret;
149
150     printf("password: ");
151     fflush(stdout);
152     term_init();
153     i = 0;
154     for(;;) {
155         ret = read(0, &ch, 1);
156         if (ret == -1) {
157             if (errno == EAGAIN || errno == EINTR) {
158                 continue;
159             } else {
160                 ret = -1;
161                 break;
162             }
163         } else if (ret == 0) {
164             ret = -1;
165             break;
166         } else {
167             if (ch == '\r') {
168                 ret = 0;
169                 break;
170             }
171             if (i < (buf_size - 1))
172                 buf[i++] = ch;
173         }
174     }
175     term_exit();
176     buf[i] = '\0';
177     printf("\n");
178     return ret;
179 }
180 #endif
181
182 static int print_block_option_help(const char *filename, const char *fmt)
183 {
184     BlockDriver *drv, *proto_drv;
185     QEMUOptionParameter *create_options = NULL;
186
187     /* Find driver and parse its options */
188     drv = bdrv_find_format(fmt);
189     if (!drv) {
190         error_report("Unknown file format '%s'", fmt);
191         return 1;
192     }
193
194     proto_drv = bdrv_find_protocol(filename);
195     if (!proto_drv) {
196         error_report("Unknown protocol '%s'", filename);
197         return 1;
198     }
199
200     create_options = append_option_parameters(create_options,
201                                               drv->create_options);
202     create_options = append_option_parameters(create_options,
203                                               proto_drv->create_options);
204     print_option_help(create_options);
205     free_option_parameters(create_options);
206     return 0;
207 }
208
209 static BlockDriverState *bdrv_new_open(const char *filename,
210                                        const char *fmt,
211                                        int flags)
212 {
213     BlockDriverState *bs;
214     BlockDriver *drv;
215     char password[256];
216
217     bs = bdrv_new("");
218
219     if (fmt) {
220         drv = bdrv_find_format(fmt);
221         if (!drv) {
222             error_report("Unknown file format '%s'", fmt);
223             goto fail;
224         }
225     } else {
226         drv = NULL;
227     }
228     if (bdrv_open(bs, filename, flags, drv) < 0) {
229         error_report("Could not open '%s'", filename);
230         goto fail;
231     }
232     if (bdrv_is_encrypted(bs)) {
233         printf("Disk image '%s' is encrypted.\n", filename);
234         if (read_password(password, sizeof(password)) < 0) {
235             error_report("No password given");
236             goto fail;
237         }
238         if (bdrv_set_key(bs, password) < 0) {
239             error_report("invalid password");
240             goto fail;
241         }
242     }
243     return bs;
244 fail:
245     if (bs) {
246         bdrv_delete(bs);
247     }
248     return NULL;
249 }
250
251 static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
252                                  const char *base_filename,
253                                  const char *base_fmt)
254 {
255     if (base_filename) {
256         if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
257             error_report("Backing file not supported for file format '%s'",
258                          fmt);
259             return -1;
260         }
261     }
262     if (base_fmt) {
263         if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
264             error_report("Backing file format not supported for file "
265                          "format '%s'", fmt);
266             return -1;
267         }
268     }
269     return 0;
270 }
271
272 static int img_create(int argc, char **argv)
273 {
274     int c, ret = 0;
275     uint64_t img_size = -1;
276     const char *fmt = "raw";
277     const char *base_fmt = NULL;
278     const char *filename;
279     const char *base_filename = NULL;
280     char *options = NULL;
281
282     for(;;) {
283         c = getopt(argc, argv, "F:b:f:he6o:");
284         if (c == -1) {
285             break;
286         }
287         switch(c) {
288         case '?':
289         case 'h':
290             help();
291             break;
292         case 'F':
293             base_fmt = optarg;
294             break;
295         case 'b':
296             base_filename = optarg;
297             break;
298         case 'f':
299             fmt = optarg;
300             break;
301         case 'e':
302             error_report("qemu-img: option -e is deprecated, please use \'-o "
303                   "encryption\' instead!");
304             return 1;
305         case '6':
306             error_report("qemu-img: option -6 is deprecated, please use \'-o "
307                   "compat6\' instead!");
308             return 1;
309         case 'o':
310             options = optarg;
311             break;
312         }
313     }
314
315     /* Get the filename */
316     if (optind >= argc) {
317         help();
318     }
319     filename = argv[optind++];
320
321     /* Get image size, if specified */
322     if (optind < argc) {
323         int64_t sval;
324         sval = strtosz_suffix(argv[optind++], NULL, STRTOSZ_DEFSUFFIX_B);
325         if (sval < 0) {
326             error_report("Invalid image size specified! You may use k, M, G or "
327                   "T suffixes for ");
328             error_report("kilobytes, megabytes, gigabytes and terabytes.");
329             ret = -1;
330             goto out;
331         }
332         img_size = (uint64_t)sval;
333     }
334
335     if (options && !strcmp(options, "?")) {
336         ret = print_block_option_help(filename, fmt);
337         goto out;
338     }
339
340     ret = bdrv_img_create(filename, fmt, base_filename, base_fmt,
341                           options, img_size, BDRV_O_FLAGS);
342 out:
343     if (ret) {
344         return 1;
345     }
346     return 0;
347 }
348
349 /*
350  * Checks an image for consistency. Exit codes:
351  *
352  * 0 - Check completed, image is good
353  * 1 - Check not completed because of internal errors
354  * 2 - Check completed, image is corrupted
355  * 3 - Check completed, image has leaked clusters, but is good otherwise
356  */
357 static int img_check(int argc, char **argv)
358 {
359     int c, ret;
360     const char *filename, *fmt;
361     BlockDriverState *bs;
362     BdrvCheckResult result;
363
364     fmt = NULL;
365     for(;;) {
366         c = getopt(argc, argv, "f:h");
367         if (c == -1) {
368             break;
369         }
370         switch(c) {
371         case '?':
372         case 'h':
373             help();
374             break;
375         case 'f':
376             fmt = optarg;
377             break;
378         }
379     }
380     if (optind >= argc) {
381         help();
382     }
383     filename = argv[optind++];
384
385     bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS);
386     if (!bs) {
387         return 1;
388     }
389     ret = bdrv_check(bs, &result);
390
391     if (ret == -ENOTSUP) {
392         error_report("This image format does not support checks");
393         bdrv_delete(bs);
394         return 1;
395     }
396
397     if (!(result.corruptions || result.leaks || result.check_errors)) {
398         printf("No errors were found on the image.\n");
399     } else {
400         if (result.corruptions) {
401             printf("\n%d errors were found on the image.\n"
402                 "Data may be corrupted, or further writes to the image "
403                 "may corrupt it.\n",
404                 result.corruptions);
405         }
406
407         if (result.leaks) {
408             printf("\n%d leaked clusters were found on the image.\n"
409                 "This means waste of disk space, but no harm to data.\n",
410                 result.leaks);
411         }
412
413         if (result.check_errors) {
414             printf("\n%d internal errors have occurred during the check.\n",
415                 result.check_errors);
416         }
417     }
418
419     bdrv_delete(bs);
420
421     if (ret < 0 || result.check_errors) {
422         printf("\nAn error has occurred during the check: %s\n"
423             "The check is not complete and may have missed error.\n",
424             strerror(-ret));
425         return 1;
426     }
427
428     if (result.corruptions) {
429         return 2;
430     } else if (result.leaks) {
431         return 3;
432     } else {
433         return 0;
434     }
435 }
436
437 static int img_commit(int argc, char **argv)
438 {
439     int c, ret;
440     const char *filename, *fmt;
441     BlockDriverState *bs;
442
443     fmt = NULL;
444     for(;;) {
445         c = getopt(argc, argv, "f:h");
446         if (c == -1) {
447             break;
448         }
449         switch(c) {
450         case '?':
451         case 'h':
452             help();
453             break;
454         case 'f':
455             fmt = optarg;
456             break;
457         }
458     }
459     if (optind >= argc) {
460         help();
461     }
462     filename = argv[optind++];
463
464     bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR);
465     if (!bs) {
466         return 1;
467     }
468     ret = bdrv_commit(bs);
469     switch(ret) {
470     case 0:
471         printf("Image committed.\n");
472         break;
473     case -ENOENT:
474         error_report("No disk inserted");
475         break;
476     case -EACCES:
477         error_report("Image is read-only");
478         break;
479     case -ENOTSUP:
480         error_report("Image is already committed");
481         break;
482     default:
483         error_report("Error while committing image");
484         break;
485     }
486
487     bdrv_delete(bs);
488     if (ret) {
489         return 1;
490     }
491     return 0;
492 }
493
494 static int is_not_zero(const uint8_t *sector, int len)
495 {
496     int i;
497     len >>= 2;
498     for(i = 0;i < len; i++) {
499         if (((uint32_t *)sector)[i] != 0)
500             return 1;
501     }
502     return 0;
503 }
504
505 /*
506  * Returns true iff the first sector pointed to by 'buf' contains at least
507  * a non-NUL byte.
508  *
509  * 'pnum' is set to the number of sectors (including and immediately following
510  * the first one) that are known to be in the same allocated/unallocated state.
511  */
512 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
513 {
514     int v, i;
515
516     if (n <= 0) {
517         *pnum = 0;
518         return 0;
519     }
520     v = is_not_zero(buf, 512);
521     for(i = 1; i < n; i++) {
522         buf += 512;
523         if (v != is_not_zero(buf, 512))
524             break;
525     }
526     *pnum = i;
527     return v;
528 }
529
530 /*
531  * Compares two buffers sector by sector. Returns 0 if the first sector of both
532  * buffers matches, non-zero otherwise.
533  *
534  * pnum is set to the number of sectors (including and immediately following
535  * the first one) that are known to have the same comparison result
536  */
537 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
538     int *pnum)
539 {
540     int res, i;
541
542     if (n <= 0) {
543         *pnum = 0;
544         return 0;
545     }
546
547     res = !!memcmp(buf1, buf2, 512);
548     for(i = 1; i < n; i++) {
549         buf1 += 512;
550         buf2 += 512;
551
552         if (!!memcmp(buf1, buf2, 512) != res) {
553             break;
554         }
555     }
556
557     *pnum = i;
558     return res;
559 }
560
561 #define IO_BUF_SIZE (2 * 1024 * 1024)
562
563 static int img_convert(int argc, char **argv)
564 {
565     int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
566     const char *fmt, *out_fmt, *out_baseimg, *out_filename;
567     BlockDriver *drv, *proto_drv;
568     BlockDriverState **bs = NULL, *out_bs = NULL;
569     int64_t total_sectors, nb_sectors, sector_num, bs_offset;
570     uint64_t bs_sectors;
571     uint8_t * buf = NULL;
572     const uint8_t *buf1;
573     BlockDriverInfo bdi;
574     QEMUOptionParameter *param = NULL, *create_options = NULL;
575     QEMUOptionParameter *out_baseimg_param;
576     char *options = NULL;
577     const char *snapshot_name = NULL;
578
579     fmt = NULL;
580     out_fmt = "raw";
581     out_baseimg = NULL;
582     compress = 0;
583     for(;;) {
584         c = getopt(argc, argv, "f:O:B:s:hce6o:");
585         if (c == -1) {
586             break;
587         }
588         switch(c) {
589         case '?':
590         case 'h':
591             help();
592             break;
593         case 'f':
594             fmt = optarg;
595             break;
596         case 'O':
597             out_fmt = optarg;
598             break;
599         case 'B':
600             out_baseimg = optarg;
601             break;
602         case 'c':
603             compress = 1;
604             break;
605         case 'e':
606             error_report("qemu-img: option -e is deprecated, please use \'-o "
607                   "encryption\' instead!");
608             return 1;
609         case '6':
610             error_report("qemu-img: option -6 is deprecated, please use \'-o "
611                   "compat6\' instead!");
612             return 1;
613         case 'o':
614             options = optarg;
615             break;
616         case 's':
617             snapshot_name = optarg;
618             break;
619         }
620     }
621
622     bs_n = argc - optind - 1;
623     if (bs_n < 1) {
624         help();
625     }
626
627     out_filename = argv[argc - 1];
628
629     if (options && !strcmp(options, "?")) {
630         ret = print_block_option_help(out_filename, out_fmt);
631         goto out;
632     }
633
634     if (bs_n > 1 && out_baseimg) {
635         error_report("-B makes no sense when concatenating multiple input "
636                      "images");
637         ret = -1;
638         goto out;
639     }
640         
641     bs = qemu_mallocz(bs_n * sizeof(BlockDriverState *));
642
643     total_sectors = 0;
644     for (bs_i = 0; bs_i < bs_n; bs_i++) {
645         bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS);
646         if (!bs[bs_i]) {
647             error_report("Could not open '%s'", argv[optind + bs_i]);
648             ret = -1;
649             goto out;
650         }
651         bdrv_get_geometry(bs[bs_i], &bs_sectors);
652         total_sectors += bs_sectors;
653     }
654
655     if (snapshot_name != NULL) {
656         if (bs_n > 1) {
657             error_report("No support for concatenating multiple snapshot\n");
658             ret = -1;
659             goto out;
660         }
661         if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
662             error_report("Failed to load snapshot\n");
663             ret = -1;
664             goto out;
665         }
666     }
667
668     /* Find driver and parse its options */
669     drv = bdrv_find_format(out_fmt);
670     if (!drv) {
671         error_report("Unknown file format '%s'", out_fmt);
672         ret = -1;
673         goto out;
674     }
675
676     proto_drv = bdrv_find_protocol(out_filename);
677     if (!proto_drv) {
678         error_report("Unknown protocol '%s'", out_filename);
679         ret = -1;
680         goto out;
681     }
682
683     create_options = append_option_parameters(create_options,
684                                               drv->create_options);
685     create_options = append_option_parameters(create_options,
686                                               proto_drv->create_options);
687
688     if (options) {
689         param = parse_option_parameters(options, create_options, param);
690         if (param == NULL) {
691             error_report("Invalid options for file format '%s'.", out_fmt);
692             ret = -1;
693             goto out;
694         }
695     } else {
696         param = parse_option_parameters("", create_options, param);
697     }
698
699     set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
700     ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
701     if (ret < 0) {
702         goto out;
703     }
704
705     /* Get backing file name if -o backing_file was used */
706     out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
707     if (out_baseimg_param) {
708         out_baseimg = out_baseimg_param->value.s;
709     }
710
711     /* Check if compression is supported */
712     if (compress) {
713         QEMUOptionParameter *encryption =
714             get_option_parameter(param, BLOCK_OPT_ENCRYPT);
715
716         if (!drv->bdrv_write_compressed) {
717             error_report("Compression not supported for this file format");
718             ret = -1;
719             goto out;
720         }
721
722         if (encryption && encryption->value.n) {
723             error_report("Compression and encryption not supported at "
724                          "the same time");
725             ret = -1;
726             goto out;
727         }
728     }
729
730     /* Create the new image */
731     ret = bdrv_create(drv, out_filename, param);
732     if (ret < 0) {
733         if (ret == -ENOTSUP) {
734             error_report("Formatting not supported for file format '%s'",
735                          out_fmt);
736         } else if (ret == -EFBIG) {
737             error_report("The image size is too large for file format '%s'",
738                          out_fmt);
739         } else {
740             error_report("%s: error while converting %s: %s",
741                          out_filename, out_fmt, strerror(-ret));
742         }
743         goto out;
744     }
745
746     out_bs = bdrv_new_open(out_filename, out_fmt,
747         BDRV_O_FLAGS | BDRV_O_RDWR | BDRV_O_NO_FLUSH);
748     if (!out_bs) {
749         ret = -1;
750         goto out;
751     }
752
753     bs_i = 0;
754     bs_offset = 0;
755     bdrv_get_geometry(bs[0], &bs_sectors);
756     buf = qemu_malloc(IO_BUF_SIZE);
757
758     if (compress) {
759         ret = bdrv_get_info(out_bs, &bdi);
760         if (ret < 0) {
761             error_report("could not get block driver info");
762             goto out;
763         }
764         cluster_size = bdi.cluster_size;
765         if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
766             error_report("invalid cluster size");
767             ret = -1;
768             goto out;
769         }
770         cluster_sectors = cluster_size >> 9;
771         sector_num = 0;
772         for(;;) {
773             int64_t bs_num;
774             int remainder;
775             uint8_t *buf2;
776
777             nb_sectors = total_sectors - sector_num;
778             if (nb_sectors <= 0)
779                 break;
780             if (nb_sectors >= cluster_sectors)
781                 n = cluster_sectors;
782             else
783                 n = nb_sectors;
784
785             bs_num = sector_num - bs_offset;
786             assert (bs_num >= 0);
787             remainder = n;
788             buf2 = buf;
789             while (remainder > 0) {
790                 int nlow;
791                 while (bs_num == bs_sectors) {
792                     bs_i++;
793                     assert (bs_i < bs_n);
794                     bs_offset += bs_sectors;
795                     bdrv_get_geometry(bs[bs_i], &bs_sectors);
796                     bs_num = 0;
797                     /* printf("changing part: sector_num=%" PRId64 ", "
798                        "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
799                        "\n", sector_num, bs_i, bs_offset, bs_sectors); */
800                 }
801                 assert (bs_num < bs_sectors);
802
803                 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
804
805                 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
806                 if (ret < 0) {
807                     error_report("error while reading");
808                     goto out;
809                 }
810
811                 buf2 += nlow * 512;
812                 bs_num += nlow;
813
814                 remainder -= nlow;
815             }
816             assert (remainder == 0);
817
818             if (n < cluster_sectors) {
819                 memset(buf + n * 512, 0, cluster_size - n * 512);
820             }
821             if (is_not_zero(buf, cluster_size)) {
822                 ret = bdrv_write_compressed(out_bs, sector_num, buf,
823                                             cluster_sectors);
824                 if (ret != 0) {
825                     error_report("error while compressing sector %" PRId64,
826                           sector_num);
827                     goto out;
828                 }
829             }
830             sector_num += n;
831         }
832         /* signal EOF to align */
833         bdrv_write_compressed(out_bs, 0, NULL, 0);
834     } else {
835         int has_zero_init = bdrv_has_zero_init(out_bs);
836
837         sector_num = 0; // total number of sectors converted so far
838         for(;;) {
839             nb_sectors = total_sectors - sector_num;
840             if (nb_sectors <= 0) {
841                 break;
842             }
843             if (nb_sectors >= (IO_BUF_SIZE / 512)) {
844                 n = (IO_BUF_SIZE / 512);
845             } else {
846                 n = nb_sectors;
847             }
848
849             while (sector_num - bs_offset >= bs_sectors) {
850                 bs_i ++;
851                 assert (bs_i < bs_n);
852                 bs_offset += bs_sectors;
853                 bdrv_get_geometry(bs[bs_i], &bs_sectors);
854                 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
855                   "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
856                    sector_num, bs_i, bs_offset, bs_sectors); */
857             }
858
859             if (n > bs_offset + bs_sectors - sector_num) {
860                 n = bs_offset + bs_sectors - sector_num;
861             }
862
863             if (has_zero_init) {
864                 /* If the output image is being created as a copy on write image,
865                    assume that sectors which are unallocated in the input image
866                    are present in both the output's and input's base images (no
867                    need to copy them). */
868                 if (out_baseimg) {
869                     if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
870                                            n, &n1)) {
871                         sector_num += n1;
872                         continue;
873                     }
874                     /* The next 'n1' sectors are allocated in the input image. Copy
875                        only those as they may be followed by unallocated sectors. */
876                     n = n1;
877                 }
878             } else {
879                 n1 = n;
880             }
881
882             ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
883             if (ret < 0) {
884                 error_report("error while reading");
885                 goto out;
886             }
887             /* NOTE: at the same time we convert, we do not write zero
888                sectors to have a chance to compress the image. Ideally, we
889                should add a specific call to have the info to go faster */
890             buf1 = buf;
891             while (n > 0) {
892                 /* If the output image is being created as a copy on write image,
893                    copy all sectors even the ones containing only NUL bytes,
894                    because they may differ from the sectors in the base image.
895
896                    If the output is to a host device, we also write out
897                    sectors that are entirely 0, since whatever data was
898                    already there is garbage, not 0s. */
899                 if (!has_zero_init || out_baseimg ||
900                     is_allocated_sectors(buf1, n, &n1)) {
901                     ret = bdrv_write(out_bs, sector_num, buf1, n1);
902                     if (ret < 0) {
903                         error_report("error while writing");
904                         goto out;
905                     }
906                 }
907                 sector_num += n1;
908                 n -= n1;
909                 buf1 += n1 * 512;
910             }
911         }
912     }
913 out:
914     free_option_parameters(create_options);
915     free_option_parameters(param);
916     qemu_free(buf);
917     if (out_bs) {
918         bdrv_delete(out_bs);
919     }
920     if (bs) {
921         for (bs_i = 0; bs_i < bs_n; bs_i++) {
922             if (bs[bs_i]) {
923                 bdrv_delete(bs[bs_i]);
924             }
925         }
926         qemu_free(bs);
927     }
928     if (ret) {
929         return 1;
930     }
931     return 0;
932 }
933
934 #ifdef _WIN32
935 static int64_t get_allocated_file_size(const char *filename)
936 {
937     typedef DWORD (WINAPI * get_compressed_t)(const char *filename, DWORD *high);
938     get_compressed_t get_compressed;
939     struct _stati64 st;
940
941     /* WinNT support GetCompressedFileSize to determine allocate size */
942     get_compressed = (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"), "GetCompressedFileSizeA");
943     if (get_compressed) {
944         DWORD high, low;
945         low = get_compressed(filename, &high);
946         if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR)
947             return (((int64_t) high) << 32) + low;
948     }
949
950     if (_stati64(filename, &st) < 0)
951         return -1;
952     return st.st_size;
953 }
954 #else
955 static int64_t get_allocated_file_size(const char *filename)
956 {
957     struct stat st;
958     if (stat(filename, &st) < 0)
959         return -1;
960     return (int64_t)st.st_blocks * 512;
961 }
962 #endif
963
964 static void dump_snapshots(BlockDriverState *bs)
965 {
966     QEMUSnapshotInfo *sn_tab, *sn;
967     int nb_sns, i;
968     char buf[256];
969
970     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
971     if (nb_sns <= 0)
972         return;
973     printf("Snapshot list:\n");
974     printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
975     for(i = 0; i < nb_sns; i++) {
976         sn = &sn_tab[i];
977         printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
978     }
979     qemu_free(sn_tab);
980 }
981
982 static int img_info(int argc, char **argv)
983 {
984     int c;
985     const char *filename, *fmt;
986     BlockDriverState *bs;
987     char fmt_name[128], size_buf[128], dsize_buf[128];
988     uint64_t total_sectors;
989     int64_t allocated_size;
990     char backing_filename[1024];
991     char backing_filename2[1024];
992     BlockDriverInfo bdi;
993
994     fmt = NULL;
995     for(;;) {
996         c = getopt(argc, argv, "f:h");
997         if (c == -1) {
998             break;
999         }
1000         switch(c) {
1001         case '?':
1002         case 'h':
1003             help();
1004             break;
1005         case 'f':
1006             fmt = optarg;
1007             break;
1008         }
1009     }
1010     if (optind >= argc) {
1011         help();
1012     }
1013     filename = argv[optind++];
1014
1015     bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING);
1016     if (!bs) {
1017         return 1;
1018     }
1019     bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
1020     bdrv_get_geometry(bs, &total_sectors);
1021     get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
1022     allocated_size = get_allocated_file_size(filename);
1023     if (allocated_size < 0) {
1024         snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1025     } else {
1026         get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1027                                 allocated_size);
1028     }
1029     printf("image: %s\n"
1030            "file format: %s\n"
1031            "virtual size: %s (%" PRId64 " bytes)\n"
1032            "disk size: %s\n",
1033            filename, fmt_name, size_buf,
1034            (total_sectors * 512),
1035            dsize_buf);
1036     if (bdrv_is_encrypted(bs)) {
1037         printf("encrypted: yes\n");
1038     }
1039     if (bdrv_get_info(bs, &bdi) >= 0) {
1040         if (bdi.cluster_size != 0) {
1041             printf("cluster_size: %d\n", bdi.cluster_size);
1042         }
1043     }
1044     bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1045     if (backing_filename[0] != '\0') {
1046         path_combine(backing_filename2, sizeof(backing_filename2),
1047                      filename, backing_filename);
1048         printf("backing file: %s (actual path: %s)\n",
1049                backing_filename,
1050                backing_filename2);
1051     }
1052     dump_snapshots(bs);
1053     bdrv_delete(bs);
1054     return 0;
1055 }
1056
1057 #define SNAPSHOT_LIST   1
1058 #define SNAPSHOT_CREATE 2
1059 #define SNAPSHOT_APPLY  3
1060 #define SNAPSHOT_DELETE 4
1061
1062 static int img_snapshot(int argc, char **argv)
1063 {
1064     BlockDriverState *bs;
1065     QEMUSnapshotInfo sn;
1066     char *filename, *snapshot_name = NULL;
1067     int c, ret = 0, bdrv_oflags;
1068     int action = 0;
1069     qemu_timeval tv;
1070
1071     bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
1072     /* Parse commandline parameters */
1073     for(;;) {
1074         c = getopt(argc, argv, "la:c:d:h");
1075         if (c == -1) {
1076             break;
1077         }
1078         switch(c) {
1079         case '?':
1080         case 'h':
1081             help();
1082             return 0;
1083         case 'l':
1084             if (action) {
1085                 help();
1086                 return 0;
1087             }
1088             action = SNAPSHOT_LIST;
1089             bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
1090             break;
1091         case 'a':
1092             if (action) {
1093                 help();
1094                 return 0;
1095             }
1096             action = SNAPSHOT_APPLY;
1097             snapshot_name = optarg;
1098             break;
1099         case 'c':
1100             if (action) {
1101                 help();
1102                 return 0;
1103             }
1104             action = SNAPSHOT_CREATE;
1105             snapshot_name = optarg;
1106             break;
1107         case 'd':
1108             if (action) {
1109                 help();
1110                 return 0;
1111             }
1112             action = SNAPSHOT_DELETE;
1113             snapshot_name = optarg;
1114             break;
1115         }
1116     }
1117
1118     if (optind >= argc) {
1119         help();
1120     }
1121     filename = argv[optind++];
1122
1123     /* Open the image */
1124     bs = bdrv_new_open(filename, NULL, bdrv_oflags);
1125     if (!bs) {
1126         return 1;
1127     }
1128
1129     /* Perform the requested action */
1130     switch(action) {
1131     case SNAPSHOT_LIST:
1132         dump_snapshots(bs);
1133         break;
1134
1135     case SNAPSHOT_CREATE:
1136         memset(&sn, 0, sizeof(sn));
1137         pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1138
1139         qemu_gettimeofday(&tv);
1140         sn.date_sec = tv.tv_sec;
1141         sn.date_nsec = tv.tv_usec * 1000;
1142
1143         ret = bdrv_snapshot_create(bs, &sn);
1144         if (ret) {
1145             error_report("Could not create snapshot '%s': %d (%s)",
1146                 snapshot_name, ret, strerror(-ret));
1147         }
1148         break;
1149
1150     case SNAPSHOT_APPLY:
1151         ret = bdrv_snapshot_goto(bs, snapshot_name);
1152         if (ret) {
1153             error_report("Could not apply snapshot '%s': %d (%s)",
1154                 snapshot_name, ret, strerror(-ret));
1155         }
1156         break;
1157
1158     case SNAPSHOT_DELETE:
1159         ret = bdrv_snapshot_delete(bs, snapshot_name);
1160         if (ret) {
1161             error_report("Could not delete snapshot '%s': %d (%s)",
1162                 snapshot_name, ret, strerror(-ret));
1163         }
1164         break;
1165     }
1166
1167     /* Cleanup */
1168     bdrv_delete(bs);
1169     if (ret) {
1170         return 1;
1171     }
1172     return 0;
1173 }
1174
1175 static int img_rebase(int argc, char **argv)
1176 {
1177     BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
1178     BlockDriver *old_backing_drv, *new_backing_drv;
1179     char *filename;
1180     const char *fmt, *out_basefmt, *out_baseimg;
1181     int c, flags, ret;
1182     int unsafe = 0;
1183
1184     /* Parse commandline parameters */
1185     fmt = NULL;
1186     out_baseimg = NULL;
1187     out_basefmt = NULL;
1188
1189     for(;;) {
1190         c = getopt(argc, argv, "uhf:F:b:");
1191         if (c == -1) {
1192             break;
1193         }
1194         switch(c) {
1195         case '?':
1196         case 'h':
1197             help();
1198             return 0;
1199         case 'f':
1200             fmt = optarg;
1201             break;
1202         case 'F':
1203             out_basefmt = optarg;
1204             break;
1205         case 'b':
1206             out_baseimg = optarg;
1207             break;
1208         case 'u':
1209             unsafe = 1;
1210             break;
1211         }
1212     }
1213
1214     if ((optind >= argc) || !out_baseimg) {
1215         help();
1216     }
1217     filename = argv[optind++];
1218
1219     /*
1220      * Open the images.
1221      *
1222      * Ignore the old backing file for unsafe rebase in case we want to correct
1223      * the reference to a renamed or moved backing file.
1224      */
1225     flags = BDRV_O_FLAGS | BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
1226     bs = bdrv_new_open(filename, fmt, flags);
1227     if (!bs) {
1228         return 1;
1229     }
1230
1231     /* Find the right drivers for the backing files */
1232     old_backing_drv = NULL;
1233     new_backing_drv = NULL;
1234
1235     if (!unsafe && bs->backing_format[0] != '\0') {
1236         old_backing_drv = bdrv_find_format(bs->backing_format);
1237         if (old_backing_drv == NULL) {
1238             error_report("Invalid format name: '%s'", bs->backing_format);
1239             ret = -1;
1240             goto out;
1241         }
1242     }
1243
1244     if (out_basefmt != NULL) {
1245         new_backing_drv = bdrv_find_format(out_basefmt);
1246         if (new_backing_drv == NULL) {
1247             error_report("Invalid format name: '%s'", out_basefmt);
1248             ret = -1;
1249             goto out;
1250         }
1251     }
1252
1253     /* For safe rebasing we need to compare old and new backing file */
1254     if (unsafe) {
1255         /* Make the compiler happy */
1256         bs_old_backing = NULL;
1257         bs_new_backing = NULL;
1258     } else {
1259         char backing_name[1024];
1260
1261         bs_old_backing = bdrv_new("old_backing");
1262         bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
1263         ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1264                         old_backing_drv);
1265         if (ret) {
1266             error_report("Could not open old backing file '%s'", backing_name);
1267             goto out;
1268         }
1269
1270         bs_new_backing = bdrv_new("new_backing");
1271         ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
1272                         new_backing_drv);
1273         if (ret) {
1274             error_report("Could not open new backing file '%s'", out_baseimg);
1275             goto out;
1276         }
1277     }
1278
1279     /*
1280      * Check each unallocated cluster in the COW file. If it is unallocated,
1281      * accesses go to the backing file. We must therefore compare this cluster
1282      * in the old and new backing file, and if they differ we need to copy it
1283      * from the old backing file into the COW file.
1284      *
1285      * If qemu-img crashes during this step, no harm is done. The content of
1286      * the image is the same as the original one at any time.
1287      */
1288     if (!unsafe) {
1289         uint64_t num_sectors;
1290         uint64_t sector;
1291         int n;
1292         uint8_t * buf_old;
1293         uint8_t * buf_new;
1294
1295         buf_old = qemu_malloc(IO_BUF_SIZE);
1296         buf_new = qemu_malloc(IO_BUF_SIZE);
1297
1298         bdrv_get_geometry(bs, &num_sectors);
1299
1300         for (sector = 0; sector < num_sectors; sector += n) {
1301
1302             /* How many sectors can we handle with the next read? */
1303             if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1304                 n = (IO_BUF_SIZE / 512);
1305             } else {
1306                 n = num_sectors - sector;
1307             }
1308
1309             /* If the cluster is allocated, we don't need to take action */
1310             ret = bdrv_is_allocated(bs, sector, n, &n);
1311             if (ret) {
1312                 continue;
1313             }
1314
1315             /* Read old and new backing file */
1316             ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1317             if (ret < 0) {
1318                 error_report("error while reading from old backing file");
1319                 goto out;
1320             }
1321             ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1322             if (ret < 0) {
1323                 error_report("error while reading from new backing file");
1324                 goto out;
1325             }
1326
1327             /* If they differ, we need to write to the COW file */
1328             uint64_t written = 0;
1329
1330             while (written < n) {
1331                 int pnum;
1332
1333                 if (compare_sectors(buf_old + written * 512,
1334                     buf_new + written * 512, n - written, &pnum))
1335                 {
1336                     ret = bdrv_write(bs, sector + written,
1337                         buf_old + written * 512, pnum);
1338                     if (ret < 0) {
1339                         error_report("Error while writing to COW image: %s",
1340                             strerror(-ret));
1341                         goto out;
1342                     }
1343                 }
1344
1345                 written += pnum;
1346             }
1347         }
1348
1349         qemu_free(buf_old);
1350         qemu_free(buf_new);
1351     }
1352
1353     /*
1354      * Change the backing file. All clusters that are different from the old
1355      * backing file are overwritten in the COW file now, so the visible content
1356      * doesn't change when we switch the backing file.
1357      */
1358     ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
1359     if (ret == -ENOSPC) {
1360         error_report("Could not change the backing file to '%s': No "
1361                      "space left in the file header", out_baseimg);
1362     } else if (ret < 0) {
1363         error_report("Could not change the backing file to '%s': %s",
1364             out_baseimg, strerror(-ret));
1365     }
1366
1367     /*
1368      * TODO At this point it is possible to check if any clusters that are
1369      * allocated in the COW file are the same in the backing file. If so, they
1370      * could be dropped from the COW file. Don't do this before switching the
1371      * backing file, in case of a crash this would lead to corruption.
1372      */
1373 out:
1374     /* Cleanup */
1375     if (!unsafe) {
1376         bdrv_delete(bs_old_backing);
1377         bdrv_delete(bs_new_backing);
1378     }
1379
1380     bdrv_delete(bs);
1381     if (ret) {
1382         return 1;
1383     }
1384     return 0;
1385 }
1386
1387 static int img_resize(int argc, char **argv)
1388 {
1389     int c, ret, relative;
1390     const char *filename, *fmt, *size;
1391     int64_t n, total_size;
1392     BlockDriverState *bs = NULL;
1393     QEMUOptionParameter *param;
1394     QEMUOptionParameter resize_options[] = {
1395         {
1396             .name = BLOCK_OPT_SIZE,
1397             .type = OPT_SIZE,
1398             .help = "Virtual disk size"
1399         },
1400         { NULL }
1401     };
1402
1403     fmt = NULL;
1404     for(;;) {
1405         c = getopt(argc, argv, "f:h");
1406         if (c == -1) {
1407             break;
1408         }
1409         switch(c) {
1410         case '?':
1411         case 'h':
1412             help();
1413             break;
1414         case 'f':
1415             fmt = optarg;
1416             break;
1417         }
1418     }
1419     if (optind + 1 >= argc) {
1420         help();
1421     }
1422     filename = argv[optind++];
1423     size = argv[optind++];
1424
1425     /* Choose grow, shrink, or absolute resize mode */
1426     switch (size[0]) {
1427     case '+':
1428         relative = 1;
1429         size++;
1430         break;
1431     case '-':
1432         relative = -1;
1433         size++;
1434         break;
1435     default:
1436         relative = 0;
1437         break;
1438     }
1439
1440     /* Parse size */
1441     param = parse_option_parameters("", resize_options, NULL);
1442     if (set_option_parameter(param, BLOCK_OPT_SIZE, size)) {
1443         /* Error message already printed when size parsing fails */
1444         ret = -1;
1445         goto out;
1446     }
1447     n = get_option_parameter(param, BLOCK_OPT_SIZE)->value.n;
1448     free_option_parameters(param);
1449
1450     bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR);
1451     if (!bs) {
1452         ret = -1;
1453         goto out;
1454     }
1455
1456     if (relative) {
1457         total_size = bdrv_getlength(bs) + n * relative;
1458     } else {
1459         total_size = n;
1460     }
1461     if (total_size <= 0) {
1462         error_report("New image size must be positive");
1463         ret = -1;
1464         goto out;
1465     }
1466
1467     ret = bdrv_truncate(bs, total_size);
1468     switch (ret) {
1469     case 0:
1470         printf("Image resized.\n");
1471         break;
1472     case -ENOTSUP:
1473         error_report("This image format does not support resize");
1474         break;
1475     case -EACCES:
1476         error_report("Image is read-only");
1477         break;
1478     default:
1479         error_report("Error resizing image (%d)", -ret);
1480         break;
1481     }
1482 out:
1483     if (bs) {
1484         bdrv_delete(bs);
1485     }
1486     if (ret) {
1487         return 1;
1488     }
1489     return 0;
1490 }
1491
1492 static const img_cmd_t img_cmds[] = {
1493 #define DEF(option, callback, arg_string)        \
1494     { option, callback },
1495 #include "qemu-img-cmds.h"
1496 #undef DEF
1497 #undef GEN_DOCS
1498     { NULL, NULL, },
1499 };
1500
1501 int main(int argc, char **argv)
1502 {
1503     const img_cmd_t *cmd;
1504     const char *cmdname;
1505
1506     error_set_progname(argv[0]);
1507
1508     bdrv_init();
1509     if (argc < 2)
1510         help();
1511     cmdname = argv[1];
1512     argc--; argv++;
1513
1514     /* find the command */
1515     for(cmd = img_cmds; cmd->name != NULL; cmd++) {
1516         if (!strcmp(cmdname, cmd->name)) {
1517             return cmd->handler(argc, argv);
1518         }
1519     }
1520
1521     /* not found */
1522     help();
1523     return 0;
1524 }