block: Switch blk_*write_zeroes() to byte interface
[qemu/ar7.git] / qemu-img.c
blob76430a83cd355bdbd2ccd27addfb5b6b58b70d39
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 "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qapi-visit.h"
27 #include "qapi/qmp-output-visitor.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qapi/qmp/qjson.h"
30 #include "qemu/cutils.h"
31 #include "qemu/config-file.h"
32 #include "qemu/option.h"
33 #include "qemu/error-report.h"
34 #include "qom/object_interfaces.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/block-backend.h"
37 #include "block/block_int.h"
38 #include "block/blockjob.h"
39 #include "block/qapi.h"
40 #include "crypto/init.h"
41 #include <getopt.h>
43 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
44 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
46 typedef struct img_cmd_t {
47 const char *name;
48 int (*handler)(int argc, char **argv);
49 } img_cmd_t;
51 enum {
52 OPTION_OUTPUT = 256,
53 OPTION_BACKING_CHAIN = 257,
54 OPTION_OBJECT = 258,
55 OPTION_IMAGE_OPTS = 259,
58 typedef enum OutputFormat {
59 OFORMAT_JSON,
60 OFORMAT_HUMAN,
61 } OutputFormat;
63 /* Default to cache=writeback as data integrity is not important for qemu-img */
64 #define BDRV_DEFAULT_CACHE "writeback"
66 static void format_print(void *opaque, const char *name)
68 printf(" %s", name);
71 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
73 va_list ap;
75 error_printf("qemu-img: ");
77 va_start(ap, fmt);
78 error_vprintf(fmt, ap);
79 va_end(ap);
81 error_printf("\nTry 'qemu-img --help' for more information\n");
82 exit(EXIT_FAILURE);
85 /* Please keep in synch with qemu-img.texi */
86 static void QEMU_NORETURN help(void)
88 const char *help_msg =
89 QEMU_IMG_VERSION
90 "usage: qemu-img command [command options]\n"
91 "QEMU disk image utility\n"
92 "\n"
93 "Command syntax:\n"
94 #define DEF(option, callback, arg_string) \
95 " " arg_string "\n"
96 #include "qemu-img-cmds.h"
97 #undef DEF
98 #undef GEN_DOCS
99 "\n"
100 "Command parameters:\n"
101 " 'filename' is a disk image filename\n"
102 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
103 " manual page for a description of the object properties. The most common\n"
104 " object type is a 'secret', which is used to supply passwords and/or\n"
105 " encryption keys.\n"
106 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
107 " 'cache' is the cache mode used to write the output disk image, the valid\n"
108 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
109 " 'directsync' and 'unsafe' (default for convert)\n"
110 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
111 " options are the same as for the 'cache' option\n"
112 " 'size' is the disk image size in bytes. Optional suffixes\n"
113 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
114 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
115 " supported. 'b' is ignored.\n"
116 " 'output_filename' is the destination disk image filename\n"
117 " 'output_fmt' is the destination format\n"
118 " 'options' is a comma separated list of format specific options in a\n"
119 " name=value format. Use -o ? for an overview of the options supported by the\n"
120 " used format\n"
121 " 'snapshot_param' is param used for internal snapshot, format\n"
122 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
123 " '[ID_OR_NAME]'\n"
124 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
125 " instead\n"
126 " '-c' indicates that target image must be compressed (qcow format only)\n"
127 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
128 " match exactly. The image doesn't need a working backing file before\n"
129 " rebasing in this case (useful for renaming the backing file)\n"
130 " '-h' with or without a command shows this help and lists the supported formats\n"
131 " '-p' show progress of command (only certain commands)\n"
132 " '-q' use Quiet mode - do not print any output (except errors)\n"
133 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
134 " contain only zeros for qemu-img to create a sparse image during\n"
135 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
136 " unallocated or zero sectors, and the destination image will always be\n"
137 " fully allocated\n"
138 " '--output' takes the format in which the output must be done (human or json)\n"
139 " '-n' skips the target volume creation (useful if the volume is created\n"
140 " prior to running qemu-img)\n"
141 "\n"
142 "Parameters to check subcommand:\n"
143 " '-r' tries to repair any inconsistencies that are found during the check.\n"
144 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
145 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
146 " hiding corruption that has already occurred.\n"
147 "\n"
148 "Parameters to snapshot subcommand:\n"
149 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
150 " '-a' applies a snapshot (revert disk to saved state)\n"
151 " '-c' creates a snapshot\n"
152 " '-d' deletes a snapshot\n"
153 " '-l' lists all snapshots in the given image\n"
154 "\n"
155 "Parameters to compare subcommand:\n"
156 " '-f' first image format\n"
157 " '-F' second image format\n"
158 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
160 printf("%s\nSupported formats:", help_msg);
161 bdrv_iterate_format(format_print, NULL);
162 printf("\n");
163 exit(EXIT_SUCCESS);
166 static QemuOptsList qemu_object_opts = {
167 .name = "object",
168 .implied_opt_name = "qom-type",
169 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
170 .desc = {
175 static QemuOptsList qemu_source_opts = {
176 .name = "source",
177 .implied_opt_name = "file",
178 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
179 .desc = {
184 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
186 int ret = 0;
187 if (!quiet) {
188 va_list args;
189 va_start(args, fmt);
190 ret = vprintf(fmt, args);
191 va_end(args);
193 return ret;
197 static int print_block_option_help(const char *filename, const char *fmt)
199 BlockDriver *drv, *proto_drv;
200 QemuOptsList *create_opts = NULL;
201 Error *local_err = NULL;
203 /* Find driver and parse its options */
204 drv = bdrv_find_format(fmt);
205 if (!drv) {
206 error_report("Unknown file format '%s'", fmt);
207 return 1;
210 create_opts = qemu_opts_append(create_opts, drv->create_opts);
211 if (filename) {
212 proto_drv = bdrv_find_protocol(filename, true, &local_err);
213 if (!proto_drv) {
214 error_report_err(local_err);
215 qemu_opts_free(create_opts);
216 return 1;
218 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
221 qemu_opts_print_help(create_opts);
222 qemu_opts_free(create_opts);
223 return 0;
227 static int img_open_password(BlockBackend *blk, const char *filename,
228 int flags, bool quiet)
230 BlockDriverState *bs;
231 char password[256];
233 bs = blk_bs(blk);
234 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
235 !(flags & BDRV_O_NO_IO)) {
236 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
237 if (qemu_read_password(password, sizeof(password)) < 0) {
238 error_report("No password given");
239 return -1;
241 if (bdrv_set_key(bs, password) < 0) {
242 error_report("invalid password");
243 return -1;
246 return 0;
250 static BlockBackend *img_open_opts(const char *optstr,
251 QemuOpts *opts, int flags, bool writethrough,
252 bool quiet)
254 QDict *options;
255 Error *local_err = NULL;
256 BlockBackend *blk;
257 options = qemu_opts_to_qdict(opts, NULL);
258 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
259 if (!blk) {
260 error_reportf_err(local_err, "Could not open '%s': ", optstr);
261 return NULL;
263 blk_set_enable_write_cache(blk, !writethrough);
265 if (img_open_password(blk, optstr, flags, quiet) < 0) {
266 blk_unref(blk);
267 return NULL;
269 return blk;
272 static BlockBackend *img_open_file(const char *filename,
273 const char *fmt, int flags,
274 bool writethrough, bool quiet)
276 BlockBackend *blk;
277 Error *local_err = NULL;
278 QDict *options = NULL;
280 if (fmt) {
281 options = qdict_new();
282 qdict_put(options, "driver", qstring_from_str(fmt));
285 blk = blk_new_open(filename, NULL, options, flags, &local_err);
286 if (!blk) {
287 error_reportf_err(local_err, "Could not open '%s': ", filename);
288 return NULL;
290 blk_set_enable_write_cache(blk, !writethrough);
292 if (img_open_password(blk, filename, flags, quiet) < 0) {
293 blk_unref(blk);
294 return NULL;
296 return blk;
300 static BlockBackend *img_open(bool image_opts,
301 const char *filename,
302 const char *fmt, int flags, bool writethrough,
303 bool quiet)
305 BlockBackend *blk;
306 if (image_opts) {
307 QemuOpts *opts;
308 if (fmt) {
309 error_report("--image-opts and --format are mutually exclusive");
310 return NULL;
312 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
313 filename, true);
314 if (!opts) {
315 return NULL;
317 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
318 } else {
319 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
321 return blk;
325 static int add_old_style_options(const char *fmt, QemuOpts *opts,
326 const char *base_filename,
327 const char *base_fmt)
329 Error *err = NULL;
331 if (base_filename) {
332 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
333 if (err) {
334 error_report("Backing file not supported for file format '%s'",
335 fmt);
336 error_free(err);
337 return -1;
340 if (base_fmt) {
341 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
342 if (err) {
343 error_report("Backing file format not supported for file "
344 "format '%s'", fmt);
345 error_free(err);
346 return -1;
349 return 0;
352 static int img_create(int argc, char **argv)
354 int c;
355 uint64_t img_size = -1;
356 const char *fmt = "raw";
357 const char *base_fmt = NULL;
358 const char *filename;
359 const char *base_filename = NULL;
360 char *options = NULL;
361 Error *local_err = NULL;
362 bool quiet = false;
364 for(;;) {
365 static const struct option long_options[] = {
366 {"help", no_argument, 0, 'h'},
367 {"object", required_argument, 0, OPTION_OBJECT},
368 {0, 0, 0, 0}
370 c = getopt_long(argc, argv, "F:b:f:he6o:q",
371 long_options, NULL);
372 if (c == -1) {
373 break;
375 switch(c) {
376 case '?':
377 case 'h':
378 help();
379 break;
380 case 'F':
381 base_fmt = optarg;
382 break;
383 case 'b':
384 base_filename = optarg;
385 break;
386 case 'f':
387 fmt = optarg;
388 break;
389 case 'e':
390 error_report("option -e is deprecated, please use \'-o "
391 "encryption\' instead!");
392 goto fail;
393 case '6':
394 error_report("option -6 is deprecated, please use \'-o "
395 "compat6\' instead!");
396 goto fail;
397 case 'o':
398 if (!is_valid_option_list(optarg)) {
399 error_report("Invalid option list: %s", optarg);
400 goto fail;
402 if (!options) {
403 options = g_strdup(optarg);
404 } else {
405 char *old_options = options;
406 options = g_strdup_printf("%s,%s", options, optarg);
407 g_free(old_options);
409 break;
410 case 'q':
411 quiet = true;
412 break;
413 case OPTION_OBJECT: {
414 QemuOpts *opts;
415 opts = qemu_opts_parse_noisily(&qemu_object_opts,
416 optarg, true);
417 if (!opts) {
418 goto fail;
420 } break;
424 /* Get the filename */
425 filename = (optind < argc) ? argv[optind] : NULL;
426 if (options && has_help_option(options)) {
427 g_free(options);
428 return print_block_option_help(filename, fmt);
431 if (optind >= argc) {
432 error_exit("Expecting image file name");
434 optind++;
436 if (qemu_opts_foreach(&qemu_object_opts,
437 user_creatable_add_opts_foreach,
438 NULL, NULL)) {
439 goto fail;
442 /* Get image size, if specified */
443 if (optind < argc) {
444 int64_t sval;
445 char *end;
446 sval = qemu_strtosz_suffix(argv[optind++], &end,
447 QEMU_STRTOSZ_DEFSUFFIX_B);
448 if (sval < 0 || *end) {
449 if (sval == -ERANGE) {
450 error_report("Image size must be less than 8 EiB!");
451 } else {
452 error_report("Invalid image size specified! You may use k, M, "
453 "G, T, P or E suffixes for ");
454 error_report("kilobytes, megabytes, gigabytes, terabytes, "
455 "petabytes and exabytes.");
457 goto fail;
459 img_size = (uint64_t)sval;
461 if (optind != argc) {
462 error_exit("Unexpected argument: %s", argv[optind]);
465 bdrv_img_create(filename, fmt, base_filename, base_fmt,
466 options, img_size, 0, &local_err, quiet);
467 if (local_err) {
468 error_reportf_err(local_err, "%s: ", filename);
469 goto fail;
472 g_free(options);
473 return 0;
475 fail:
476 g_free(options);
477 return 1;
480 static void dump_json_image_check(ImageCheck *check, bool quiet)
482 Error *local_err = NULL;
483 QString *str;
484 QmpOutputVisitor *ov = qmp_output_visitor_new();
485 QObject *obj;
486 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
487 &local_err);
488 obj = qmp_output_get_qobject(ov);
489 str = qobject_to_json_pretty(obj);
490 assert(str != NULL);
491 qprintf(quiet, "%s\n", qstring_get_str(str));
492 qobject_decref(obj);
493 qmp_output_visitor_cleanup(ov);
494 QDECREF(str);
497 static void dump_human_image_check(ImageCheck *check, bool quiet)
499 if (!(check->corruptions || check->leaks || check->check_errors)) {
500 qprintf(quiet, "No errors were found on the image.\n");
501 } else {
502 if (check->corruptions) {
503 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
504 "Data may be corrupted, or further writes to the image "
505 "may corrupt it.\n",
506 check->corruptions);
509 if (check->leaks) {
510 qprintf(quiet,
511 "\n%" PRId64 " leaked clusters were found on the image.\n"
512 "This means waste of disk space, but no harm to data.\n",
513 check->leaks);
516 if (check->check_errors) {
517 qprintf(quiet,
518 "\n%" PRId64
519 " internal errors have occurred during the check.\n",
520 check->check_errors);
524 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
525 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
526 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
527 check->allocated_clusters, check->total_clusters,
528 check->allocated_clusters * 100.0 / check->total_clusters,
529 check->fragmented_clusters * 100.0 / check->allocated_clusters,
530 check->compressed_clusters * 100.0 /
531 check->allocated_clusters);
534 if (check->image_end_offset) {
535 qprintf(quiet,
536 "Image end offset: %" PRId64 "\n", check->image_end_offset);
540 static int collect_image_check(BlockDriverState *bs,
541 ImageCheck *check,
542 const char *filename,
543 const char *fmt,
544 int fix)
546 int ret;
547 BdrvCheckResult result;
549 ret = bdrv_check(bs, &result, fix);
550 if (ret < 0) {
551 return ret;
554 check->filename = g_strdup(filename);
555 check->format = g_strdup(bdrv_get_format_name(bs));
556 check->check_errors = result.check_errors;
557 check->corruptions = result.corruptions;
558 check->has_corruptions = result.corruptions != 0;
559 check->leaks = result.leaks;
560 check->has_leaks = result.leaks != 0;
561 check->corruptions_fixed = result.corruptions_fixed;
562 check->has_corruptions_fixed = result.corruptions != 0;
563 check->leaks_fixed = result.leaks_fixed;
564 check->has_leaks_fixed = result.leaks != 0;
565 check->image_end_offset = result.image_end_offset;
566 check->has_image_end_offset = result.image_end_offset != 0;
567 check->total_clusters = result.bfi.total_clusters;
568 check->has_total_clusters = result.bfi.total_clusters != 0;
569 check->allocated_clusters = result.bfi.allocated_clusters;
570 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
571 check->fragmented_clusters = result.bfi.fragmented_clusters;
572 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
573 check->compressed_clusters = result.bfi.compressed_clusters;
574 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
576 return 0;
580 * Checks an image for consistency. Exit codes:
582 * 0 - Check completed, image is good
583 * 1 - Check not completed because of internal errors
584 * 2 - Check completed, image is corrupted
585 * 3 - Check completed, image has leaked clusters, but is good otherwise
586 * 63 - Checks are not supported by the image format
588 static int img_check(int argc, char **argv)
590 int c, ret;
591 OutputFormat output_format = OFORMAT_HUMAN;
592 const char *filename, *fmt, *output, *cache;
593 BlockBackend *blk;
594 BlockDriverState *bs;
595 int fix = 0;
596 int flags = BDRV_O_CHECK;
597 bool writethrough;
598 ImageCheck *check;
599 bool quiet = false;
600 bool image_opts = false;
602 fmt = NULL;
603 output = NULL;
604 cache = BDRV_DEFAULT_CACHE;
606 for(;;) {
607 int option_index = 0;
608 static const struct option long_options[] = {
609 {"help", no_argument, 0, 'h'},
610 {"format", required_argument, 0, 'f'},
611 {"repair", required_argument, 0, 'r'},
612 {"output", required_argument, 0, OPTION_OUTPUT},
613 {"object", required_argument, 0, OPTION_OBJECT},
614 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
615 {0, 0, 0, 0}
617 c = getopt_long(argc, argv, "hf:r:T:q",
618 long_options, &option_index);
619 if (c == -1) {
620 break;
622 switch(c) {
623 case '?':
624 case 'h':
625 help();
626 break;
627 case 'f':
628 fmt = optarg;
629 break;
630 case 'r':
631 flags |= BDRV_O_RDWR;
633 if (!strcmp(optarg, "leaks")) {
634 fix = BDRV_FIX_LEAKS;
635 } else if (!strcmp(optarg, "all")) {
636 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
637 } else {
638 error_exit("Unknown option value for -r "
639 "(expecting 'leaks' or 'all'): %s", optarg);
641 break;
642 case OPTION_OUTPUT:
643 output = optarg;
644 break;
645 case 'T':
646 cache = optarg;
647 break;
648 case 'q':
649 quiet = true;
650 break;
651 case OPTION_OBJECT: {
652 QemuOpts *opts;
653 opts = qemu_opts_parse_noisily(&qemu_object_opts,
654 optarg, true);
655 if (!opts) {
656 return 1;
658 } break;
659 case OPTION_IMAGE_OPTS:
660 image_opts = true;
661 break;
664 if (optind != argc - 1) {
665 error_exit("Expecting one image file name");
667 filename = argv[optind++];
669 if (output && !strcmp(output, "json")) {
670 output_format = OFORMAT_JSON;
671 } else if (output && !strcmp(output, "human")) {
672 output_format = OFORMAT_HUMAN;
673 } else if (output) {
674 error_report("--output must be used with human or json as argument.");
675 return 1;
678 if (qemu_opts_foreach(&qemu_object_opts,
679 user_creatable_add_opts_foreach,
680 NULL, NULL)) {
681 return 1;
684 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
685 if (ret < 0) {
686 error_report("Invalid source cache option: %s", cache);
687 return 1;
690 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
691 if (!blk) {
692 return 1;
694 bs = blk_bs(blk);
696 check = g_new0(ImageCheck, 1);
697 ret = collect_image_check(bs, check, filename, fmt, fix);
699 if (ret == -ENOTSUP) {
700 error_report("This image format does not support checks");
701 ret = 63;
702 goto fail;
705 if (check->corruptions_fixed || check->leaks_fixed) {
706 int corruptions_fixed, leaks_fixed;
708 leaks_fixed = check->leaks_fixed;
709 corruptions_fixed = check->corruptions_fixed;
711 if (output_format == OFORMAT_HUMAN) {
712 qprintf(quiet,
713 "The following inconsistencies were found and repaired:\n\n"
714 " %" PRId64 " leaked clusters\n"
715 " %" PRId64 " corruptions\n\n"
716 "Double checking the fixed image now...\n",
717 check->leaks_fixed,
718 check->corruptions_fixed);
721 ret = collect_image_check(bs, check, filename, fmt, 0);
723 check->leaks_fixed = leaks_fixed;
724 check->corruptions_fixed = corruptions_fixed;
727 if (!ret) {
728 switch (output_format) {
729 case OFORMAT_HUMAN:
730 dump_human_image_check(check, quiet);
731 break;
732 case OFORMAT_JSON:
733 dump_json_image_check(check, quiet);
734 break;
738 if (ret || check->check_errors) {
739 if (ret) {
740 error_report("Check failed: %s", strerror(-ret));
741 } else {
742 error_report("Check failed");
744 ret = 1;
745 goto fail;
748 if (check->corruptions) {
749 ret = 2;
750 } else if (check->leaks) {
751 ret = 3;
752 } else {
753 ret = 0;
756 fail:
757 qapi_free_ImageCheck(check);
758 blk_unref(blk);
759 return ret;
762 typedef struct CommonBlockJobCBInfo {
763 BlockDriverState *bs;
764 Error **errp;
765 } CommonBlockJobCBInfo;
767 static void common_block_job_cb(void *opaque, int ret)
769 CommonBlockJobCBInfo *cbi = opaque;
771 if (ret < 0) {
772 error_setg_errno(cbi->errp, -ret, "Block job failed");
776 static void run_block_job(BlockJob *job, Error **errp)
778 AioContext *aio_context = bdrv_get_aio_context(job->bs);
780 do {
781 aio_poll(aio_context, true);
782 qemu_progress_print(job->len ?
783 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
784 } while (!job->ready);
786 block_job_complete_sync(job, errp);
788 /* A block job may finish instantaneously without publishing any progress,
789 * so just signal completion here */
790 qemu_progress_print(100.f, 0);
793 static int img_commit(int argc, char **argv)
795 int c, ret, flags;
796 const char *filename, *fmt, *cache, *base;
797 BlockBackend *blk;
798 BlockDriverState *bs, *base_bs;
799 bool progress = false, quiet = false, drop = false;
800 bool writethrough;
801 Error *local_err = NULL;
802 CommonBlockJobCBInfo cbi;
803 bool image_opts = false;
805 fmt = NULL;
806 cache = BDRV_DEFAULT_CACHE;
807 base = NULL;
808 for(;;) {
809 static const struct option long_options[] = {
810 {"help", no_argument, 0, 'h'},
811 {"object", required_argument, 0, OPTION_OBJECT},
812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
813 {0, 0, 0, 0}
815 c = getopt_long(argc, argv, "f:ht:b:dpq",
816 long_options, NULL);
817 if (c == -1) {
818 break;
820 switch(c) {
821 case '?':
822 case 'h':
823 help();
824 break;
825 case 'f':
826 fmt = optarg;
827 break;
828 case 't':
829 cache = optarg;
830 break;
831 case 'b':
832 base = optarg;
833 /* -b implies -d */
834 drop = true;
835 break;
836 case 'd':
837 drop = true;
838 break;
839 case 'p':
840 progress = true;
841 break;
842 case 'q':
843 quiet = true;
844 break;
845 case OPTION_OBJECT: {
846 QemuOpts *opts;
847 opts = qemu_opts_parse_noisily(&qemu_object_opts,
848 optarg, true);
849 if (!opts) {
850 return 1;
852 } break;
853 case OPTION_IMAGE_OPTS:
854 image_opts = true;
855 break;
859 /* Progress is not shown in Quiet mode */
860 if (quiet) {
861 progress = false;
864 if (optind != argc - 1) {
865 error_exit("Expecting one image file name");
867 filename = argv[optind++];
869 if (qemu_opts_foreach(&qemu_object_opts,
870 user_creatable_add_opts_foreach,
871 NULL, NULL)) {
872 return 1;
875 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
876 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
877 if (ret < 0) {
878 error_report("Invalid cache option: %s", cache);
879 return 1;
882 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
883 if (!blk) {
884 return 1;
886 bs = blk_bs(blk);
888 qemu_progress_init(progress, 1.f);
889 qemu_progress_print(0.f, 100);
891 if (base) {
892 base_bs = bdrv_find_backing_image(bs, base);
893 if (!base_bs) {
894 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
895 goto done;
897 } else {
898 /* This is different from QMP, which by default uses the deepest file in
899 * the backing chain (i.e., the very base); however, the traditional
900 * behavior of qemu-img commit is using the immediate backing file. */
901 base_bs = backing_bs(bs);
902 if (!base_bs) {
903 error_setg(&local_err, "Image does not have a backing file");
904 goto done;
908 cbi = (CommonBlockJobCBInfo){
909 .errp = &local_err,
910 .bs = bs,
913 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
914 common_block_job_cb, &cbi, &local_err);
915 if (local_err) {
916 goto done;
919 /* When the block job completes, the BlockBackend reference will point to
920 * the old backing file. In order to avoid that the top image is already
921 * deleted, so we can still empty it afterwards, increment the reference
922 * counter here preemptively. */
923 if (!drop) {
924 bdrv_ref(bs);
927 run_block_job(bs->job, &local_err);
928 if (local_err) {
929 goto unref_backing;
932 if (!drop && bs->drv->bdrv_make_empty) {
933 ret = bs->drv->bdrv_make_empty(bs);
934 if (ret) {
935 error_setg_errno(&local_err, -ret, "Could not empty %s",
936 filename);
937 goto unref_backing;
941 unref_backing:
942 if (!drop) {
943 bdrv_unref(bs);
946 done:
947 qemu_progress_end();
949 blk_unref(blk);
951 if (local_err) {
952 error_report_err(local_err);
953 return 1;
956 qprintf(quiet, "Image committed.\n");
957 return 0;
961 * Returns true iff the first sector pointed to by 'buf' contains at least
962 * a non-NUL byte.
964 * 'pnum' is set to the number of sectors (including and immediately following
965 * the first one) that are known to be in the same allocated/unallocated state.
967 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
969 bool is_zero;
970 int i;
972 if (n <= 0) {
973 *pnum = 0;
974 return 0;
976 is_zero = buffer_is_zero(buf, 512);
977 for(i = 1; i < n; i++) {
978 buf += 512;
979 if (is_zero != buffer_is_zero(buf, 512)) {
980 break;
983 *pnum = i;
984 return !is_zero;
988 * Like is_allocated_sectors, but if the buffer starts with a used sector,
989 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
990 * breaking up write requests for only small sparse areas.
992 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
993 int min)
995 int ret;
996 int num_checked, num_used;
998 if (n < min) {
999 min = n;
1002 ret = is_allocated_sectors(buf, n, pnum);
1003 if (!ret) {
1004 return ret;
1007 num_used = *pnum;
1008 buf += BDRV_SECTOR_SIZE * *pnum;
1009 n -= *pnum;
1010 num_checked = num_used;
1012 while (n > 0) {
1013 ret = is_allocated_sectors(buf, n, pnum);
1015 buf += BDRV_SECTOR_SIZE * *pnum;
1016 n -= *pnum;
1017 num_checked += *pnum;
1018 if (ret) {
1019 num_used = num_checked;
1020 } else if (*pnum >= min) {
1021 break;
1025 *pnum = num_used;
1026 return 1;
1030 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1031 * buffers matches, non-zero otherwise.
1033 * pnum is set to the number of sectors (including and immediately following
1034 * the first one) that are known to have the same comparison result
1036 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1037 int *pnum)
1039 bool res;
1040 int i;
1042 if (n <= 0) {
1043 *pnum = 0;
1044 return 0;
1047 res = !!memcmp(buf1, buf2, 512);
1048 for(i = 1; i < n; i++) {
1049 buf1 += 512;
1050 buf2 += 512;
1052 if (!!memcmp(buf1, buf2, 512) != res) {
1053 break;
1057 *pnum = i;
1058 return res;
1061 #define IO_BUF_SIZE (2 * 1024 * 1024)
1063 static int64_t sectors_to_bytes(int64_t sectors)
1065 return sectors << BDRV_SECTOR_BITS;
1068 static int64_t sectors_to_process(int64_t total, int64_t from)
1070 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1074 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1076 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1077 * data and negative value on error.
1079 * @param blk: BlockBackend for the image
1080 * @param sect_num: Number of first sector to check
1081 * @param sect_count: Number of sectors to check
1082 * @param filename: Name of disk file we are checking (logging purpose)
1083 * @param buffer: Allocated buffer for storing read data
1084 * @param quiet: Flag for quiet mode
1086 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1087 int sect_count, const char *filename,
1088 uint8_t *buffer, bool quiet)
1090 int pnum, ret = 0;
1091 ret = blk_read(blk, sect_num, buffer, sect_count);
1092 if (ret < 0) {
1093 error_report("Error while reading offset %" PRId64 " of %s: %s",
1094 sectors_to_bytes(sect_num), filename, strerror(-ret));
1095 return ret;
1097 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1098 if (ret || pnum != sect_count) {
1099 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1100 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1101 return 1;
1104 return 0;
1108 * Compares two images. Exit codes:
1110 * 0 - Images are identical
1111 * 1 - Images differ
1112 * >1 - Error occurred
1114 static int img_compare(int argc, char **argv)
1116 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1117 BlockBackend *blk1, *blk2;
1118 BlockDriverState *bs1, *bs2;
1119 int64_t total_sectors1, total_sectors2;
1120 uint8_t *buf1 = NULL, *buf2 = NULL;
1121 int pnum1, pnum2;
1122 int allocated1, allocated2;
1123 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1124 bool progress = false, quiet = false, strict = false;
1125 int flags;
1126 bool writethrough;
1127 int64_t total_sectors;
1128 int64_t sector_num = 0;
1129 int64_t nb_sectors;
1130 int c, pnum;
1131 uint64_t progress_base;
1132 bool image_opts = false;
1134 cache = BDRV_DEFAULT_CACHE;
1135 for (;;) {
1136 static const struct option long_options[] = {
1137 {"help", no_argument, 0, 'h'},
1138 {"object", required_argument, 0, OPTION_OBJECT},
1139 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1140 {0, 0, 0, 0}
1142 c = getopt_long(argc, argv, "hf:F:T:pqs",
1143 long_options, NULL);
1144 if (c == -1) {
1145 break;
1147 switch (c) {
1148 case '?':
1149 case 'h':
1150 help();
1151 break;
1152 case 'f':
1153 fmt1 = optarg;
1154 break;
1155 case 'F':
1156 fmt2 = optarg;
1157 break;
1158 case 'T':
1159 cache = optarg;
1160 break;
1161 case 'p':
1162 progress = true;
1163 break;
1164 case 'q':
1165 quiet = true;
1166 break;
1167 case 's':
1168 strict = true;
1169 break;
1170 case OPTION_OBJECT: {
1171 QemuOpts *opts;
1172 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1173 optarg, true);
1174 if (!opts) {
1175 ret = 2;
1176 goto out4;
1178 } break;
1179 case OPTION_IMAGE_OPTS:
1180 image_opts = true;
1181 break;
1185 /* Progress is not shown in Quiet mode */
1186 if (quiet) {
1187 progress = false;
1191 if (optind != argc - 2) {
1192 error_exit("Expecting two image file names");
1194 filename1 = argv[optind++];
1195 filename2 = argv[optind++];
1197 if (qemu_opts_foreach(&qemu_object_opts,
1198 user_creatable_add_opts_foreach,
1199 NULL, NULL)) {
1200 ret = 2;
1201 goto out4;
1204 /* Initialize before goto out */
1205 qemu_progress_init(progress, 2.0);
1207 flags = 0;
1208 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1209 if (ret < 0) {
1210 error_report("Invalid source cache option: %s", cache);
1211 ret = 2;
1212 goto out3;
1215 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
1216 if (!blk1) {
1217 ret = 2;
1218 goto out3;
1221 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
1222 if (!blk2) {
1223 ret = 2;
1224 goto out2;
1226 bs1 = blk_bs(blk1);
1227 bs2 = blk_bs(blk2);
1229 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1230 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1231 total_sectors1 = blk_nb_sectors(blk1);
1232 if (total_sectors1 < 0) {
1233 error_report("Can't get size of %s: %s",
1234 filename1, strerror(-total_sectors1));
1235 ret = 4;
1236 goto out;
1238 total_sectors2 = blk_nb_sectors(blk2);
1239 if (total_sectors2 < 0) {
1240 error_report("Can't get size of %s: %s",
1241 filename2, strerror(-total_sectors2));
1242 ret = 4;
1243 goto out;
1245 total_sectors = MIN(total_sectors1, total_sectors2);
1246 progress_base = MAX(total_sectors1, total_sectors2);
1248 qemu_progress_print(0, 100);
1250 if (strict && total_sectors1 != total_sectors2) {
1251 ret = 1;
1252 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1253 goto out;
1256 for (;;) {
1257 int64_t status1, status2;
1258 BlockDriverState *file;
1260 nb_sectors = sectors_to_process(total_sectors, sector_num);
1261 if (nb_sectors <= 0) {
1262 break;
1264 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1265 total_sectors1 - sector_num,
1266 &pnum1, &file);
1267 if (status1 < 0) {
1268 ret = 3;
1269 error_report("Sector allocation test failed for %s", filename1);
1270 goto out;
1272 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1274 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1275 total_sectors2 - sector_num,
1276 &pnum2, &file);
1277 if (status2 < 0) {
1278 ret = 3;
1279 error_report("Sector allocation test failed for %s", filename2);
1280 goto out;
1282 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1283 if (pnum1) {
1284 nb_sectors = MIN(nb_sectors, pnum1);
1286 if (pnum2) {
1287 nb_sectors = MIN(nb_sectors, pnum2);
1290 if (strict) {
1291 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1292 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1293 ret = 1;
1294 qprintf(quiet, "Strict mode: Offset %" PRId64
1295 " block status mismatch!\n",
1296 sectors_to_bytes(sector_num));
1297 goto out;
1300 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1301 nb_sectors = MIN(pnum1, pnum2);
1302 } else if (allocated1 == allocated2) {
1303 if (allocated1) {
1304 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
1305 if (ret < 0) {
1306 error_report("Error while reading offset %" PRId64 " of %s:"
1307 " %s", sectors_to_bytes(sector_num), filename1,
1308 strerror(-ret));
1309 ret = 4;
1310 goto out;
1312 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
1313 if (ret < 0) {
1314 error_report("Error while reading offset %" PRId64
1315 " of %s: %s", sectors_to_bytes(sector_num),
1316 filename2, strerror(-ret));
1317 ret = 4;
1318 goto out;
1320 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1321 if (ret || pnum != nb_sectors) {
1322 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1323 sectors_to_bytes(
1324 ret ? sector_num : sector_num + pnum));
1325 ret = 1;
1326 goto out;
1329 } else {
1331 if (allocated1) {
1332 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1333 filename1, buf1, quiet);
1334 } else {
1335 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1336 filename2, buf1, quiet);
1338 if (ret) {
1339 if (ret < 0) {
1340 error_report("Error while reading offset %" PRId64 ": %s",
1341 sectors_to_bytes(sector_num), strerror(-ret));
1342 ret = 4;
1344 goto out;
1347 sector_num += nb_sectors;
1348 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1351 if (total_sectors1 != total_sectors2) {
1352 BlockBackend *blk_over;
1353 int64_t total_sectors_over;
1354 const char *filename_over;
1356 qprintf(quiet, "Warning: Image size mismatch!\n");
1357 if (total_sectors1 > total_sectors2) {
1358 total_sectors_over = total_sectors1;
1359 blk_over = blk1;
1360 filename_over = filename1;
1361 } else {
1362 total_sectors_over = total_sectors2;
1363 blk_over = blk2;
1364 filename_over = filename2;
1367 for (;;) {
1368 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1369 if (nb_sectors <= 0) {
1370 break;
1372 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1373 nb_sectors, &pnum);
1374 if (ret < 0) {
1375 ret = 3;
1376 error_report("Sector allocation test failed for %s",
1377 filename_over);
1378 goto out;
1381 nb_sectors = pnum;
1382 if (ret) {
1383 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1384 filename_over, buf1, quiet);
1385 if (ret) {
1386 if (ret < 0) {
1387 error_report("Error while reading offset %" PRId64
1388 " of %s: %s", sectors_to_bytes(sector_num),
1389 filename_over, strerror(-ret));
1390 ret = 4;
1392 goto out;
1395 sector_num += nb_sectors;
1396 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1400 qprintf(quiet, "Images are identical.\n");
1401 ret = 0;
1403 out:
1404 qemu_vfree(buf1);
1405 qemu_vfree(buf2);
1406 blk_unref(blk2);
1407 out2:
1408 blk_unref(blk1);
1409 out3:
1410 qemu_progress_end();
1411 out4:
1412 return ret;
1415 enum ImgConvertBlockStatus {
1416 BLK_DATA,
1417 BLK_ZERO,
1418 BLK_BACKING_FILE,
1421 typedef struct ImgConvertState {
1422 BlockBackend **src;
1423 int64_t *src_sectors;
1424 int src_cur, src_num;
1425 int64_t src_cur_offset;
1426 int64_t total_sectors;
1427 int64_t allocated_sectors;
1428 enum ImgConvertBlockStatus status;
1429 int64_t sector_next_status;
1430 BlockBackend *target;
1431 bool has_zero_init;
1432 bool compressed;
1433 bool target_has_backing;
1434 int min_sparse;
1435 size_t cluster_sectors;
1436 size_t buf_sectors;
1437 } ImgConvertState;
1439 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1441 assert(sector_num >= s->src_cur_offset);
1442 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1443 s->src_cur_offset += s->src_sectors[s->src_cur];
1444 s->src_cur++;
1445 assert(s->src_cur < s->src_num);
1449 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1451 int64_t ret;
1452 int n;
1454 convert_select_part(s, sector_num);
1456 assert(s->total_sectors > sector_num);
1457 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1459 if (s->sector_next_status <= sector_num) {
1460 BlockDriverState *file;
1461 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1462 sector_num - s->src_cur_offset,
1463 n, &n, &file);
1464 if (ret < 0) {
1465 return ret;
1468 if (ret & BDRV_BLOCK_ZERO) {
1469 s->status = BLK_ZERO;
1470 } else if (ret & BDRV_BLOCK_DATA) {
1471 s->status = BLK_DATA;
1472 } else if (!s->target_has_backing) {
1473 /* Without a target backing file we must copy over the contents of
1474 * the backing file as well. */
1475 /* TODO Check block status of the backing file chain to avoid
1476 * needlessly reading zeroes and limiting the iteration to the
1477 * buffer size */
1478 s->status = BLK_DATA;
1479 } else {
1480 s->status = BLK_BACKING_FILE;
1483 s->sector_next_status = sector_num + n;
1486 n = MIN(n, s->sector_next_status - sector_num);
1487 if (s->status == BLK_DATA) {
1488 n = MIN(n, s->buf_sectors);
1491 /* We need to write complete clusters for compressed images, so if an
1492 * unallocated area is shorter than that, we must consider the whole
1493 * cluster allocated. */
1494 if (s->compressed) {
1495 if (n < s->cluster_sectors) {
1496 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1497 s->status = BLK_DATA;
1498 } else {
1499 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1503 return n;
1506 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1507 uint8_t *buf)
1509 int n;
1510 int ret;
1512 assert(nb_sectors <= s->buf_sectors);
1513 while (nb_sectors > 0) {
1514 BlockBackend *blk;
1515 int64_t bs_sectors;
1517 /* In the case of compression with multiple source files, we can get a
1518 * nb_sectors that spreads into the next part. So we must be able to
1519 * read across multiple BDSes for one convert_read() call. */
1520 convert_select_part(s, sector_num);
1521 blk = s->src[s->src_cur];
1522 bs_sectors = s->src_sectors[s->src_cur];
1524 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1525 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1526 if (ret < 0) {
1527 return ret;
1530 sector_num += n;
1531 nb_sectors -= n;
1532 buf += n * BDRV_SECTOR_SIZE;
1535 return 0;
1538 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1539 const uint8_t *buf)
1541 int ret;
1543 while (nb_sectors > 0) {
1544 int n = nb_sectors;
1546 switch (s->status) {
1547 case BLK_BACKING_FILE:
1548 /* If we have a backing file, leave clusters unallocated that are
1549 * unallocated in the source image, so that the backing file is
1550 * visible at the respective offset. */
1551 assert(s->target_has_backing);
1552 break;
1554 case BLK_DATA:
1555 /* We must always write compressed clusters as a whole, so don't
1556 * try to find zeroed parts in the buffer. We can only save the
1557 * write if the buffer is completely zeroed and we're allowed to
1558 * keep the target sparse. */
1559 if (s->compressed) {
1560 if (s->has_zero_init && s->min_sparse &&
1561 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1563 assert(!s->target_has_backing);
1564 break;
1567 ret = blk_write_compressed(s->target, sector_num, buf, n);
1568 if (ret < 0) {
1569 return ret;
1571 break;
1574 /* If there is real non-zero data or we're told to keep the target
1575 * fully allocated (-S 0), we must write it. Otherwise we can treat
1576 * it as zero sectors. */
1577 if (!s->min_sparse ||
1578 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1580 ret = blk_write(s->target, sector_num, buf, n);
1581 if (ret < 0) {
1582 return ret;
1584 break;
1586 /* fall-through */
1588 case BLK_ZERO:
1589 if (s->has_zero_init) {
1590 break;
1592 ret = blk_write_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1593 n << BDRV_SECTOR_BITS, 0);
1594 if (ret < 0) {
1595 return ret;
1597 break;
1600 sector_num += n;
1601 nb_sectors -= n;
1602 buf += n * BDRV_SECTOR_SIZE;
1605 return 0;
1608 static int convert_do_copy(ImgConvertState *s)
1610 uint8_t *buf = NULL;
1611 int64_t sector_num, allocated_done;
1612 int ret;
1613 int n;
1615 /* Check whether we have zero initialisation or can get it efficiently */
1616 s->has_zero_init = s->min_sparse && !s->target_has_backing
1617 ? bdrv_has_zero_init(blk_bs(s->target))
1618 : false;
1620 if (!s->has_zero_init && !s->target_has_backing &&
1621 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1623 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1624 if (ret == 0) {
1625 s->has_zero_init = true;
1629 /* Allocate buffer for copied data. For compressed images, only one cluster
1630 * can be copied at a time. */
1631 if (s->compressed) {
1632 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1633 error_report("invalid cluster size");
1634 ret = -EINVAL;
1635 goto fail;
1637 s->buf_sectors = s->cluster_sectors;
1639 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1641 /* Calculate allocated sectors for progress */
1642 s->allocated_sectors = 0;
1643 sector_num = 0;
1644 while (sector_num < s->total_sectors) {
1645 n = convert_iteration_sectors(s, sector_num);
1646 if (n < 0) {
1647 ret = n;
1648 goto fail;
1650 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1652 s->allocated_sectors += n;
1654 sector_num += n;
1657 /* Do the copy */
1658 s->src_cur = 0;
1659 s->src_cur_offset = 0;
1660 s->sector_next_status = 0;
1662 sector_num = 0;
1663 allocated_done = 0;
1665 while (sector_num < s->total_sectors) {
1666 n = convert_iteration_sectors(s, sector_num);
1667 if (n < 0) {
1668 ret = n;
1669 goto fail;
1671 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1673 allocated_done += n;
1674 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1678 if (s->status == BLK_DATA) {
1679 ret = convert_read(s, sector_num, n, buf);
1680 if (ret < 0) {
1681 error_report("error while reading sector %" PRId64
1682 ": %s", sector_num, strerror(-ret));
1683 goto fail;
1685 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1686 n = MIN(n, s->buf_sectors);
1687 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1688 s->status = BLK_DATA;
1691 ret = convert_write(s, sector_num, n, buf);
1692 if (ret < 0) {
1693 error_report("error while writing sector %" PRId64
1694 ": %s", sector_num, strerror(-ret));
1695 goto fail;
1698 sector_num += n;
1701 if (s->compressed) {
1702 /* signal EOF to align */
1703 ret = blk_write_compressed(s->target, 0, NULL, 0);
1704 if (ret < 0) {
1705 goto fail;
1709 ret = 0;
1710 fail:
1711 qemu_vfree(buf);
1712 return ret;
1715 static int img_convert(int argc, char **argv)
1717 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1718 int64_t ret = 0;
1719 int progress = 0, flags, src_flags;
1720 bool writethrough, src_writethrough;
1721 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1722 BlockDriver *drv, *proto_drv;
1723 BlockBackend **blk = NULL, *out_blk = NULL;
1724 BlockDriverState **bs = NULL, *out_bs = NULL;
1725 int64_t total_sectors;
1726 int64_t *bs_sectors = NULL;
1727 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1728 BlockDriverInfo bdi;
1729 QemuOpts *opts = NULL;
1730 QemuOptsList *create_opts = NULL;
1731 const char *out_baseimg_param;
1732 char *options = NULL;
1733 const char *snapshot_name = NULL;
1734 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1735 bool quiet = false;
1736 Error *local_err = NULL;
1737 QemuOpts *sn_opts = NULL;
1738 ImgConvertState state;
1739 bool image_opts = false;
1741 fmt = NULL;
1742 out_fmt = "raw";
1743 cache = "unsafe";
1744 src_cache = BDRV_DEFAULT_CACHE;
1745 out_baseimg = NULL;
1746 compress = 0;
1747 skip_create = 0;
1748 for(;;) {
1749 static const struct option long_options[] = {
1750 {"help", no_argument, 0, 'h'},
1751 {"object", required_argument, 0, OPTION_OBJECT},
1752 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1753 {0, 0, 0, 0}
1755 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1756 long_options, NULL);
1757 if (c == -1) {
1758 break;
1760 switch(c) {
1761 case '?':
1762 case 'h':
1763 help();
1764 break;
1765 case 'f':
1766 fmt = optarg;
1767 break;
1768 case 'O':
1769 out_fmt = optarg;
1770 break;
1771 case 'B':
1772 out_baseimg = optarg;
1773 break;
1774 case 'c':
1775 compress = 1;
1776 break;
1777 case 'e':
1778 error_report("option -e is deprecated, please use \'-o "
1779 "encryption\' instead!");
1780 ret = -1;
1781 goto fail_getopt;
1782 case '6':
1783 error_report("option -6 is deprecated, please use \'-o "
1784 "compat6\' instead!");
1785 ret = -1;
1786 goto fail_getopt;
1787 case 'o':
1788 if (!is_valid_option_list(optarg)) {
1789 error_report("Invalid option list: %s", optarg);
1790 ret = -1;
1791 goto fail_getopt;
1793 if (!options) {
1794 options = g_strdup(optarg);
1795 } else {
1796 char *old_options = options;
1797 options = g_strdup_printf("%s,%s", options, optarg);
1798 g_free(old_options);
1800 break;
1801 case 's':
1802 snapshot_name = optarg;
1803 break;
1804 case 'l':
1805 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1806 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1807 optarg, false);
1808 if (!sn_opts) {
1809 error_report("Failed in parsing snapshot param '%s'",
1810 optarg);
1811 ret = -1;
1812 goto fail_getopt;
1814 } else {
1815 snapshot_name = optarg;
1817 break;
1818 case 'S':
1820 int64_t sval;
1821 char *end;
1822 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1823 if (sval < 0 || *end) {
1824 error_report("Invalid minimum zero buffer size for sparse output specified");
1825 ret = -1;
1826 goto fail_getopt;
1829 min_sparse = sval / BDRV_SECTOR_SIZE;
1830 break;
1832 case 'p':
1833 progress = 1;
1834 break;
1835 case 't':
1836 cache = optarg;
1837 break;
1838 case 'T':
1839 src_cache = optarg;
1840 break;
1841 case 'q':
1842 quiet = true;
1843 break;
1844 case 'n':
1845 skip_create = 1;
1846 break;
1847 case OPTION_OBJECT:
1848 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1849 optarg, true);
1850 if (!opts) {
1851 goto fail_getopt;
1853 break;
1854 case OPTION_IMAGE_OPTS:
1855 image_opts = true;
1856 break;
1860 if (qemu_opts_foreach(&qemu_object_opts,
1861 user_creatable_add_opts_foreach,
1862 NULL, NULL)) {
1863 goto fail_getopt;
1866 /* Initialize before goto out */
1867 if (quiet) {
1868 progress = 0;
1870 qemu_progress_init(progress, 1.0);
1872 bs_n = argc - optind - 1;
1873 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1875 if (options && has_help_option(options)) {
1876 ret = print_block_option_help(out_filename, out_fmt);
1877 goto out;
1880 if (bs_n < 1) {
1881 error_exit("Must specify image file name");
1885 if (bs_n > 1 && out_baseimg) {
1886 error_report("-B makes no sense when concatenating multiple input "
1887 "images");
1888 ret = -1;
1889 goto out;
1892 src_flags = 0;
1893 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
1894 if (ret < 0) {
1895 error_report("Invalid source cache option: %s", src_cache);
1896 goto out;
1899 qemu_progress_print(0, 100);
1901 blk = g_new0(BlockBackend *, bs_n);
1902 bs = g_new0(BlockDriverState *, bs_n);
1903 bs_sectors = g_new(int64_t, bs_n);
1905 total_sectors = 0;
1906 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1907 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1908 fmt, src_flags, src_writethrough, quiet);
1909 if (!blk[bs_i]) {
1910 ret = -1;
1911 goto out;
1913 bs[bs_i] = blk_bs(blk[bs_i]);
1914 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1915 if (bs_sectors[bs_i] < 0) {
1916 error_report("Could not get size of %s: %s",
1917 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1918 ret = -1;
1919 goto out;
1921 total_sectors += bs_sectors[bs_i];
1924 if (sn_opts) {
1925 ret = bdrv_snapshot_load_tmp(bs[0],
1926 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1927 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1928 &local_err);
1929 } else if (snapshot_name != NULL) {
1930 if (bs_n > 1) {
1931 error_report("No support for concatenating multiple snapshot");
1932 ret = -1;
1933 goto out;
1936 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1938 if (local_err) {
1939 error_reportf_err(local_err, "Failed to load snapshot: ");
1940 ret = -1;
1941 goto out;
1944 /* Find driver and parse its options */
1945 drv = bdrv_find_format(out_fmt);
1946 if (!drv) {
1947 error_report("Unknown file format '%s'", out_fmt);
1948 ret = -1;
1949 goto out;
1952 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1953 if (!proto_drv) {
1954 error_report_err(local_err);
1955 ret = -1;
1956 goto out;
1959 if (!skip_create) {
1960 if (!drv->create_opts) {
1961 error_report("Format driver '%s' does not support image creation",
1962 drv->format_name);
1963 ret = -1;
1964 goto out;
1967 if (!proto_drv->create_opts) {
1968 error_report("Protocol driver '%s' does not support image creation",
1969 proto_drv->format_name);
1970 ret = -1;
1971 goto out;
1974 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1975 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1977 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1978 if (options) {
1979 qemu_opts_do_parse(opts, options, NULL, &local_err);
1980 if (local_err) {
1981 error_report_err(local_err);
1982 ret = -1;
1983 goto out;
1987 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1988 &error_abort);
1989 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1990 if (ret < 0) {
1991 goto out;
1995 /* Get backing file name if -o backing_file was used */
1996 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
1997 if (out_baseimg_param) {
1998 out_baseimg = out_baseimg_param;
2001 /* Check if compression is supported */
2002 if (compress) {
2003 bool encryption =
2004 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2005 const char *preallocation =
2006 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2008 if (!drv->bdrv_write_compressed) {
2009 error_report("Compression not supported for this file format");
2010 ret = -1;
2011 goto out;
2014 if (encryption) {
2015 error_report("Compression and encryption not supported at "
2016 "the same time");
2017 ret = -1;
2018 goto out;
2021 if (preallocation
2022 && strcmp(preallocation, "off"))
2024 error_report("Compression and preallocation not supported at "
2025 "the same time");
2026 ret = -1;
2027 goto out;
2031 if (!skip_create) {
2032 /* Create the new image */
2033 ret = bdrv_create(drv, out_filename, opts, &local_err);
2034 if (ret < 0) {
2035 error_reportf_err(local_err, "%s: error while converting %s: ",
2036 out_filename, out_fmt);
2037 goto out;
2041 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2042 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2043 if (ret < 0) {
2044 error_report("Invalid cache option: %s", cache);
2045 goto out;
2048 /* XXX we should allow --image-opts to trigger use of
2049 * img_open() here, but then we have trouble with
2050 * the bdrv_create() call which takes different params.
2051 * Not critical right now, so fix can wait...
2053 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
2054 if (!out_blk) {
2055 ret = -1;
2056 goto out;
2058 out_bs = blk_bs(out_blk);
2060 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2061 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2062 * as maximum. */
2063 bufsectors = MIN(32768,
2064 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2065 out_bs->bl.discard_alignment))
2068 if (skip_create) {
2069 int64_t output_sectors = blk_nb_sectors(out_blk);
2070 if (output_sectors < 0) {
2071 error_report("unable to get output image length: %s",
2072 strerror(-output_sectors));
2073 ret = -1;
2074 goto out;
2075 } else if (output_sectors < total_sectors) {
2076 error_report("output file is smaller than input file");
2077 ret = -1;
2078 goto out;
2082 cluster_sectors = 0;
2083 ret = bdrv_get_info(out_bs, &bdi);
2084 if (ret < 0) {
2085 if (compress) {
2086 error_report("could not get block driver info");
2087 goto out;
2089 } else {
2090 compress = compress || bdi.needs_compressed_writes;
2091 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2094 state = (ImgConvertState) {
2095 .src = blk,
2096 .src_sectors = bs_sectors,
2097 .src_num = bs_n,
2098 .total_sectors = total_sectors,
2099 .target = out_blk,
2100 .compressed = compress,
2101 .target_has_backing = (bool) out_baseimg,
2102 .min_sparse = min_sparse,
2103 .cluster_sectors = cluster_sectors,
2104 .buf_sectors = bufsectors,
2106 ret = convert_do_copy(&state);
2108 out:
2109 if (!ret) {
2110 qemu_progress_print(100, 0);
2112 qemu_progress_end();
2113 qemu_opts_del(opts);
2114 qemu_opts_free(create_opts);
2115 qemu_opts_del(sn_opts);
2116 blk_unref(out_blk);
2117 g_free(bs);
2118 if (blk) {
2119 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2120 blk_unref(blk[bs_i]);
2122 g_free(blk);
2124 g_free(bs_sectors);
2125 fail_getopt:
2126 g_free(options);
2128 if (ret) {
2129 return 1;
2131 return 0;
2135 static void dump_snapshots(BlockDriverState *bs)
2137 QEMUSnapshotInfo *sn_tab, *sn;
2138 int nb_sns, i;
2140 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2141 if (nb_sns <= 0)
2142 return;
2143 printf("Snapshot list:\n");
2144 bdrv_snapshot_dump(fprintf, stdout, NULL);
2145 printf("\n");
2146 for(i = 0; i < nb_sns; i++) {
2147 sn = &sn_tab[i];
2148 bdrv_snapshot_dump(fprintf, stdout, sn);
2149 printf("\n");
2151 g_free(sn_tab);
2154 static void dump_json_image_info_list(ImageInfoList *list)
2156 Error *local_err = NULL;
2157 QString *str;
2158 QmpOutputVisitor *ov = qmp_output_visitor_new();
2159 QObject *obj;
2160 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2161 &local_err);
2162 obj = qmp_output_get_qobject(ov);
2163 str = qobject_to_json_pretty(obj);
2164 assert(str != NULL);
2165 printf("%s\n", qstring_get_str(str));
2166 qobject_decref(obj);
2167 qmp_output_visitor_cleanup(ov);
2168 QDECREF(str);
2171 static void dump_json_image_info(ImageInfo *info)
2173 Error *local_err = NULL;
2174 QString *str;
2175 QmpOutputVisitor *ov = qmp_output_visitor_new();
2176 QObject *obj;
2177 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2178 obj = qmp_output_get_qobject(ov);
2179 str = qobject_to_json_pretty(obj);
2180 assert(str != NULL);
2181 printf("%s\n", qstring_get_str(str));
2182 qobject_decref(obj);
2183 qmp_output_visitor_cleanup(ov);
2184 QDECREF(str);
2187 static void dump_human_image_info_list(ImageInfoList *list)
2189 ImageInfoList *elem;
2190 bool delim = false;
2192 for (elem = list; elem; elem = elem->next) {
2193 if (delim) {
2194 printf("\n");
2196 delim = true;
2198 bdrv_image_info_dump(fprintf, stdout, elem->value);
2202 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2204 return strcmp(a, b) == 0;
2208 * Open an image file chain and return an ImageInfoList
2210 * @filename: topmost image filename
2211 * @fmt: topmost image format (may be NULL to autodetect)
2212 * @chain: true - enumerate entire backing file chain
2213 * false - only topmost image file
2215 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2216 * image file. If there was an error a message will have been printed to
2217 * stderr.
2219 static ImageInfoList *collect_image_info_list(bool image_opts,
2220 const char *filename,
2221 const char *fmt,
2222 bool chain)
2224 ImageInfoList *head = NULL;
2225 ImageInfoList **last = &head;
2226 GHashTable *filenames;
2227 Error *err = NULL;
2229 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2231 while (filename) {
2232 BlockBackend *blk;
2233 BlockDriverState *bs;
2234 ImageInfo *info;
2235 ImageInfoList *elem;
2237 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2238 error_report("Backing file '%s' creates an infinite loop.",
2239 filename);
2240 goto err;
2242 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2244 blk = img_open(image_opts, filename, fmt,
2245 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
2246 if (!blk) {
2247 goto err;
2249 bs = blk_bs(blk);
2251 bdrv_query_image_info(bs, &info, &err);
2252 if (err) {
2253 error_report_err(err);
2254 blk_unref(blk);
2255 goto err;
2258 elem = g_new0(ImageInfoList, 1);
2259 elem->value = info;
2260 *last = elem;
2261 last = &elem->next;
2263 blk_unref(blk);
2265 filename = fmt = NULL;
2266 if (chain) {
2267 if (info->has_full_backing_filename) {
2268 filename = info->full_backing_filename;
2269 } else if (info->has_backing_filename) {
2270 error_report("Could not determine absolute backing filename,"
2271 " but backing filename '%s' present",
2272 info->backing_filename);
2273 goto err;
2275 if (info->has_backing_filename_format) {
2276 fmt = info->backing_filename_format;
2280 g_hash_table_destroy(filenames);
2281 return head;
2283 err:
2284 qapi_free_ImageInfoList(head);
2285 g_hash_table_destroy(filenames);
2286 return NULL;
2289 static int img_info(int argc, char **argv)
2291 int c;
2292 OutputFormat output_format = OFORMAT_HUMAN;
2293 bool chain = false;
2294 const char *filename, *fmt, *output;
2295 ImageInfoList *list;
2296 bool image_opts = false;
2298 fmt = NULL;
2299 output = NULL;
2300 for(;;) {
2301 int option_index = 0;
2302 static const struct option long_options[] = {
2303 {"help", no_argument, 0, 'h'},
2304 {"format", required_argument, 0, 'f'},
2305 {"output", required_argument, 0, OPTION_OUTPUT},
2306 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2307 {"object", required_argument, 0, OPTION_OBJECT},
2308 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2309 {0, 0, 0, 0}
2311 c = getopt_long(argc, argv, "f:h",
2312 long_options, &option_index);
2313 if (c == -1) {
2314 break;
2316 switch(c) {
2317 case '?':
2318 case 'h':
2319 help();
2320 break;
2321 case 'f':
2322 fmt = optarg;
2323 break;
2324 case OPTION_OUTPUT:
2325 output = optarg;
2326 break;
2327 case OPTION_BACKING_CHAIN:
2328 chain = true;
2329 break;
2330 case OPTION_OBJECT: {
2331 QemuOpts *opts;
2332 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2333 optarg, true);
2334 if (!opts) {
2335 return 1;
2337 } break;
2338 case OPTION_IMAGE_OPTS:
2339 image_opts = true;
2340 break;
2343 if (optind != argc - 1) {
2344 error_exit("Expecting one image file name");
2346 filename = argv[optind++];
2348 if (output && !strcmp(output, "json")) {
2349 output_format = OFORMAT_JSON;
2350 } else if (output && !strcmp(output, "human")) {
2351 output_format = OFORMAT_HUMAN;
2352 } else if (output) {
2353 error_report("--output must be used with human or json as argument.");
2354 return 1;
2357 if (qemu_opts_foreach(&qemu_object_opts,
2358 user_creatable_add_opts_foreach,
2359 NULL, NULL)) {
2360 return 1;
2363 list = collect_image_info_list(image_opts, filename, fmt, chain);
2364 if (!list) {
2365 return 1;
2368 switch (output_format) {
2369 case OFORMAT_HUMAN:
2370 dump_human_image_info_list(list);
2371 break;
2372 case OFORMAT_JSON:
2373 if (chain) {
2374 dump_json_image_info_list(list);
2375 } else {
2376 dump_json_image_info(list->value);
2378 break;
2381 qapi_free_ImageInfoList(list);
2382 return 0;
2385 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2386 MapEntry *next)
2388 switch (output_format) {
2389 case OFORMAT_HUMAN:
2390 if (e->data && !e->has_offset) {
2391 error_report("File contains external, encrypted or compressed clusters.");
2392 exit(1);
2394 if (e->data && !e->zero) {
2395 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2396 e->start, e->length,
2397 e->has_offset ? e->offset : 0,
2398 e->has_filename ? e->filename : "");
2400 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2401 * Modify the flags here to allow more coalescing.
2403 if (next && (!next->data || next->zero)) {
2404 next->data = false;
2405 next->zero = true;
2407 break;
2408 case OFORMAT_JSON:
2409 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2410 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2411 (e->start == 0 ? "[" : ",\n"),
2412 e->start, e->length, e->depth,
2413 e->zero ? "true" : "false",
2414 e->data ? "true" : "false");
2415 if (e->has_offset) {
2416 printf(", \"offset\": %"PRId64"", e->offset);
2418 putchar('}');
2420 if (!next) {
2421 printf("]\n");
2423 break;
2427 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2428 int nb_sectors, MapEntry *e)
2430 int64_t ret;
2431 int depth;
2432 BlockDriverState *file;
2433 bool has_offset;
2435 /* As an optimization, we could cache the current range of unallocated
2436 * clusters in each file of the chain, and avoid querying the same
2437 * range repeatedly.
2440 depth = 0;
2441 for (;;) {
2442 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2443 &file);
2444 if (ret < 0) {
2445 return ret;
2447 assert(nb_sectors);
2448 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2449 break;
2451 bs = backing_bs(bs);
2452 if (bs == NULL) {
2453 ret = 0;
2454 break;
2457 depth++;
2460 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2462 *e = (MapEntry) {
2463 .start = sector_num * BDRV_SECTOR_SIZE,
2464 .length = nb_sectors * BDRV_SECTOR_SIZE,
2465 .data = !!(ret & BDRV_BLOCK_DATA),
2466 .zero = !!(ret & BDRV_BLOCK_ZERO),
2467 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2468 .has_offset = has_offset,
2469 .depth = depth,
2470 .has_filename = file && has_offset,
2471 .filename = file && has_offset ? file->filename : NULL,
2474 return 0;
2477 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2479 if (curr->length == 0) {
2480 return false;
2482 if (curr->zero != next->zero ||
2483 curr->data != next->data ||
2484 curr->depth != next->depth ||
2485 curr->has_filename != next->has_filename ||
2486 curr->has_offset != next->has_offset) {
2487 return false;
2489 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2490 return false;
2492 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2493 return false;
2495 return true;
2498 static int img_map(int argc, char **argv)
2500 int c;
2501 OutputFormat output_format = OFORMAT_HUMAN;
2502 BlockBackend *blk;
2503 BlockDriverState *bs;
2504 const char *filename, *fmt, *output;
2505 int64_t length;
2506 MapEntry curr = { .length = 0 }, next;
2507 int ret = 0;
2508 bool image_opts = false;
2510 fmt = NULL;
2511 output = NULL;
2512 for (;;) {
2513 int option_index = 0;
2514 static const struct option long_options[] = {
2515 {"help", no_argument, 0, 'h'},
2516 {"format", required_argument, 0, 'f'},
2517 {"output", required_argument, 0, OPTION_OUTPUT},
2518 {"object", required_argument, 0, OPTION_OBJECT},
2519 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2520 {0, 0, 0, 0}
2522 c = getopt_long(argc, argv, "f:h",
2523 long_options, &option_index);
2524 if (c == -1) {
2525 break;
2527 switch (c) {
2528 case '?':
2529 case 'h':
2530 help();
2531 break;
2532 case 'f':
2533 fmt = optarg;
2534 break;
2535 case OPTION_OUTPUT:
2536 output = optarg;
2537 break;
2538 case OPTION_OBJECT: {
2539 QemuOpts *opts;
2540 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2541 optarg, true);
2542 if (!opts) {
2543 return 1;
2545 } break;
2546 case OPTION_IMAGE_OPTS:
2547 image_opts = true;
2548 break;
2551 if (optind != argc - 1) {
2552 error_exit("Expecting one image file name");
2554 filename = argv[optind];
2556 if (output && !strcmp(output, "json")) {
2557 output_format = OFORMAT_JSON;
2558 } else if (output && !strcmp(output, "human")) {
2559 output_format = OFORMAT_HUMAN;
2560 } else if (output) {
2561 error_report("--output must be used with human or json as argument.");
2562 return 1;
2565 if (qemu_opts_foreach(&qemu_object_opts,
2566 user_creatable_add_opts_foreach,
2567 NULL, NULL)) {
2568 return 1;
2571 blk = img_open(image_opts, filename, fmt, 0, false, false);
2572 if (!blk) {
2573 return 1;
2575 bs = blk_bs(blk);
2577 if (output_format == OFORMAT_HUMAN) {
2578 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2581 length = blk_getlength(blk);
2582 while (curr.start + curr.length < length) {
2583 int64_t nsectors_left;
2584 int64_t sector_num;
2585 int n;
2587 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2589 /* Probe up to 1 GiB at a time. */
2590 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2591 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2592 ret = get_block_status(bs, sector_num, n, &next);
2594 if (ret < 0) {
2595 error_report("Could not read file metadata: %s", strerror(-ret));
2596 goto out;
2599 if (entry_mergeable(&curr, &next)) {
2600 curr.length += next.length;
2601 continue;
2604 if (curr.length > 0) {
2605 dump_map_entry(output_format, &curr, &next);
2607 curr = next;
2610 dump_map_entry(output_format, &curr, NULL);
2612 out:
2613 blk_unref(blk);
2614 return ret < 0;
2617 #define SNAPSHOT_LIST 1
2618 #define SNAPSHOT_CREATE 2
2619 #define SNAPSHOT_APPLY 3
2620 #define SNAPSHOT_DELETE 4
2622 static int img_snapshot(int argc, char **argv)
2624 BlockBackend *blk;
2625 BlockDriverState *bs;
2626 QEMUSnapshotInfo sn;
2627 char *filename, *snapshot_name = NULL;
2628 int c, ret = 0, bdrv_oflags;
2629 int action = 0;
2630 qemu_timeval tv;
2631 bool quiet = false;
2632 Error *err = NULL;
2633 bool image_opts = false;
2635 bdrv_oflags = BDRV_O_RDWR;
2636 /* Parse commandline parameters */
2637 for(;;) {
2638 static const struct option long_options[] = {
2639 {"help", no_argument, 0, 'h'},
2640 {"object", required_argument, 0, OPTION_OBJECT},
2641 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2642 {0, 0, 0, 0}
2644 c = getopt_long(argc, argv, "la:c:d:hq",
2645 long_options, NULL);
2646 if (c == -1) {
2647 break;
2649 switch(c) {
2650 case '?':
2651 case 'h':
2652 help();
2653 return 0;
2654 case 'l':
2655 if (action) {
2656 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2657 return 0;
2659 action = SNAPSHOT_LIST;
2660 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2661 break;
2662 case 'a':
2663 if (action) {
2664 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2665 return 0;
2667 action = SNAPSHOT_APPLY;
2668 snapshot_name = optarg;
2669 break;
2670 case 'c':
2671 if (action) {
2672 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2673 return 0;
2675 action = SNAPSHOT_CREATE;
2676 snapshot_name = optarg;
2677 break;
2678 case 'd':
2679 if (action) {
2680 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2681 return 0;
2683 action = SNAPSHOT_DELETE;
2684 snapshot_name = optarg;
2685 break;
2686 case 'q':
2687 quiet = true;
2688 break;
2689 case OPTION_OBJECT: {
2690 QemuOpts *opts;
2691 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2692 optarg, true);
2693 if (!opts) {
2694 return 1;
2696 } break;
2697 case OPTION_IMAGE_OPTS:
2698 image_opts = true;
2699 break;
2703 if (optind != argc - 1) {
2704 error_exit("Expecting one image file name");
2706 filename = argv[optind++];
2708 if (qemu_opts_foreach(&qemu_object_opts,
2709 user_creatable_add_opts_foreach,
2710 NULL, NULL)) {
2711 return 1;
2714 /* Open the image */
2715 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
2716 if (!blk) {
2717 return 1;
2719 bs = blk_bs(blk);
2721 /* Perform the requested action */
2722 switch(action) {
2723 case SNAPSHOT_LIST:
2724 dump_snapshots(bs);
2725 break;
2727 case SNAPSHOT_CREATE:
2728 memset(&sn, 0, sizeof(sn));
2729 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2731 qemu_gettimeofday(&tv);
2732 sn.date_sec = tv.tv_sec;
2733 sn.date_nsec = tv.tv_usec * 1000;
2735 ret = bdrv_snapshot_create(bs, &sn);
2736 if (ret) {
2737 error_report("Could not create snapshot '%s': %d (%s)",
2738 snapshot_name, ret, strerror(-ret));
2740 break;
2742 case SNAPSHOT_APPLY:
2743 ret = bdrv_snapshot_goto(bs, snapshot_name);
2744 if (ret) {
2745 error_report("Could not apply snapshot '%s': %d (%s)",
2746 snapshot_name, ret, strerror(-ret));
2748 break;
2750 case SNAPSHOT_DELETE:
2751 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2752 if (err) {
2753 error_reportf_err(err, "Could not delete snapshot '%s': ",
2754 snapshot_name);
2755 ret = 1;
2757 break;
2760 /* Cleanup */
2761 blk_unref(blk);
2762 if (ret) {
2763 return 1;
2765 return 0;
2768 static int img_rebase(int argc, char **argv)
2770 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2771 uint8_t *buf_old = NULL;
2772 uint8_t *buf_new = NULL;
2773 BlockDriverState *bs = NULL;
2774 char *filename;
2775 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2776 int c, flags, src_flags, ret;
2777 bool writethrough, src_writethrough;
2778 int unsafe = 0;
2779 int progress = 0;
2780 bool quiet = false;
2781 Error *local_err = NULL;
2782 bool image_opts = false;
2784 /* Parse commandline parameters */
2785 fmt = NULL;
2786 cache = BDRV_DEFAULT_CACHE;
2787 src_cache = BDRV_DEFAULT_CACHE;
2788 out_baseimg = NULL;
2789 out_basefmt = NULL;
2790 for(;;) {
2791 static const struct option long_options[] = {
2792 {"help", no_argument, 0, 'h'},
2793 {"object", required_argument, 0, OPTION_OBJECT},
2794 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2795 {0, 0, 0, 0}
2797 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2798 long_options, NULL);
2799 if (c == -1) {
2800 break;
2802 switch(c) {
2803 case '?':
2804 case 'h':
2805 help();
2806 return 0;
2807 case 'f':
2808 fmt = optarg;
2809 break;
2810 case 'F':
2811 out_basefmt = optarg;
2812 break;
2813 case 'b':
2814 out_baseimg = optarg;
2815 break;
2816 case 'u':
2817 unsafe = 1;
2818 break;
2819 case 'p':
2820 progress = 1;
2821 break;
2822 case 't':
2823 cache = optarg;
2824 break;
2825 case 'T':
2826 src_cache = optarg;
2827 break;
2828 case 'q':
2829 quiet = true;
2830 break;
2831 case OPTION_OBJECT: {
2832 QemuOpts *opts;
2833 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2834 optarg, true);
2835 if (!opts) {
2836 return 1;
2838 } break;
2839 case OPTION_IMAGE_OPTS:
2840 image_opts = true;
2841 break;
2845 if (quiet) {
2846 progress = 0;
2849 if (optind != argc - 1) {
2850 error_exit("Expecting one image file name");
2852 if (!unsafe && !out_baseimg) {
2853 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2855 filename = argv[optind++];
2857 if (qemu_opts_foreach(&qemu_object_opts,
2858 user_creatable_add_opts_foreach,
2859 NULL, NULL)) {
2860 return 1;
2863 qemu_progress_init(progress, 2.0);
2864 qemu_progress_print(0, 100);
2866 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2867 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2868 if (ret < 0) {
2869 error_report("Invalid cache option: %s", cache);
2870 goto out;
2873 src_flags = 0;
2874 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2875 if (ret < 0) {
2876 error_report("Invalid source cache option: %s", src_cache);
2877 goto out;
2880 /* The source files are opened read-only, don't care about WCE */
2881 assert((src_flags & BDRV_O_RDWR) == 0);
2882 (void) src_writethrough;
2885 * Open the images.
2887 * Ignore the old backing file for unsafe rebase in case we want to correct
2888 * the reference to a renamed or moved backing file.
2890 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
2891 if (!blk) {
2892 ret = -1;
2893 goto out;
2895 bs = blk_bs(blk);
2897 if (out_basefmt != NULL) {
2898 if (bdrv_find_format(out_basefmt) == NULL) {
2899 error_report("Invalid format name: '%s'", out_basefmt);
2900 ret = -1;
2901 goto out;
2905 /* For safe rebasing we need to compare old and new backing file */
2906 if (!unsafe) {
2907 char backing_name[PATH_MAX];
2908 QDict *options = NULL;
2910 if (bs->backing_format[0] != '\0') {
2911 options = qdict_new();
2912 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2915 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2916 blk_old_backing = blk_new_open(backing_name, NULL,
2917 options, src_flags, &local_err);
2918 if (!blk_old_backing) {
2919 error_reportf_err(local_err,
2920 "Could not open old backing file '%s': ",
2921 backing_name);
2922 goto out;
2925 if (out_baseimg[0]) {
2926 if (out_basefmt) {
2927 options = qdict_new();
2928 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2929 } else {
2930 options = NULL;
2933 blk_new_backing = blk_new_open(out_baseimg, NULL,
2934 options, src_flags, &local_err);
2935 if (!blk_new_backing) {
2936 error_reportf_err(local_err,
2937 "Could not open new backing file '%s': ",
2938 out_baseimg);
2939 goto out;
2945 * Check each unallocated cluster in the COW file. If it is unallocated,
2946 * accesses go to the backing file. We must therefore compare this cluster
2947 * in the old and new backing file, and if they differ we need to copy it
2948 * from the old backing file into the COW file.
2950 * If qemu-img crashes during this step, no harm is done. The content of
2951 * the image is the same as the original one at any time.
2953 if (!unsafe) {
2954 int64_t num_sectors;
2955 int64_t old_backing_num_sectors;
2956 int64_t new_backing_num_sectors = 0;
2957 uint64_t sector;
2958 int n;
2959 float local_progress = 0;
2961 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2962 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2964 num_sectors = blk_nb_sectors(blk);
2965 if (num_sectors < 0) {
2966 error_report("Could not get size of '%s': %s",
2967 filename, strerror(-num_sectors));
2968 ret = -1;
2969 goto out;
2971 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2972 if (old_backing_num_sectors < 0) {
2973 char backing_name[PATH_MAX];
2975 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2976 error_report("Could not get size of '%s': %s",
2977 backing_name, strerror(-old_backing_num_sectors));
2978 ret = -1;
2979 goto out;
2981 if (blk_new_backing) {
2982 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
2983 if (new_backing_num_sectors < 0) {
2984 error_report("Could not get size of '%s': %s",
2985 out_baseimg, strerror(-new_backing_num_sectors));
2986 ret = -1;
2987 goto out;
2991 if (num_sectors != 0) {
2992 local_progress = (float)100 /
2993 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2996 for (sector = 0; sector < num_sectors; sector += n) {
2998 /* How many sectors can we handle with the next read? */
2999 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3000 n = (IO_BUF_SIZE / 512);
3001 } else {
3002 n = num_sectors - sector;
3005 /* If the cluster is allocated, we don't need to take action */
3006 ret = bdrv_is_allocated(bs, sector, n, &n);
3007 if (ret < 0) {
3008 error_report("error while reading image metadata: %s",
3009 strerror(-ret));
3010 goto out;
3012 if (ret) {
3013 continue;
3017 * Read old and new backing file and take into consideration that
3018 * backing files may be smaller than the COW image.
3020 if (sector >= old_backing_num_sectors) {
3021 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3022 } else {
3023 if (sector + n > old_backing_num_sectors) {
3024 n = old_backing_num_sectors - sector;
3027 ret = blk_read(blk_old_backing, sector, buf_old, n);
3028 if (ret < 0) {
3029 error_report("error while reading from old backing file");
3030 goto out;
3034 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3035 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3036 } else {
3037 if (sector + n > new_backing_num_sectors) {
3038 n = new_backing_num_sectors - sector;
3041 ret = blk_read(blk_new_backing, sector, buf_new, n);
3042 if (ret < 0) {
3043 error_report("error while reading from new backing file");
3044 goto out;
3048 /* If they differ, we need to write to the COW file */
3049 uint64_t written = 0;
3051 while (written < n) {
3052 int pnum;
3054 if (compare_sectors(buf_old + written * 512,
3055 buf_new + written * 512, n - written, &pnum))
3057 ret = blk_write(blk, sector + written,
3058 buf_old + written * 512, pnum);
3059 if (ret < 0) {
3060 error_report("Error while writing to COW image: %s",
3061 strerror(-ret));
3062 goto out;
3066 written += pnum;
3068 qemu_progress_print(local_progress, 100);
3073 * Change the backing file. All clusters that are different from the old
3074 * backing file are overwritten in the COW file now, so the visible content
3075 * doesn't change when we switch the backing file.
3077 if (out_baseimg && *out_baseimg) {
3078 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3079 } else {
3080 ret = bdrv_change_backing_file(bs, NULL, NULL);
3083 if (ret == -ENOSPC) {
3084 error_report("Could not change the backing file to '%s': No "
3085 "space left in the file header", out_baseimg);
3086 } else if (ret < 0) {
3087 error_report("Could not change the backing file to '%s': %s",
3088 out_baseimg, strerror(-ret));
3091 qemu_progress_print(100, 0);
3093 * TODO At this point it is possible to check if any clusters that are
3094 * allocated in the COW file are the same in the backing file. If so, they
3095 * could be dropped from the COW file. Don't do this before switching the
3096 * backing file, in case of a crash this would lead to corruption.
3098 out:
3099 qemu_progress_end();
3100 /* Cleanup */
3101 if (!unsafe) {
3102 blk_unref(blk_old_backing);
3103 blk_unref(blk_new_backing);
3105 qemu_vfree(buf_old);
3106 qemu_vfree(buf_new);
3108 blk_unref(blk);
3109 if (ret) {
3110 return 1;
3112 return 0;
3115 static int img_resize(int argc, char **argv)
3117 Error *err = NULL;
3118 int c, ret, relative;
3119 const char *filename, *fmt, *size;
3120 int64_t n, total_size;
3121 bool quiet = false;
3122 BlockBackend *blk = NULL;
3123 QemuOpts *param;
3125 static QemuOptsList resize_options = {
3126 .name = "resize_options",
3127 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3128 .desc = {
3130 .name = BLOCK_OPT_SIZE,
3131 .type = QEMU_OPT_SIZE,
3132 .help = "Virtual disk size"
3133 }, {
3134 /* end of list */
3138 bool image_opts = false;
3140 /* Remove size from argv manually so that negative numbers are not treated
3141 * as options by getopt. */
3142 if (argc < 3) {
3143 error_exit("Not enough arguments");
3144 return 1;
3147 size = argv[--argc];
3149 /* Parse getopt arguments */
3150 fmt = NULL;
3151 for(;;) {
3152 static const struct option long_options[] = {
3153 {"help", no_argument, 0, 'h'},
3154 {"object", required_argument, 0, OPTION_OBJECT},
3155 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3156 {0, 0, 0, 0}
3158 c = getopt_long(argc, argv, "f:hq",
3159 long_options, NULL);
3160 if (c == -1) {
3161 break;
3163 switch(c) {
3164 case '?':
3165 case 'h':
3166 help();
3167 break;
3168 case 'f':
3169 fmt = optarg;
3170 break;
3171 case 'q':
3172 quiet = true;
3173 break;
3174 case OPTION_OBJECT: {
3175 QemuOpts *opts;
3176 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3177 optarg, true);
3178 if (!opts) {
3179 return 1;
3181 } break;
3182 case OPTION_IMAGE_OPTS:
3183 image_opts = true;
3184 break;
3187 if (optind != argc - 1) {
3188 error_exit("Expecting one image file name");
3190 filename = argv[optind++];
3192 if (qemu_opts_foreach(&qemu_object_opts,
3193 user_creatable_add_opts_foreach,
3194 NULL, NULL)) {
3195 return 1;
3198 /* Choose grow, shrink, or absolute resize mode */
3199 switch (size[0]) {
3200 case '+':
3201 relative = 1;
3202 size++;
3203 break;
3204 case '-':
3205 relative = -1;
3206 size++;
3207 break;
3208 default:
3209 relative = 0;
3210 break;
3213 /* Parse size */
3214 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3215 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3216 if (err) {
3217 error_report_err(err);
3218 ret = -1;
3219 qemu_opts_del(param);
3220 goto out;
3222 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3223 qemu_opts_del(param);
3225 blk = img_open(image_opts, filename, fmt,
3226 BDRV_O_RDWR, false, quiet);
3227 if (!blk) {
3228 ret = -1;
3229 goto out;
3232 if (relative) {
3233 total_size = blk_getlength(blk) + n * relative;
3234 } else {
3235 total_size = n;
3237 if (total_size <= 0) {
3238 error_report("New image size must be positive");
3239 ret = -1;
3240 goto out;
3243 ret = blk_truncate(blk, total_size);
3244 switch (ret) {
3245 case 0:
3246 qprintf(quiet, "Image resized.\n");
3247 break;
3248 case -ENOTSUP:
3249 error_report("This image does not support resize");
3250 break;
3251 case -EACCES:
3252 error_report("Image is read-only");
3253 break;
3254 default:
3255 error_report("Error resizing image (%d)", -ret);
3256 break;
3258 out:
3259 blk_unref(blk);
3260 if (ret) {
3261 return 1;
3263 return 0;
3266 static void amend_status_cb(BlockDriverState *bs,
3267 int64_t offset, int64_t total_work_size,
3268 void *opaque)
3270 qemu_progress_print(100.f * offset / total_work_size, 0);
3273 static int img_amend(int argc, char **argv)
3275 Error *err = NULL;
3276 int c, ret = 0;
3277 char *options = NULL;
3278 QemuOptsList *create_opts = NULL;
3279 QemuOpts *opts = NULL;
3280 const char *fmt = NULL, *filename, *cache;
3281 int flags;
3282 bool writethrough;
3283 bool quiet = false, progress = false;
3284 BlockBackend *blk = NULL;
3285 BlockDriverState *bs = NULL;
3286 bool image_opts = false;
3288 cache = BDRV_DEFAULT_CACHE;
3289 for (;;) {
3290 static const struct option long_options[] = {
3291 {"help", no_argument, 0, 'h'},
3292 {"object", required_argument, 0, OPTION_OBJECT},
3293 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3294 {0, 0, 0, 0}
3296 c = getopt_long(argc, argv, "ho:f:t:pq",
3297 long_options, NULL);
3298 if (c == -1) {
3299 break;
3302 switch (c) {
3303 case 'h':
3304 case '?':
3305 help();
3306 break;
3307 case 'o':
3308 if (!is_valid_option_list(optarg)) {
3309 error_report("Invalid option list: %s", optarg);
3310 ret = -1;
3311 goto out_no_progress;
3313 if (!options) {
3314 options = g_strdup(optarg);
3315 } else {
3316 char *old_options = options;
3317 options = g_strdup_printf("%s,%s", options, optarg);
3318 g_free(old_options);
3320 break;
3321 case 'f':
3322 fmt = optarg;
3323 break;
3324 case 't':
3325 cache = optarg;
3326 break;
3327 case 'p':
3328 progress = true;
3329 break;
3330 case 'q':
3331 quiet = true;
3332 break;
3333 case OPTION_OBJECT:
3334 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3335 optarg, true);
3336 if (!opts) {
3337 ret = -1;
3338 goto out_no_progress;
3340 break;
3341 case OPTION_IMAGE_OPTS:
3342 image_opts = true;
3343 break;
3347 if (!options) {
3348 error_exit("Must specify options (-o)");
3351 if (qemu_opts_foreach(&qemu_object_opts,
3352 user_creatable_add_opts_foreach,
3353 NULL, NULL)) {
3354 ret = -1;
3355 goto out_no_progress;
3358 if (quiet) {
3359 progress = false;
3361 qemu_progress_init(progress, 1.0);
3363 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3364 if (fmt && has_help_option(options)) {
3365 /* If a format is explicitly specified (and possibly no filename is
3366 * given), print option help here */
3367 ret = print_block_option_help(filename, fmt);
3368 goto out;
3371 if (optind != argc - 1) {
3372 error_report("Expecting one image file name");
3373 ret = -1;
3374 goto out;
3377 flags = BDRV_O_RDWR;
3378 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3379 if (ret < 0) {
3380 error_report("Invalid cache option: %s", cache);
3381 goto out;
3384 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3385 if (!blk) {
3386 ret = -1;
3387 goto out;
3389 bs = blk_bs(blk);
3391 fmt = bs->drv->format_name;
3393 if (has_help_option(options)) {
3394 /* If the format was auto-detected, print option help here */
3395 ret = print_block_option_help(filename, fmt);
3396 goto out;
3399 if (!bs->drv->create_opts) {
3400 error_report("Format driver '%s' does not support any options to amend",
3401 fmt);
3402 ret = -1;
3403 goto out;
3406 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3407 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3408 if (options) {
3409 qemu_opts_do_parse(opts, options, NULL, &err);
3410 if (err) {
3411 error_report_err(err);
3412 ret = -1;
3413 goto out;
3417 /* In case the driver does not call amend_status_cb() */
3418 qemu_progress_print(0.f, 0);
3419 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3420 qemu_progress_print(100.f, 0);
3421 if (ret < 0) {
3422 error_report("Error while amending options: %s", strerror(-ret));
3423 goto out;
3426 out:
3427 qemu_progress_end();
3429 out_no_progress:
3430 blk_unref(blk);
3431 qemu_opts_del(opts);
3432 qemu_opts_free(create_opts);
3433 g_free(options);
3435 if (ret) {
3436 return 1;
3438 return 0;
3441 static const img_cmd_t img_cmds[] = {
3442 #define DEF(option, callback, arg_string) \
3443 { option, callback },
3444 #include "qemu-img-cmds.h"
3445 #undef DEF
3446 #undef GEN_DOCS
3447 { NULL, NULL, },
3450 int main(int argc, char **argv)
3452 const img_cmd_t *cmd;
3453 const char *cmdname;
3454 Error *local_error = NULL;
3455 int c;
3456 static const struct option long_options[] = {
3457 {"help", no_argument, 0, 'h'},
3458 {"version", no_argument, 0, 'v'},
3459 {0, 0, 0, 0}
3462 #ifdef CONFIG_POSIX
3463 signal(SIGPIPE, SIG_IGN);
3464 #endif
3466 error_set_progname(argv[0]);
3467 qemu_init_exec_dir(argv[0]);
3469 if (qemu_init_main_loop(&local_error)) {
3470 error_report_err(local_error);
3471 exit(EXIT_FAILURE);
3474 if (qcrypto_init(&local_error) < 0) {
3475 error_reportf_err(local_error, "cannot initialize crypto: ");
3476 exit(1);
3479 module_call_init(MODULE_INIT_QOM);
3480 bdrv_init();
3481 if (argc < 2) {
3482 error_exit("Not enough arguments");
3484 cmdname = argv[1];
3486 qemu_add_opts(&qemu_object_opts);
3487 qemu_add_opts(&qemu_source_opts);
3489 /* find the command */
3490 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3491 if (!strcmp(cmdname, cmd->name)) {
3492 return cmd->handler(argc - 1, argv + 1);
3496 c = getopt_long(argc, argv, "h", long_options, NULL);
3498 if (c == 'h') {
3499 help();
3501 if (c == 'v') {
3502 printf(QEMU_IMG_VERSION);
3503 return 0;
3506 /* not found */
3507 error_exit("Command not found: %s", cmdname);