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 "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"
40 typedef struct img_cmd_t {
42 int (*handler)(int argc, char **argv);
47 OPTION_BACKING_CHAIN = 257,
50 typedef enum OutputFormat {
55 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
56 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
57 #define BDRV_DEFAULT_CACHE "writeback"
59 static void format_print(void *opaque, const char *name)
64 /* Please keep in synch with qemu-img.texi */
65 static void help(void)
67 const char *help_msg =
68 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
69 "usage: qemu-img command [command options]\n"
70 "QEMU disk image utility\n"
73 #define DEF(option, callback, arg_string) \
75 #include "qemu-img-cmds.h"
79 "Command parameters:\n"
80 " 'filename' is a disk image filename\n"
81 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
82 " 'cache' is the cache mode used to write the output disk image, the valid\n"
83 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
84 " 'directsync' and 'unsafe' (default for convert)\n"
85 " 'size' is the disk image size in bytes. Optional suffixes\n"
86 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
87 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
88 " 'output_filename' is the destination disk image filename\n"
89 " 'output_fmt' is the destination format\n"
90 " 'options' is a comma separated list of format specific options in a\n"
91 " name=value format. Use -o ? for an overview of the options supported by the\n"
93 " '-c' indicates that target image must be compressed (qcow format only)\n"
94 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
95 " match exactly. The image doesn't need a working backing file before\n"
96 " rebasing in this case (useful for renaming the backing file)\n"
97 " '-h' with or without a command shows this help and lists the supported formats\n"
98 " '-p' show progress of command (only certain commands)\n"
99 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
100 " for qemu-img to create a sparse image during conversion\n"
101 " '--output' takes the format in which the output must be done (human or json)\n"
103 "Parameters to check subcommand:\n"
104 " '-r' tries to repair any inconsistencies that are found during the check.\n"
105 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
106 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
107 " hiding corruption that has already occurred.\n"
109 "Parameters to snapshot subcommand:\n"
110 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
111 " '-a' applies a snapshot (revert disk to saved state)\n"
112 " '-c' creates a snapshot\n"
113 " '-d' deletes a snapshot\n"
114 " '-l' lists all snapshots in the given image\n";
116 printf("%s\nSupported formats:", help_msg);
117 bdrv_iterate_format(format_print, NULL);
123 /* XXX: put correct support for win32 */
124 static int read_password(char *buf, int buf_size)
127 printf("Password: ");
134 if (i < (buf_size - 1))
145 static struct termios oldtty;
147 static void term_exit(void)
149 tcsetattr (0, TCSANOW, &oldtty);
152 static void term_init(void)
159 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
160 |INLCR|IGNCR|ICRNL|IXON);
161 tty.c_oflag |= OPOST;
162 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
163 tty.c_cflag &= ~(CSIZE|PARENB);
168 tcsetattr (0, TCSANOW, &tty);
173 static int read_password(char *buf, int buf_size)
178 printf("password: ");
183 ret = read(0, &ch, 1);
185 if (errno == EAGAIN || errno == EINTR) {
191 } else if (ret == 0) {
199 if (i < (buf_size - 1))
210 static int print_block_option_help(const char *filename, const char *fmt)
212 BlockDriver *drv, *proto_drv;
213 QEMUOptionParameter *create_options = NULL;
215 /* Find driver and parse its options */
216 drv = bdrv_find_format(fmt);
218 error_report("Unknown file format '%s'", fmt);
222 proto_drv = bdrv_find_protocol(filename);
224 error_report("Unknown protocol '%s'", filename);
228 create_options = append_option_parameters(create_options,
229 drv->create_options);
230 create_options = append_option_parameters(create_options,
231 proto_drv->create_options);
232 print_option_help(create_options);
233 free_option_parameters(create_options);
237 static BlockDriverState *bdrv_new_open(const char *filename,
242 BlockDriverState *bs;
247 bs = bdrv_new("image");
250 drv = bdrv_find_format(fmt);
252 error_report("Unknown file format '%s'", fmt);
259 ret = bdrv_open(bs, filename, flags, drv);
261 error_report("Could not open '%s': %s", filename, strerror(-ret));
265 if (bdrv_is_encrypted(bs) && require_io) {
266 printf("Disk image '%s' is encrypted.\n", filename);
267 if (read_password(password, sizeof(password)) < 0) {
268 error_report("No password given");
271 if (bdrv_set_key(bs, password) < 0) {
272 error_report("invalid password");
284 static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
285 const char *base_filename,
286 const char *base_fmt)
289 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
290 error_report("Backing file not supported for file format '%s'",
296 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
297 error_report("Backing file format not supported for file "
305 static int img_create(int argc, char **argv)
308 uint64_t img_size = -1;
309 const char *fmt = "raw";
310 const char *base_fmt = NULL;
311 const char *filename;
312 const char *base_filename = NULL;
313 char *options = NULL;
314 Error *local_err = NULL;
317 c = getopt(argc, argv, "F:b:f:he6o:");
330 base_filename = optarg;
336 error_report("option -e is deprecated, please use \'-o "
337 "encryption\' instead!");
340 error_report("option -6 is deprecated, please use \'-o "
341 "compat6\' instead!");
349 /* Get the filename */
350 if (optind >= argc) {
353 filename = argv[optind++];
355 /* Get image size, if specified */
359 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
360 if (sval < 0 || *end) {
361 if (sval == -ERANGE) {
362 error_report("Image size must be less than 8 EiB!");
364 error_report("Invalid image size specified! You may use k, M, "
365 "G or T suffixes for ");
366 error_report("kilobytes, megabytes, gigabytes and terabytes.");
370 img_size = (uint64_t)sval;
373 if (options && is_help_option(options)) {
374 return print_block_option_help(filename, fmt);
377 bdrv_img_create(filename, fmt, base_filename, base_fmt,
378 options, img_size, BDRV_O_FLAGS, &local_err);
379 if (error_is_set(&local_err)) {
380 error_report("%s", error_get_pretty(local_err));
381 error_free(local_err);
388 static void dump_json_image_check(ImageCheck *check)
392 QmpOutputVisitor *ov = qmp_output_visitor_new();
394 visit_type_ImageCheck(qmp_output_get_visitor(ov),
395 &check, NULL, &errp);
396 obj = qmp_output_get_qobject(ov);
397 str = qobject_to_json_pretty(obj);
399 printf("%s\n", qstring_get_str(str));
401 qmp_output_visitor_cleanup(ov);
405 static void dump_human_image_check(ImageCheck *check)
407 if (!(check->corruptions || check->leaks || check->check_errors)) {
408 printf("No errors were found on the image.\n");
410 if (check->corruptions) {
411 printf("\n%" PRId64 " errors were found on the image.\n"
412 "Data may be corrupted, or further writes to the image "
418 printf("\n%" PRId64 " leaked clusters were found on the image.\n"
419 "This means waste of disk space, but no harm to data.\n",
423 if (check->check_errors) {
424 printf("\n%" PRId64 " internal errors have occurred during the check.\n",
425 check->check_errors);
429 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
430 printf("%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
431 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
432 check->allocated_clusters, check->total_clusters,
433 check->allocated_clusters * 100.0 / check->total_clusters,
434 check->fragmented_clusters * 100.0 / check->allocated_clusters,
435 check->compressed_clusters * 100.0 / check->allocated_clusters);
438 if (check->image_end_offset) {
439 printf("Image end offset: %" PRId64 "\n", check->image_end_offset);
443 static int collect_image_check(BlockDriverState *bs,
445 const char *filename,
450 BdrvCheckResult result;
452 ret = bdrv_check(bs, &result, fix);
457 check->filename = g_strdup(filename);
458 check->format = g_strdup(bdrv_get_format_name(bs));
459 check->check_errors = result.check_errors;
460 check->corruptions = result.corruptions;
461 check->has_corruptions = result.corruptions != 0;
462 check->leaks = result.leaks;
463 check->has_leaks = result.leaks != 0;
464 check->corruptions_fixed = result.corruptions_fixed;
465 check->has_corruptions_fixed = result.corruptions != 0;
466 check->leaks_fixed = result.leaks_fixed;
467 check->has_leaks_fixed = result.leaks != 0;
468 check->image_end_offset = result.image_end_offset;
469 check->has_image_end_offset = result.image_end_offset != 0;
470 check->total_clusters = result.bfi.total_clusters;
471 check->has_total_clusters = result.bfi.total_clusters != 0;
472 check->allocated_clusters = result.bfi.allocated_clusters;
473 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
474 check->fragmented_clusters = result.bfi.fragmented_clusters;
475 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
476 check->compressed_clusters = result.bfi.compressed_clusters;
477 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
483 * Checks an image for consistency. Exit codes:
485 * 0 - Check completed, image is good
486 * 1 - Check not completed because of internal errors
487 * 2 - Check completed, image is corrupted
488 * 3 - Check completed, image has leaked clusters, but is good otherwise
490 static int img_check(int argc, char **argv)
493 OutputFormat output_format = OFORMAT_HUMAN;
494 const char *filename, *fmt, *output;
495 BlockDriverState *bs;
497 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
503 int option_index = 0;
504 static const struct option long_options[] = {
505 {"help", no_argument, 0, 'h'},
506 {"format", required_argument, 0, 'f'},
507 {"repair", no_argument, 0, 'r'},
508 {"output", required_argument, 0, OPTION_OUTPUT},
511 c = getopt_long(argc, argv, "f:hr:",
512 long_options, &option_index);
525 flags |= BDRV_O_RDWR;
527 if (!strcmp(optarg, "leaks")) {
528 fix = BDRV_FIX_LEAKS;
529 } else if (!strcmp(optarg, "all")) {
530 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
540 if (optind >= argc) {
543 filename = argv[optind++];
545 if (output && !strcmp(output, "json")) {
546 output_format = OFORMAT_JSON;
547 } else if (output && !strcmp(output, "human")) {
548 output_format = OFORMAT_HUMAN;
550 error_report("--output must be used with human or json as argument.");
554 bs = bdrv_new_open(filename, fmt, flags, true);
559 check = g_new0(ImageCheck, 1);
560 ret = collect_image_check(bs, check, filename, fmt, fix);
562 if (ret == -ENOTSUP) {
563 if (output_format == OFORMAT_HUMAN) {
564 error_report("This image format does not support checks");
570 if (check->corruptions_fixed || check->leaks_fixed) {
571 int corruptions_fixed, leaks_fixed;
573 leaks_fixed = check->leaks_fixed;
574 corruptions_fixed = check->corruptions_fixed;
576 if (output_format == OFORMAT_HUMAN) {
577 printf("The following inconsistencies were found and repaired:\n\n"
578 " %" PRId64 " leaked clusters\n"
579 " %" PRId64 " corruptions\n\n"
580 "Double checking the fixed image now...\n",
582 check->corruptions_fixed);
585 ret = collect_image_check(bs, check, filename, fmt, 0);
587 check->leaks_fixed = leaks_fixed;
588 check->corruptions_fixed = corruptions_fixed;
591 switch (output_format) {
593 dump_human_image_check(check);
596 dump_json_image_check(check);
600 if (ret || check->check_errors) {
605 if (check->corruptions) {
607 } else if (check->leaks) {
614 qapi_free_ImageCheck(check);
620 static int img_commit(int argc, char **argv)
623 const char *filename, *fmt, *cache;
624 BlockDriverState *bs;
627 cache = BDRV_DEFAULT_CACHE;
629 c = getopt(argc, argv, "f:ht:");
646 if (optind >= argc) {
649 filename = argv[optind++];
652 ret = bdrv_parse_cache_flags(cache, &flags);
654 error_report("Invalid cache option: %s", cache);
658 bs = bdrv_new_open(filename, fmt, flags, true);
662 ret = bdrv_commit(bs);
665 printf("Image committed.\n");
668 error_report("No disk inserted");
671 error_report("Image is read-only");
674 error_report("Image is already committed");
677 error_report("Error while committing image");
689 * Returns true iff the first sector pointed to by 'buf' contains at least
692 * 'pnum' is set to the number of sectors (including and immediately following
693 * the first one) that are known to be in the same allocated/unallocated state.
695 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
704 is_zero = buffer_is_zero(buf, 512);
705 for(i = 1; i < n; i++) {
707 if (is_zero != buffer_is_zero(buf, 512)) {
716 * Like is_allocated_sectors, but if the buffer starts with a used sector,
717 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
718 * breaking up write requests for only small sparse areas.
720 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
724 int num_checked, num_used;
730 ret = is_allocated_sectors(buf, n, pnum);
736 buf += BDRV_SECTOR_SIZE * *pnum;
738 num_checked = num_used;
741 ret = is_allocated_sectors(buf, n, pnum);
743 buf += BDRV_SECTOR_SIZE * *pnum;
745 num_checked += *pnum;
747 num_used = num_checked;
748 } else if (*pnum >= min) {
758 * Compares two buffers sector by sector. Returns 0 if the first sector of both
759 * buffers matches, non-zero otherwise.
761 * pnum is set to the number of sectors (including and immediately following
762 * the first one) that are known to have the same comparison result
764 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
774 res = !!memcmp(buf1, buf2, 512);
775 for(i = 1; i < n; i++) {
779 if (!!memcmp(buf1, buf2, 512) != res) {
788 #define IO_BUF_SIZE (2 * 1024 * 1024)
790 static int img_convert(int argc, char **argv)
792 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
793 int progress = 0, flags;
794 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
795 BlockDriver *drv, *proto_drv;
796 BlockDriverState **bs = NULL, *out_bs = NULL;
797 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
799 uint8_t * buf = NULL;
802 QEMUOptionParameter *param = NULL, *create_options = NULL;
803 QEMUOptionParameter *out_baseimg_param;
804 char *options = NULL;
805 const char *snapshot_name = NULL;
806 float local_progress = 0;
807 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
815 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:");
831 out_baseimg = optarg;
837 error_report("option -e is deprecated, please use \'-o "
838 "encryption\' instead!");
841 error_report("option -6 is deprecated, please use \'-o "
842 "compat6\' instead!");
848 snapshot_name = optarg;
854 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
855 if (sval < 0 || *end) {
856 error_report("Invalid minimum zero buffer size for sparse output specified");
860 min_sparse = sval / BDRV_SECTOR_SIZE;
872 bs_n = argc - optind - 1;
877 out_filename = argv[argc - 1];
879 /* Initialize before goto out */
880 qemu_progress_init(progress, 2.0);
882 if (options && is_help_option(options)) {
883 ret = print_block_option_help(out_filename, out_fmt);
887 if (bs_n > 1 && out_baseimg) {
888 error_report("-B makes no sense when concatenating multiple input "
894 qemu_progress_print(0, 100);
896 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
899 for (bs_i = 0; bs_i < bs_n; bs_i++) {
900 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true);
902 error_report("Could not open '%s'", argv[optind + bs_i]);
906 bdrv_get_geometry(bs[bs_i], &bs_sectors);
907 total_sectors += bs_sectors;
910 if (snapshot_name != NULL) {
912 error_report("No support for concatenating multiple snapshot");
916 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
917 error_report("Failed to load snapshot");
923 /* Find driver and parse its options */
924 drv = bdrv_find_format(out_fmt);
926 error_report("Unknown file format '%s'", out_fmt);
931 proto_drv = bdrv_find_protocol(out_filename);
933 error_report("Unknown protocol '%s'", out_filename);
938 create_options = append_option_parameters(create_options,
939 drv->create_options);
940 create_options = append_option_parameters(create_options,
941 proto_drv->create_options);
944 param = parse_option_parameters(options, create_options, param);
946 error_report("Invalid options for file format '%s'.", out_fmt);
951 param = parse_option_parameters("", create_options, param);
954 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
955 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
960 /* Get backing file name if -o backing_file was used */
961 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
962 if (out_baseimg_param) {
963 out_baseimg = out_baseimg_param->value.s;
966 /* Check if compression is supported */
968 QEMUOptionParameter *encryption =
969 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
970 QEMUOptionParameter *preallocation =
971 get_option_parameter(param, BLOCK_OPT_PREALLOC);
973 if (!drv->bdrv_write_compressed) {
974 error_report("Compression not supported for this file format");
979 if (encryption && encryption->value.n) {
980 error_report("Compression and encryption not supported at "
986 if (preallocation && preallocation->value.s
987 && strcmp(preallocation->value.s, "off"))
989 error_report("Compression and preallocation not supported at "
996 /* Create the new image */
997 ret = bdrv_create(drv, out_filename, param);
999 if (ret == -ENOTSUP) {
1000 error_report("Formatting not supported for file format '%s'",
1002 } else if (ret == -EFBIG) {
1003 error_report("The image size is too large for file format '%s'",
1006 error_report("%s: error while converting %s: %s",
1007 out_filename, out_fmt, strerror(-ret));
1012 flags = BDRV_O_RDWR;
1013 ret = bdrv_parse_cache_flags(cache, &flags);
1015 error_report("Invalid cache option: %s", cache);
1019 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true);
1027 bdrv_get_geometry(bs[0], &bs_sectors);
1028 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
1031 ret = bdrv_get_info(out_bs, &bdi);
1033 error_report("could not get block driver info");
1036 cluster_size = bdi.cluster_size;
1037 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
1038 error_report("invalid cluster size");
1042 cluster_sectors = cluster_size >> 9;
1045 nb_sectors = total_sectors;
1046 if (nb_sectors != 0) {
1047 local_progress = (float)100 /
1048 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1056 nb_sectors = total_sectors - sector_num;
1057 if (nb_sectors <= 0)
1059 if (nb_sectors >= cluster_sectors)
1060 n = cluster_sectors;
1064 bs_num = sector_num - bs_offset;
1065 assert (bs_num >= 0);
1068 while (remainder > 0) {
1070 while (bs_num == bs_sectors) {
1072 assert (bs_i < bs_n);
1073 bs_offset += bs_sectors;
1074 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1076 /* printf("changing part: sector_num=%" PRId64 ", "
1077 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1078 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1080 assert (bs_num < bs_sectors);
1082 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1084 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1086 error_report("error while reading sector %" PRId64 ": %s",
1087 bs_num, strerror(-ret));
1096 assert (remainder == 0);
1098 if (n < cluster_sectors) {
1099 memset(buf + n * 512, 0, cluster_size - n * 512);
1101 if (!buffer_is_zero(buf, cluster_size)) {
1102 ret = bdrv_write_compressed(out_bs, sector_num, buf,
1105 error_report("error while compressing sector %" PRId64
1106 ": %s", sector_num, strerror(-ret));
1111 qemu_progress_print(local_progress, 100);
1113 /* signal EOF to align */
1114 bdrv_write_compressed(out_bs, 0, NULL, 0);
1116 int has_zero_init = bdrv_has_zero_init(out_bs);
1118 sector_num = 0; // total number of sectors converted so far
1119 nb_sectors = total_sectors - sector_num;
1120 if (nb_sectors != 0) {
1121 local_progress = (float)100 /
1122 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1126 nb_sectors = total_sectors - sector_num;
1127 if (nb_sectors <= 0) {
1130 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
1131 n = (IO_BUF_SIZE / 512);
1136 while (sector_num - bs_offset >= bs_sectors) {
1138 assert (bs_i < bs_n);
1139 bs_offset += bs_sectors;
1140 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1141 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1142 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1143 sector_num, bs_i, bs_offset, bs_sectors); */
1146 if (n > bs_offset + bs_sectors - sector_num) {
1147 n = bs_offset + bs_sectors - sector_num;
1150 if (has_zero_init) {
1151 /* If the output image is being created as a copy on write image,
1152 assume that sectors which are unallocated in the input image
1153 are present in both the output's and input's base images (no
1154 need to copy them). */
1156 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1161 /* The next 'n1' sectors are allocated in the input image. Copy
1162 only those as they may be followed by unallocated sectors. */
1169 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1171 error_report("error while reading sector %" PRId64 ": %s",
1172 sector_num - bs_offset, strerror(-ret));
1175 /* NOTE: at the same time we convert, we do not write zero
1176 sectors to have a chance to compress the image. Ideally, we
1177 should add a specific call to have the info to go faster */
1180 /* If the output image is being created as a copy on write image,
1181 copy all sectors even the ones containing only NUL bytes,
1182 because they may differ from the sectors in the base image.
1184 If the output is to a host device, we also write out
1185 sectors that are entirely 0, since whatever data was
1186 already there is garbage, not 0s. */
1187 if (!has_zero_init || out_baseimg ||
1188 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1189 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1191 error_report("error while writing sector %" PRId64
1192 ": %s", sector_num, strerror(-ret));
1200 qemu_progress_print(local_progress, 100);
1204 qemu_progress_end();
1205 free_option_parameters(create_options);
1206 free_option_parameters(param);
1209 bdrv_delete(out_bs);
1212 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1214 bdrv_delete(bs[bs_i]);
1226 static void dump_snapshots(BlockDriverState *bs)
1228 QEMUSnapshotInfo *sn_tab, *sn;
1232 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1235 printf("Snapshot list:\n");
1236 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1237 for(i = 0; i < nb_sns; i++) {
1239 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1244 static void dump_json_image_info_list(ImageInfoList *list)
1248 QmpOutputVisitor *ov = qmp_output_visitor_new();
1250 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1251 &list, NULL, &errp);
1252 obj = qmp_output_get_qobject(ov);
1253 str = qobject_to_json_pretty(obj);
1254 assert(str != NULL);
1255 printf("%s\n", qstring_get_str(str));
1256 qobject_decref(obj);
1257 qmp_output_visitor_cleanup(ov);
1261 static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
1264 QEMUSnapshotInfo *sn_tab = NULL;
1265 SnapshotInfoList *info_list, *cur_item = NULL;
1266 sn_count = bdrv_snapshot_list(bs, &sn_tab);
1268 for (i = 0; i < sn_count; i++) {
1269 info->has_snapshots = true;
1270 info_list = g_new0(SnapshotInfoList, 1);
1272 info_list->value = g_new0(SnapshotInfo, 1);
1273 info_list->value->id = g_strdup(sn_tab[i].id_str);
1274 info_list->value->name = g_strdup(sn_tab[i].name);
1275 info_list->value->vm_state_size = sn_tab[i].vm_state_size;
1276 info_list->value->date_sec = sn_tab[i].date_sec;
1277 info_list->value->date_nsec = sn_tab[i].date_nsec;
1278 info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
1279 info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
1281 /* XXX: waiting for the qapi to support qemu-queue.h types */
1283 info->snapshots = cur_item = info_list;
1285 cur_item->next = info_list;
1286 cur_item = info_list;
1294 static void dump_json_image_info(ImageInfo *info)
1298 QmpOutputVisitor *ov = qmp_output_visitor_new();
1300 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1301 &info, NULL, &errp);
1302 obj = qmp_output_get_qobject(ov);
1303 str = qobject_to_json_pretty(obj);
1304 assert(str != NULL);
1305 printf("%s\n", qstring_get_str(str));
1306 qobject_decref(obj);
1307 qmp_output_visitor_cleanup(ov);
1311 static void collect_image_info(BlockDriverState *bs,
1313 const char *filename,
1316 uint64_t total_sectors;
1317 char backing_filename[1024];
1318 char backing_filename2[1024];
1319 BlockDriverInfo bdi;
1321 bdrv_get_geometry(bs, &total_sectors);
1323 info->filename = g_strdup(filename);
1324 info->format = g_strdup(bdrv_get_format_name(bs));
1325 info->virtual_size = total_sectors * 512;
1326 info->actual_size = bdrv_get_allocated_file_size(bs);
1327 info->has_actual_size = info->actual_size >= 0;
1328 if (bdrv_is_encrypted(bs)) {
1329 info->encrypted = true;
1330 info->has_encrypted = true;
1332 if (bdrv_get_info(bs, &bdi) >= 0) {
1333 if (bdi.cluster_size != 0) {
1334 info->cluster_size = bdi.cluster_size;
1335 info->has_cluster_size = true;
1337 info->dirty_flag = bdi.is_dirty;
1338 info->has_dirty_flag = true;
1340 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1341 if (backing_filename[0] != '\0') {
1342 info->backing_filename = g_strdup(backing_filename);
1343 info->has_backing_filename = true;
1344 bdrv_get_full_backing_filename(bs, backing_filename2,
1345 sizeof(backing_filename2));
1347 if (strcmp(backing_filename, backing_filename2) != 0) {
1348 info->full_backing_filename =
1349 g_strdup(backing_filename2);
1350 info->has_full_backing_filename = true;
1353 if (bs->backing_format[0]) {
1354 info->backing_filename_format = g_strdup(bs->backing_format);
1355 info->has_backing_filename_format = true;
1360 static void dump_human_image_info(ImageInfo *info)
1362 char size_buf[128], dsize_buf[128];
1363 if (!info->has_actual_size) {
1364 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1366 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1369 get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
1370 printf("image: %s\n"
1372 "virtual size: %s (%" PRId64 " bytes)\n"
1374 info->filename, info->format, size_buf,
1378 if (info->has_encrypted && info->encrypted) {
1379 printf("encrypted: yes\n");
1382 if (info->has_cluster_size) {
1383 printf("cluster_size: %" PRId64 "\n", info->cluster_size);
1386 if (info->has_dirty_flag && info->dirty_flag) {
1387 printf("cleanly shut down: no\n");
1390 if (info->has_backing_filename) {
1391 printf("backing file: %s", info->backing_filename);
1392 if (info->has_full_backing_filename) {
1393 printf(" (actual path: %s)", info->full_backing_filename);
1396 if (info->has_backing_filename_format) {
1397 printf("backing file format: %s\n", info->backing_filename_format);
1401 if (info->has_snapshots) {
1402 SnapshotInfoList *elem;
1405 printf("Snapshot list:\n");
1406 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1408 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1409 * we convert to the block layer's native QEMUSnapshotInfo for now.
1411 for (elem = info->snapshots; elem; elem = elem->next) {
1412 QEMUSnapshotInfo sn = {
1413 .vm_state_size = elem->value->vm_state_size,
1414 .date_sec = elem->value->date_sec,
1415 .date_nsec = elem->value->date_nsec,
1416 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1417 elem->value->vm_clock_nsec,
1420 pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1421 pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1422 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
1427 static void dump_human_image_info_list(ImageInfoList *list)
1429 ImageInfoList *elem;
1432 for (elem = list; elem; elem = elem->next) {
1438 dump_human_image_info(elem->value);
1442 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1444 return strcmp(a, b) == 0;
1448 * Open an image file chain and return an ImageInfoList
1450 * @filename: topmost image filename
1451 * @fmt: topmost image format (may be NULL to autodetect)
1452 * @chain: true - enumerate entire backing file chain
1453 * false - only topmost image file
1455 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1456 * image file. If there was an error a message will have been printed to
1459 static ImageInfoList *collect_image_info_list(const char *filename,
1463 ImageInfoList *head = NULL;
1464 ImageInfoList **last = &head;
1465 GHashTable *filenames;
1467 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1470 BlockDriverState *bs;
1472 ImageInfoList *elem;
1474 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1475 error_report("Backing file '%s' creates an infinite loop.",
1479 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1481 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1487 info = g_new0(ImageInfo, 1);
1488 collect_image_info(bs, info, filename, fmt);
1489 collect_snapshots(bs, info);
1491 elem = g_new0(ImageInfoList, 1);
1498 filename = fmt = NULL;
1500 if (info->has_full_backing_filename) {
1501 filename = info->full_backing_filename;
1502 } else if (info->has_backing_filename) {
1503 filename = info->backing_filename;
1505 if (info->has_backing_filename_format) {
1506 fmt = info->backing_filename_format;
1510 g_hash_table_destroy(filenames);
1514 qapi_free_ImageInfoList(head);
1515 g_hash_table_destroy(filenames);
1519 static int img_info(int argc, char **argv)
1522 OutputFormat output_format = OFORMAT_HUMAN;
1524 const char *filename, *fmt, *output;
1525 ImageInfoList *list;
1530 int option_index = 0;
1531 static const struct option long_options[] = {
1532 {"help", no_argument, 0, 'h'},
1533 {"format", required_argument, 0, 'f'},
1534 {"output", required_argument, 0, OPTION_OUTPUT},
1535 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1538 c = getopt_long(argc, argv, "f:h",
1539 long_options, &option_index);
1554 case OPTION_BACKING_CHAIN:
1559 if (optind >= argc) {
1562 filename = argv[optind++];
1564 if (output && !strcmp(output, "json")) {
1565 output_format = OFORMAT_JSON;
1566 } else if (output && !strcmp(output, "human")) {
1567 output_format = OFORMAT_HUMAN;
1568 } else if (output) {
1569 error_report("--output must be used with human or json as argument.");
1573 list = collect_image_info_list(filename, fmt, chain);
1578 switch (output_format) {
1580 dump_human_image_info_list(list);
1584 dump_json_image_info_list(list);
1586 dump_json_image_info(list->value);
1591 qapi_free_ImageInfoList(list);
1595 #define SNAPSHOT_LIST 1
1596 #define SNAPSHOT_CREATE 2
1597 #define SNAPSHOT_APPLY 3
1598 #define SNAPSHOT_DELETE 4
1600 static int img_snapshot(int argc, char **argv)
1602 BlockDriverState *bs;
1603 QEMUSnapshotInfo sn;
1604 char *filename, *snapshot_name = NULL;
1605 int c, ret = 0, bdrv_oflags;
1609 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
1610 /* Parse commandline parameters */
1612 c = getopt(argc, argv, "la:c:d:h");
1626 action = SNAPSHOT_LIST;
1627 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
1634 action = SNAPSHOT_APPLY;
1635 snapshot_name = optarg;
1642 action = SNAPSHOT_CREATE;
1643 snapshot_name = optarg;
1650 action = SNAPSHOT_DELETE;
1651 snapshot_name = optarg;
1656 if (optind >= argc) {
1659 filename = argv[optind++];
1661 /* Open the image */
1662 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true);
1667 /* Perform the requested action */
1673 case SNAPSHOT_CREATE:
1674 memset(&sn, 0, sizeof(sn));
1675 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1677 qemu_gettimeofday(&tv);
1678 sn.date_sec = tv.tv_sec;
1679 sn.date_nsec = tv.tv_usec * 1000;
1681 ret = bdrv_snapshot_create(bs, &sn);
1683 error_report("Could not create snapshot '%s': %d (%s)",
1684 snapshot_name, ret, strerror(-ret));
1688 case SNAPSHOT_APPLY:
1689 ret = bdrv_snapshot_goto(bs, snapshot_name);
1691 error_report("Could not apply snapshot '%s': %d (%s)",
1692 snapshot_name, ret, strerror(-ret));
1696 case SNAPSHOT_DELETE:
1697 ret = bdrv_snapshot_delete(bs, snapshot_name);
1699 error_report("Could not delete snapshot '%s': %d (%s)",
1700 snapshot_name, ret, strerror(-ret));
1713 static int img_rebase(int argc, char **argv)
1715 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
1716 BlockDriver *old_backing_drv, *new_backing_drv;
1718 const char *fmt, *cache, *out_basefmt, *out_baseimg;
1723 /* Parse commandline parameters */
1725 cache = BDRV_DEFAULT_CACHE;
1729 c = getopt(argc, argv, "uhf:F:b:pt:");
1742 out_basefmt = optarg;
1745 out_baseimg = optarg;
1759 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
1762 filename = argv[optind++];
1764 qemu_progress_init(progress, 2.0);
1765 qemu_progress_print(0, 100);
1767 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
1768 ret = bdrv_parse_cache_flags(cache, &flags);
1770 error_report("Invalid cache option: %s", cache);
1777 * Ignore the old backing file for unsafe rebase in case we want to correct
1778 * the reference to a renamed or moved backing file.
1780 bs = bdrv_new_open(filename, fmt, flags, true);
1785 /* Find the right drivers for the backing files */
1786 old_backing_drv = NULL;
1787 new_backing_drv = NULL;
1789 if (!unsafe && bs->backing_format[0] != '\0') {
1790 old_backing_drv = bdrv_find_format(bs->backing_format);
1791 if (old_backing_drv == NULL) {
1792 error_report("Invalid format name: '%s'", bs->backing_format);
1798 if (out_basefmt != NULL) {
1799 new_backing_drv = bdrv_find_format(out_basefmt);
1800 if (new_backing_drv == NULL) {
1801 error_report("Invalid format name: '%s'", out_basefmt);
1807 /* For safe rebasing we need to compare old and new backing file */
1809 /* Make the compiler happy */
1810 bs_old_backing = NULL;
1811 bs_new_backing = NULL;
1813 char backing_name[1024];
1815 bs_old_backing = bdrv_new("old_backing");
1816 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
1817 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1820 error_report("Could not open old backing file '%s'", backing_name);
1823 if (out_baseimg[0]) {
1824 bs_new_backing = bdrv_new("new_backing");
1825 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
1828 error_report("Could not open new backing file '%s'",
1836 * Check each unallocated cluster in the COW file. If it is unallocated,
1837 * accesses go to the backing file. We must therefore compare this cluster
1838 * in the old and new backing file, and if they differ we need to copy it
1839 * from the old backing file into the COW file.
1841 * If qemu-img crashes during this step, no harm is done. The content of
1842 * the image is the same as the original one at any time.
1845 uint64_t num_sectors;
1846 uint64_t old_backing_num_sectors;
1847 uint64_t new_backing_num_sectors = 0;
1852 float local_progress = 0;
1854 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
1855 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
1857 bdrv_get_geometry(bs, &num_sectors);
1858 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
1859 if (bs_new_backing) {
1860 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
1863 if (num_sectors != 0) {
1864 local_progress = (float)100 /
1865 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
1868 for (sector = 0; sector < num_sectors; sector += n) {
1870 /* How many sectors can we handle with the next read? */
1871 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1872 n = (IO_BUF_SIZE / 512);
1874 n = num_sectors - sector;
1877 /* If the cluster is allocated, we don't need to take action */
1878 ret = bdrv_is_allocated(bs, sector, n, &n);
1884 * Read old and new backing file and take into consideration that
1885 * backing files may be smaller than the COW image.
1887 if (sector >= old_backing_num_sectors) {
1888 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
1890 if (sector + n > old_backing_num_sectors) {
1891 n = old_backing_num_sectors - sector;
1894 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1896 error_report("error while reading from old backing file");
1901 if (sector >= new_backing_num_sectors || !bs_new_backing) {
1902 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
1904 if (sector + n > new_backing_num_sectors) {
1905 n = new_backing_num_sectors - sector;
1908 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1910 error_report("error while reading from new backing file");
1915 /* If they differ, we need to write to the COW file */
1916 uint64_t written = 0;
1918 while (written < n) {
1921 if (compare_sectors(buf_old + written * 512,
1922 buf_new + written * 512, n - written, &pnum))
1924 ret = bdrv_write(bs, sector + written,
1925 buf_old + written * 512, pnum);
1927 error_report("Error while writing to COW image: %s",
1935 qemu_progress_print(local_progress, 100);
1938 qemu_vfree(buf_old);
1939 qemu_vfree(buf_new);
1943 * Change the backing file. All clusters that are different from the old
1944 * backing file are overwritten in the COW file now, so the visible content
1945 * doesn't change when we switch the backing file.
1947 if (out_baseimg && *out_baseimg) {
1948 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
1950 ret = bdrv_change_backing_file(bs, NULL, NULL);
1953 if (ret == -ENOSPC) {
1954 error_report("Could not change the backing file to '%s': No "
1955 "space left in the file header", out_baseimg);
1956 } else if (ret < 0) {
1957 error_report("Could not change the backing file to '%s': %s",
1958 out_baseimg, strerror(-ret));
1961 qemu_progress_print(100, 0);
1963 * TODO At this point it is possible to check if any clusters that are
1964 * allocated in the COW file are the same in the backing file. If so, they
1965 * could be dropped from the COW file. Don't do this before switching the
1966 * backing file, in case of a crash this would lead to corruption.
1969 qemu_progress_end();
1972 if (bs_old_backing != NULL) {
1973 bdrv_delete(bs_old_backing);
1975 if (bs_new_backing != NULL) {
1976 bdrv_delete(bs_new_backing);
1987 static int img_resize(int argc, char **argv)
1989 int c, ret, relative;
1990 const char *filename, *fmt, *size;
1991 int64_t n, total_size;
1992 BlockDriverState *bs = NULL;
1994 static QemuOptsList resize_options = {
1995 .name = "resize_options",
1996 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
1999 .name = BLOCK_OPT_SIZE,
2000 .type = QEMU_OPT_SIZE,
2001 .help = "Virtual disk size"
2008 /* Remove size from argv manually so that negative numbers are not treated
2009 * as options by getopt. */
2015 size = argv[--argc];
2017 /* Parse getopt arguments */
2020 c = getopt(argc, argv, "f:h");
2034 if (optind >= argc) {
2037 filename = argv[optind++];
2039 /* Choose grow, shrink, or absolute resize mode */
2055 param = qemu_opts_create_nofail(&resize_options);
2056 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2057 /* Error message already printed when size parsing fails */
2059 qemu_opts_del(param);
2062 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2063 qemu_opts_del(param);
2065 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true);
2072 total_size = bdrv_getlength(bs) + n * relative;
2076 if (total_size <= 0) {
2077 error_report("New image size must be positive");
2082 ret = bdrv_truncate(bs, total_size);
2085 printf("Image resized.\n");
2088 error_report("This image does not support resize");
2091 error_report("Image is read-only");
2094 error_report("Error resizing image (%d)", -ret);
2107 static const img_cmd_t img_cmds[] = {
2108 #define DEF(option, callback, arg_string) \
2109 { option, callback },
2110 #include "qemu-img-cmds.h"
2116 int main(int argc, char **argv)
2118 const img_cmd_t *cmd;
2119 const char *cmdname;
2121 error_set_progname(argv[0]);
2123 qemu_init_main_loop();
2130 /* find the command */
2131 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2132 if (!strcmp(cmdname, cmd->name)) {
2133 return cmd->handler(argc, argv);