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"
41 typedef struct img_cmd_t {
43 int (*handler)(int argc, char **argv);
48 OPTION_BACKING_CHAIN = 257,
51 typedef enum OutputFormat {
56 /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
57 #define BDRV_O_FLAGS BDRV_O_CACHE_WB
58 #define BDRV_DEFAULT_CACHE "writeback"
60 static void format_print(void *opaque, const char *name)
65 /* Please keep in synch with qemu-img.texi */
66 static void help(void)
68 const char *help_msg =
69 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
70 "usage: qemu-img command [command options]\n"
71 "QEMU disk image utility\n"
74 #define DEF(option, callback, arg_string) \
76 #include "qemu-img-cmds.h"
80 "Command parameters:\n"
81 " 'filename' is a disk image filename\n"
82 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
83 " 'cache' is the cache mode used to write the output disk image, the valid\n"
84 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
85 " 'directsync' and 'unsafe' (default for convert)\n"
86 " 'size' is the disk image size in bytes. Optional suffixes\n"
87 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
88 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
89 " 'output_filename' is the destination disk image filename\n"
90 " 'output_fmt' is the destination format\n"
91 " 'options' is a comma separated list of format specific options in a\n"
92 " name=value format. Use -o ? for an overview of the options supported by the\n"
94 " '-c' indicates that target image must be compressed (qcow format only)\n"
95 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
96 " match exactly. The image doesn't need a working backing file before\n"
97 " rebasing in this case (useful for renaming the backing file)\n"
98 " '-h' with or without a command shows this help and lists the supported formats\n"
99 " '-p' show progress of command (only certain commands)\n"
100 " '-q' use Quiet mode - do not print any output (except errors)\n"
101 " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
102 " for qemu-img to create a sparse image during conversion\n"
103 " '--output' takes the format in which the output must be done (human or json)\n"
105 "Parameters to check subcommand:\n"
106 " '-r' tries to repair any inconsistencies that are found during the check.\n"
107 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
108 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
109 " hiding corruption that has already occurred.\n"
111 "Parameters to snapshot subcommand:\n"
112 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
113 " '-a' applies a snapshot (revert disk to saved state)\n"
114 " '-c' creates a snapshot\n"
115 " '-d' deletes a snapshot\n"
116 " '-l' lists all snapshots in the given image\n";
118 printf("%s\nSupported formats:", help_msg);
119 bdrv_iterate_format(format_print, NULL);
124 static int qprintf(bool quiet, const char *fmt, ...)
130 ret = vprintf(fmt, args);
137 /* XXX: put correct support for win32 */
138 static int read_password(char *buf, int buf_size)
141 printf("Password: ");
148 if (i < (buf_size - 1))
159 static struct termios oldtty;
161 static void term_exit(void)
163 tcsetattr (0, TCSANOW, &oldtty);
166 static void term_init(void)
173 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
174 |INLCR|IGNCR|ICRNL|IXON);
175 tty.c_oflag |= OPOST;
176 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
177 tty.c_cflag &= ~(CSIZE|PARENB);
182 tcsetattr (0, TCSANOW, &tty);
187 static int read_password(char *buf, int buf_size)
192 printf("password: ");
197 ret = read(0, &ch, 1);
199 if (errno == EAGAIN || errno == EINTR) {
205 } else if (ret == 0) {
213 if (i < (buf_size - 1))
224 static int print_block_option_help(const char *filename, const char *fmt)
226 BlockDriver *drv, *proto_drv;
227 QEMUOptionParameter *create_options = NULL;
229 /* Find driver and parse its options */
230 drv = bdrv_find_format(fmt);
232 error_report("Unknown file format '%s'", fmt);
236 proto_drv = bdrv_find_protocol(filename);
238 error_report("Unknown protocol '%s'", filename);
242 create_options = append_option_parameters(create_options,
243 drv->create_options);
244 create_options = append_option_parameters(create_options,
245 proto_drv->create_options);
246 print_option_help(create_options);
247 free_option_parameters(create_options);
251 static BlockDriverState *bdrv_new_open(const char *filename,
257 BlockDriverState *bs;
262 bs = bdrv_new("image");
265 drv = bdrv_find_format(fmt);
267 error_report("Unknown file format '%s'", fmt);
274 ret = bdrv_open(bs, filename, flags, drv);
276 error_report("Could not open '%s': %s", filename, strerror(-ret));
280 if (bdrv_is_encrypted(bs) && require_io) {
281 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
282 if (read_password(password, sizeof(password)) < 0) {
283 error_report("No password given");
286 if (bdrv_set_key(bs, password) < 0) {
287 error_report("invalid password");
299 static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
300 const char *base_filename,
301 const char *base_fmt)
304 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
305 error_report("Backing file not supported for file format '%s'",
311 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
312 error_report("Backing file format not supported for file "
320 static int img_create(int argc, char **argv)
323 uint64_t img_size = -1;
324 const char *fmt = "raw";
325 const char *base_fmt = NULL;
326 const char *filename;
327 const char *base_filename = NULL;
328 char *options = NULL;
329 Error *local_err = NULL;
333 c = getopt(argc, argv, "F:b:f:he6o:q");
346 base_filename = optarg;
352 error_report("option -e is deprecated, please use \'-o "
353 "encryption\' instead!");
356 error_report("option -6 is deprecated, please use \'-o "
357 "compat6\' instead!");
368 /* Get the filename */
369 if (optind >= argc) {
372 filename = argv[optind++];
374 /* Get image size, if specified */
378 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
379 if (sval < 0 || *end) {
380 if (sval == -ERANGE) {
381 error_report("Image size must be less than 8 EiB!");
383 error_report("Invalid image size specified! You may use k, M, "
384 "G or T suffixes for ");
385 error_report("kilobytes, megabytes, gigabytes and terabytes.");
389 img_size = (uint64_t)sval;
392 if (options && is_help_option(options)) {
393 return print_block_option_help(filename, fmt);
396 bdrv_img_create(filename, fmt, base_filename, base_fmt,
397 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
398 if (error_is_set(&local_err)) {
399 error_report("%s", error_get_pretty(local_err));
400 error_free(local_err);
407 static void dump_json_image_check(ImageCheck *check, bool quiet)
411 QmpOutputVisitor *ov = qmp_output_visitor_new();
413 visit_type_ImageCheck(qmp_output_get_visitor(ov),
414 &check, NULL, &errp);
415 obj = qmp_output_get_qobject(ov);
416 str = qobject_to_json_pretty(obj);
418 qprintf(quiet, "%s\n", qstring_get_str(str));
420 qmp_output_visitor_cleanup(ov);
424 static void dump_human_image_check(ImageCheck *check, bool quiet)
426 if (!(check->corruptions || check->leaks || check->check_errors)) {
427 qprintf(quiet, "No errors were found on the image.\n");
429 if (check->corruptions) {
430 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
431 "Data may be corrupted, or further writes to the image "
438 "\n%" PRId64 " leaked clusters were found on the image.\n"
439 "This means waste of disk space, but no harm to data.\n",
443 if (check->check_errors) {
446 " internal errors have occurred during the check.\n",
447 check->check_errors);
451 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
452 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
453 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
454 check->allocated_clusters, check->total_clusters,
455 check->allocated_clusters * 100.0 / check->total_clusters,
456 check->fragmented_clusters * 100.0 / check->allocated_clusters,
457 check->compressed_clusters * 100.0 /
458 check->allocated_clusters);
461 if (check->image_end_offset) {
463 "Image end offset: %" PRId64 "\n", check->image_end_offset);
467 static int collect_image_check(BlockDriverState *bs,
469 const char *filename,
474 BdrvCheckResult result;
476 ret = bdrv_check(bs, &result, fix);
481 check->filename = g_strdup(filename);
482 check->format = g_strdup(bdrv_get_format_name(bs));
483 check->check_errors = result.check_errors;
484 check->corruptions = result.corruptions;
485 check->has_corruptions = result.corruptions != 0;
486 check->leaks = result.leaks;
487 check->has_leaks = result.leaks != 0;
488 check->corruptions_fixed = result.corruptions_fixed;
489 check->has_corruptions_fixed = result.corruptions != 0;
490 check->leaks_fixed = result.leaks_fixed;
491 check->has_leaks_fixed = result.leaks != 0;
492 check->image_end_offset = result.image_end_offset;
493 check->has_image_end_offset = result.image_end_offset != 0;
494 check->total_clusters = result.bfi.total_clusters;
495 check->has_total_clusters = result.bfi.total_clusters != 0;
496 check->allocated_clusters = result.bfi.allocated_clusters;
497 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
498 check->fragmented_clusters = result.bfi.fragmented_clusters;
499 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
500 check->compressed_clusters = result.bfi.compressed_clusters;
501 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
507 * Checks an image for consistency. Exit codes:
509 * 0 - Check completed, image is good
510 * 1 - Check not completed because of internal errors
511 * 2 - Check completed, image is corrupted
512 * 3 - Check completed, image has leaked clusters, but is good otherwise
514 static int img_check(int argc, char **argv)
517 OutputFormat output_format = OFORMAT_HUMAN;
518 const char *filename, *fmt, *output;
519 BlockDriverState *bs;
521 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
528 int option_index = 0;
529 static const struct option long_options[] = {
530 {"help", no_argument, 0, 'h'},
531 {"format", required_argument, 0, 'f'},
532 {"repair", no_argument, 0, 'r'},
533 {"output", required_argument, 0, OPTION_OUTPUT},
536 c = getopt_long(argc, argv, "f:hr:q",
537 long_options, &option_index);
550 flags |= BDRV_O_RDWR;
552 if (!strcmp(optarg, "leaks")) {
553 fix = BDRV_FIX_LEAKS;
554 } else if (!strcmp(optarg, "all")) {
555 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
568 if (optind >= argc) {
571 filename = argv[optind++];
573 if (output && !strcmp(output, "json")) {
574 output_format = OFORMAT_JSON;
575 } else if (output && !strcmp(output, "human")) {
576 output_format = OFORMAT_HUMAN;
578 error_report("--output must be used with human or json as argument.");
582 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
587 check = g_new0(ImageCheck, 1);
588 ret = collect_image_check(bs, check, filename, fmt, fix);
590 if (ret == -ENOTSUP) {
591 if (output_format == OFORMAT_HUMAN) {
592 error_report("This image format does not support checks");
598 if (check->corruptions_fixed || check->leaks_fixed) {
599 int corruptions_fixed, leaks_fixed;
601 leaks_fixed = check->leaks_fixed;
602 corruptions_fixed = check->corruptions_fixed;
604 if (output_format == OFORMAT_HUMAN) {
606 "The following inconsistencies were found and repaired:\n\n"
607 " %" PRId64 " leaked clusters\n"
608 " %" PRId64 " corruptions\n\n"
609 "Double checking the fixed image now...\n",
611 check->corruptions_fixed);
614 ret = collect_image_check(bs, check, filename, fmt, 0);
616 check->leaks_fixed = leaks_fixed;
617 check->corruptions_fixed = corruptions_fixed;
620 switch (output_format) {
622 dump_human_image_check(check, quiet);
625 dump_json_image_check(check, quiet);
629 if (ret || check->check_errors) {
634 if (check->corruptions) {
636 } else if (check->leaks) {
643 qapi_free_ImageCheck(check);
649 static int img_commit(int argc, char **argv)
652 const char *filename, *fmt, *cache;
653 BlockDriverState *bs;
657 cache = BDRV_DEFAULT_CACHE;
659 c = getopt(argc, argv, "f:ht:q");
679 if (optind >= argc) {
682 filename = argv[optind++];
685 ret = bdrv_parse_cache_flags(cache, &flags);
687 error_report("Invalid cache option: %s", cache);
691 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
695 ret = bdrv_commit(bs);
698 qprintf(quiet, "Image committed.\n");
701 error_report("No disk inserted");
704 error_report("Image is read-only");
707 error_report("Image is already committed");
710 error_report("Error while committing image");
722 * Returns true iff the first sector pointed to by 'buf' contains at least
725 * 'pnum' is set to the number of sectors (including and immediately following
726 * the first one) that are known to be in the same allocated/unallocated state.
728 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
737 is_zero = buffer_is_zero(buf, 512);
738 for(i = 1; i < n; i++) {
740 if (is_zero != buffer_is_zero(buf, 512)) {
749 * Like is_allocated_sectors, but if the buffer starts with a used sector,
750 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
751 * breaking up write requests for only small sparse areas.
753 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
757 int num_checked, num_used;
763 ret = is_allocated_sectors(buf, n, pnum);
769 buf += BDRV_SECTOR_SIZE * *pnum;
771 num_checked = num_used;
774 ret = is_allocated_sectors(buf, n, pnum);
776 buf += BDRV_SECTOR_SIZE * *pnum;
778 num_checked += *pnum;
780 num_used = num_checked;
781 } else if (*pnum >= min) {
791 * Compares two buffers sector by sector. Returns 0 if the first sector of both
792 * buffers matches, non-zero otherwise.
794 * pnum is set to the number of sectors (including and immediately following
795 * the first one) that are known to have the same comparison result
797 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
807 res = !!memcmp(buf1, buf2, 512);
808 for(i = 1; i < n; i++) {
812 if (!!memcmp(buf1, buf2, 512) != res) {
821 #define IO_BUF_SIZE (2 * 1024 * 1024)
823 static int img_convert(int argc, char **argv)
825 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
826 int progress = 0, flags;
827 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
828 BlockDriver *drv, *proto_drv;
829 BlockDriverState **bs = NULL, *out_bs = NULL;
830 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
832 uint8_t * buf = NULL;
835 QEMUOptionParameter *param = NULL, *create_options = NULL;
836 QEMUOptionParameter *out_baseimg_param;
837 char *options = NULL;
838 const char *snapshot_name = NULL;
839 float local_progress = 0;
840 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
849 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:q");
865 out_baseimg = optarg;
871 error_report("option -e is deprecated, please use \'-o "
872 "encryption\' instead!");
875 error_report("option -6 is deprecated, please use \'-o "
876 "compat6\' instead!");
882 snapshot_name = optarg;
888 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
889 if (sval < 0 || *end) {
890 error_report("Invalid minimum zero buffer size for sparse output specified");
894 min_sparse = sval / BDRV_SECTOR_SIZE;
913 bs_n = argc - optind - 1;
918 out_filename = argv[argc - 1];
920 /* Initialize before goto out */
921 qemu_progress_init(progress, 2.0);
923 if (options && is_help_option(options)) {
924 ret = print_block_option_help(out_filename, out_fmt);
928 if (bs_n > 1 && out_baseimg) {
929 error_report("-B makes no sense when concatenating multiple input "
935 qemu_progress_print(0, 100);
937 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
940 for (bs_i = 0; bs_i < bs_n; bs_i++) {
941 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
944 error_report("Could not open '%s'", argv[optind + bs_i]);
948 bdrv_get_geometry(bs[bs_i], &bs_sectors);
949 total_sectors += bs_sectors;
952 if (snapshot_name != NULL) {
954 error_report("No support for concatenating multiple snapshot");
958 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
959 error_report("Failed to load snapshot");
965 /* Find driver and parse its options */
966 drv = bdrv_find_format(out_fmt);
968 error_report("Unknown file format '%s'", out_fmt);
973 proto_drv = bdrv_find_protocol(out_filename);
975 error_report("Unknown protocol '%s'", out_filename);
980 create_options = append_option_parameters(create_options,
981 drv->create_options);
982 create_options = append_option_parameters(create_options,
983 proto_drv->create_options);
986 param = parse_option_parameters(options, create_options, param);
988 error_report("Invalid options for file format '%s'.", out_fmt);
993 param = parse_option_parameters("", create_options, param);
996 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
997 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
1002 /* Get backing file name if -o backing_file was used */
1003 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
1004 if (out_baseimg_param) {
1005 out_baseimg = out_baseimg_param->value.s;
1008 /* Check if compression is supported */
1010 QEMUOptionParameter *encryption =
1011 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
1012 QEMUOptionParameter *preallocation =
1013 get_option_parameter(param, BLOCK_OPT_PREALLOC);
1015 if (!drv->bdrv_write_compressed) {
1016 error_report("Compression not supported for this file format");
1021 if (encryption && encryption->value.n) {
1022 error_report("Compression and encryption not supported at "
1028 if (preallocation && preallocation->value.s
1029 && strcmp(preallocation->value.s, "off"))
1031 error_report("Compression and preallocation not supported at "
1038 /* Create the new image */
1039 ret = bdrv_create(drv, out_filename, param);
1041 if (ret == -ENOTSUP) {
1042 error_report("Formatting not supported for file format '%s'",
1044 } else if (ret == -EFBIG) {
1045 error_report("The image size is too large for file format '%s'",
1048 error_report("%s: error while converting %s: %s",
1049 out_filename, out_fmt, strerror(-ret));
1054 flags = BDRV_O_RDWR;
1055 ret = bdrv_parse_cache_flags(cache, &flags);
1057 error_report("Invalid cache option: %s", cache);
1061 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
1069 bdrv_get_geometry(bs[0], &bs_sectors);
1070 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
1073 ret = bdrv_get_info(out_bs, &bdi);
1075 error_report("could not get block driver info");
1078 cluster_size = bdi.cluster_size;
1079 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
1080 error_report("invalid cluster size");
1084 cluster_sectors = cluster_size >> 9;
1087 nb_sectors = total_sectors;
1088 if (nb_sectors != 0) {
1089 local_progress = (float)100 /
1090 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1098 nb_sectors = total_sectors - sector_num;
1099 if (nb_sectors <= 0)
1101 if (nb_sectors >= cluster_sectors)
1102 n = cluster_sectors;
1106 bs_num = sector_num - bs_offset;
1107 assert (bs_num >= 0);
1110 while (remainder > 0) {
1112 while (bs_num == bs_sectors) {
1114 assert (bs_i < bs_n);
1115 bs_offset += bs_sectors;
1116 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1118 /* printf("changing part: sector_num=%" PRId64 ", "
1119 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1120 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1122 assert (bs_num < bs_sectors);
1124 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1126 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1128 error_report("error while reading sector %" PRId64 ": %s",
1129 bs_num, strerror(-ret));
1138 assert (remainder == 0);
1140 if (n < cluster_sectors) {
1141 memset(buf + n * 512, 0, cluster_size - n * 512);
1143 if (!buffer_is_zero(buf, cluster_size)) {
1144 ret = bdrv_write_compressed(out_bs, sector_num, buf,
1147 error_report("error while compressing sector %" PRId64
1148 ": %s", sector_num, strerror(-ret));
1153 qemu_progress_print(local_progress, 100);
1155 /* signal EOF to align */
1156 bdrv_write_compressed(out_bs, 0, NULL, 0);
1158 int has_zero_init = bdrv_has_zero_init(out_bs);
1160 sector_num = 0; // total number of sectors converted so far
1161 nb_sectors = total_sectors - sector_num;
1162 if (nb_sectors != 0) {
1163 local_progress = (float)100 /
1164 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1168 nb_sectors = total_sectors - sector_num;
1169 if (nb_sectors <= 0) {
1172 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
1173 n = (IO_BUF_SIZE / 512);
1178 while (sector_num - bs_offset >= bs_sectors) {
1180 assert (bs_i < bs_n);
1181 bs_offset += bs_sectors;
1182 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1183 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1184 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1185 sector_num, bs_i, bs_offset, bs_sectors); */
1188 if (n > bs_offset + bs_sectors - sector_num) {
1189 n = bs_offset + bs_sectors - sector_num;
1192 if (has_zero_init) {
1193 /* If the output image is being created as a copy on write image,
1194 assume that sectors which are unallocated in the input image
1195 are present in both the output's and input's base images (no
1196 need to copy them). */
1198 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1203 /* The next 'n1' sectors are allocated in the input image. Copy
1204 only those as they may be followed by unallocated sectors. */
1211 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1213 error_report("error while reading sector %" PRId64 ": %s",
1214 sector_num - bs_offset, strerror(-ret));
1217 /* NOTE: at the same time we convert, we do not write zero
1218 sectors to have a chance to compress the image. Ideally, we
1219 should add a specific call to have the info to go faster */
1222 /* If the output image is being created as a copy on write image,
1223 copy all sectors even the ones containing only NUL bytes,
1224 because they may differ from the sectors in the base image.
1226 If the output is to a host device, we also write out
1227 sectors that are entirely 0, since whatever data was
1228 already there is garbage, not 0s. */
1229 if (!has_zero_init || out_baseimg ||
1230 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1231 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1233 error_report("error while writing sector %" PRId64
1234 ": %s", sector_num, strerror(-ret));
1242 qemu_progress_print(local_progress, 100);
1246 qemu_progress_end();
1247 free_option_parameters(create_options);
1248 free_option_parameters(param);
1251 bdrv_delete(out_bs);
1254 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1256 bdrv_delete(bs[bs_i]);
1268 static void dump_snapshots(BlockDriverState *bs)
1270 QEMUSnapshotInfo *sn_tab, *sn;
1274 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1277 printf("Snapshot list:\n");
1278 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1279 for(i = 0; i < nb_sns; i++) {
1281 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1286 static void dump_json_image_info_list(ImageInfoList *list)
1290 QmpOutputVisitor *ov = qmp_output_visitor_new();
1292 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1293 &list, NULL, &errp);
1294 obj = qmp_output_get_qobject(ov);
1295 str = qobject_to_json_pretty(obj);
1296 assert(str != NULL);
1297 printf("%s\n", qstring_get_str(str));
1298 qobject_decref(obj);
1299 qmp_output_visitor_cleanup(ov);
1303 static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
1306 QEMUSnapshotInfo *sn_tab = NULL;
1307 SnapshotInfoList *info_list, *cur_item = NULL;
1308 sn_count = bdrv_snapshot_list(bs, &sn_tab);
1310 for (i = 0; i < sn_count; i++) {
1311 info->has_snapshots = true;
1312 info_list = g_new0(SnapshotInfoList, 1);
1314 info_list->value = g_new0(SnapshotInfo, 1);
1315 info_list->value->id = g_strdup(sn_tab[i].id_str);
1316 info_list->value->name = g_strdup(sn_tab[i].name);
1317 info_list->value->vm_state_size = sn_tab[i].vm_state_size;
1318 info_list->value->date_sec = sn_tab[i].date_sec;
1319 info_list->value->date_nsec = sn_tab[i].date_nsec;
1320 info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
1321 info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
1323 /* XXX: waiting for the qapi to support qemu-queue.h types */
1325 info->snapshots = cur_item = info_list;
1327 cur_item->next = info_list;
1328 cur_item = info_list;
1336 static void dump_json_image_info(ImageInfo *info)
1340 QmpOutputVisitor *ov = qmp_output_visitor_new();
1342 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1343 &info, NULL, &errp);
1344 obj = qmp_output_get_qobject(ov);
1345 str = qobject_to_json_pretty(obj);
1346 assert(str != NULL);
1347 printf("%s\n", qstring_get_str(str));
1348 qobject_decref(obj);
1349 qmp_output_visitor_cleanup(ov);
1353 static void collect_image_info(BlockDriverState *bs,
1355 const char *filename,
1358 uint64_t total_sectors;
1359 char backing_filename[1024];
1360 char backing_filename2[1024];
1361 BlockDriverInfo bdi;
1363 bdrv_get_geometry(bs, &total_sectors);
1365 info->filename = g_strdup(filename);
1366 info->format = g_strdup(bdrv_get_format_name(bs));
1367 info->virtual_size = total_sectors * 512;
1368 info->actual_size = bdrv_get_allocated_file_size(bs);
1369 info->has_actual_size = info->actual_size >= 0;
1370 if (bdrv_is_encrypted(bs)) {
1371 info->encrypted = true;
1372 info->has_encrypted = true;
1374 if (bdrv_get_info(bs, &bdi) >= 0) {
1375 if (bdi.cluster_size != 0) {
1376 info->cluster_size = bdi.cluster_size;
1377 info->has_cluster_size = true;
1379 info->dirty_flag = bdi.is_dirty;
1380 info->has_dirty_flag = true;
1382 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1383 if (backing_filename[0] != '\0') {
1384 info->backing_filename = g_strdup(backing_filename);
1385 info->has_backing_filename = true;
1386 bdrv_get_full_backing_filename(bs, backing_filename2,
1387 sizeof(backing_filename2));
1389 if (strcmp(backing_filename, backing_filename2) != 0) {
1390 info->full_backing_filename =
1391 g_strdup(backing_filename2);
1392 info->has_full_backing_filename = true;
1395 if (bs->backing_format[0]) {
1396 info->backing_filename_format = g_strdup(bs->backing_format);
1397 info->has_backing_filename_format = true;
1402 static void dump_human_image_info(ImageInfo *info)
1404 char size_buf[128], dsize_buf[128];
1405 if (!info->has_actual_size) {
1406 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1408 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1411 get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
1412 printf("image: %s\n"
1414 "virtual size: %s (%" PRId64 " bytes)\n"
1416 info->filename, info->format, size_buf,
1420 if (info->has_encrypted && info->encrypted) {
1421 printf("encrypted: yes\n");
1424 if (info->has_cluster_size) {
1425 printf("cluster_size: %" PRId64 "\n", info->cluster_size);
1428 if (info->has_dirty_flag && info->dirty_flag) {
1429 printf("cleanly shut down: no\n");
1432 if (info->has_backing_filename) {
1433 printf("backing file: %s", info->backing_filename);
1434 if (info->has_full_backing_filename) {
1435 printf(" (actual path: %s)", info->full_backing_filename);
1438 if (info->has_backing_filename_format) {
1439 printf("backing file format: %s\n", info->backing_filename_format);
1443 if (info->has_snapshots) {
1444 SnapshotInfoList *elem;
1447 printf("Snapshot list:\n");
1448 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1450 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1451 * we convert to the block layer's native QEMUSnapshotInfo for now.
1453 for (elem = info->snapshots; elem; elem = elem->next) {
1454 QEMUSnapshotInfo sn = {
1455 .vm_state_size = elem->value->vm_state_size,
1456 .date_sec = elem->value->date_sec,
1457 .date_nsec = elem->value->date_nsec,
1458 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1459 elem->value->vm_clock_nsec,
1462 pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1463 pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1464 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
1469 static void dump_human_image_info_list(ImageInfoList *list)
1471 ImageInfoList *elem;
1474 for (elem = list; elem; elem = elem->next) {
1480 dump_human_image_info(elem->value);
1484 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1486 return strcmp(a, b) == 0;
1490 * Open an image file chain and return an ImageInfoList
1492 * @filename: topmost image filename
1493 * @fmt: topmost image format (may be NULL to autodetect)
1494 * @chain: true - enumerate entire backing file chain
1495 * false - only topmost image file
1497 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1498 * image file. If there was an error a message will have been printed to
1501 static ImageInfoList *collect_image_info_list(const char *filename,
1505 ImageInfoList *head = NULL;
1506 ImageInfoList **last = &head;
1507 GHashTable *filenames;
1509 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1512 BlockDriverState *bs;
1514 ImageInfoList *elem;
1516 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1517 error_report("Backing file '%s' creates an infinite loop.",
1521 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1523 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1529 info = g_new0(ImageInfo, 1);
1530 collect_image_info(bs, info, filename, fmt);
1531 collect_snapshots(bs, info);
1533 elem = g_new0(ImageInfoList, 1);
1540 filename = fmt = NULL;
1542 if (info->has_full_backing_filename) {
1543 filename = info->full_backing_filename;
1544 } else if (info->has_backing_filename) {
1545 filename = info->backing_filename;
1547 if (info->has_backing_filename_format) {
1548 fmt = info->backing_filename_format;
1552 g_hash_table_destroy(filenames);
1556 qapi_free_ImageInfoList(head);
1557 g_hash_table_destroy(filenames);
1561 static int img_info(int argc, char **argv)
1564 OutputFormat output_format = OFORMAT_HUMAN;
1566 const char *filename, *fmt, *output;
1567 ImageInfoList *list;
1572 int option_index = 0;
1573 static const struct option long_options[] = {
1574 {"help", no_argument, 0, 'h'},
1575 {"format", required_argument, 0, 'f'},
1576 {"output", required_argument, 0, OPTION_OUTPUT},
1577 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1580 c = getopt_long(argc, argv, "f:h",
1581 long_options, &option_index);
1596 case OPTION_BACKING_CHAIN:
1601 if (optind >= argc) {
1604 filename = argv[optind++];
1606 if (output && !strcmp(output, "json")) {
1607 output_format = OFORMAT_JSON;
1608 } else if (output && !strcmp(output, "human")) {
1609 output_format = OFORMAT_HUMAN;
1610 } else if (output) {
1611 error_report("--output must be used with human or json as argument.");
1615 list = collect_image_info_list(filename, fmt, chain);
1620 switch (output_format) {
1622 dump_human_image_info_list(list);
1626 dump_json_image_info_list(list);
1628 dump_json_image_info(list->value);
1633 qapi_free_ImageInfoList(list);
1637 #define SNAPSHOT_LIST 1
1638 #define SNAPSHOT_CREATE 2
1639 #define SNAPSHOT_APPLY 3
1640 #define SNAPSHOT_DELETE 4
1642 static int img_snapshot(int argc, char **argv)
1644 BlockDriverState *bs;
1645 QEMUSnapshotInfo sn;
1646 char *filename, *snapshot_name = NULL;
1647 int c, ret = 0, bdrv_oflags;
1652 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
1653 /* Parse commandline parameters */
1655 c = getopt(argc, argv, "la:c:d:hq");
1669 action = SNAPSHOT_LIST;
1670 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
1677 action = SNAPSHOT_APPLY;
1678 snapshot_name = optarg;
1685 action = SNAPSHOT_CREATE;
1686 snapshot_name = optarg;
1693 action = SNAPSHOT_DELETE;
1694 snapshot_name = optarg;
1702 if (optind >= argc) {
1705 filename = argv[optind++];
1707 /* Open the image */
1708 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
1713 /* Perform the requested action */
1719 case SNAPSHOT_CREATE:
1720 memset(&sn, 0, sizeof(sn));
1721 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1723 qemu_gettimeofday(&tv);
1724 sn.date_sec = tv.tv_sec;
1725 sn.date_nsec = tv.tv_usec * 1000;
1727 ret = bdrv_snapshot_create(bs, &sn);
1729 error_report("Could not create snapshot '%s': %d (%s)",
1730 snapshot_name, ret, strerror(-ret));
1734 case SNAPSHOT_APPLY:
1735 ret = bdrv_snapshot_goto(bs, snapshot_name);
1737 error_report("Could not apply snapshot '%s': %d (%s)",
1738 snapshot_name, ret, strerror(-ret));
1742 case SNAPSHOT_DELETE:
1743 ret = bdrv_snapshot_delete(bs, snapshot_name);
1745 error_report("Could not delete snapshot '%s': %d (%s)",
1746 snapshot_name, ret, strerror(-ret));
1759 static int img_rebase(int argc, char **argv)
1761 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
1762 BlockDriver *old_backing_drv, *new_backing_drv;
1764 const char *fmt, *cache, *out_basefmt, *out_baseimg;
1770 /* Parse commandline parameters */
1772 cache = BDRV_DEFAULT_CACHE;
1776 c = getopt(argc, argv, "uhf:F:b:pt:q");
1789 out_basefmt = optarg;
1792 out_baseimg = optarg;
1813 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
1816 filename = argv[optind++];
1818 qemu_progress_init(progress, 2.0);
1819 qemu_progress_print(0, 100);
1821 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
1822 ret = bdrv_parse_cache_flags(cache, &flags);
1824 error_report("Invalid cache option: %s", cache);
1831 * Ignore the old backing file for unsafe rebase in case we want to correct
1832 * the reference to a renamed or moved backing file.
1834 bs = bdrv_new_open(filename, fmt, flags, true, quiet);
1839 /* Find the right drivers for the backing files */
1840 old_backing_drv = NULL;
1841 new_backing_drv = NULL;
1843 if (!unsafe && bs->backing_format[0] != '\0') {
1844 old_backing_drv = bdrv_find_format(bs->backing_format);
1845 if (old_backing_drv == NULL) {
1846 error_report("Invalid format name: '%s'", bs->backing_format);
1852 if (out_basefmt != NULL) {
1853 new_backing_drv = bdrv_find_format(out_basefmt);
1854 if (new_backing_drv == NULL) {
1855 error_report("Invalid format name: '%s'", out_basefmt);
1861 /* For safe rebasing we need to compare old and new backing file */
1863 /* Make the compiler happy */
1864 bs_old_backing = NULL;
1865 bs_new_backing = NULL;
1867 char backing_name[1024];
1869 bs_old_backing = bdrv_new("old_backing");
1870 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
1871 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1874 error_report("Could not open old backing file '%s'", backing_name);
1877 if (out_baseimg[0]) {
1878 bs_new_backing = bdrv_new("new_backing");
1879 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
1882 error_report("Could not open new backing file '%s'",
1890 * Check each unallocated cluster in the COW file. If it is unallocated,
1891 * accesses go to the backing file. We must therefore compare this cluster
1892 * in the old and new backing file, and if they differ we need to copy it
1893 * from the old backing file into the COW file.
1895 * If qemu-img crashes during this step, no harm is done. The content of
1896 * the image is the same as the original one at any time.
1899 uint64_t num_sectors;
1900 uint64_t old_backing_num_sectors;
1901 uint64_t new_backing_num_sectors = 0;
1906 float local_progress = 0;
1908 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
1909 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
1911 bdrv_get_geometry(bs, &num_sectors);
1912 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
1913 if (bs_new_backing) {
1914 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
1917 if (num_sectors != 0) {
1918 local_progress = (float)100 /
1919 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
1922 for (sector = 0; sector < num_sectors; sector += n) {
1924 /* How many sectors can we handle with the next read? */
1925 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1926 n = (IO_BUF_SIZE / 512);
1928 n = num_sectors - sector;
1931 /* If the cluster is allocated, we don't need to take action */
1932 ret = bdrv_is_allocated(bs, sector, n, &n);
1938 * Read old and new backing file and take into consideration that
1939 * backing files may be smaller than the COW image.
1941 if (sector >= old_backing_num_sectors) {
1942 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
1944 if (sector + n > old_backing_num_sectors) {
1945 n = old_backing_num_sectors - sector;
1948 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1950 error_report("error while reading from old backing file");
1955 if (sector >= new_backing_num_sectors || !bs_new_backing) {
1956 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
1958 if (sector + n > new_backing_num_sectors) {
1959 n = new_backing_num_sectors - sector;
1962 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1964 error_report("error while reading from new backing file");
1969 /* If they differ, we need to write to the COW file */
1970 uint64_t written = 0;
1972 while (written < n) {
1975 if (compare_sectors(buf_old + written * 512,
1976 buf_new + written * 512, n - written, &pnum))
1978 ret = bdrv_write(bs, sector + written,
1979 buf_old + written * 512, pnum);
1981 error_report("Error while writing to COW image: %s",
1989 qemu_progress_print(local_progress, 100);
1992 qemu_vfree(buf_old);
1993 qemu_vfree(buf_new);
1997 * Change the backing file. All clusters that are different from the old
1998 * backing file are overwritten in the COW file now, so the visible content
1999 * doesn't change when we switch the backing file.
2001 if (out_baseimg && *out_baseimg) {
2002 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2004 ret = bdrv_change_backing_file(bs, NULL, NULL);
2007 if (ret == -ENOSPC) {
2008 error_report("Could not change the backing file to '%s': No "
2009 "space left in the file header", out_baseimg);
2010 } else if (ret < 0) {
2011 error_report("Could not change the backing file to '%s': %s",
2012 out_baseimg, strerror(-ret));
2015 qemu_progress_print(100, 0);
2017 * TODO At this point it is possible to check if any clusters that are
2018 * allocated in the COW file are the same in the backing file. If so, they
2019 * could be dropped from the COW file. Don't do this before switching the
2020 * backing file, in case of a crash this would lead to corruption.
2023 qemu_progress_end();
2026 if (bs_old_backing != NULL) {
2027 bdrv_delete(bs_old_backing);
2029 if (bs_new_backing != NULL) {
2030 bdrv_delete(bs_new_backing);
2041 static int img_resize(int argc, char **argv)
2043 int c, ret, relative;
2044 const char *filename, *fmt, *size;
2045 int64_t n, total_size;
2047 BlockDriverState *bs = NULL;
2049 static QemuOptsList resize_options = {
2050 .name = "resize_options",
2051 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2054 .name = BLOCK_OPT_SIZE,
2055 .type = QEMU_OPT_SIZE,
2056 .help = "Virtual disk size"
2063 /* Remove size from argv manually so that negative numbers are not treated
2064 * as options by getopt. */
2070 size = argv[--argc];
2072 /* Parse getopt arguments */
2075 c = getopt(argc, argv, "f:hq");
2092 if (optind >= argc) {
2095 filename = argv[optind++];
2097 /* Choose grow, shrink, or absolute resize mode */
2113 param = qemu_opts_create_nofail(&resize_options);
2114 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2115 /* Error message already printed when size parsing fails */
2117 qemu_opts_del(param);
2120 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2121 qemu_opts_del(param);
2123 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
2130 total_size = bdrv_getlength(bs) + n * relative;
2134 if (total_size <= 0) {
2135 error_report("New image size must be positive");
2140 ret = bdrv_truncate(bs, total_size);
2143 qprintf(quiet, "Image resized.\n");
2146 error_report("This image does not support resize");
2149 error_report("Image is read-only");
2152 error_report("Error resizing image (%d)", -ret);
2165 static const img_cmd_t img_cmds[] = {
2166 #define DEF(option, callback, arg_string) \
2167 { option, callback },
2168 #include "qemu-img-cmds.h"
2174 int main(int argc, char **argv)
2176 const img_cmd_t *cmd;
2177 const char *cmdname;
2179 error_set_progname(argv[0]);
2181 qemu_init_main_loop();
2188 /* find the command */
2189 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2190 if (!strcmp(cmdname, cmd->name)) {
2191 return cmd->handler(argc, argv);