2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
24 #include "qemu-common.h"
25 #include "qemu-option.h"
27 #include "block_int.h"
34 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
35 #define BRDV_O_FLAGS BDRV_O_CACHE_WB
37 static void QEMU_NORETURN error(const char *fmt, ...)
41 fprintf(stderr, "qemu-img: ");
42 vfprintf(stderr, fmt, ap);
43 fprintf(stderr, "\n");
48 static void format_print(void *opaque, const char *name)
53 /* Please keep in synch with qemu-img.texi */
54 static void help(void)
56 printf("qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
57 "usage: qemu-img command [command options]\n"
58 "QEMU disk image utility\n"
61 " check [-f fmt] filename\n"
62 " create [-F fmt] [-b base_image] [-f fmt] [-o options] filename [size]\n"
63 " commit [-f fmt] filename\n"
64 " convert [-c] [-f fmt] [-O output_fmt] [-o options] [-B output_base_image] filename [filename2 [...]] output_filename\n"
65 " info [-f fmt] filename\n"
66 " snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename\n"
68 "Command parameters:\n"
69 " 'filename' is a disk image filename\n"
70 " 'base_image' is the read-only disk image which is used as base for a copy on\n"
71 " write image; the copy on write image only stores the modified data\n"
72 " 'output_base_image' forces the output image to be created as a copy on write\n"
73 " image of the specified base image; 'output_base_image' should have the same\n"
74 " content as the input's base image, however the path, image format, etc may\n"
76 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
77 " 'size' is the disk image size in kilobytes. Optional suffixes\n"
78 " 'M' (megabyte, 1024 * 1024) and 'G' (gigabyte, 1024 * 1024 * 1024) are\n"
79 " supported any 'k' or 'K' is ignored\n"
80 " 'output_filename' is the destination disk image filename\n"
81 " 'output_fmt' is the destination format\n"
82 " 'options' is a comma separated list of format specific options in a\n"
83 " name=value format. Use -o ? for an overview of the options supported by the\n"
85 " '-c' indicates that target image must be compressed (qcow format only)\n"
86 " '-h' with or without a command shows this help and lists the supported formats\n"
88 "Parameters to snapshot subcommand:\n"
89 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
90 " '-a' applies a snapshot (revert disk to saved state)\n"
91 " '-c' creates a snapshot\n"
92 " '-d' deletes a snapshot\n"
93 " '-l' lists all snapshots in the given image\n"
95 printf("\nSupported formats:");
96 bdrv_iterate_format(format_print, NULL);
102 /* XXX: put correct support for win32 */
103 static int read_password(char *buf, int buf_size)
106 printf("Password: ");
113 if (i < (buf_size - 1))
124 static struct termios oldtty;
126 static void term_exit(void)
128 tcsetattr (0, TCSANOW, &oldtty);
131 static void term_init(void)
138 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
139 |INLCR|IGNCR|ICRNL|IXON);
140 tty.c_oflag |= OPOST;
141 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
142 tty.c_cflag &= ~(CSIZE|PARENB);
147 tcsetattr (0, TCSANOW, &tty);
152 static int read_password(char *buf, int buf_size)
157 printf("password: ");
162 ret = read(0, &ch, 1);
164 if (errno == EAGAIN || errno == EINTR) {
170 } else if (ret == 0) {
178 if (i < (buf_size - 1))
189 static BlockDriverState *bdrv_new_open(const char *filename,
192 BlockDriverState *bs;
198 error("Not enough memory");
200 drv = bdrv_find_format(fmt);
202 error("Unknown file format '%s'", fmt);
206 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
207 error("Could not open '%s'", filename);
209 if (bdrv_is_encrypted(bs)) {
210 printf("Disk image '%s' is encrypted.\n", filename);
211 if (read_password(password, sizeof(password)) < 0)
212 error("No password given");
213 if (bdrv_set_key(bs, password) < 0)
214 error("invalid password");
219 static void add_old_style_options(const char *fmt, QEMUOptionParameter *list,
220 int flags, const char *base_filename, const char *base_fmt)
222 if (flags & BLOCK_FLAG_ENCRYPT) {
223 if (set_option_parameter(list, BLOCK_OPT_ENCRYPT, "on")) {
224 error("Encryption not supported for file format '%s'", fmt);
227 if (flags & BLOCK_FLAG_COMPAT6) {
228 if (set_option_parameter(list, BLOCK_OPT_COMPAT6, "on")) {
229 error("VMDK version 6 not supported for file format '%s'", fmt);
234 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
235 error("Backing file not supported for file format '%s'", fmt);
239 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
240 error("Backing file format not supported for file format '%s'", fmt);
245 static int img_create(int argc, char **argv)
248 const char *fmt = "raw";
249 const char *base_fmt = NULL;
250 const char *filename;
251 const char *base_filename = NULL;
253 QEMUOptionParameter *param = NULL;
254 char *options = NULL;
258 c = getopt(argc, argv, "F:b:f:he6o:");
269 base_filename = optarg;
275 flags |= BLOCK_FLAG_ENCRYPT;
278 flags |= BLOCK_FLAG_COMPAT6;
286 /* Find driver and parse its options */
287 drv = bdrv_find_format(fmt);
289 error("Unknown file format '%s'", fmt);
291 if (options && !strcmp(options, "?")) {
292 print_option_help(drv->create_options);
297 param = parse_option_parameters(options, drv->create_options, param);
299 error("Invalid options for file format '%s'.", fmt);
302 param = parse_option_parameters("", drv->create_options, param);
305 /* Get the filename */
308 filename = argv[optind++];
310 /* Add size to parameters */
312 set_option_parameter(param, BLOCK_OPT_SIZE, argv[optind++]);
315 /* Add old-style options to parameters */
316 add_old_style_options(fmt, param, flags, base_filename, base_fmt);
318 // The size for the image must always be specified, with one exception:
319 // If we are using a backing file, we can obtain the size from there
320 if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == 0) {
322 QEMUOptionParameter *backing_file =
323 get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
324 QEMUOptionParameter *backing_fmt =
325 get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
327 if (backing_file && backing_file->value.s) {
328 BlockDriverState *bs;
330 const char *fmt = NULL;
333 if (backing_fmt && backing_fmt->value.s) {
334 if (bdrv_find_format(backing_fmt->value.s)) {
335 fmt = backing_fmt->value.s;
337 error("Unknown backing file format '%s'",
338 backing_fmt->value.s);
342 bs = bdrv_new_open(backing_file->value.s, fmt);
343 bdrv_get_geometry(bs, &size);
347 snprintf(buf, sizeof(buf), "%" PRId64, size);
348 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
350 error("Image creation needs a size parameter");
354 printf("Formatting '%s', fmt=%s ", filename, fmt);
355 print_option_parameters(param);
358 ret = bdrv_create(drv, filename, param);
359 free_option_parameters(param);
362 if (ret == -ENOTSUP) {
363 error("Formatting or formatting option not supported for file format '%s'", fmt);
364 } else if (ret == -EFBIG) {
365 error("The image size is too large for file format '%s'", fmt);
367 error("Error while formatting");
373 static int img_check(int argc, char **argv)
376 const char *filename, *fmt;
378 BlockDriverState *bs;
382 c = getopt(argc, argv, "f:h");
396 filename = argv[optind++];
400 error("Not enough memory");
402 drv = bdrv_find_format(fmt);
404 error("Unknown file format '%s'", fmt);
408 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
409 error("Could not open '%s'", filename);
411 ret = bdrv_check(bs);
414 printf("No errors were found on the image.\n");
417 error("This image format does not support checks");
421 error("An error occurred during the check");
423 printf("%d errors were found on the image.\n", ret);
432 static int img_commit(int argc, char **argv)
435 const char *filename, *fmt;
437 BlockDriverState *bs;
441 c = getopt(argc, argv, "f:h");
455 filename = argv[optind++];
459 error("Not enough memory");
461 drv = bdrv_find_format(fmt);
463 error("Unknown file format '%s'", fmt);
467 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
468 error("Could not open '%s'", filename);
470 ret = bdrv_commit(bs);
473 printf("Image committed.\n");
476 error("No disk inserted");
479 error("Image is read-only");
482 error("Image is already committed");
485 error("Error while committing image");
493 static int is_not_zero(const uint8_t *sector, int len)
497 for(i = 0;i < len; i++) {
498 if (((uint32_t *)sector)[i] != 0)
505 * Returns true iff the first sector pointed to by 'buf' contains at least
508 * 'pnum' is set to the number of sectors (including and immediately following
509 * the first one) that are known to be in the same allocated/unallocated state.
511 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
519 v = is_not_zero(buf, 512);
520 for(i = 1; i < n; i++) {
522 if (v != is_not_zero(buf, 512))
529 #define IO_BUF_SIZE 65536
531 static int img_convert(int argc, char **argv)
533 int c, ret, n, n1, bs_n, bs_i, flags, cluster_size, cluster_sectors;
534 const char *fmt, *out_fmt, *out_baseimg, *out_filename;
536 BlockDriverState **bs, *out_bs;
537 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
539 uint8_t buf[IO_BUF_SIZE];
542 QEMUOptionParameter *param = NULL;
543 char *options = NULL;
550 c = getopt(argc, argv, "f:O:B:hce6o:");
564 out_baseimg = optarg;
567 flags |= BLOCK_FLAG_COMPRESS;
570 flags |= BLOCK_FLAG_ENCRYPT;
573 flags |= BLOCK_FLAG_COMPAT6;
581 bs_n = argc - optind - 1;
582 if (bs_n < 1) help();
584 out_filename = argv[argc - 1];
586 if (bs_n > 1 && out_baseimg)
587 error("-B makes no sense when concatenating multiple input images");
589 bs = calloc(bs_n, sizeof(BlockDriverState *));
591 error("Out of memory");
594 for (bs_i = 0; bs_i < bs_n; bs_i++) {
595 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt);
597 error("Could not open '%s'", argv[optind + bs_i]);
598 bdrv_get_geometry(bs[bs_i], &bs_sectors);
599 total_sectors += bs_sectors;
602 /* Find driver and parse its options */
603 drv = bdrv_find_format(out_fmt);
605 error("Unknown file format '%s'", out_fmt);
607 if (options && !strcmp(options, "?")) {
608 print_option_help(drv->create_options);
613 param = parse_option_parameters(options, drv->create_options, param);
615 error("Invalid options for file format '%s'.", out_fmt);
618 param = parse_option_parameters("", drv->create_options, param);
621 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
622 add_old_style_options(out_fmt, param, flags, out_baseimg, NULL);
624 /* Check if compression is supported */
625 if (flags & BLOCK_FLAG_COMPRESS) {
626 QEMUOptionParameter *encryption =
627 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
629 if (!drv->bdrv_write_compressed) {
630 error("Compression not supported for this file format");
633 if (encryption && encryption->value.n) {
634 error("Compression and encryption not supported at the same time");
638 /* Create the new image */
639 ret = bdrv_create(drv, out_filename, param);
640 free_option_parameters(param);
643 if (ret == -ENOTSUP) {
644 error("Formatting not supported for file format '%s'", out_fmt);
645 } else if (ret == -EFBIG) {
646 error("The image size is too large for file format '%s'", out_fmt);
648 error("Error while formatting '%s'", out_filename);
652 out_bs = bdrv_new_open(out_filename, out_fmt);
656 bdrv_get_geometry(bs[0], &bs_sectors);
658 if (flags & BLOCK_FLAG_COMPRESS) {
659 if (bdrv_get_info(out_bs, &bdi) < 0)
660 error("could not get block driver info");
661 cluster_size = bdi.cluster_size;
662 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE)
663 error("invalid cluster size");
664 cluster_sectors = cluster_size >> 9;
671 nb_sectors = total_sectors - sector_num;
674 if (nb_sectors >= cluster_sectors)
679 bs_num = sector_num - bs_offset;
680 assert (bs_num >= 0);
683 while (remainder > 0) {
685 while (bs_num == bs_sectors) {
687 assert (bs_i < bs_n);
688 bs_offset += bs_sectors;
689 bdrv_get_geometry(bs[bs_i], &bs_sectors);
691 /* printf("changing part: sector_num=%lld, "
692 "bs_i=%d, bs_offset=%lld, bs_sectors=%lld\n",
693 sector_num, bs_i, bs_offset, bs_sectors); */
695 assert (bs_num < bs_sectors);
697 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
699 if (bdrv_read(bs[bs_i], bs_num, buf2, nlow) < 0)
700 error("error while reading");
707 assert (remainder == 0);
709 if (n < cluster_sectors)
710 memset(buf + n * 512, 0, cluster_size - n * 512);
711 if (is_not_zero(buf, cluster_size)) {
712 if (bdrv_write_compressed(out_bs, sector_num, buf,
713 cluster_sectors) != 0)
714 error("error while compressing sector %" PRId64,
719 /* signal EOF to align */
720 bdrv_write_compressed(out_bs, 0, NULL, 0);
722 sector_num = 0; // total number of sectors converted so far
724 nb_sectors = total_sectors - sector_num;
727 if (nb_sectors >= (IO_BUF_SIZE / 512))
728 n = (IO_BUF_SIZE / 512);
732 while (sector_num - bs_offset >= bs_sectors) {
734 assert (bs_i < bs_n);
735 bs_offset += bs_sectors;
736 bdrv_get_geometry(bs[bs_i], &bs_sectors);
737 /* printf("changing part: sector_num=%lld, bs_i=%d, "
738 "bs_offset=%lld, bs_sectors=%lld\n",
739 sector_num, bs_i, bs_offset, bs_sectors); */
742 if (n > bs_offset + bs_sectors - sector_num)
743 n = bs_offset + bs_sectors - sector_num;
745 if (strcmp(drv->format_name, "host_device")) {
746 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
751 /* The next 'n1' sectors are allocated in the input image. Copy
752 only those as they may be followed by unallocated sectors. */
758 if (bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n) < 0)
759 error("error while reading");
760 /* NOTE: at the same time we convert, we do not write zero
761 sectors to have a chance to compress the image. Ideally, we
762 should add a specific call to have the info to go faster */
765 /* If the output image is being created as a copy on write image,
766 copy all sectors even the ones containing only NUL bytes,
767 because they may differ from the sectors in the base image.
769 If the output is to a host device, we also write out
770 sectors that are entirely 0, since whatever data was
771 already there is garbage, not 0s. */
772 if (strcmp(drv->format_name, "host_device") == 0 || out_baseimg ||
773 is_allocated_sectors(buf1, n, &n1)) {
774 if (bdrv_write(out_bs, sector_num, buf1, n1) < 0)
775 error("error while writing");
784 for (bs_i = 0; bs_i < bs_n; bs_i++)
785 bdrv_delete(bs[bs_i]);
791 static int64_t get_allocated_file_size(const char *filename)
793 typedef DWORD (WINAPI * get_compressed_t)(const char *filename, DWORD *high);
794 get_compressed_t get_compressed;
797 /* WinNT support GetCompressedFileSize to determine allocate size */
798 get_compressed = (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"), "GetCompressedFileSizeA");
799 if (get_compressed) {
801 low = get_compressed(filename, &high);
802 if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR)
803 return (((int64_t) high) << 32) + low;
806 if (_stati64(filename, &st) < 0)
811 static int64_t get_allocated_file_size(const char *filename)
814 if (stat(filename, &st) < 0)
816 return (int64_t)st.st_blocks * 512;
820 static void dump_snapshots(BlockDriverState *bs)
822 QEMUSnapshotInfo *sn_tab, *sn;
826 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
829 printf("Snapshot list:\n");
830 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
831 for(i = 0; i < nb_sns; i++) {
833 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
838 static int img_info(int argc, char **argv)
841 const char *filename, *fmt;
843 BlockDriverState *bs;
844 char fmt_name[128], size_buf[128], dsize_buf[128];
845 uint64_t total_sectors;
846 int64_t allocated_size;
847 char backing_filename[1024];
848 char backing_filename2[1024];
853 c = getopt(argc, argv, "f:h");
867 filename = argv[optind++];
871 error("Not enough memory");
873 drv = bdrv_find_format(fmt);
875 error("Unknown file format '%s'", fmt);
879 if (bdrv_open2(bs, filename, BRDV_O_FLAGS, drv) < 0) {
880 error("Could not open '%s'", filename);
882 bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
883 bdrv_get_geometry(bs, &total_sectors);
884 get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
885 allocated_size = get_allocated_file_size(filename);
886 if (allocated_size < 0)
887 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
889 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
893 "virtual size: %s (%" PRId64 " bytes)\n"
895 filename, fmt_name, size_buf,
896 (total_sectors * 512),
898 if (bdrv_is_encrypted(bs))
899 printf("encrypted: yes\n");
900 if (bdrv_get_info(bs, &bdi) >= 0) {
901 if (bdi.cluster_size != 0)
902 printf("cluster_size: %d\n", bdi.cluster_size);
904 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
905 if (backing_filename[0] != '\0') {
906 path_combine(backing_filename2, sizeof(backing_filename2),
907 filename, backing_filename);
908 printf("backing file: %s (actual path: %s)\n",
917 #define SNAPSHOT_LIST 1
918 #define SNAPSHOT_CREATE 2
919 #define SNAPSHOT_APPLY 3
920 #define SNAPSHOT_DELETE 4
922 static void img_snapshot(int argc, char **argv)
924 BlockDriverState *bs;
926 char *filename, *snapshot_name = NULL;
931 /* Parse commandline parameters */
933 c = getopt(argc, argv, "la:c:d:h");
945 action = SNAPSHOT_LIST;
952 action = SNAPSHOT_APPLY;
953 snapshot_name = optarg;
960 action = SNAPSHOT_CREATE;
961 snapshot_name = optarg;
968 action = SNAPSHOT_DELETE;
969 snapshot_name = optarg;
976 filename = argv[optind++];
981 error("Not enough memory");
983 if (bdrv_open2(bs, filename, 0, NULL) < 0) {
984 error("Could not open '%s'", filename);
987 /* Perform the requested action */
993 case SNAPSHOT_CREATE:
994 memset(&sn, 0, sizeof(sn));
995 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
997 qemu_gettimeofday(&tv);
998 sn.date_sec = tv.tv_sec;
999 sn.date_nsec = tv.tv_usec * 1000;
1001 ret = bdrv_snapshot_create(bs, &sn);
1003 error("Could not create snapshot '%s': %d (%s)",
1004 snapshot_name, ret, strerror(-ret));
1007 case SNAPSHOT_APPLY:
1008 ret = bdrv_snapshot_goto(bs, snapshot_name);
1010 error("Could not apply snapshot '%s': %d (%s)",
1011 snapshot_name, ret, strerror(-ret));
1014 case SNAPSHOT_DELETE:
1015 ret = bdrv_snapshot_delete(bs, snapshot_name);
1017 error("Could not delete snapshot '%s': %d (%s)",
1018 snapshot_name, ret, strerror(-ret));
1026 int main(int argc, char **argv)
1035 if (!strcmp(cmd, "create")) {
1036 img_create(argc, argv);
1037 } else if (!strcmp(cmd, "check")) {
1038 img_check(argc, argv);
1039 } else if (!strcmp(cmd, "commit")) {
1040 img_commit(argc, argv);
1041 } else if (!strcmp(cmd, "convert")) {
1042 img_convert(argc, argv);
1043 } else if (!strcmp(cmd, "info")) {
1044 img_info(argc, argv);
1045 } else if (!strcmp(cmd, "snapshot")) {
1046 img_snapshot(argc, argv);