qcow2: record fragmentation statistics during check
[qemu/ar7.git] / qemu-img.c
blob34249fee126c81bbc653f8e681ac9b40a0d83055
1 /*
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
22 * THE SOFTWARE.
24 #include "qapi-visit.h"
25 #include "qapi/qmp-output-visitor.h"
26 #include "qapi/qmp/qjson.h"
27 #include "qemu-common.h"
28 #include "qemu/option.h"
29 #include "qemu/error-report.h"
30 #include "qemu/osdep.h"
31 #include "sysemu/sysemu.h"
32 #include "block/block_int.h"
33 #include <getopt.h>
34 #include <stdio.h>
36 #ifdef _WIN32
37 #include <windows.h>
38 #endif
40 typedef struct img_cmd_t {
41 const char *name;
42 int (*handler)(int argc, char **argv);
43 } img_cmd_t;
45 enum {
46 OPTION_OUTPUT = 256,
47 OPTION_BACKING_CHAIN = 257,
50 typedef enum OutputFormat {
51 OFORMAT_JSON,
52 OFORMAT_HUMAN,
53 } 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)
61 printf(" %s", 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"
71 "\n"
72 "Command syntax:\n"
73 #define DEF(option, callback, arg_string) \
74 " " arg_string "\n"
75 #include "qemu-img-cmds.h"
76 #undef DEF
77 #undef GEN_DOCS
78 "\n"
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"
92 " used format\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"
102 "\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"
108 "\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);
118 printf("\n");
119 exit(1);
122 #if defined(WIN32)
123 /* XXX: put correct support for win32 */
124 static int read_password(char *buf, int buf_size)
126 int c, i;
127 printf("Password: ");
128 fflush(stdout);
129 i = 0;
130 for(;;) {
131 c = getchar();
132 if (c == '\n')
133 break;
134 if (i < (buf_size - 1))
135 buf[i++] = c;
137 buf[i] = '\0';
138 return 0;
141 #else
143 #include <termios.h>
145 static struct termios oldtty;
147 static void term_exit(void)
149 tcsetattr (0, TCSANOW, &oldtty);
152 static void term_init(void)
154 struct termios tty;
156 tcgetattr (0, &tty);
157 oldtty = tty;
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);
164 tty.c_cflag |= CS8;
165 tty.c_cc[VMIN] = 1;
166 tty.c_cc[VTIME] = 0;
168 tcsetattr (0, TCSANOW, &tty);
170 atexit(term_exit);
173 static int read_password(char *buf, int buf_size)
175 uint8_t ch;
176 int i, ret;
178 printf("password: ");
179 fflush(stdout);
180 term_init();
181 i = 0;
182 for(;;) {
183 ret = read(0, &ch, 1);
184 if (ret == -1) {
185 if (errno == EAGAIN || errno == EINTR) {
186 continue;
187 } else {
188 ret = -1;
189 break;
191 } else if (ret == 0) {
192 ret = -1;
193 break;
194 } else {
195 if (ch == '\r') {
196 ret = 0;
197 break;
199 if (i < (buf_size - 1))
200 buf[i++] = ch;
203 term_exit();
204 buf[i] = '\0';
205 printf("\n");
206 return ret;
208 #endif
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);
217 if (!drv) {
218 error_report("Unknown file format '%s'", fmt);
219 return 1;
222 proto_drv = bdrv_find_protocol(filename);
223 if (!proto_drv) {
224 error_report("Unknown protocol '%s'", filename);
225 return 1;
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);
234 return 0;
237 static BlockDriverState *bdrv_new_open(const char *filename,
238 const char *fmt,
239 int flags,
240 bool require_io)
242 BlockDriverState *bs;
243 BlockDriver *drv;
244 char password[256];
245 int ret;
247 bs = bdrv_new("image");
249 if (fmt) {
250 drv = bdrv_find_format(fmt);
251 if (!drv) {
252 error_report("Unknown file format '%s'", fmt);
253 goto fail;
255 } else {
256 drv = NULL;
259 ret = bdrv_open(bs, filename, flags, drv);
260 if (ret < 0) {
261 error_report("Could not open '%s': %s", filename, strerror(-ret));
262 goto fail;
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");
269 goto fail;
271 if (bdrv_set_key(bs, password) < 0) {
272 error_report("invalid password");
273 goto fail;
276 return bs;
277 fail:
278 if (bs) {
279 bdrv_delete(bs);
281 return NULL;
284 static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
285 const char *base_filename,
286 const char *base_fmt)
288 if (base_filename) {
289 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
290 error_report("Backing file not supported for file format '%s'",
291 fmt);
292 return -1;
295 if (base_fmt) {
296 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
297 error_report("Backing file format not supported for file "
298 "format '%s'", fmt);
299 return -1;
302 return 0;
305 static int img_create(int argc, char **argv)
307 int c;
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;
316 for(;;) {
317 c = getopt(argc, argv, "F:b:f:he6o:");
318 if (c == -1) {
319 break;
321 switch(c) {
322 case '?':
323 case 'h':
324 help();
325 break;
326 case 'F':
327 base_fmt = optarg;
328 break;
329 case 'b':
330 base_filename = optarg;
331 break;
332 case 'f':
333 fmt = optarg;
334 break;
335 case 'e':
336 error_report("option -e is deprecated, please use \'-o "
337 "encryption\' instead!");
338 return 1;
339 case '6':
340 error_report("option -6 is deprecated, please use \'-o "
341 "compat6\' instead!");
342 return 1;
343 case 'o':
344 options = optarg;
345 break;
349 /* Get the filename */
350 if (optind >= argc) {
351 help();
353 filename = argv[optind++];
355 /* Get image size, if specified */
356 if (optind < argc) {
357 int64_t sval;
358 char *end;
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!");
363 } else {
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.");
368 return 1;
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);
382 return 1;
385 return 0;
388 static void dump_json_image_check(ImageCheck *check)
390 Error *errp = NULL;
391 QString *str;
392 QmpOutputVisitor *ov = qmp_output_visitor_new();
393 QObject *obj;
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);
398 assert(str != NULL);
399 printf("%s\n", qstring_get_str(str));
400 qobject_decref(obj);
401 qmp_output_visitor_cleanup(ov);
402 QDECREF(str);
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");
409 } else {
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 "
413 "may corrupt it.\n",
414 check->corruptions);
417 if (check->leaks) {
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",
420 check->leaks);
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, %0.2f%% fragmented\n",
431 check->allocated_clusters, check->total_clusters,
432 check->allocated_clusters * 100.0 / check->total_clusters,
433 check->fragmented_clusters * 100.0 / check->allocated_clusters);
436 if (check->image_end_offset) {
437 printf("Image end offset: %" PRId64 "\n", check->image_end_offset);
441 static int collect_image_check(BlockDriverState *bs,
442 ImageCheck *check,
443 const char *filename,
444 const char *fmt,
445 int fix)
447 int ret;
448 BdrvCheckResult result;
450 ret = bdrv_check(bs, &result, fix);
451 if (ret < 0) {
452 return ret;
455 check->filename = g_strdup(filename);
456 check->format = g_strdup(bdrv_get_format_name(bs));
457 check->check_errors = result.check_errors;
458 check->corruptions = result.corruptions;
459 check->has_corruptions = result.corruptions != 0;
460 check->leaks = result.leaks;
461 check->has_leaks = result.leaks != 0;
462 check->corruptions_fixed = result.corruptions_fixed;
463 check->has_corruptions_fixed = result.corruptions != 0;
464 check->leaks_fixed = result.leaks_fixed;
465 check->has_leaks_fixed = result.leaks != 0;
466 check->image_end_offset = result.image_end_offset;
467 check->has_image_end_offset = result.image_end_offset != 0;
468 check->total_clusters = result.bfi.total_clusters;
469 check->has_total_clusters = result.bfi.total_clusters != 0;
470 check->allocated_clusters = result.bfi.allocated_clusters;
471 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
472 check->fragmented_clusters = result.bfi.fragmented_clusters;
473 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
475 return 0;
479 * Checks an image for consistency. Exit codes:
481 * 0 - Check completed, image is good
482 * 1 - Check not completed because of internal errors
483 * 2 - Check completed, image is corrupted
484 * 3 - Check completed, image has leaked clusters, but is good otherwise
486 static int img_check(int argc, char **argv)
488 int c, ret;
489 OutputFormat output_format = OFORMAT_HUMAN;
490 const char *filename, *fmt, *output;
491 BlockDriverState *bs;
492 int fix = 0;
493 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
494 ImageCheck *check;
496 fmt = NULL;
497 output = NULL;
498 for(;;) {
499 int option_index = 0;
500 static const struct option long_options[] = {
501 {"help", no_argument, 0, 'h'},
502 {"format", required_argument, 0, 'f'},
503 {"repair", no_argument, 0, 'r'},
504 {"output", required_argument, 0, OPTION_OUTPUT},
505 {0, 0, 0, 0}
507 c = getopt_long(argc, argv, "f:hr:",
508 long_options, &option_index);
509 if (c == -1) {
510 break;
512 switch(c) {
513 case '?':
514 case 'h':
515 help();
516 break;
517 case 'f':
518 fmt = optarg;
519 break;
520 case 'r':
521 flags |= BDRV_O_RDWR;
523 if (!strcmp(optarg, "leaks")) {
524 fix = BDRV_FIX_LEAKS;
525 } else if (!strcmp(optarg, "all")) {
526 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
527 } else {
528 help();
530 break;
531 case OPTION_OUTPUT:
532 output = optarg;
533 break;
536 if (optind >= argc) {
537 help();
539 filename = argv[optind++];
541 if (output && !strcmp(output, "json")) {
542 output_format = OFORMAT_JSON;
543 } else if (output && !strcmp(output, "human")) {
544 output_format = OFORMAT_HUMAN;
545 } else if (output) {
546 error_report("--output must be used with human or json as argument.");
547 return 1;
550 bs = bdrv_new_open(filename, fmt, flags, true);
551 if (!bs) {
552 return 1;
555 check = g_new0(ImageCheck, 1);
556 ret = collect_image_check(bs, check, filename, fmt, fix);
558 if (ret == -ENOTSUP) {
559 if (output_format == OFORMAT_HUMAN) {
560 error_report("This image format does not support checks");
562 ret = 1;
563 goto fail;
566 if (check->corruptions_fixed || check->leaks_fixed) {
567 int corruptions_fixed, leaks_fixed;
569 leaks_fixed = check->leaks_fixed;
570 corruptions_fixed = check->corruptions_fixed;
572 if (output_format == OFORMAT_HUMAN) {
573 printf("The following inconsistencies were found and repaired:\n\n"
574 " %" PRId64 " leaked clusters\n"
575 " %" PRId64 " corruptions\n\n"
576 "Double checking the fixed image now...\n",
577 check->leaks_fixed,
578 check->corruptions_fixed);
581 ret = collect_image_check(bs, check, filename, fmt, 0);
583 check->leaks_fixed = leaks_fixed;
584 check->corruptions_fixed = corruptions_fixed;
587 switch (output_format) {
588 case OFORMAT_HUMAN:
589 dump_human_image_check(check);
590 break;
591 case OFORMAT_JSON:
592 dump_json_image_check(check);
593 break;
596 if (ret || check->check_errors) {
597 ret = 1;
598 goto fail;
601 if (check->corruptions) {
602 ret = 2;
603 } else if (check->leaks) {
604 ret = 3;
605 } else {
606 ret = 0;
609 fail:
610 qapi_free_ImageCheck(check);
611 bdrv_delete(bs);
613 return ret;
616 static int img_commit(int argc, char **argv)
618 int c, ret, flags;
619 const char *filename, *fmt, *cache;
620 BlockDriverState *bs;
622 fmt = NULL;
623 cache = BDRV_DEFAULT_CACHE;
624 for(;;) {
625 c = getopt(argc, argv, "f:ht:");
626 if (c == -1) {
627 break;
629 switch(c) {
630 case '?':
631 case 'h':
632 help();
633 break;
634 case 'f':
635 fmt = optarg;
636 break;
637 case 't':
638 cache = optarg;
639 break;
642 if (optind >= argc) {
643 help();
645 filename = argv[optind++];
647 flags = BDRV_O_RDWR;
648 ret = bdrv_parse_cache_flags(cache, &flags);
649 if (ret < 0) {
650 error_report("Invalid cache option: %s", cache);
651 return -1;
654 bs = bdrv_new_open(filename, fmt, flags, true);
655 if (!bs) {
656 return 1;
658 ret = bdrv_commit(bs);
659 switch(ret) {
660 case 0:
661 printf("Image committed.\n");
662 break;
663 case -ENOENT:
664 error_report("No disk inserted");
665 break;
666 case -EACCES:
667 error_report("Image is read-only");
668 break;
669 case -ENOTSUP:
670 error_report("Image is already committed");
671 break;
672 default:
673 error_report("Error while committing image");
674 break;
677 bdrv_delete(bs);
678 if (ret) {
679 return 1;
681 return 0;
685 * Returns true iff the first sector pointed to by 'buf' contains at least
686 * a non-NUL byte.
688 * 'pnum' is set to the number of sectors (including and immediately following
689 * the first one) that are known to be in the same allocated/unallocated state.
691 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
693 bool is_zero;
694 int i;
696 if (n <= 0) {
697 *pnum = 0;
698 return 0;
700 is_zero = buffer_is_zero(buf, 512);
701 for(i = 1; i < n; i++) {
702 buf += 512;
703 if (is_zero != buffer_is_zero(buf, 512)) {
704 break;
707 *pnum = i;
708 return !is_zero;
712 * Like is_allocated_sectors, but if the buffer starts with a used sector,
713 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
714 * breaking up write requests for only small sparse areas.
716 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
717 int min)
719 int ret;
720 int num_checked, num_used;
722 if (n < min) {
723 min = n;
726 ret = is_allocated_sectors(buf, n, pnum);
727 if (!ret) {
728 return ret;
731 num_used = *pnum;
732 buf += BDRV_SECTOR_SIZE * *pnum;
733 n -= *pnum;
734 num_checked = num_used;
736 while (n > 0) {
737 ret = is_allocated_sectors(buf, n, pnum);
739 buf += BDRV_SECTOR_SIZE * *pnum;
740 n -= *pnum;
741 num_checked += *pnum;
742 if (ret) {
743 num_used = num_checked;
744 } else if (*pnum >= min) {
745 break;
749 *pnum = num_used;
750 return 1;
754 * Compares two buffers sector by sector. Returns 0 if the first sector of both
755 * buffers matches, non-zero otherwise.
757 * pnum is set to the number of sectors (including and immediately following
758 * the first one) that are known to have the same comparison result
760 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
761 int *pnum)
763 int res, i;
765 if (n <= 0) {
766 *pnum = 0;
767 return 0;
770 res = !!memcmp(buf1, buf2, 512);
771 for(i = 1; i < n; i++) {
772 buf1 += 512;
773 buf2 += 512;
775 if (!!memcmp(buf1, buf2, 512) != res) {
776 break;
780 *pnum = i;
781 return res;
784 #define IO_BUF_SIZE (2 * 1024 * 1024)
786 static int img_convert(int argc, char **argv)
788 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
789 int progress = 0, flags;
790 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
791 BlockDriver *drv, *proto_drv;
792 BlockDriverState **bs = NULL, *out_bs = NULL;
793 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
794 uint64_t bs_sectors;
795 uint8_t * buf = NULL;
796 const uint8_t *buf1;
797 BlockDriverInfo bdi;
798 QEMUOptionParameter *param = NULL, *create_options = NULL;
799 QEMUOptionParameter *out_baseimg_param;
800 char *options = NULL;
801 const char *snapshot_name = NULL;
802 float local_progress = 0;
803 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
805 fmt = NULL;
806 out_fmt = "raw";
807 cache = "unsafe";
808 out_baseimg = NULL;
809 compress = 0;
810 for(;;) {
811 c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:");
812 if (c == -1) {
813 break;
815 switch(c) {
816 case '?':
817 case 'h':
818 help();
819 break;
820 case 'f':
821 fmt = optarg;
822 break;
823 case 'O':
824 out_fmt = optarg;
825 break;
826 case 'B':
827 out_baseimg = optarg;
828 break;
829 case 'c':
830 compress = 1;
831 break;
832 case 'e':
833 error_report("option -e is deprecated, please use \'-o "
834 "encryption\' instead!");
835 return 1;
836 case '6':
837 error_report("option -6 is deprecated, please use \'-o "
838 "compat6\' instead!");
839 return 1;
840 case 'o':
841 options = optarg;
842 break;
843 case 's':
844 snapshot_name = optarg;
845 break;
846 case 'S':
848 int64_t sval;
849 char *end;
850 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
851 if (sval < 0 || *end) {
852 error_report("Invalid minimum zero buffer size for sparse output specified");
853 return 1;
856 min_sparse = sval / BDRV_SECTOR_SIZE;
857 break;
859 case 'p':
860 progress = 1;
861 break;
862 case 't':
863 cache = optarg;
864 break;
868 bs_n = argc - optind - 1;
869 if (bs_n < 1) {
870 help();
873 out_filename = argv[argc - 1];
875 /* Initialize before goto out */
876 qemu_progress_init(progress, 2.0);
878 if (options && is_help_option(options)) {
879 ret = print_block_option_help(out_filename, out_fmt);
880 goto out;
883 if (bs_n > 1 && out_baseimg) {
884 error_report("-B makes no sense when concatenating multiple input "
885 "images");
886 ret = -1;
887 goto out;
890 qemu_progress_print(0, 100);
892 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
894 total_sectors = 0;
895 for (bs_i = 0; bs_i < bs_n; bs_i++) {
896 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true);
897 if (!bs[bs_i]) {
898 error_report("Could not open '%s'", argv[optind + bs_i]);
899 ret = -1;
900 goto out;
902 bdrv_get_geometry(bs[bs_i], &bs_sectors);
903 total_sectors += bs_sectors;
906 if (snapshot_name != NULL) {
907 if (bs_n > 1) {
908 error_report("No support for concatenating multiple snapshot");
909 ret = -1;
910 goto out;
912 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
913 error_report("Failed to load snapshot");
914 ret = -1;
915 goto out;
919 /* Find driver and parse its options */
920 drv = bdrv_find_format(out_fmt);
921 if (!drv) {
922 error_report("Unknown file format '%s'", out_fmt);
923 ret = -1;
924 goto out;
927 proto_drv = bdrv_find_protocol(out_filename);
928 if (!proto_drv) {
929 error_report("Unknown protocol '%s'", out_filename);
930 ret = -1;
931 goto out;
934 create_options = append_option_parameters(create_options,
935 drv->create_options);
936 create_options = append_option_parameters(create_options,
937 proto_drv->create_options);
939 if (options) {
940 param = parse_option_parameters(options, create_options, param);
941 if (param == NULL) {
942 error_report("Invalid options for file format '%s'.", out_fmt);
943 ret = -1;
944 goto out;
946 } else {
947 param = parse_option_parameters("", create_options, param);
950 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
951 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
952 if (ret < 0) {
953 goto out;
956 /* Get backing file name if -o backing_file was used */
957 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
958 if (out_baseimg_param) {
959 out_baseimg = out_baseimg_param->value.s;
962 /* Check if compression is supported */
963 if (compress) {
964 QEMUOptionParameter *encryption =
965 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
966 QEMUOptionParameter *preallocation =
967 get_option_parameter(param, BLOCK_OPT_PREALLOC);
969 if (!drv->bdrv_write_compressed) {
970 error_report("Compression not supported for this file format");
971 ret = -1;
972 goto out;
975 if (encryption && encryption->value.n) {
976 error_report("Compression and encryption not supported at "
977 "the same time");
978 ret = -1;
979 goto out;
982 if (preallocation && preallocation->value.s
983 && strcmp(preallocation->value.s, "off"))
985 error_report("Compression and preallocation not supported at "
986 "the same time");
987 ret = -1;
988 goto out;
992 /* Create the new image */
993 ret = bdrv_create(drv, out_filename, param);
994 if (ret < 0) {
995 if (ret == -ENOTSUP) {
996 error_report("Formatting not supported for file format '%s'",
997 out_fmt);
998 } else if (ret == -EFBIG) {
999 error_report("The image size is too large for file format '%s'",
1000 out_fmt);
1001 } else {
1002 error_report("%s: error while converting %s: %s",
1003 out_filename, out_fmt, strerror(-ret));
1005 goto out;
1008 flags = BDRV_O_RDWR;
1009 ret = bdrv_parse_cache_flags(cache, &flags);
1010 if (ret < 0) {
1011 error_report("Invalid cache option: %s", cache);
1012 return -1;
1015 out_bs = bdrv_new_open(out_filename, out_fmt, flags, true);
1016 if (!out_bs) {
1017 ret = -1;
1018 goto out;
1021 bs_i = 0;
1022 bs_offset = 0;
1023 bdrv_get_geometry(bs[0], &bs_sectors);
1024 buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
1026 if (compress) {
1027 ret = bdrv_get_info(out_bs, &bdi);
1028 if (ret < 0) {
1029 error_report("could not get block driver info");
1030 goto out;
1032 cluster_size = bdi.cluster_size;
1033 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
1034 error_report("invalid cluster size");
1035 ret = -1;
1036 goto out;
1038 cluster_sectors = cluster_size >> 9;
1039 sector_num = 0;
1041 nb_sectors = total_sectors;
1042 if (nb_sectors != 0) {
1043 local_progress = (float)100 /
1044 (nb_sectors / MIN(nb_sectors, cluster_sectors));
1047 for(;;) {
1048 int64_t bs_num;
1049 int remainder;
1050 uint8_t *buf2;
1052 nb_sectors = total_sectors - sector_num;
1053 if (nb_sectors <= 0)
1054 break;
1055 if (nb_sectors >= cluster_sectors)
1056 n = cluster_sectors;
1057 else
1058 n = nb_sectors;
1060 bs_num = sector_num - bs_offset;
1061 assert (bs_num >= 0);
1062 remainder = n;
1063 buf2 = buf;
1064 while (remainder > 0) {
1065 int nlow;
1066 while (bs_num == bs_sectors) {
1067 bs_i++;
1068 assert (bs_i < bs_n);
1069 bs_offset += bs_sectors;
1070 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1071 bs_num = 0;
1072 /* printf("changing part: sector_num=%" PRId64 ", "
1073 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
1074 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
1076 assert (bs_num < bs_sectors);
1078 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
1080 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1081 if (ret < 0) {
1082 error_report("error while reading sector %" PRId64 ": %s",
1083 bs_num, strerror(-ret));
1084 goto out;
1087 buf2 += nlow * 512;
1088 bs_num += nlow;
1090 remainder -= nlow;
1092 assert (remainder == 0);
1094 if (n < cluster_sectors) {
1095 memset(buf + n * 512, 0, cluster_size - n * 512);
1097 if (!buffer_is_zero(buf, cluster_size)) {
1098 ret = bdrv_write_compressed(out_bs, sector_num, buf,
1099 cluster_sectors);
1100 if (ret != 0) {
1101 error_report("error while compressing sector %" PRId64
1102 ": %s", sector_num, strerror(-ret));
1103 goto out;
1106 sector_num += n;
1107 qemu_progress_print(local_progress, 100);
1109 /* signal EOF to align */
1110 bdrv_write_compressed(out_bs, 0, NULL, 0);
1111 } else {
1112 int has_zero_init = bdrv_has_zero_init(out_bs);
1114 sector_num = 0; // total number of sectors converted so far
1115 nb_sectors = total_sectors - sector_num;
1116 if (nb_sectors != 0) {
1117 local_progress = (float)100 /
1118 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
1121 for(;;) {
1122 nb_sectors = total_sectors - sector_num;
1123 if (nb_sectors <= 0) {
1124 break;
1126 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
1127 n = (IO_BUF_SIZE / 512);
1128 } else {
1129 n = nb_sectors;
1132 while (sector_num - bs_offset >= bs_sectors) {
1133 bs_i ++;
1134 assert (bs_i < bs_n);
1135 bs_offset += bs_sectors;
1136 bdrv_get_geometry(bs[bs_i], &bs_sectors);
1137 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1138 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
1139 sector_num, bs_i, bs_offset, bs_sectors); */
1142 if (n > bs_offset + bs_sectors - sector_num) {
1143 n = bs_offset + bs_sectors - sector_num;
1146 if (has_zero_init) {
1147 /* If the output image is being created as a copy on write image,
1148 assume that sectors which are unallocated in the input image
1149 are present in both the output's and input's base images (no
1150 need to copy them). */
1151 if (out_baseimg) {
1152 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
1153 n, &n1)) {
1154 sector_num += n1;
1155 continue;
1157 /* The next 'n1' sectors are allocated in the input image. Copy
1158 only those as they may be followed by unallocated sectors. */
1159 n = n1;
1161 } else {
1162 n1 = n;
1165 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1166 if (ret < 0) {
1167 error_report("error while reading sector %" PRId64 ": %s",
1168 sector_num - bs_offset, strerror(-ret));
1169 goto out;
1171 /* NOTE: at the same time we convert, we do not write zero
1172 sectors to have a chance to compress the image. Ideally, we
1173 should add a specific call to have the info to go faster */
1174 buf1 = buf;
1175 while (n > 0) {
1176 /* If the output image is being created as a copy on write image,
1177 copy all sectors even the ones containing only NUL bytes,
1178 because they may differ from the sectors in the base image.
1180 If the output is to a host device, we also write out
1181 sectors that are entirely 0, since whatever data was
1182 already there is garbage, not 0s. */
1183 if (!has_zero_init || out_baseimg ||
1184 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
1185 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1186 if (ret < 0) {
1187 error_report("error while writing sector %" PRId64
1188 ": %s", sector_num, strerror(-ret));
1189 goto out;
1192 sector_num += n1;
1193 n -= n1;
1194 buf1 += n1 * 512;
1196 qemu_progress_print(local_progress, 100);
1199 out:
1200 qemu_progress_end();
1201 free_option_parameters(create_options);
1202 free_option_parameters(param);
1203 qemu_vfree(buf);
1204 if (out_bs) {
1205 bdrv_delete(out_bs);
1207 if (bs) {
1208 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1209 if (bs[bs_i]) {
1210 bdrv_delete(bs[bs_i]);
1213 g_free(bs);
1215 if (ret) {
1216 return 1;
1218 return 0;
1222 static void dump_snapshots(BlockDriverState *bs)
1224 QEMUSnapshotInfo *sn_tab, *sn;
1225 int nb_sns, i;
1226 char buf[256];
1228 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1229 if (nb_sns <= 0)
1230 return;
1231 printf("Snapshot list:\n");
1232 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1233 for(i = 0; i < nb_sns; i++) {
1234 sn = &sn_tab[i];
1235 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1237 g_free(sn_tab);
1240 static void dump_json_image_info_list(ImageInfoList *list)
1242 Error *errp = NULL;
1243 QString *str;
1244 QmpOutputVisitor *ov = qmp_output_visitor_new();
1245 QObject *obj;
1246 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
1247 &list, NULL, &errp);
1248 obj = qmp_output_get_qobject(ov);
1249 str = qobject_to_json_pretty(obj);
1250 assert(str != NULL);
1251 printf("%s\n", qstring_get_str(str));
1252 qobject_decref(obj);
1253 qmp_output_visitor_cleanup(ov);
1254 QDECREF(str);
1257 static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
1259 int i, sn_count;
1260 QEMUSnapshotInfo *sn_tab = NULL;
1261 SnapshotInfoList *info_list, *cur_item = NULL;
1262 sn_count = bdrv_snapshot_list(bs, &sn_tab);
1264 for (i = 0; i < sn_count; i++) {
1265 info->has_snapshots = true;
1266 info_list = g_new0(SnapshotInfoList, 1);
1268 info_list->value = g_new0(SnapshotInfo, 1);
1269 info_list->value->id = g_strdup(sn_tab[i].id_str);
1270 info_list->value->name = g_strdup(sn_tab[i].name);
1271 info_list->value->vm_state_size = sn_tab[i].vm_state_size;
1272 info_list->value->date_sec = sn_tab[i].date_sec;
1273 info_list->value->date_nsec = sn_tab[i].date_nsec;
1274 info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
1275 info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
1277 /* XXX: waiting for the qapi to support qemu-queue.h types */
1278 if (!cur_item) {
1279 info->snapshots = cur_item = info_list;
1280 } else {
1281 cur_item->next = info_list;
1282 cur_item = info_list;
1287 g_free(sn_tab);
1290 static void dump_json_image_info(ImageInfo *info)
1292 Error *errp = NULL;
1293 QString *str;
1294 QmpOutputVisitor *ov = qmp_output_visitor_new();
1295 QObject *obj;
1296 visit_type_ImageInfo(qmp_output_get_visitor(ov),
1297 &info, NULL, &errp);
1298 obj = qmp_output_get_qobject(ov);
1299 str = qobject_to_json_pretty(obj);
1300 assert(str != NULL);
1301 printf("%s\n", qstring_get_str(str));
1302 qobject_decref(obj);
1303 qmp_output_visitor_cleanup(ov);
1304 QDECREF(str);
1307 static void collect_image_info(BlockDriverState *bs,
1308 ImageInfo *info,
1309 const char *filename,
1310 const char *fmt)
1312 uint64_t total_sectors;
1313 char backing_filename[1024];
1314 char backing_filename2[1024];
1315 BlockDriverInfo bdi;
1317 bdrv_get_geometry(bs, &total_sectors);
1319 info->filename = g_strdup(filename);
1320 info->format = g_strdup(bdrv_get_format_name(bs));
1321 info->virtual_size = total_sectors * 512;
1322 info->actual_size = bdrv_get_allocated_file_size(bs);
1323 info->has_actual_size = info->actual_size >= 0;
1324 if (bdrv_is_encrypted(bs)) {
1325 info->encrypted = true;
1326 info->has_encrypted = true;
1328 if (bdrv_get_info(bs, &bdi) >= 0) {
1329 if (bdi.cluster_size != 0) {
1330 info->cluster_size = bdi.cluster_size;
1331 info->has_cluster_size = true;
1333 info->dirty_flag = bdi.is_dirty;
1334 info->has_dirty_flag = true;
1336 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
1337 if (backing_filename[0] != '\0') {
1338 info->backing_filename = g_strdup(backing_filename);
1339 info->has_backing_filename = true;
1340 bdrv_get_full_backing_filename(bs, backing_filename2,
1341 sizeof(backing_filename2));
1343 if (strcmp(backing_filename, backing_filename2) != 0) {
1344 info->full_backing_filename =
1345 g_strdup(backing_filename2);
1346 info->has_full_backing_filename = true;
1349 if (bs->backing_format[0]) {
1350 info->backing_filename_format = g_strdup(bs->backing_format);
1351 info->has_backing_filename_format = true;
1356 static void dump_human_image_info(ImageInfo *info)
1358 char size_buf[128], dsize_buf[128];
1359 if (!info->has_actual_size) {
1360 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
1361 } else {
1362 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
1363 info->actual_size);
1365 get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
1366 printf("image: %s\n"
1367 "file format: %s\n"
1368 "virtual size: %s (%" PRId64 " bytes)\n"
1369 "disk size: %s\n",
1370 info->filename, info->format, size_buf,
1371 info->virtual_size,
1372 dsize_buf);
1374 if (info->has_encrypted && info->encrypted) {
1375 printf("encrypted: yes\n");
1378 if (info->has_cluster_size) {
1379 printf("cluster_size: %" PRId64 "\n", info->cluster_size);
1382 if (info->has_dirty_flag && info->dirty_flag) {
1383 printf("cleanly shut down: no\n");
1386 if (info->has_backing_filename) {
1387 printf("backing file: %s", info->backing_filename);
1388 if (info->has_full_backing_filename) {
1389 printf(" (actual path: %s)", info->full_backing_filename);
1391 putchar('\n');
1392 if (info->has_backing_filename_format) {
1393 printf("backing file format: %s\n", info->backing_filename_format);
1397 if (info->has_snapshots) {
1398 SnapshotInfoList *elem;
1399 char buf[256];
1401 printf("Snapshot list:\n");
1402 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1404 /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
1405 * we convert to the block layer's native QEMUSnapshotInfo for now.
1407 for (elem = info->snapshots; elem; elem = elem->next) {
1408 QEMUSnapshotInfo sn = {
1409 .vm_state_size = elem->value->vm_state_size,
1410 .date_sec = elem->value->date_sec,
1411 .date_nsec = elem->value->date_nsec,
1412 .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
1413 elem->value->vm_clock_nsec,
1416 pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
1417 pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
1418 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
1423 static void dump_human_image_info_list(ImageInfoList *list)
1425 ImageInfoList *elem;
1426 bool delim = false;
1428 for (elem = list; elem; elem = elem->next) {
1429 if (delim) {
1430 printf("\n");
1432 delim = true;
1434 dump_human_image_info(elem->value);
1438 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1440 return strcmp(a, b) == 0;
1444 * Open an image file chain and return an ImageInfoList
1446 * @filename: topmost image filename
1447 * @fmt: topmost image format (may be NULL to autodetect)
1448 * @chain: true - enumerate entire backing file chain
1449 * false - only topmost image file
1451 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1452 * image file. If there was an error a message will have been printed to
1453 * stderr.
1455 static ImageInfoList *collect_image_info_list(const char *filename,
1456 const char *fmt,
1457 bool chain)
1459 ImageInfoList *head = NULL;
1460 ImageInfoList **last = &head;
1461 GHashTable *filenames;
1463 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1465 while (filename) {
1466 BlockDriverState *bs;
1467 ImageInfo *info;
1468 ImageInfoList *elem;
1470 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1471 error_report("Backing file '%s' creates an infinite loop.",
1472 filename);
1473 goto err;
1475 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1477 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
1478 false);
1479 if (!bs) {
1480 goto err;
1483 info = g_new0(ImageInfo, 1);
1484 collect_image_info(bs, info, filename, fmt);
1485 collect_snapshots(bs, info);
1487 elem = g_new0(ImageInfoList, 1);
1488 elem->value = info;
1489 *last = elem;
1490 last = &elem->next;
1492 bdrv_delete(bs);
1494 filename = fmt = NULL;
1495 if (chain) {
1496 if (info->has_full_backing_filename) {
1497 filename = info->full_backing_filename;
1498 } else if (info->has_backing_filename) {
1499 filename = info->backing_filename;
1501 if (info->has_backing_filename_format) {
1502 fmt = info->backing_filename_format;
1506 g_hash_table_destroy(filenames);
1507 return head;
1509 err:
1510 qapi_free_ImageInfoList(head);
1511 g_hash_table_destroy(filenames);
1512 return NULL;
1515 static int img_info(int argc, char **argv)
1517 int c;
1518 OutputFormat output_format = OFORMAT_HUMAN;
1519 bool chain = false;
1520 const char *filename, *fmt, *output;
1521 ImageInfoList *list;
1523 fmt = NULL;
1524 output = NULL;
1525 for(;;) {
1526 int option_index = 0;
1527 static const struct option long_options[] = {
1528 {"help", no_argument, 0, 'h'},
1529 {"format", required_argument, 0, 'f'},
1530 {"output", required_argument, 0, OPTION_OUTPUT},
1531 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
1532 {0, 0, 0, 0}
1534 c = getopt_long(argc, argv, "f:h",
1535 long_options, &option_index);
1536 if (c == -1) {
1537 break;
1539 switch(c) {
1540 case '?':
1541 case 'h':
1542 help();
1543 break;
1544 case 'f':
1545 fmt = optarg;
1546 break;
1547 case OPTION_OUTPUT:
1548 output = optarg;
1549 break;
1550 case OPTION_BACKING_CHAIN:
1551 chain = true;
1552 break;
1555 if (optind >= argc) {
1556 help();
1558 filename = argv[optind++];
1560 if (output && !strcmp(output, "json")) {
1561 output_format = OFORMAT_JSON;
1562 } else if (output && !strcmp(output, "human")) {
1563 output_format = OFORMAT_HUMAN;
1564 } else if (output) {
1565 error_report("--output must be used with human or json as argument.");
1566 return 1;
1569 list = collect_image_info_list(filename, fmt, chain);
1570 if (!list) {
1571 return 1;
1574 switch (output_format) {
1575 case OFORMAT_HUMAN:
1576 dump_human_image_info_list(list);
1577 break;
1578 case OFORMAT_JSON:
1579 if (chain) {
1580 dump_json_image_info_list(list);
1581 } else {
1582 dump_json_image_info(list->value);
1584 break;
1587 qapi_free_ImageInfoList(list);
1588 return 0;
1591 #define SNAPSHOT_LIST 1
1592 #define SNAPSHOT_CREATE 2
1593 #define SNAPSHOT_APPLY 3
1594 #define SNAPSHOT_DELETE 4
1596 static int img_snapshot(int argc, char **argv)
1598 BlockDriverState *bs;
1599 QEMUSnapshotInfo sn;
1600 char *filename, *snapshot_name = NULL;
1601 int c, ret = 0, bdrv_oflags;
1602 int action = 0;
1603 qemu_timeval tv;
1605 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
1606 /* Parse commandline parameters */
1607 for(;;) {
1608 c = getopt(argc, argv, "la:c:d:h");
1609 if (c == -1) {
1610 break;
1612 switch(c) {
1613 case '?':
1614 case 'h':
1615 help();
1616 return 0;
1617 case 'l':
1618 if (action) {
1619 help();
1620 return 0;
1622 action = SNAPSHOT_LIST;
1623 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
1624 break;
1625 case 'a':
1626 if (action) {
1627 help();
1628 return 0;
1630 action = SNAPSHOT_APPLY;
1631 snapshot_name = optarg;
1632 break;
1633 case 'c':
1634 if (action) {
1635 help();
1636 return 0;
1638 action = SNAPSHOT_CREATE;
1639 snapshot_name = optarg;
1640 break;
1641 case 'd':
1642 if (action) {
1643 help();
1644 return 0;
1646 action = SNAPSHOT_DELETE;
1647 snapshot_name = optarg;
1648 break;
1652 if (optind >= argc) {
1653 help();
1655 filename = argv[optind++];
1657 /* Open the image */
1658 bs = bdrv_new_open(filename, NULL, bdrv_oflags, true);
1659 if (!bs) {
1660 return 1;
1663 /* Perform the requested action */
1664 switch(action) {
1665 case SNAPSHOT_LIST:
1666 dump_snapshots(bs);
1667 break;
1669 case SNAPSHOT_CREATE:
1670 memset(&sn, 0, sizeof(sn));
1671 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1673 qemu_gettimeofday(&tv);
1674 sn.date_sec = tv.tv_sec;
1675 sn.date_nsec = tv.tv_usec * 1000;
1677 ret = bdrv_snapshot_create(bs, &sn);
1678 if (ret) {
1679 error_report("Could not create snapshot '%s': %d (%s)",
1680 snapshot_name, ret, strerror(-ret));
1682 break;
1684 case SNAPSHOT_APPLY:
1685 ret = bdrv_snapshot_goto(bs, snapshot_name);
1686 if (ret) {
1687 error_report("Could not apply snapshot '%s': %d (%s)",
1688 snapshot_name, ret, strerror(-ret));
1690 break;
1692 case SNAPSHOT_DELETE:
1693 ret = bdrv_snapshot_delete(bs, snapshot_name);
1694 if (ret) {
1695 error_report("Could not delete snapshot '%s': %d (%s)",
1696 snapshot_name, ret, strerror(-ret));
1698 break;
1701 /* Cleanup */
1702 bdrv_delete(bs);
1703 if (ret) {
1704 return 1;
1706 return 0;
1709 static int img_rebase(int argc, char **argv)
1711 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
1712 BlockDriver *old_backing_drv, *new_backing_drv;
1713 char *filename;
1714 const char *fmt, *cache, *out_basefmt, *out_baseimg;
1715 int c, flags, ret;
1716 int unsafe = 0;
1717 int progress = 0;
1719 /* Parse commandline parameters */
1720 fmt = NULL;
1721 cache = BDRV_DEFAULT_CACHE;
1722 out_baseimg = NULL;
1723 out_basefmt = NULL;
1724 for(;;) {
1725 c = getopt(argc, argv, "uhf:F:b:pt:");
1726 if (c == -1) {
1727 break;
1729 switch(c) {
1730 case '?':
1731 case 'h':
1732 help();
1733 return 0;
1734 case 'f':
1735 fmt = optarg;
1736 break;
1737 case 'F':
1738 out_basefmt = optarg;
1739 break;
1740 case 'b':
1741 out_baseimg = optarg;
1742 break;
1743 case 'u':
1744 unsafe = 1;
1745 break;
1746 case 'p':
1747 progress = 1;
1748 break;
1749 case 't':
1750 cache = optarg;
1751 break;
1755 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
1756 help();
1758 filename = argv[optind++];
1760 qemu_progress_init(progress, 2.0);
1761 qemu_progress_print(0, 100);
1763 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
1764 ret = bdrv_parse_cache_flags(cache, &flags);
1765 if (ret < 0) {
1766 error_report("Invalid cache option: %s", cache);
1767 return -1;
1771 * Open the images.
1773 * Ignore the old backing file for unsafe rebase in case we want to correct
1774 * the reference to a renamed or moved backing file.
1776 bs = bdrv_new_open(filename, fmt, flags, true);
1777 if (!bs) {
1778 return 1;
1781 /* Find the right drivers for the backing files */
1782 old_backing_drv = NULL;
1783 new_backing_drv = NULL;
1785 if (!unsafe && bs->backing_format[0] != '\0') {
1786 old_backing_drv = bdrv_find_format(bs->backing_format);
1787 if (old_backing_drv == NULL) {
1788 error_report("Invalid format name: '%s'", bs->backing_format);
1789 ret = -1;
1790 goto out;
1794 if (out_basefmt != NULL) {
1795 new_backing_drv = bdrv_find_format(out_basefmt);
1796 if (new_backing_drv == NULL) {
1797 error_report("Invalid format name: '%s'", out_basefmt);
1798 ret = -1;
1799 goto out;
1803 /* For safe rebasing we need to compare old and new backing file */
1804 if (unsafe) {
1805 /* Make the compiler happy */
1806 bs_old_backing = NULL;
1807 bs_new_backing = NULL;
1808 } else {
1809 char backing_name[1024];
1811 bs_old_backing = bdrv_new("old_backing");
1812 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
1813 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1814 old_backing_drv);
1815 if (ret) {
1816 error_report("Could not open old backing file '%s'", backing_name);
1817 goto out;
1819 if (out_baseimg[0]) {
1820 bs_new_backing = bdrv_new("new_backing");
1821 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
1822 new_backing_drv);
1823 if (ret) {
1824 error_report("Could not open new backing file '%s'",
1825 out_baseimg);
1826 goto out;
1832 * Check each unallocated cluster in the COW file. If it is unallocated,
1833 * accesses go to the backing file. We must therefore compare this cluster
1834 * in the old and new backing file, and if they differ we need to copy it
1835 * from the old backing file into the COW file.
1837 * If qemu-img crashes during this step, no harm is done. The content of
1838 * the image is the same as the original one at any time.
1840 if (!unsafe) {
1841 uint64_t num_sectors;
1842 uint64_t old_backing_num_sectors;
1843 uint64_t new_backing_num_sectors = 0;
1844 uint64_t sector;
1845 int n;
1846 uint8_t * buf_old;
1847 uint8_t * buf_new;
1848 float local_progress = 0;
1850 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
1851 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
1853 bdrv_get_geometry(bs, &num_sectors);
1854 bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
1855 if (bs_new_backing) {
1856 bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
1859 if (num_sectors != 0) {
1860 local_progress = (float)100 /
1861 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
1864 for (sector = 0; sector < num_sectors; sector += n) {
1866 /* How many sectors can we handle with the next read? */
1867 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1868 n = (IO_BUF_SIZE / 512);
1869 } else {
1870 n = num_sectors - sector;
1873 /* If the cluster is allocated, we don't need to take action */
1874 ret = bdrv_is_allocated(bs, sector, n, &n);
1875 if (ret) {
1876 continue;
1880 * Read old and new backing file and take into consideration that
1881 * backing files may be smaller than the COW image.
1883 if (sector >= old_backing_num_sectors) {
1884 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
1885 } else {
1886 if (sector + n > old_backing_num_sectors) {
1887 n = old_backing_num_sectors - sector;
1890 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1891 if (ret < 0) {
1892 error_report("error while reading from old backing file");
1893 goto out;
1897 if (sector >= new_backing_num_sectors || !bs_new_backing) {
1898 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
1899 } else {
1900 if (sector + n > new_backing_num_sectors) {
1901 n = new_backing_num_sectors - sector;
1904 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1905 if (ret < 0) {
1906 error_report("error while reading from new backing file");
1907 goto out;
1911 /* If they differ, we need to write to the COW file */
1912 uint64_t written = 0;
1914 while (written < n) {
1915 int pnum;
1917 if (compare_sectors(buf_old + written * 512,
1918 buf_new + written * 512, n - written, &pnum))
1920 ret = bdrv_write(bs, sector + written,
1921 buf_old + written * 512, pnum);
1922 if (ret < 0) {
1923 error_report("Error while writing to COW image: %s",
1924 strerror(-ret));
1925 goto out;
1929 written += pnum;
1931 qemu_progress_print(local_progress, 100);
1934 qemu_vfree(buf_old);
1935 qemu_vfree(buf_new);
1939 * Change the backing file. All clusters that are different from the old
1940 * backing file are overwritten in the COW file now, so the visible content
1941 * doesn't change when we switch the backing file.
1943 if (out_baseimg && *out_baseimg) {
1944 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
1945 } else {
1946 ret = bdrv_change_backing_file(bs, NULL, NULL);
1949 if (ret == -ENOSPC) {
1950 error_report("Could not change the backing file to '%s': No "
1951 "space left in the file header", out_baseimg);
1952 } else if (ret < 0) {
1953 error_report("Could not change the backing file to '%s': %s",
1954 out_baseimg, strerror(-ret));
1957 qemu_progress_print(100, 0);
1959 * TODO At this point it is possible to check if any clusters that are
1960 * allocated in the COW file are the same in the backing file. If so, they
1961 * could be dropped from the COW file. Don't do this before switching the
1962 * backing file, in case of a crash this would lead to corruption.
1964 out:
1965 qemu_progress_end();
1966 /* Cleanup */
1967 if (!unsafe) {
1968 if (bs_old_backing != NULL) {
1969 bdrv_delete(bs_old_backing);
1971 if (bs_new_backing != NULL) {
1972 bdrv_delete(bs_new_backing);
1976 bdrv_delete(bs);
1977 if (ret) {
1978 return 1;
1980 return 0;
1983 static int img_resize(int argc, char **argv)
1985 int c, ret, relative;
1986 const char *filename, *fmt, *size;
1987 int64_t n, total_size;
1988 BlockDriverState *bs = NULL;
1989 QemuOpts *param;
1990 static QemuOptsList resize_options = {
1991 .name = "resize_options",
1992 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
1993 .desc = {
1995 .name = BLOCK_OPT_SIZE,
1996 .type = QEMU_OPT_SIZE,
1997 .help = "Virtual disk size"
1998 }, {
1999 /* end of list */
2004 /* Remove size from argv manually so that negative numbers are not treated
2005 * as options by getopt. */
2006 if (argc < 3) {
2007 help();
2008 return 1;
2011 size = argv[--argc];
2013 /* Parse getopt arguments */
2014 fmt = NULL;
2015 for(;;) {
2016 c = getopt(argc, argv, "f:h");
2017 if (c == -1) {
2018 break;
2020 switch(c) {
2021 case '?':
2022 case 'h':
2023 help();
2024 break;
2025 case 'f':
2026 fmt = optarg;
2027 break;
2030 if (optind >= argc) {
2031 help();
2033 filename = argv[optind++];
2035 /* Choose grow, shrink, or absolute resize mode */
2036 switch (size[0]) {
2037 case '+':
2038 relative = 1;
2039 size++;
2040 break;
2041 case '-':
2042 relative = -1;
2043 size++;
2044 break;
2045 default:
2046 relative = 0;
2047 break;
2050 /* Parse size */
2051 param = qemu_opts_create_nofail(&resize_options);
2052 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
2053 /* Error message already printed when size parsing fails */
2054 ret = -1;
2055 qemu_opts_del(param);
2056 goto out;
2058 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2059 qemu_opts_del(param);
2061 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true);
2062 if (!bs) {
2063 ret = -1;
2064 goto out;
2067 if (relative) {
2068 total_size = bdrv_getlength(bs) + n * relative;
2069 } else {
2070 total_size = n;
2072 if (total_size <= 0) {
2073 error_report("New image size must be positive");
2074 ret = -1;
2075 goto out;
2078 ret = bdrv_truncate(bs, total_size);
2079 switch (ret) {
2080 case 0:
2081 printf("Image resized.\n");
2082 break;
2083 case -ENOTSUP:
2084 error_report("This image does not support resize");
2085 break;
2086 case -EACCES:
2087 error_report("Image is read-only");
2088 break;
2089 default:
2090 error_report("Error resizing image (%d)", -ret);
2091 break;
2093 out:
2094 if (bs) {
2095 bdrv_delete(bs);
2097 if (ret) {
2098 return 1;
2100 return 0;
2103 static const img_cmd_t img_cmds[] = {
2104 #define DEF(option, callback, arg_string) \
2105 { option, callback },
2106 #include "qemu-img-cmds.h"
2107 #undef DEF
2108 #undef GEN_DOCS
2109 { NULL, NULL, },
2112 int main(int argc, char **argv)
2114 const img_cmd_t *cmd;
2115 const char *cmdname;
2117 error_set_progname(argv[0]);
2119 qemu_init_main_loop();
2120 bdrv_init();
2121 if (argc < 2)
2122 help();
2123 cmdname = argv[1];
2124 argc--; argv++;
2126 /* find the command */
2127 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
2128 if (!strcmp(cmdname, cmd->name)) {
2129 return cmd->handler(argc, argv);
2133 /* not found */
2134 help();
2135 return 0;