tpm: use loop iterator to set sts data field
[qemu/ar7.git] / qemu-img.c
blob13a6ca31b402ea50f036cb5db57bd8412a8caee2
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.
25 #include "qemu/osdep.h"
26 #include <getopt.h>
28 #include "qemu-version.h"
29 #include "qapi/error.h"
30 #include "qapi/qapi-visit-block-core.h"
31 #include "qapi/qobject-output-visitor.h"
32 #include "qapi/qmp/qjson.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qemu/cutils.h"
36 #include "qemu/config-file.h"
37 #include "qemu/option.h"
38 #include "qemu/error-report.h"
39 #include "qemu/log.h"
40 #include "qom/object_interfaces.h"
41 #include "sysemu/sysemu.h"
42 #include "sysemu/block-backend.h"
43 #include "block/block_int.h"
44 #include "block/blockjob.h"
45 #include "block/qapi.h"
46 #include "crypto/init.h"
47 #include "trace/control.h"
49 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
50 "\n" QEMU_COPYRIGHT "\n"
52 typedef struct img_cmd_t {
53 const char *name;
54 int (*handler)(int argc, char **argv);
55 } img_cmd_t;
57 enum {
58 OPTION_OUTPUT = 256,
59 OPTION_BACKING_CHAIN = 257,
60 OPTION_OBJECT = 258,
61 OPTION_IMAGE_OPTS = 259,
62 OPTION_PATTERN = 260,
63 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
65 OPTION_TARGET_IMAGE_OPTS = 263,
66 OPTION_SIZE = 264,
67 OPTION_PREALLOCATION = 265,
68 OPTION_SHRINK = 266,
71 typedef enum OutputFormat {
72 OFORMAT_JSON,
73 OFORMAT_HUMAN,
74 } OutputFormat;
76 /* Default to cache=writeback as data integrity is not important for qemu-img */
77 #define BDRV_DEFAULT_CACHE "writeback"
79 static void format_print(void *opaque, const char *name)
81 printf(" %s", name);
84 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
86 va_list ap;
88 error_printf("qemu-img: ");
90 va_start(ap, fmt);
91 error_vprintf(fmt, ap);
92 va_end(ap);
94 error_printf("\nTry 'qemu-img --help' for more information\n");
95 exit(EXIT_FAILURE);
98 static void QEMU_NORETURN missing_argument(const char *option)
100 error_exit("missing argument for option '%s'", option);
103 static void QEMU_NORETURN unrecognized_option(const char *option)
105 error_exit("unrecognized option '%s'", option);
108 /* Please keep in synch with qemu-img.texi */
109 static void QEMU_NORETURN help(void)
111 const char *help_msg =
112 QEMU_IMG_VERSION
113 "usage: qemu-img [standard options] command [command options]\n"
114 "QEMU disk image utility\n"
115 "\n"
116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
120 "\n"
121 "Command syntax:\n"
122 #define DEF(option, callback, arg_string) \
123 " " arg_string "\n"
124 #include "qemu-img-cmds.h"
125 #undef DEF
126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
139 " 'size' is the disk image size in bytes. Optional suffixes\n"
140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
151 " '-c' indicates that target image must be compressed (qcow format only)\n"
152 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
153 " new backing file match exactly. The image doesn't need a working\n"
154 " backing file before rebasing in this case (useful for renaming the\n"
155 " backing file). For image creation, allow creating without attempting\n"
156 " to open the backing file.\n"
157 " '-h' with or without a command shows this help and lists the supported formats\n"
158 " '-p' show progress of command (only certain commands)\n"
159 " '-q' use Quiet mode - do not print any output (except errors)\n"
160 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
161 " contain only zeros for qemu-img to create a sparse image during\n"
162 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
163 " unallocated or zero sectors, and the destination image will always be\n"
164 " fully allocated\n"
165 " '--output' takes the format in which the output must be done (human or json)\n"
166 " '-n' skips the target volume creation (useful if the volume is created\n"
167 " prior to running qemu-img)\n"
168 "\n"
169 "Parameters to check subcommand:\n"
170 " '-r' tries to repair any inconsistencies that are found during the check.\n"
171 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
172 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
173 " hiding corruption that has already occurred.\n"
174 "\n"
175 "Parameters to convert subcommand:\n"
176 " '-m' specifies how many coroutines work in parallel during the convert\n"
177 " process (defaults to 8)\n"
178 " '-W' allow to write to the target out of order rather than sequential\n"
179 "\n"
180 "Parameters to snapshot subcommand:\n"
181 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
182 " '-a' applies a snapshot (revert disk to saved state)\n"
183 " '-c' creates a snapshot\n"
184 " '-d' deletes a snapshot\n"
185 " '-l' lists all snapshots in the given image\n"
186 "\n"
187 "Parameters to compare subcommand:\n"
188 " '-f' first image format\n"
189 " '-F' second image format\n"
190 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
191 "\n"
192 "Parameters to dd subcommand:\n"
193 " 'bs=BYTES' read and write up to BYTES bytes at a time "
194 "(default: 512)\n"
195 " 'count=N' copy only N input blocks\n"
196 " 'if=FILE' read from FILE\n"
197 " 'of=FILE' write to FILE\n"
198 " 'skip=N' skip N bs-sized blocks at the start of input\n";
200 printf("%s\nSupported formats:", help_msg);
201 bdrv_iterate_format(format_print, NULL);
202 printf("\n\n" QEMU_HELP_BOTTOM "\n");
203 exit(EXIT_SUCCESS);
206 static QemuOptsList qemu_object_opts = {
207 .name = "object",
208 .implied_opt_name = "qom-type",
209 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
210 .desc = {
215 static QemuOptsList qemu_source_opts = {
216 .name = "source",
217 .implied_opt_name = "file",
218 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
219 .desc = {
224 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
226 int ret = 0;
227 if (!quiet) {
228 va_list args;
229 va_start(args, fmt);
230 ret = vprintf(fmt, args);
231 va_end(args);
233 return ret;
237 static int print_block_option_help(const char *filename, const char *fmt)
239 BlockDriver *drv, *proto_drv;
240 QemuOptsList *create_opts = NULL;
241 Error *local_err = NULL;
243 /* Find driver and parse its options */
244 drv = bdrv_find_format(fmt);
245 if (!drv) {
246 error_report("Unknown file format '%s'", fmt);
247 return 1;
250 if (!drv->create_opts) {
251 error_report("Format driver '%s' does not support image creation", fmt);
252 return 1;
255 create_opts = qemu_opts_append(create_opts, drv->create_opts);
256 if (filename) {
257 proto_drv = bdrv_find_protocol(filename, true, &local_err);
258 if (!proto_drv) {
259 error_report_err(local_err);
260 qemu_opts_free(create_opts);
261 return 1;
263 if (!proto_drv->create_opts) {
264 error_report("Protocal driver '%s' does not support image creation",
265 proto_drv->format_name);
266 return 1;
268 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
271 printf("Supported options:\n");
272 qemu_opts_print_help(create_opts, false);
273 qemu_opts_free(create_opts);
274 return 0;
278 static BlockBackend *img_open_opts(const char *optstr,
279 QemuOpts *opts, int flags, bool writethrough,
280 bool quiet, bool force_share)
282 QDict *options;
283 Error *local_err = NULL;
284 BlockBackend *blk;
285 options = qemu_opts_to_qdict(opts, NULL);
286 if (force_share) {
287 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
288 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
289 error_report("--force-share/-U conflicts with image options");
290 qobject_unref(options);
291 return NULL;
293 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
295 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
296 if (!blk) {
297 error_reportf_err(local_err, "Could not open '%s': ", optstr);
298 return NULL;
300 blk_set_enable_write_cache(blk, !writethrough);
302 return blk;
305 static BlockBackend *img_open_file(const char *filename,
306 QDict *options,
307 const char *fmt, int flags,
308 bool writethrough, bool quiet,
309 bool force_share)
311 BlockBackend *blk;
312 Error *local_err = NULL;
314 if (!options) {
315 options = qdict_new();
317 if (fmt) {
318 qdict_put_str(options, "driver", fmt);
321 if (force_share) {
322 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
324 blk = blk_new_open(filename, NULL, options, flags, &local_err);
325 if (!blk) {
326 error_reportf_err(local_err, "Could not open '%s': ", filename);
327 return NULL;
329 blk_set_enable_write_cache(blk, !writethrough);
331 return blk;
335 static int img_add_key_secrets(void *opaque,
336 const char *name, const char *value,
337 Error **errp)
339 QDict *options = opaque;
341 if (g_str_has_suffix(name, "key-secret")) {
342 qdict_put_str(options, name, value);
345 return 0;
349 static BlockBackend *img_open(bool image_opts,
350 const char *filename,
351 const char *fmt, int flags, bool writethrough,
352 bool quiet, bool force_share)
354 BlockBackend *blk;
355 if (image_opts) {
356 QemuOpts *opts;
357 if (fmt) {
358 error_report("--image-opts and --format are mutually exclusive");
359 return NULL;
361 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
362 filename, true);
363 if (!opts) {
364 return NULL;
366 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
367 force_share);
368 } else {
369 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
370 force_share);
372 return blk;
376 static int add_old_style_options(const char *fmt, QemuOpts *opts,
377 const char *base_filename,
378 const char *base_fmt)
380 Error *err = NULL;
382 if (base_filename) {
383 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
384 if (err) {
385 error_report("Backing file not supported for file format '%s'",
386 fmt);
387 error_free(err);
388 return -1;
391 if (base_fmt) {
392 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
393 if (err) {
394 error_report("Backing file format not supported for file "
395 "format '%s'", fmt);
396 error_free(err);
397 return -1;
400 return 0;
403 static int64_t cvtnum(const char *s)
405 int err;
406 uint64_t value;
408 err = qemu_strtosz(s, NULL, &value);
409 if (err < 0) {
410 return err;
412 if (value > INT64_MAX) {
413 return -ERANGE;
415 return value;
418 static int img_create(int argc, char **argv)
420 int c;
421 uint64_t img_size = -1;
422 const char *fmt = "raw";
423 const char *base_fmt = NULL;
424 const char *filename;
425 const char *base_filename = NULL;
426 char *options = NULL;
427 Error *local_err = NULL;
428 bool quiet = false;
429 int flags = 0;
431 for(;;) {
432 static const struct option long_options[] = {
433 {"help", no_argument, 0, 'h'},
434 {"object", required_argument, 0, OPTION_OBJECT},
435 {0, 0, 0, 0}
437 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
438 long_options, NULL);
439 if (c == -1) {
440 break;
442 switch(c) {
443 case ':':
444 missing_argument(argv[optind - 1]);
445 break;
446 case '?':
447 unrecognized_option(argv[optind - 1]);
448 break;
449 case 'h':
450 help();
451 break;
452 case 'F':
453 base_fmt = optarg;
454 break;
455 case 'b':
456 base_filename = optarg;
457 break;
458 case 'f':
459 fmt = optarg;
460 break;
461 case 'o':
462 if (!is_valid_option_list(optarg)) {
463 error_report("Invalid option list: %s", optarg);
464 goto fail;
466 if (!options) {
467 options = g_strdup(optarg);
468 } else {
469 char *old_options = options;
470 options = g_strdup_printf("%s,%s", options, optarg);
471 g_free(old_options);
473 break;
474 case 'q':
475 quiet = true;
476 break;
477 case 'u':
478 flags |= BDRV_O_NO_BACKING;
479 break;
480 case OPTION_OBJECT: {
481 QemuOpts *opts;
482 opts = qemu_opts_parse_noisily(&qemu_object_opts,
483 optarg, true);
484 if (!opts) {
485 goto fail;
487 } break;
491 /* Get the filename */
492 filename = (optind < argc) ? argv[optind] : NULL;
493 if (options && has_help_option(options)) {
494 g_free(options);
495 return print_block_option_help(filename, fmt);
498 if (optind >= argc) {
499 error_exit("Expecting image file name");
501 optind++;
503 if (qemu_opts_foreach(&qemu_object_opts,
504 user_creatable_add_opts_foreach,
505 NULL, NULL)) {
506 goto fail;
509 /* Get image size, if specified */
510 if (optind < argc) {
511 int64_t sval;
513 sval = cvtnum(argv[optind++]);
514 if (sval < 0) {
515 if (sval == -ERANGE) {
516 error_report("Image size must be less than 8 EiB!");
517 } else {
518 error_report("Invalid image size specified! You may use k, M, "
519 "G, T, P or E suffixes for ");
520 error_report("kilobytes, megabytes, gigabytes, terabytes, "
521 "petabytes and exabytes.");
523 goto fail;
525 img_size = (uint64_t)sval;
527 if (optind != argc) {
528 error_exit("Unexpected argument: %s", argv[optind]);
531 bdrv_img_create(filename, fmt, base_filename, base_fmt,
532 options, img_size, flags, quiet, &local_err);
533 if (local_err) {
534 error_reportf_err(local_err, "%s: ", filename);
535 goto fail;
538 g_free(options);
539 return 0;
541 fail:
542 g_free(options);
543 return 1;
546 static void dump_json_image_check(ImageCheck *check, bool quiet)
548 QString *str;
549 QObject *obj;
550 Visitor *v = qobject_output_visitor_new(&obj);
552 visit_type_ImageCheck(v, NULL, &check, &error_abort);
553 visit_complete(v, &obj);
554 str = qobject_to_json_pretty(obj);
555 assert(str != NULL);
556 qprintf(quiet, "%s\n", qstring_get_str(str));
557 qobject_unref(obj);
558 visit_free(v);
559 qobject_unref(str);
562 static void dump_human_image_check(ImageCheck *check, bool quiet)
564 if (!(check->corruptions || check->leaks || check->check_errors)) {
565 qprintf(quiet, "No errors were found on the image.\n");
566 } else {
567 if (check->corruptions) {
568 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
569 "Data may be corrupted, or further writes to the image "
570 "may corrupt it.\n",
571 check->corruptions);
574 if (check->leaks) {
575 qprintf(quiet,
576 "\n%" PRId64 " leaked clusters were found on the image.\n"
577 "This means waste of disk space, but no harm to data.\n",
578 check->leaks);
581 if (check->check_errors) {
582 qprintf(quiet,
583 "\n%" PRId64
584 " internal errors have occurred during the check.\n",
585 check->check_errors);
589 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
590 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
591 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
592 check->allocated_clusters, check->total_clusters,
593 check->allocated_clusters * 100.0 / check->total_clusters,
594 check->fragmented_clusters * 100.0 / check->allocated_clusters,
595 check->compressed_clusters * 100.0 /
596 check->allocated_clusters);
599 if (check->image_end_offset) {
600 qprintf(quiet,
601 "Image end offset: %" PRId64 "\n", check->image_end_offset);
605 static int collect_image_check(BlockDriverState *bs,
606 ImageCheck *check,
607 const char *filename,
608 const char *fmt,
609 int fix)
611 int ret;
612 BdrvCheckResult result;
614 ret = bdrv_check(bs, &result, fix);
615 if (ret < 0) {
616 return ret;
619 check->filename = g_strdup(filename);
620 check->format = g_strdup(bdrv_get_format_name(bs));
621 check->check_errors = result.check_errors;
622 check->corruptions = result.corruptions;
623 check->has_corruptions = result.corruptions != 0;
624 check->leaks = result.leaks;
625 check->has_leaks = result.leaks != 0;
626 check->corruptions_fixed = result.corruptions_fixed;
627 check->has_corruptions_fixed = result.corruptions != 0;
628 check->leaks_fixed = result.leaks_fixed;
629 check->has_leaks_fixed = result.leaks != 0;
630 check->image_end_offset = result.image_end_offset;
631 check->has_image_end_offset = result.image_end_offset != 0;
632 check->total_clusters = result.bfi.total_clusters;
633 check->has_total_clusters = result.bfi.total_clusters != 0;
634 check->allocated_clusters = result.bfi.allocated_clusters;
635 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
636 check->fragmented_clusters = result.bfi.fragmented_clusters;
637 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
638 check->compressed_clusters = result.bfi.compressed_clusters;
639 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
641 return 0;
645 * Checks an image for consistency. Exit codes:
647 * 0 - Check completed, image is good
648 * 1 - Check not completed because of internal errors
649 * 2 - Check completed, image is corrupted
650 * 3 - Check completed, image has leaked clusters, but is good otherwise
651 * 63 - Checks are not supported by the image format
653 static int img_check(int argc, char **argv)
655 int c, ret;
656 OutputFormat output_format = OFORMAT_HUMAN;
657 const char *filename, *fmt, *output, *cache;
658 BlockBackend *blk;
659 BlockDriverState *bs;
660 int fix = 0;
661 int flags = BDRV_O_CHECK;
662 bool writethrough;
663 ImageCheck *check;
664 bool quiet = false;
665 bool image_opts = false;
666 bool force_share = false;
668 fmt = NULL;
669 output = NULL;
670 cache = BDRV_DEFAULT_CACHE;
672 for(;;) {
673 int option_index = 0;
674 static const struct option long_options[] = {
675 {"help", no_argument, 0, 'h'},
676 {"format", required_argument, 0, 'f'},
677 {"repair", required_argument, 0, 'r'},
678 {"output", required_argument, 0, OPTION_OUTPUT},
679 {"object", required_argument, 0, OPTION_OBJECT},
680 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
681 {"force-share", no_argument, 0, 'U'},
682 {0, 0, 0, 0}
684 c = getopt_long(argc, argv, ":hf:r:T:qU",
685 long_options, &option_index);
686 if (c == -1) {
687 break;
689 switch(c) {
690 case ':':
691 missing_argument(argv[optind - 1]);
692 break;
693 case '?':
694 unrecognized_option(argv[optind - 1]);
695 break;
696 case 'h':
697 help();
698 break;
699 case 'f':
700 fmt = optarg;
701 break;
702 case 'r':
703 flags |= BDRV_O_RDWR;
705 if (!strcmp(optarg, "leaks")) {
706 fix = BDRV_FIX_LEAKS;
707 } else if (!strcmp(optarg, "all")) {
708 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
709 } else {
710 error_exit("Unknown option value for -r "
711 "(expecting 'leaks' or 'all'): %s", optarg);
713 break;
714 case OPTION_OUTPUT:
715 output = optarg;
716 break;
717 case 'T':
718 cache = optarg;
719 break;
720 case 'q':
721 quiet = true;
722 break;
723 case 'U':
724 force_share = true;
725 break;
726 case OPTION_OBJECT: {
727 QemuOpts *opts;
728 opts = qemu_opts_parse_noisily(&qemu_object_opts,
729 optarg, true);
730 if (!opts) {
731 return 1;
733 } break;
734 case OPTION_IMAGE_OPTS:
735 image_opts = true;
736 break;
739 if (optind != argc - 1) {
740 error_exit("Expecting one image file name");
742 filename = argv[optind++];
744 if (output && !strcmp(output, "json")) {
745 output_format = OFORMAT_JSON;
746 } else if (output && !strcmp(output, "human")) {
747 output_format = OFORMAT_HUMAN;
748 } else if (output) {
749 error_report("--output must be used with human or json as argument.");
750 return 1;
753 if (qemu_opts_foreach(&qemu_object_opts,
754 user_creatable_add_opts_foreach,
755 NULL, NULL)) {
756 return 1;
759 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
760 if (ret < 0) {
761 error_report("Invalid source cache option: %s", cache);
762 return 1;
765 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
766 force_share);
767 if (!blk) {
768 return 1;
770 bs = blk_bs(blk);
772 check = g_new0(ImageCheck, 1);
773 ret = collect_image_check(bs, check, filename, fmt, fix);
775 if (ret == -ENOTSUP) {
776 error_report("This image format does not support checks");
777 ret = 63;
778 goto fail;
781 if (check->corruptions_fixed || check->leaks_fixed) {
782 int corruptions_fixed, leaks_fixed;
784 leaks_fixed = check->leaks_fixed;
785 corruptions_fixed = check->corruptions_fixed;
787 if (output_format == OFORMAT_HUMAN) {
788 qprintf(quiet,
789 "The following inconsistencies were found and repaired:\n\n"
790 " %" PRId64 " leaked clusters\n"
791 " %" PRId64 " corruptions\n\n"
792 "Double checking the fixed image now...\n",
793 check->leaks_fixed,
794 check->corruptions_fixed);
797 ret = collect_image_check(bs, check, filename, fmt, 0);
799 check->leaks_fixed = leaks_fixed;
800 check->corruptions_fixed = corruptions_fixed;
803 if (!ret) {
804 switch (output_format) {
805 case OFORMAT_HUMAN:
806 dump_human_image_check(check, quiet);
807 break;
808 case OFORMAT_JSON:
809 dump_json_image_check(check, quiet);
810 break;
814 if (ret || check->check_errors) {
815 if (ret) {
816 error_report("Check failed: %s", strerror(-ret));
817 } else {
818 error_report("Check failed");
820 ret = 1;
821 goto fail;
824 if (check->corruptions) {
825 ret = 2;
826 } else if (check->leaks) {
827 ret = 3;
828 } else {
829 ret = 0;
832 fail:
833 qapi_free_ImageCheck(check);
834 blk_unref(blk);
835 return ret;
838 typedef struct CommonBlockJobCBInfo {
839 BlockDriverState *bs;
840 Error **errp;
841 } CommonBlockJobCBInfo;
843 static void common_block_job_cb(void *opaque, int ret)
845 CommonBlockJobCBInfo *cbi = opaque;
847 if (ret < 0) {
848 error_setg_errno(cbi->errp, -ret, "Block job failed");
852 static void run_block_job(BlockJob *job, Error **errp)
854 AioContext *aio_context = blk_get_aio_context(job->blk);
855 int ret = 0;
857 aio_context_acquire(aio_context);
858 job_ref(&job->job);
859 do {
860 float progress = 0.0f;
861 aio_poll(aio_context, true);
862 if (job->job.progress_total) {
863 progress = (float)job->job.progress_current /
864 job->job.progress_total * 100.f;
866 qemu_progress_print(progress, 0);
867 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
869 if (!job_is_completed(&job->job)) {
870 ret = job_complete_sync(&job->job, errp);
871 } else {
872 ret = job->job.ret;
874 job_unref(&job->job);
875 aio_context_release(aio_context);
877 /* publish completion progress only when success */
878 if (!ret) {
879 qemu_progress_print(100.f, 0);
883 static int img_commit(int argc, char **argv)
885 int c, ret, flags;
886 const char *filename, *fmt, *cache, *base;
887 BlockBackend *blk;
888 BlockDriverState *bs, *base_bs;
889 BlockJob *job;
890 bool progress = false, quiet = false, drop = false;
891 bool writethrough;
892 Error *local_err = NULL;
893 CommonBlockJobCBInfo cbi;
894 bool image_opts = false;
895 AioContext *aio_context;
897 fmt = NULL;
898 cache = BDRV_DEFAULT_CACHE;
899 base = NULL;
900 for(;;) {
901 static const struct option long_options[] = {
902 {"help", no_argument, 0, 'h'},
903 {"object", required_argument, 0, OPTION_OBJECT},
904 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
905 {0, 0, 0, 0}
907 c = getopt_long(argc, argv, ":f:ht:b:dpq",
908 long_options, NULL);
909 if (c == -1) {
910 break;
912 switch(c) {
913 case ':':
914 missing_argument(argv[optind - 1]);
915 break;
916 case '?':
917 unrecognized_option(argv[optind - 1]);
918 break;
919 case 'h':
920 help();
921 break;
922 case 'f':
923 fmt = optarg;
924 break;
925 case 't':
926 cache = optarg;
927 break;
928 case 'b':
929 base = optarg;
930 /* -b implies -d */
931 drop = true;
932 break;
933 case 'd':
934 drop = true;
935 break;
936 case 'p':
937 progress = true;
938 break;
939 case 'q':
940 quiet = true;
941 break;
942 case OPTION_OBJECT: {
943 QemuOpts *opts;
944 opts = qemu_opts_parse_noisily(&qemu_object_opts,
945 optarg, true);
946 if (!opts) {
947 return 1;
949 } break;
950 case OPTION_IMAGE_OPTS:
951 image_opts = true;
952 break;
956 /* Progress is not shown in Quiet mode */
957 if (quiet) {
958 progress = false;
961 if (optind != argc - 1) {
962 error_exit("Expecting one image file name");
964 filename = argv[optind++];
966 if (qemu_opts_foreach(&qemu_object_opts,
967 user_creatable_add_opts_foreach,
968 NULL, NULL)) {
969 return 1;
972 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
973 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
974 if (ret < 0) {
975 error_report("Invalid cache option: %s", cache);
976 return 1;
979 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
980 false);
981 if (!blk) {
982 return 1;
984 bs = blk_bs(blk);
986 qemu_progress_init(progress, 1.f);
987 qemu_progress_print(0.f, 100);
989 if (base) {
990 base_bs = bdrv_find_backing_image(bs, base);
991 if (!base_bs) {
992 error_setg(&local_err,
993 "Did not find '%s' in the backing chain of '%s'",
994 base, filename);
995 goto done;
997 } else {
998 /* This is different from QMP, which by default uses the deepest file in
999 * the backing chain (i.e., the very base); however, the traditional
1000 * behavior of qemu-img commit is using the immediate backing file. */
1001 base_bs = backing_bs(bs);
1002 if (!base_bs) {
1003 error_setg(&local_err, "Image does not have a backing file");
1004 goto done;
1008 cbi = (CommonBlockJobCBInfo){
1009 .errp = &local_err,
1010 .bs = bs,
1013 aio_context = bdrv_get_aio_context(bs);
1014 aio_context_acquire(aio_context);
1015 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
1016 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1017 &cbi, false, &local_err);
1018 aio_context_release(aio_context);
1019 if (local_err) {
1020 goto done;
1023 /* When the block job completes, the BlockBackend reference will point to
1024 * the old backing file. In order to avoid that the top image is already
1025 * deleted, so we can still empty it afterwards, increment the reference
1026 * counter here preemptively. */
1027 if (!drop) {
1028 bdrv_ref(bs);
1031 job = block_job_get("commit");
1032 assert(job);
1033 run_block_job(job, &local_err);
1034 if (local_err) {
1035 goto unref_backing;
1038 if (!drop && bs->drv->bdrv_make_empty) {
1039 ret = bs->drv->bdrv_make_empty(bs);
1040 if (ret) {
1041 error_setg_errno(&local_err, -ret, "Could not empty %s",
1042 filename);
1043 goto unref_backing;
1047 unref_backing:
1048 if (!drop) {
1049 bdrv_unref(bs);
1052 done:
1053 qemu_progress_end();
1055 blk_unref(blk);
1057 if (local_err) {
1058 error_report_err(local_err);
1059 return 1;
1062 qprintf(quiet, "Image committed.\n");
1063 return 0;
1067 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1068 * of the first sector boundary within buf where the sector contains a
1069 * non-zero byte. This function is robust to a buffer that is not
1070 * sector-aligned.
1072 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1074 int64_t i;
1075 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1077 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1078 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1079 return i;
1082 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1083 return i;
1085 return -1;
1089 * Returns true iff the first sector pointed to by 'buf' contains at least
1090 * a non-NUL byte.
1092 * 'pnum' is set to the number of sectors (including and immediately following
1093 * the first one) that are known to be in the same allocated/unallocated state.
1094 * The function will try to align the end offset to alignment boundaries so
1095 * that the request will at least end aligned and consequtive requests will
1096 * also start at an aligned offset.
1098 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1099 int64_t sector_num, int alignment)
1101 bool is_zero;
1102 int i, tail;
1104 if (n <= 0) {
1105 *pnum = 0;
1106 return 0;
1108 is_zero = buffer_is_zero(buf, 512);
1109 for(i = 1; i < n; i++) {
1110 buf += 512;
1111 if (is_zero != buffer_is_zero(buf, 512)) {
1112 break;
1116 tail = (sector_num + i) & (alignment - 1);
1117 if (tail) {
1118 if (is_zero && i <= tail) {
1119 /* treat unallocated areas which only consist
1120 * of a small tail as allocated. */
1121 is_zero = false;
1123 if (!is_zero) {
1124 /* align up end offset of allocated areas. */
1125 i += alignment - tail;
1126 i = MIN(i, n);
1127 } else {
1128 /* align down end offset of zero areas. */
1129 i -= tail;
1132 *pnum = i;
1133 return !is_zero;
1137 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1138 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1139 * breaking up write requests for only small sparse areas.
1141 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1142 int min, int64_t sector_num, int alignment)
1144 int ret;
1145 int num_checked, num_used;
1147 if (n < min) {
1148 min = n;
1151 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1152 if (!ret) {
1153 return ret;
1156 num_used = *pnum;
1157 buf += BDRV_SECTOR_SIZE * *pnum;
1158 n -= *pnum;
1159 sector_num += *pnum;
1160 num_checked = num_used;
1162 while (n > 0) {
1163 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1165 buf += BDRV_SECTOR_SIZE * *pnum;
1166 n -= *pnum;
1167 sector_num += *pnum;
1168 num_checked += *pnum;
1169 if (ret) {
1170 num_used = num_checked;
1171 } else if (*pnum >= min) {
1172 break;
1176 *pnum = num_used;
1177 return 1;
1181 * Compares two buffers sector by sector. Returns 0 if the first
1182 * sector of each buffer matches, non-zero otherwise.
1184 * pnum is set to the sector-aligned size of the buffer prefix that
1185 * has the same matching status as the first sector.
1187 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1188 int64_t bytes, int64_t *pnum)
1190 bool res;
1191 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1193 assert(bytes > 0);
1195 res = !!memcmp(buf1, buf2, i);
1196 while (i < bytes) {
1197 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1199 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1200 break;
1202 i += len;
1205 *pnum = i;
1206 return res;
1209 #define IO_BUF_SIZE (2 * 1024 * 1024)
1212 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1214 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1215 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1216 * failure), and 4 on error (the exit status for read errors), after emitting
1217 * an error message.
1219 * @param blk: BlockBackend for the image
1220 * @param offset: Starting offset to check
1221 * @param bytes: Number of bytes to check
1222 * @param filename: Name of disk file we are checking (logging purpose)
1223 * @param buffer: Allocated buffer for storing read data
1224 * @param quiet: Flag for quiet mode
1226 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1227 int64_t bytes, const char *filename,
1228 uint8_t *buffer, bool quiet)
1230 int ret = 0;
1231 int64_t idx;
1233 ret = blk_pread(blk, offset, buffer, bytes);
1234 if (ret < 0) {
1235 error_report("Error while reading offset %" PRId64 " of %s: %s",
1236 offset, filename, strerror(-ret));
1237 return 4;
1239 idx = find_nonzero(buffer, bytes);
1240 if (idx >= 0) {
1241 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1242 offset + idx);
1243 return 1;
1246 return 0;
1250 * Compares two images. Exit codes:
1252 * 0 - Images are identical
1253 * 1 - Images differ
1254 * >1 - Error occurred
1256 static int img_compare(int argc, char **argv)
1258 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1259 BlockBackend *blk1, *blk2;
1260 BlockDriverState *bs1, *bs2;
1261 int64_t total_size1, total_size2;
1262 uint8_t *buf1 = NULL, *buf2 = NULL;
1263 int64_t pnum1, pnum2;
1264 int allocated1, allocated2;
1265 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1266 bool progress = false, quiet = false, strict = false;
1267 int flags;
1268 bool writethrough;
1269 int64_t total_size;
1270 int64_t offset = 0;
1271 int64_t chunk;
1272 int c;
1273 uint64_t progress_base;
1274 bool image_opts = false;
1275 bool force_share = false;
1277 cache = BDRV_DEFAULT_CACHE;
1278 for (;;) {
1279 static const struct option long_options[] = {
1280 {"help", no_argument, 0, 'h'},
1281 {"object", required_argument, 0, OPTION_OBJECT},
1282 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1283 {"force-share", no_argument, 0, 'U'},
1284 {0, 0, 0, 0}
1286 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1287 long_options, NULL);
1288 if (c == -1) {
1289 break;
1291 switch (c) {
1292 case ':':
1293 missing_argument(argv[optind - 1]);
1294 break;
1295 case '?':
1296 unrecognized_option(argv[optind - 1]);
1297 break;
1298 case 'h':
1299 help();
1300 break;
1301 case 'f':
1302 fmt1 = optarg;
1303 break;
1304 case 'F':
1305 fmt2 = optarg;
1306 break;
1307 case 'T':
1308 cache = optarg;
1309 break;
1310 case 'p':
1311 progress = true;
1312 break;
1313 case 'q':
1314 quiet = true;
1315 break;
1316 case 's':
1317 strict = true;
1318 break;
1319 case 'U':
1320 force_share = true;
1321 break;
1322 case OPTION_OBJECT: {
1323 QemuOpts *opts;
1324 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1325 optarg, true);
1326 if (!opts) {
1327 ret = 2;
1328 goto out4;
1330 } break;
1331 case OPTION_IMAGE_OPTS:
1332 image_opts = true;
1333 break;
1337 /* Progress is not shown in Quiet mode */
1338 if (quiet) {
1339 progress = false;
1343 if (optind != argc - 2) {
1344 error_exit("Expecting two image file names");
1346 filename1 = argv[optind++];
1347 filename2 = argv[optind++];
1349 if (qemu_opts_foreach(&qemu_object_opts,
1350 user_creatable_add_opts_foreach,
1351 NULL, NULL)) {
1352 ret = 2;
1353 goto out4;
1356 /* Initialize before goto out */
1357 qemu_progress_init(progress, 2.0);
1359 flags = 0;
1360 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1361 if (ret < 0) {
1362 error_report("Invalid source cache option: %s", cache);
1363 ret = 2;
1364 goto out3;
1367 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1368 force_share);
1369 if (!blk1) {
1370 ret = 2;
1371 goto out3;
1374 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1375 force_share);
1376 if (!blk2) {
1377 ret = 2;
1378 goto out2;
1380 bs1 = blk_bs(blk1);
1381 bs2 = blk_bs(blk2);
1383 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1384 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1385 total_size1 = blk_getlength(blk1);
1386 if (total_size1 < 0) {
1387 error_report("Can't get size of %s: %s",
1388 filename1, strerror(-total_size1));
1389 ret = 4;
1390 goto out;
1392 total_size2 = blk_getlength(blk2);
1393 if (total_size2 < 0) {
1394 error_report("Can't get size of %s: %s",
1395 filename2, strerror(-total_size2));
1396 ret = 4;
1397 goto out;
1399 total_size = MIN(total_size1, total_size2);
1400 progress_base = MAX(total_size1, total_size2);
1402 qemu_progress_print(0, 100);
1404 if (strict && total_size1 != total_size2) {
1405 ret = 1;
1406 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1407 goto out;
1410 while (offset < total_size) {
1411 int status1, status2;
1413 status1 = bdrv_block_status_above(bs1, NULL, offset,
1414 total_size1 - offset, &pnum1, NULL,
1415 NULL);
1416 if (status1 < 0) {
1417 ret = 3;
1418 error_report("Sector allocation test failed for %s", filename1);
1419 goto out;
1421 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1423 status2 = bdrv_block_status_above(bs2, NULL, offset,
1424 total_size2 - offset, &pnum2, NULL,
1425 NULL);
1426 if (status2 < 0) {
1427 ret = 3;
1428 error_report("Sector allocation test failed for %s", filename2);
1429 goto out;
1431 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1433 assert(pnum1 && pnum2);
1434 chunk = MIN(pnum1, pnum2);
1436 if (strict) {
1437 if (status1 != status2) {
1438 ret = 1;
1439 qprintf(quiet, "Strict mode: Offset %" PRId64
1440 " block status mismatch!\n", offset);
1441 goto out;
1444 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1445 /* nothing to do */
1446 } else if (allocated1 == allocated2) {
1447 if (allocated1) {
1448 int64_t pnum;
1450 chunk = MIN(chunk, IO_BUF_SIZE);
1451 ret = blk_pread(blk1, offset, buf1, chunk);
1452 if (ret < 0) {
1453 error_report("Error while reading offset %" PRId64
1454 " of %s: %s",
1455 offset, filename1, strerror(-ret));
1456 ret = 4;
1457 goto out;
1459 ret = blk_pread(blk2, offset, buf2, chunk);
1460 if (ret < 0) {
1461 error_report("Error while reading offset %" PRId64
1462 " of %s: %s",
1463 offset, filename2, strerror(-ret));
1464 ret = 4;
1465 goto out;
1467 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1468 if (ret || pnum != chunk) {
1469 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1470 offset + (ret ? 0 : pnum));
1471 ret = 1;
1472 goto out;
1475 } else {
1476 chunk = MIN(chunk, IO_BUF_SIZE);
1477 if (allocated1) {
1478 ret = check_empty_sectors(blk1, offset, chunk,
1479 filename1, buf1, quiet);
1480 } else {
1481 ret = check_empty_sectors(blk2, offset, chunk,
1482 filename2, buf1, quiet);
1484 if (ret) {
1485 goto out;
1488 offset += chunk;
1489 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1492 if (total_size1 != total_size2) {
1493 BlockBackend *blk_over;
1494 const char *filename_over;
1496 qprintf(quiet, "Warning: Image size mismatch!\n");
1497 if (total_size1 > total_size2) {
1498 blk_over = blk1;
1499 filename_over = filename1;
1500 } else {
1501 blk_over = blk2;
1502 filename_over = filename2;
1505 while (offset < progress_base) {
1506 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1507 progress_base - offset, &chunk,
1508 NULL, NULL);
1509 if (ret < 0) {
1510 ret = 3;
1511 error_report("Sector allocation test failed for %s",
1512 filename_over);
1513 goto out;
1516 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1517 chunk = MIN(chunk, IO_BUF_SIZE);
1518 ret = check_empty_sectors(blk_over, offset, chunk,
1519 filename_over, buf1, quiet);
1520 if (ret) {
1521 goto out;
1524 offset += chunk;
1525 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1529 qprintf(quiet, "Images are identical.\n");
1530 ret = 0;
1532 out:
1533 qemu_vfree(buf1);
1534 qemu_vfree(buf2);
1535 blk_unref(blk2);
1536 out2:
1537 blk_unref(blk1);
1538 out3:
1539 qemu_progress_end();
1540 out4:
1541 return ret;
1544 enum ImgConvertBlockStatus {
1545 BLK_DATA,
1546 BLK_ZERO,
1547 BLK_BACKING_FILE,
1550 #define MAX_COROUTINES 16
1552 typedef struct ImgConvertState {
1553 BlockBackend **src;
1554 int64_t *src_sectors;
1555 int src_num;
1556 int64_t total_sectors;
1557 int64_t allocated_sectors;
1558 int64_t allocated_done;
1559 int64_t sector_num;
1560 int64_t wr_offs;
1561 enum ImgConvertBlockStatus status;
1562 int64_t sector_next_status;
1563 BlockBackend *target;
1564 bool has_zero_init;
1565 bool compressed;
1566 bool unallocated_blocks_are_zero;
1567 bool target_has_backing;
1568 int64_t target_backing_sectors; /* negative if unknown */
1569 bool wr_in_order;
1570 bool copy_range;
1571 int min_sparse;
1572 int alignment;
1573 size_t cluster_sectors;
1574 size_t buf_sectors;
1575 long num_coroutines;
1576 int running_coroutines;
1577 Coroutine *co[MAX_COROUTINES];
1578 int64_t wait_sector_num[MAX_COROUTINES];
1579 CoMutex lock;
1580 int ret;
1581 } ImgConvertState;
1583 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1584 int *src_cur, int64_t *src_cur_offset)
1586 *src_cur = 0;
1587 *src_cur_offset = 0;
1588 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1589 *src_cur_offset += s->src_sectors[*src_cur];
1590 (*src_cur)++;
1591 assert(*src_cur < s->src_num);
1595 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1597 int64_t src_cur_offset;
1598 int ret, n, src_cur;
1599 bool post_backing_zero = false;
1601 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1603 assert(s->total_sectors > sector_num);
1604 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1606 if (s->target_backing_sectors >= 0) {
1607 if (sector_num >= s->target_backing_sectors) {
1608 post_backing_zero = s->unallocated_blocks_are_zero;
1609 } else if (sector_num + n > s->target_backing_sectors) {
1610 /* Split requests around target_backing_sectors (because
1611 * starting from there, zeros are handled differently) */
1612 n = s->target_backing_sectors - sector_num;
1616 if (s->sector_next_status <= sector_num) {
1617 int64_t count = n * BDRV_SECTOR_SIZE;
1619 if (s->target_has_backing) {
1621 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1622 (sector_num - src_cur_offset) *
1623 BDRV_SECTOR_SIZE,
1624 count, &count, NULL, NULL);
1625 } else {
1626 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1627 (sector_num - src_cur_offset) *
1628 BDRV_SECTOR_SIZE,
1629 count, &count, NULL, NULL);
1631 if (ret < 0) {
1632 return ret;
1634 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1636 if (ret & BDRV_BLOCK_ZERO) {
1637 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1638 } else if (ret & BDRV_BLOCK_DATA) {
1639 s->status = BLK_DATA;
1640 } else {
1641 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1644 s->sector_next_status = sector_num + n;
1647 n = MIN(n, s->sector_next_status - sector_num);
1648 if (s->status == BLK_DATA) {
1649 n = MIN(n, s->buf_sectors);
1652 /* We need to write complete clusters for compressed images, so if an
1653 * unallocated area is shorter than that, we must consider the whole
1654 * cluster allocated. */
1655 if (s->compressed) {
1656 if (n < s->cluster_sectors) {
1657 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1658 s->status = BLK_DATA;
1659 } else {
1660 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1664 return n;
1667 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1668 int nb_sectors, uint8_t *buf)
1670 int n, ret;
1671 QEMUIOVector qiov;
1672 struct iovec iov;
1674 assert(nb_sectors <= s->buf_sectors);
1675 while (nb_sectors > 0) {
1676 BlockBackend *blk;
1677 int src_cur;
1678 int64_t bs_sectors, src_cur_offset;
1680 /* In the case of compression with multiple source files, we can get a
1681 * nb_sectors that spreads into the next part. So we must be able to
1682 * read across multiple BDSes for one convert_read() call. */
1683 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1684 blk = s->src[src_cur];
1685 bs_sectors = s->src_sectors[src_cur];
1687 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1688 iov.iov_base = buf;
1689 iov.iov_len = n << BDRV_SECTOR_BITS;
1690 qemu_iovec_init_external(&qiov, &iov, 1);
1692 ret = blk_co_preadv(
1693 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1694 n << BDRV_SECTOR_BITS, &qiov, 0);
1695 if (ret < 0) {
1696 return ret;
1699 sector_num += n;
1700 nb_sectors -= n;
1701 buf += n * BDRV_SECTOR_SIZE;
1704 return 0;
1708 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1709 int nb_sectors, uint8_t *buf,
1710 enum ImgConvertBlockStatus status)
1712 int ret;
1713 QEMUIOVector qiov;
1714 struct iovec iov;
1716 while (nb_sectors > 0) {
1717 int n = nb_sectors;
1718 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1720 switch (status) {
1721 case BLK_BACKING_FILE:
1722 /* If we have a backing file, leave clusters unallocated that are
1723 * unallocated in the source image, so that the backing file is
1724 * visible at the respective offset. */
1725 assert(s->target_has_backing);
1726 break;
1728 case BLK_DATA:
1729 /* If we're told to keep the target fully allocated (-S 0) or there
1730 * is real non-zero data, we must write it. Otherwise we can treat
1731 * it as zero sectors.
1732 * Compressed clusters need to be written as a whole, so in that
1733 * case we can only save the write if the buffer is completely
1734 * zeroed. */
1735 if (!s->min_sparse ||
1736 (!s->compressed &&
1737 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1738 sector_num, s->alignment)) ||
1739 (s->compressed &&
1740 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1742 iov.iov_base = buf;
1743 iov.iov_len = n << BDRV_SECTOR_BITS;
1744 qemu_iovec_init_external(&qiov, &iov, 1);
1746 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1747 n << BDRV_SECTOR_BITS, &qiov, flags);
1748 if (ret < 0) {
1749 return ret;
1751 break;
1753 /* fall-through */
1755 case BLK_ZERO:
1756 if (s->has_zero_init) {
1757 assert(!s->target_has_backing);
1758 break;
1760 ret = blk_co_pwrite_zeroes(s->target,
1761 sector_num << BDRV_SECTOR_BITS,
1762 n << BDRV_SECTOR_BITS, 0);
1763 if (ret < 0) {
1764 return ret;
1766 break;
1769 sector_num += n;
1770 nb_sectors -= n;
1771 buf += n * BDRV_SECTOR_SIZE;
1774 return 0;
1777 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1778 int nb_sectors)
1780 int n, ret;
1782 while (nb_sectors > 0) {
1783 BlockBackend *blk;
1784 int src_cur;
1785 int64_t bs_sectors, src_cur_offset;
1786 int64_t offset;
1788 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1789 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1790 blk = s->src[src_cur];
1791 bs_sectors = s->src_sectors[src_cur];
1793 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1795 ret = blk_co_copy_range(blk, offset, s->target,
1796 sector_num << BDRV_SECTOR_BITS,
1797 n << BDRV_SECTOR_BITS, 0, 0);
1798 if (ret < 0) {
1799 return ret;
1802 sector_num += n;
1803 nb_sectors -= n;
1805 return 0;
1808 static void coroutine_fn convert_co_do_copy(void *opaque)
1810 ImgConvertState *s = opaque;
1811 uint8_t *buf = NULL;
1812 int ret, i;
1813 int index = -1;
1815 for (i = 0; i < s->num_coroutines; i++) {
1816 if (s->co[i] == qemu_coroutine_self()) {
1817 index = i;
1818 break;
1821 assert(index >= 0);
1823 s->running_coroutines++;
1824 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1826 while (1) {
1827 int n;
1828 int64_t sector_num;
1829 enum ImgConvertBlockStatus status;
1830 bool copy_range;
1832 qemu_co_mutex_lock(&s->lock);
1833 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1834 qemu_co_mutex_unlock(&s->lock);
1835 break;
1837 n = convert_iteration_sectors(s, s->sector_num);
1838 if (n < 0) {
1839 qemu_co_mutex_unlock(&s->lock);
1840 s->ret = n;
1841 break;
1843 /* save current sector and allocation status to local variables */
1844 sector_num = s->sector_num;
1845 status = s->status;
1846 if (!s->min_sparse && s->status == BLK_ZERO) {
1847 n = MIN(n, s->buf_sectors);
1849 /* increment global sector counter so that other coroutines can
1850 * already continue reading beyond this request */
1851 s->sector_num += n;
1852 qemu_co_mutex_unlock(&s->lock);
1854 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1855 s->allocated_done += n;
1856 qemu_progress_print(100.0 * s->allocated_done /
1857 s->allocated_sectors, 0);
1860 retry:
1861 copy_range = s->copy_range && s->status == BLK_DATA;
1862 if (status == BLK_DATA && !copy_range) {
1863 ret = convert_co_read(s, sector_num, n, buf);
1864 if (ret < 0) {
1865 error_report("error while reading sector %" PRId64
1866 ": %s", sector_num, strerror(-ret));
1867 s->ret = ret;
1869 } else if (!s->min_sparse && status == BLK_ZERO) {
1870 status = BLK_DATA;
1871 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1874 if (s->wr_in_order) {
1875 /* keep writes in order */
1876 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1877 s->wait_sector_num[index] = sector_num;
1878 qemu_coroutine_yield();
1880 s->wait_sector_num[index] = -1;
1883 if (s->ret == -EINPROGRESS) {
1884 if (copy_range) {
1885 ret = convert_co_copy_range(s, sector_num, n);
1886 if (ret) {
1887 s->copy_range = false;
1888 goto retry;
1890 } else {
1891 ret = convert_co_write(s, sector_num, n, buf, status);
1893 if (ret < 0) {
1894 error_report("error while writing sector %" PRId64
1895 ": %s", sector_num, strerror(-ret));
1896 s->ret = ret;
1900 if (s->wr_in_order) {
1901 /* reenter the coroutine that might have waited
1902 * for this write to complete */
1903 s->wr_offs = sector_num + n;
1904 for (i = 0; i < s->num_coroutines; i++) {
1905 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1907 * A -> B -> A cannot occur because A has
1908 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1909 * B will never enter A during this time window.
1911 qemu_coroutine_enter(s->co[i]);
1912 break;
1918 qemu_vfree(buf);
1919 s->co[index] = NULL;
1920 s->running_coroutines--;
1921 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1922 /* the convert job finished successfully */
1923 s->ret = 0;
1927 static int convert_do_copy(ImgConvertState *s)
1929 int ret, i, n;
1930 int64_t sector_num = 0;
1932 /* Check whether we have zero initialisation or can get it efficiently */
1933 s->has_zero_init = s->min_sparse && !s->target_has_backing
1934 ? bdrv_has_zero_init(blk_bs(s->target))
1935 : false;
1937 if (!s->has_zero_init && !s->target_has_backing &&
1938 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1940 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1941 if (ret == 0) {
1942 s->has_zero_init = true;
1946 /* Allocate buffer for copied data. For compressed images, only one cluster
1947 * can be copied at a time. */
1948 if (s->compressed) {
1949 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1950 error_report("invalid cluster size");
1951 return -EINVAL;
1953 s->buf_sectors = s->cluster_sectors;
1956 while (sector_num < s->total_sectors) {
1957 n = convert_iteration_sectors(s, sector_num);
1958 if (n < 0) {
1959 return n;
1961 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1963 s->allocated_sectors += n;
1965 sector_num += n;
1968 /* Do the copy */
1969 s->sector_next_status = 0;
1970 s->ret = -EINPROGRESS;
1972 qemu_co_mutex_init(&s->lock);
1973 for (i = 0; i < s->num_coroutines; i++) {
1974 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1975 s->wait_sector_num[i] = -1;
1976 qemu_coroutine_enter(s->co[i]);
1979 while (s->running_coroutines) {
1980 main_loop_wait(false);
1983 if (s->compressed && !s->ret) {
1984 /* signal EOF to align */
1985 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1986 if (ret < 0) {
1987 return ret;
1991 return s->ret;
1994 #define MAX_BUF_SECTORS 32768
1996 static int img_convert(int argc, char **argv)
1998 int c, bs_i, flags, src_flags = 0;
1999 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2000 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2001 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2002 BlockDriver *drv = NULL, *proto_drv = NULL;
2003 BlockDriverInfo bdi;
2004 BlockDriverState *out_bs;
2005 QemuOpts *opts = NULL, *sn_opts = NULL;
2006 QemuOptsList *create_opts = NULL;
2007 QDict *open_opts = NULL;
2008 char *options = NULL;
2009 Error *local_err = NULL;
2010 bool writethrough, src_writethrough, quiet = false, image_opts = false,
2011 skip_create = false, progress = false, tgt_image_opts = false;
2012 int64_t ret = -EINVAL;
2013 bool force_share = false;
2014 bool explict_min_sparse = false;
2016 ImgConvertState s = (ImgConvertState) {
2017 /* Need at least 4k of zeros for sparse detection */
2018 .min_sparse = 8,
2019 .copy_range = false,
2020 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2021 .wr_in_order = true,
2022 .num_coroutines = 8,
2025 for(;;) {
2026 static const struct option long_options[] = {
2027 {"help", no_argument, 0, 'h'},
2028 {"object", required_argument, 0, OPTION_OBJECT},
2029 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2030 {"force-share", no_argument, 0, 'U'},
2031 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2032 {0, 0, 0, 0}
2034 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
2035 long_options, NULL);
2036 if (c == -1) {
2037 break;
2039 switch(c) {
2040 case ':':
2041 missing_argument(argv[optind - 1]);
2042 break;
2043 case '?':
2044 unrecognized_option(argv[optind - 1]);
2045 break;
2046 case 'h':
2047 help();
2048 break;
2049 case 'f':
2050 fmt = optarg;
2051 break;
2052 case 'O':
2053 out_fmt = optarg;
2054 break;
2055 case 'B':
2056 out_baseimg = optarg;
2057 break;
2058 case 'C':
2059 s.copy_range = true;
2060 break;
2061 case 'c':
2062 s.compressed = true;
2063 break;
2064 case 'o':
2065 if (!is_valid_option_list(optarg)) {
2066 error_report("Invalid option list: %s", optarg);
2067 goto fail_getopt;
2069 if (!options) {
2070 options = g_strdup(optarg);
2071 } else {
2072 char *old_options = options;
2073 options = g_strdup_printf("%s,%s", options, optarg);
2074 g_free(old_options);
2076 break;
2077 case 'l':
2078 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2079 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2080 optarg, false);
2081 if (!sn_opts) {
2082 error_report("Failed in parsing snapshot param '%s'",
2083 optarg);
2084 goto fail_getopt;
2086 } else {
2087 snapshot_name = optarg;
2089 break;
2090 case 'S':
2092 int64_t sval;
2094 sval = cvtnum(optarg);
2095 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2096 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2097 error_report("Invalid buffer size for sparse output specified. "
2098 "Valid sizes are multiples of %llu up to %llu. Select "
2099 "0 to disable sparse detection (fully allocates output).",
2100 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2101 goto fail_getopt;
2104 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2105 explict_min_sparse = true;
2106 break;
2108 case 'p':
2109 progress = true;
2110 break;
2111 case 't':
2112 cache = optarg;
2113 break;
2114 case 'T':
2115 src_cache = optarg;
2116 break;
2117 case 'q':
2118 quiet = true;
2119 break;
2120 case 'n':
2121 skip_create = true;
2122 break;
2123 case 'm':
2124 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2125 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2126 error_report("Invalid number of coroutines. Allowed number of"
2127 " coroutines is between 1 and %d", MAX_COROUTINES);
2128 goto fail_getopt;
2130 break;
2131 case 'W':
2132 s.wr_in_order = false;
2133 break;
2134 case 'U':
2135 force_share = true;
2136 break;
2137 case OPTION_OBJECT: {
2138 QemuOpts *object_opts;
2139 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2140 optarg, true);
2141 if (!object_opts) {
2142 goto fail_getopt;
2144 break;
2146 case OPTION_IMAGE_OPTS:
2147 image_opts = true;
2148 break;
2149 case OPTION_TARGET_IMAGE_OPTS:
2150 tgt_image_opts = true;
2151 break;
2155 if (!out_fmt && !tgt_image_opts) {
2156 out_fmt = "raw";
2159 if (qemu_opts_foreach(&qemu_object_opts,
2160 user_creatable_add_opts_foreach,
2161 NULL, NULL)) {
2162 goto fail_getopt;
2165 if (s.compressed && s.copy_range) {
2166 error_report("Cannot enable copy offloading when -c is used");
2167 goto fail_getopt;
2170 if (explict_min_sparse && s.copy_range) {
2171 error_report("Cannot enable copy offloading when -S is used");
2172 goto fail_getopt;
2175 if (tgt_image_opts && !skip_create) {
2176 error_report("--target-image-opts requires use of -n flag");
2177 goto fail_getopt;
2180 s.src_num = argc - optind - 1;
2181 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2183 if (options && has_help_option(options)) {
2184 if (out_fmt) {
2185 ret = print_block_option_help(out_filename, out_fmt);
2186 goto fail_getopt;
2187 } else {
2188 error_report("Option help requires a format be specified");
2189 goto fail_getopt;
2193 if (s.src_num < 1) {
2194 error_report("Must specify image file name");
2195 goto fail_getopt;
2199 /* ret is still -EINVAL until here */
2200 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2201 if (ret < 0) {
2202 error_report("Invalid source cache option: %s", src_cache);
2203 goto fail_getopt;
2206 /* Initialize before goto out */
2207 if (quiet) {
2208 progress = false;
2210 qemu_progress_init(progress, 1.0);
2211 qemu_progress_print(0, 100);
2213 s.src = g_new0(BlockBackend *, s.src_num);
2214 s.src_sectors = g_new(int64_t, s.src_num);
2216 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2217 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2218 fmt, src_flags, src_writethrough, quiet,
2219 force_share);
2220 if (!s.src[bs_i]) {
2221 ret = -1;
2222 goto out;
2224 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2225 if (s.src_sectors[bs_i] < 0) {
2226 error_report("Could not get size of %s: %s",
2227 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2228 ret = -1;
2229 goto out;
2231 s.total_sectors += s.src_sectors[bs_i];
2234 if (sn_opts) {
2235 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2236 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2237 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2238 &local_err);
2239 } else if (snapshot_name != NULL) {
2240 if (s.src_num > 1) {
2241 error_report("No support for concatenating multiple snapshot");
2242 ret = -1;
2243 goto out;
2246 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2247 &local_err);
2249 if (local_err) {
2250 error_reportf_err(local_err, "Failed to load snapshot: ");
2251 ret = -1;
2252 goto out;
2255 if (!skip_create) {
2256 /* Find driver and parse its options */
2257 drv = bdrv_find_format(out_fmt);
2258 if (!drv) {
2259 error_report("Unknown file format '%s'", out_fmt);
2260 ret = -1;
2261 goto out;
2264 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2265 if (!proto_drv) {
2266 error_report_err(local_err);
2267 ret = -1;
2268 goto out;
2271 if (!drv->create_opts) {
2272 error_report("Format driver '%s' does not support image creation",
2273 drv->format_name);
2274 ret = -1;
2275 goto out;
2278 if (!proto_drv->create_opts) {
2279 error_report("Protocol driver '%s' does not support image creation",
2280 proto_drv->format_name);
2281 ret = -1;
2282 goto out;
2285 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2286 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2288 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2289 if (options) {
2290 qemu_opts_do_parse(opts, options, NULL, &local_err);
2291 if (local_err) {
2292 error_report_err(local_err);
2293 ret = -1;
2294 goto out;
2298 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2299 &error_abort);
2300 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2301 if (ret < 0) {
2302 goto out;
2306 /* Get backing file name if -o backing_file was used */
2307 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2308 if (out_baseimg_param) {
2309 out_baseimg = out_baseimg_param;
2311 s.target_has_backing = (bool) out_baseimg;
2313 if (s.src_num > 1 && out_baseimg) {
2314 error_report("Having a backing file for the target makes no sense when "
2315 "concatenating multiple input images");
2316 ret = -1;
2317 goto out;
2320 /* Check if compression is supported */
2321 if (s.compressed) {
2322 bool encryption =
2323 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2324 const char *encryptfmt =
2325 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2326 const char *preallocation =
2327 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2329 if (drv && !drv->bdrv_co_pwritev_compressed) {
2330 error_report("Compression not supported for this file format");
2331 ret = -1;
2332 goto out;
2335 if (encryption || encryptfmt) {
2336 error_report("Compression and encryption not supported at "
2337 "the same time");
2338 ret = -1;
2339 goto out;
2342 if (preallocation
2343 && strcmp(preallocation, "off"))
2345 error_report("Compression and preallocation not supported at "
2346 "the same time");
2347 ret = -1;
2348 goto out;
2353 * The later open call will need any decryption secrets, and
2354 * bdrv_create() will purge "opts", so extract them now before
2355 * they are lost.
2357 if (!skip_create) {
2358 open_opts = qdict_new();
2359 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2362 if (!skip_create) {
2363 /* Create the new image */
2364 ret = bdrv_create(drv, out_filename, opts, &local_err);
2365 if (ret < 0) {
2366 error_reportf_err(local_err, "%s: error while converting %s: ",
2367 out_filename, out_fmt);
2368 goto out;
2372 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2373 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2374 if (ret < 0) {
2375 error_report("Invalid cache option: %s", cache);
2376 goto out;
2379 if (skip_create) {
2380 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2381 flags, writethrough, quiet, false);
2382 } else {
2383 /* TODO ultimately we should allow --target-image-opts
2384 * to be used even when -n is not given.
2385 * That has to wait for bdrv_create to be improved
2386 * to allow filenames in option syntax
2388 s.target = img_open_file(out_filename, open_opts, out_fmt,
2389 flags, writethrough, quiet, false);
2390 open_opts = NULL; /* blk_new_open will have freed it */
2392 if (!s.target) {
2393 ret = -1;
2394 goto out;
2396 out_bs = blk_bs(s.target);
2398 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2399 error_report("Compression not supported for this file format");
2400 ret = -1;
2401 goto out;
2404 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2405 * or discard_alignment of the out_bs is greater. Limit to
2406 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2407 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2408 MAX(s.buf_sectors,
2409 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2410 out_bs->bl.pdiscard_alignment >>
2411 BDRV_SECTOR_BITS)));
2413 /* try to align the write requests to the destination to avoid unnecessary
2414 * RMW cycles. */
2415 s.alignment = MAX(pow2floor(s.min_sparse),
2416 DIV_ROUND_UP(out_bs->bl.request_alignment,
2417 BDRV_SECTOR_SIZE));
2418 assert(is_power_of_2(s.alignment));
2420 if (skip_create) {
2421 int64_t output_sectors = blk_nb_sectors(s.target);
2422 if (output_sectors < 0) {
2423 error_report("unable to get output image length: %s",
2424 strerror(-output_sectors));
2425 ret = -1;
2426 goto out;
2427 } else if (output_sectors < s.total_sectors) {
2428 error_report("output file is smaller than input file");
2429 ret = -1;
2430 goto out;
2434 if (s.target_has_backing) {
2435 /* Errors are treated as "backing length unknown" (which means
2436 * s.target_backing_sectors has to be negative, which it will
2437 * be automatically). The backing file length is used only
2438 * for optimizations, so such a case is not fatal. */
2439 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2440 } else {
2441 s.target_backing_sectors = -1;
2444 ret = bdrv_get_info(out_bs, &bdi);
2445 if (ret < 0) {
2446 if (s.compressed) {
2447 error_report("could not get block driver info");
2448 goto out;
2450 } else {
2451 s.compressed = s.compressed || bdi.needs_compressed_writes;
2452 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2453 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
2456 ret = convert_do_copy(&s);
2457 out:
2458 if (!ret) {
2459 qemu_progress_print(100, 0);
2461 qemu_progress_end();
2462 qemu_opts_del(opts);
2463 qemu_opts_free(create_opts);
2464 qemu_opts_del(sn_opts);
2465 qobject_unref(open_opts);
2466 blk_unref(s.target);
2467 if (s.src) {
2468 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2469 blk_unref(s.src[bs_i]);
2471 g_free(s.src);
2473 g_free(s.src_sectors);
2474 fail_getopt:
2475 g_free(options);
2477 return !!ret;
2481 static void dump_snapshots(BlockDriverState *bs)
2483 QEMUSnapshotInfo *sn_tab, *sn;
2484 int nb_sns, i;
2486 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2487 if (nb_sns <= 0)
2488 return;
2489 printf("Snapshot list:\n");
2490 bdrv_snapshot_dump(fprintf, stdout, NULL);
2491 printf("\n");
2492 for(i = 0; i < nb_sns; i++) {
2493 sn = &sn_tab[i];
2494 bdrv_snapshot_dump(fprintf, stdout, sn);
2495 printf("\n");
2497 g_free(sn_tab);
2500 static void dump_json_image_info_list(ImageInfoList *list)
2502 QString *str;
2503 QObject *obj;
2504 Visitor *v = qobject_output_visitor_new(&obj);
2506 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2507 visit_complete(v, &obj);
2508 str = qobject_to_json_pretty(obj);
2509 assert(str != NULL);
2510 printf("%s\n", qstring_get_str(str));
2511 qobject_unref(obj);
2512 visit_free(v);
2513 qobject_unref(str);
2516 static void dump_json_image_info(ImageInfo *info)
2518 QString *str;
2519 QObject *obj;
2520 Visitor *v = qobject_output_visitor_new(&obj);
2522 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2523 visit_complete(v, &obj);
2524 str = qobject_to_json_pretty(obj);
2525 assert(str != NULL);
2526 printf("%s\n", qstring_get_str(str));
2527 qobject_unref(obj);
2528 visit_free(v);
2529 qobject_unref(str);
2532 static void dump_human_image_info_list(ImageInfoList *list)
2534 ImageInfoList *elem;
2535 bool delim = false;
2537 for (elem = list; elem; elem = elem->next) {
2538 if (delim) {
2539 printf("\n");
2541 delim = true;
2543 bdrv_image_info_dump(fprintf, stdout, elem->value);
2547 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2549 return strcmp(a, b) == 0;
2553 * Open an image file chain and return an ImageInfoList
2555 * @filename: topmost image filename
2556 * @fmt: topmost image format (may be NULL to autodetect)
2557 * @chain: true - enumerate entire backing file chain
2558 * false - only topmost image file
2560 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2561 * image file. If there was an error a message will have been printed to
2562 * stderr.
2564 static ImageInfoList *collect_image_info_list(bool image_opts,
2565 const char *filename,
2566 const char *fmt,
2567 bool chain, bool force_share)
2569 ImageInfoList *head = NULL;
2570 ImageInfoList **last = &head;
2571 GHashTable *filenames;
2572 Error *err = NULL;
2574 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2576 while (filename) {
2577 BlockBackend *blk;
2578 BlockDriverState *bs;
2579 ImageInfo *info;
2580 ImageInfoList *elem;
2582 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2583 error_report("Backing file '%s' creates an infinite loop.",
2584 filename);
2585 goto err;
2587 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2589 blk = img_open(image_opts, filename, fmt,
2590 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2591 force_share);
2592 if (!blk) {
2593 goto err;
2595 bs = blk_bs(blk);
2597 bdrv_query_image_info(bs, &info, &err);
2598 if (err) {
2599 error_report_err(err);
2600 blk_unref(blk);
2601 goto err;
2604 elem = g_new0(ImageInfoList, 1);
2605 elem->value = info;
2606 *last = elem;
2607 last = &elem->next;
2609 blk_unref(blk);
2611 filename = fmt = NULL;
2612 if (chain) {
2613 if (info->has_full_backing_filename) {
2614 filename = info->full_backing_filename;
2615 } else if (info->has_backing_filename) {
2616 error_report("Could not determine absolute backing filename,"
2617 " but backing filename '%s' present",
2618 info->backing_filename);
2619 goto err;
2621 if (info->has_backing_filename_format) {
2622 fmt = info->backing_filename_format;
2626 g_hash_table_destroy(filenames);
2627 return head;
2629 err:
2630 qapi_free_ImageInfoList(head);
2631 g_hash_table_destroy(filenames);
2632 return NULL;
2635 static int img_info(int argc, char **argv)
2637 int c;
2638 OutputFormat output_format = OFORMAT_HUMAN;
2639 bool chain = false;
2640 const char *filename, *fmt, *output;
2641 ImageInfoList *list;
2642 bool image_opts = false;
2643 bool force_share = false;
2645 fmt = NULL;
2646 output = NULL;
2647 for(;;) {
2648 int option_index = 0;
2649 static const struct option long_options[] = {
2650 {"help", no_argument, 0, 'h'},
2651 {"format", required_argument, 0, 'f'},
2652 {"output", required_argument, 0, OPTION_OUTPUT},
2653 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2654 {"object", required_argument, 0, OPTION_OBJECT},
2655 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2656 {"force-share", no_argument, 0, 'U'},
2657 {0, 0, 0, 0}
2659 c = getopt_long(argc, argv, ":f:hU",
2660 long_options, &option_index);
2661 if (c == -1) {
2662 break;
2664 switch(c) {
2665 case ':':
2666 missing_argument(argv[optind - 1]);
2667 break;
2668 case '?':
2669 unrecognized_option(argv[optind - 1]);
2670 break;
2671 case 'h':
2672 help();
2673 break;
2674 case 'f':
2675 fmt = optarg;
2676 break;
2677 case 'U':
2678 force_share = true;
2679 break;
2680 case OPTION_OUTPUT:
2681 output = optarg;
2682 break;
2683 case OPTION_BACKING_CHAIN:
2684 chain = true;
2685 break;
2686 case OPTION_OBJECT: {
2687 QemuOpts *opts;
2688 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2689 optarg, true);
2690 if (!opts) {
2691 return 1;
2693 } break;
2694 case OPTION_IMAGE_OPTS:
2695 image_opts = true;
2696 break;
2699 if (optind != argc - 1) {
2700 error_exit("Expecting one image file name");
2702 filename = argv[optind++];
2704 if (output && !strcmp(output, "json")) {
2705 output_format = OFORMAT_JSON;
2706 } else if (output && !strcmp(output, "human")) {
2707 output_format = OFORMAT_HUMAN;
2708 } else if (output) {
2709 error_report("--output must be used with human or json as argument.");
2710 return 1;
2713 if (qemu_opts_foreach(&qemu_object_opts,
2714 user_creatable_add_opts_foreach,
2715 NULL, NULL)) {
2716 return 1;
2719 list = collect_image_info_list(image_opts, filename, fmt, chain,
2720 force_share);
2721 if (!list) {
2722 return 1;
2725 switch (output_format) {
2726 case OFORMAT_HUMAN:
2727 dump_human_image_info_list(list);
2728 break;
2729 case OFORMAT_JSON:
2730 if (chain) {
2731 dump_json_image_info_list(list);
2732 } else {
2733 dump_json_image_info(list->value);
2735 break;
2738 qapi_free_ImageInfoList(list);
2739 return 0;
2742 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2743 MapEntry *next)
2745 switch (output_format) {
2746 case OFORMAT_HUMAN:
2747 if (e->data && !e->has_offset) {
2748 error_report("File contains external, encrypted or compressed clusters.");
2749 exit(1);
2751 if (e->data && !e->zero) {
2752 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2753 e->start, e->length,
2754 e->has_offset ? e->offset : 0,
2755 e->has_filename ? e->filename : "");
2757 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2758 * Modify the flags here to allow more coalescing.
2760 if (next && (!next->data || next->zero)) {
2761 next->data = false;
2762 next->zero = true;
2764 break;
2765 case OFORMAT_JSON:
2766 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2767 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2768 (e->start == 0 ? "[" : ",\n"),
2769 e->start, e->length, e->depth,
2770 e->zero ? "true" : "false",
2771 e->data ? "true" : "false");
2772 if (e->has_offset) {
2773 printf(", \"offset\": %"PRId64"", e->offset);
2775 putchar('}');
2777 if (!next) {
2778 printf("]\n");
2780 break;
2784 static int get_block_status(BlockDriverState *bs, int64_t offset,
2785 int64_t bytes, MapEntry *e)
2787 int ret;
2788 int depth;
2789 BlockDriverState *file;
2790 bool has_offset;
2791 int64_t map;
2793 /* As an optimization, we could cache the current range of unallocated
2794 * clusters in each file of the chain, and avoid querying the same
2795 * range repeatedly.
2798 depth = 0;
2799 for (;;) {
2800 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
2801 if (ret < 0) {
2802 return ret;
2804 assert(bytes);
2805 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2806 break;
2808 bs = backing_bs(bs);
2809 if (bs == NULL) {
2810 ret = 0;
2811 break;
2814 depth++;
2817 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2819 *e = (MapEntry) {
2820 .start = offset,
2821 .length = bytes,
2822 .data = !!(ret & BDRV_BLOCK_DATA),
2823 .zero = !!(ret & BDRV_BLOCK_ZERO),
2824 .offset = map,
2825 .has_offset = has_offset,
2826 .depth = depth,
2827 .has_filename = file && has_offset,
2828 .filename = file && has_offset ? file->filename : NULL,
2831 return 0;
2834 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2836 if (curr->length == 0) {
2837 return false;
2839 if (curr->zero != next->zero ||
2840 curr->data != next->data ||
2841 curr->depth != next->depth ||
2842 curr->has_filename != next->has_filename ||
2843 curr->has_offset != next->has_offset) {
2844 return false;
2846 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2847 return false;
2849 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2850 return false;
2852 return true;
2855 static int img_map(int argc, char **argv)
2857 int c;
2858 OutputFormat output_format = OFORMAT_HUMAN;
2859 BlockBackend *blk;
2860 BlockDriverState *bs;
2861 const char *filename, *fmt, *output;
2862 int64_t length;
2863 MapEntry curr = { .length = 0 }, next;
2864 int ret = 0;
2865 bool image_opts = false;
2866 bool force_share = false;
2868 fmt = NULL;
2869 output = NULL;
2870 for (;;) {
2871 int option_index = 0;
2872 static const struct option long_options[] = {
2873 {"help", no_argument, 0, 'h'},
2874 {"format", required_argument, 0, 'f'},
2875 {"output", required_argument, 0, OPTION_OUTPUT},
2876 {"object", required_argument, 0, OPTION_OBJECT},
2877 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2878 {"force-share", no_argument, 0, 'U'},
2879 {0, 0, 0, 0}
2881 c = getopt_long(argc, argv, ":f:hU",
2882 long_options, &option_index);
2883 if (c == -1) {
2884 break;
2886 switch (c) {
2887 case ':':
2888 missing_argument(argv[optind - 1]);
2889 break;
2890 case '?':
2891 unrecognized_option(argv[optind - 1]);
2892 break;
2893 case 'h':
2894 help();
2895 break;
2896 case 'f':
2897 fmt = optarg;
2898 break;
2899 case 'U':
2900 force_share = true;
2901 break;
2902 case OPTION_OUTPUT:
2903 output = optarg;
2904 break;
2905 case OPTION_OBJECT: {
2906 QemuOpts *opts;
2907 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2908 optarg, true);
2909 if (!opts) {
2910 return 1;
2912 } break;
2913 case OPTION_IMAGE_OPTS:
2914 image_opts = true;
2915 break;
2918 if (optind != argc - 1) {
2919 error_exit("Expecting one image file name");
2921 filename = argv[optind];
2923 if (output && !strcmp(output, "json")) {
2924 output_format = OFORMAT_JSON;
2925 } else if (output && !strcmp(output, "human")) {
2926 output_format = OFORMAT_HUMAN;
2927 } else if (output) {
2928 error_report("--output must be used with human or json as argument.");
2929 return 1;
2932 if (qemu_opts_foreach(&qemu_object_opts,
2933 user_creatable_add_opts_foreach,
2934 NULL, NULL)) {
2935 return 1;
2938 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2939 if (!blk) {
2940 return 1;
2942 bs = blk_bs(blk);
2944 if (output_format == OFORMAT_HUMAN) {
2945 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2948 length = blk_getlength(blk);
2949 while (curr.start + curr.length < length) {
2950 int64_t offset = curr.start + curr.length;
2951 int64_t n;
2953 /* Probe up to 1 GiB at a time. */
2954 n = MIN(1 << 30, length - offset);
2955 ret = get_block_status(bs, offset, n, &next);
2957 if (ret < 0) {
2958 error_report("Could not read file metadata: %s", strerror(-ret));
2959 goto out;
2962 if (entry_mergeable(&curr, &next)) {
2963 curr.length += next.length;
2964 continue;
2967 if (curr.length > 0) {
2968 dump_map_entry(output_format, &curr, &next);
2970 curr = next;
2973 dump_map_entry(output_format, &curr, NULL);
2975 out:
2976 blk_unref(blk);
2977 return ret < 0;
2980 #define SNAPSHOT_LIST 1
2981 #define SNAPSHOT_CREATE 2
2982 #define SNAPSHOT_APPLY 3
2983 #define SNAPSHOT_DELETE 4
2985 static int img_snapshot(int argc, char **argv)
2987 BlockBackend *blk;
2988 BlockDriverState *bs;
2989 QEMUSnapshotInfo sn;
2990 char *filename, *snapshot_name = NULL;
2991 int c, ret = 0, bdrv_oflags;
2992 int action = 0;
2993 qemu_timeval tv;
2994 bool quiet = false;
2995 Error *err = NULL;
2996 bool image_opts = false;
2997 bool force_share = false;
2999 bdrv_oflags = BDRV_O_RDWR;
3000 /* Parse commandline parameters */
3001 for(;;) {
3002 static const struct option long_options[] = {
3003 {"help", no_argument, 0, 'h'},
3004 {"object", required_argument, 0, OPTION_OBJECT},
3005 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3006 {"force-share", no_argument, 0, 'U'},
3007 {0, 0, 0, 0}
3009 c = getopt_long(argc, argv, ":la:c:d:hqU",
3010 long_options, NULL);
3011 if (c == -1) {
3012 break;
3014 switch(c) {
3015 case ':':
3016 missing_argument(argv[optind - 1]);
3017 break;
3018 case '?':
3019 unrecognized_option(argv[optind - 1]);
3020 break;
3021 case 'h':
3022 help();
3023 return 0;
3024 case 'l':
3025 if (action) {
3026 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3027 return 0;
3029 action = SNAPSHOT_LIST;
3030 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3031 break;
3032 case 'a':
3033 if (action) {
3034 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3035 return 0;
3037 action = SNAPSHOT_APPLY;
3038 snapshot_name = optarg;
3039 break;
3040 case 'c':
3041 if (action) {
3042 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3043 return 0;
3045 action = SNAPSHOT_CREATE;
3046 snapshot_name = optarg;
3047 break;
3048 case 'd':
3049 if (action) {
3050 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3051 return 0;
3053 action = SNAPSHOT_DELETE;
3054 snapshot_name = optarg;
3055 break;
3056 case 'q':
3057 quiet = true;
3058 break;
3059 case 'U':
3060 force_share = true;
3061 break;
3062 case OPTION_OBJECT: {
3063 QemuOpts *opts;
3064 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3065 optarg, true);
3066 if (!opts) {
3067 return 1;
3069 } break;
3070 case OPTION_IMAGE_OPTS:
3071 image_opts = true;
3072 break;
3076 if (optind != argc - 1) {
3077 error_exit("Expecting one image file name");
3079 filename = argv[optind++];
3081 if (qemu_opts_foreach(&qemu_object_opts,
3082 user_creatable_add_opts_foreach,
3083 NULL, NULL)) {
3084 return 1;
3087 /* Open the image */
3088 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3089 force_share);
3090 if (!blk) {
3091 return 1;
3093 bs = blk_bs(blk);
3095 /* Perform the requested action */
3096 switch(action) {
3097 case SNAPSHOT_LIST:
3098 dump_snapshots(bs);
3099 break;
3101 case SNAPSHOT_CREATE:
3102 memset(&sn, 0, sizeof(sn));
3103 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3105 qemu_gettimeofday(&tv);
3106 sn.date_sec = tv.tv_sec;
3107 sn.date_nsec = tv.tv_usec * 1000;
3109 ret = bdrv_snapshot_create(bs, &sn);
3110 if (ret) {
3111 error_report("Could not create snapshot '%s': %d (%s)",
3112 snapshot_name, ret, strerror(-ret));
3114 break;
3116 case SNAPSHOT_APPLY:
3117 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3118 if (ret) {
3119 error_reportf_err(err, "Could not apply snapshot '%s': ",
3120 snapshot_name);
3122 break;
3124 case SNAPSHOT_DELETE:
3125 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3126 if (err) {
3127 error_reportf_err(err, "Could not delete snapshot '%s': ",
3128 snapshot_name);
3129 ret = 1;
3131 break;
3134 /* Cleanup */
3135 blk_unref(blk);
3136 if (ret) {
3137 return 1;
3139 return 0;
3142 static int img_rebase(int argc, char **argv)
3144 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3145 uint8_t *buf_old = NULL;
3146 uint8_t *buf_new = NULL;
3147 BlockDriverState *bs = NULL;
3148 char *filename;
3149 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3150 int c, flags, src_flags, ret;
3151 bool writethrough, src_writethrough;
3152 int unsafe = 0;
3153 bool force_share = false;
3154 int progress = 0;
3155 bool quiet = false;
3156 Error *local_err = NULL;
3157 bool image_opts = false;
3159 /* Parse commandline parameters */
3160 fmt = NULL;
3161 cache = BDRV_DEFAULT_CACHE;
3162 src_cache = BDRV_DEFAULT_CACHE;
3163 out_baseimg = NULL;
3164 out_basefmt = NULL;
3165 for(;;) {
3166 static const struct option long_options[] = {
3167 {"help", no_argument, 0, 'h'},
3168 {"object", required_argument, 0, OPTION_OBJECT},
3169 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3170 {"force-share", no_argument, 0, 'U'},
3171 {0, 0, 0, 0}
3173 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3174 long_options, NULL);
3175 if (c == -1) {
3176 break;
3178 switch(c) {
3179 case ':':
3180 missing_argument(argv[optind - 1]);
3181 break;
3182 case '?':
3183 unrecognized_option(argv[optind - 1]);
3184 break;
3185 case 'h':
3186 help();
3187 return 0;
3188 case 'f':
3189 fmt = optarg;
3190 break;
3191 case 'F':
3192 out_basefmt = optarg;
3193 break;
3194 case 'b':
3195 out_baseimg = optarg;
3196 break;
3197 case 'u':
3198 unsafe = 1;
3199 break;
3200 case 'p':
3201 progress = 1;
3202 break;
3203 case 't':
3204 cache = optarg;
3205 break;
3206 case 'T':
3207 src_cache = optarg;
3208 break;
3209 case 'q':
3210 quiet = true;
3211 break;
3212 case OPTION_OBJECT: {
3213 QemuOpts *opts;
3214 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3215 optarg, true);
3216 if (!opts) {
3217 return 1;
3219 } break;
3220 case OPTION_IMAGE_OPTS:
3221 image_opts = true;
3222 break;
3223 case 'U':
3224 force_share = true;
3225 break;
3229 if (quiet) {
3230 progress = 0;
3233 if (optind != argc - 1) {
3234 error_exit("Expecting one image file name");
3236 if (!unsafe && !out_baseimg) {
3237 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3239 filename = argv[optind++];
3241 if (qemu_opts_foreach(&qemu_object_opts,
3242 user_creatable_add_opts_foreach,
3243 NULL, NULL)) {
3244 return 1;
3247 qemu_progress_init(progress, 2.0);
3248 qemu_progress_print(0, 100);
3250 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3251 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3252 if (ret < 0) {
3253 error_report("Invalid cache option: %s", cache);
3254 goto out;
3257 src_flags = 0;
3258 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3259 if (ret < 0) {
3260 error_report("Invalid source cache option: %s", src_cache);
3261 goto out;
3264 /* The source files are opened read-only, don't care about WCE */
3265 assert((src_flags & BDRV_O_RDWR) == 0);
3266 (void) src_writethrough;
3269 * Open the images.
3271 * Ignore the old backing file for unsafe rebase in case we want to correct
3272 * the reference to a renamed or moved backing file.
3274 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3275 false);
3276 if (!blk) {
3277 ret = -1;
3278 goto out;
3280 bs = blk_bs(blk);
3282 if (out_basefmt != NULL) {
3283 if (bdrv_find_format(out_basefmt) == NULL) {
3284 error_report("Invalid format name: '%s'", out_basefmt);
3285 ret = -1;
3286 goto out;
3290 /* For safe rebasing we need to compare old and new backing file */
3291 if (!unsafe) {
3292 char backing_name[PATH_MAX];
3293 QDict *options = NULL;
3295 if (bs->backing_format[0] != '\0') {
3296 options = qdict_new();
3297 qdict_put_str(options, "driver", bs->backing_format);
3300 if (force_share) {
3301 if (!options) {
3302 options = qdict_new();
3304 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3306 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3307 blk_old_backing = blk_new_open(backing_name, NULL,
3308 options, src_flags, &local_err);
3309 if (!blk_old_backing) {
3310 error_reportf_err(local_err,
3311 "Could not open old backing file '%s': ",
3312 backing_name);
3313 ret = -1;
3314 goto out;
3317 if (out_baseimg[0]) {
3318 const char *overlay_filename;
3319 char *out_real_path;
3321 options = qdict_new();
3322 if (out_basefmt) {
3323 qdict_put_str(options, "driver", out_basefmt);
3325 if (force_share) {
3326 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3329 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3330 : bs->filename;
3331 out_real_path = g_malloc(PATH_MAX);
3333 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3334 out_baseimg,
3335 out_real_path,
3336 PATH_MAX,
3337 &local_err);
3338 if (local_err) {
3339 error_reportf_err(local_err,
3340 "Could not resolve backing filename: ");
3341 ret = -1;
3342 g_free(out_real_path);
3343 goto out;
3346 blk_new_backing = blk_new_open(out_real_path, NULL,
3347 options, src_flags, &local_err);
3348 g_free(out_real_path);
3349 if (!blk_new_backing) {
3350 error_reportf_err(local_err,
3351 "Could not open new backing file '%s': ",
3352 out_baseimg);
3353 ret = -1;
3354 goto out;
3360 * Check each unallocated cluster in the COW file. If it is unallocated,
3361 * accesses go to the backing file. We must therefore compare this cluster
3362 * in the old and new backing file, and if they differ we need to copy it
3363 * from the old backing file into the COW file.
3365 * If qemu-img crashes during this step, no harm is done. The content of
3366 * the image is the same as the original one at any time.
3368 if (!unsafe) {
3369 int64_t size;
3370 int64_t old_backing_size;
3371 int64_t new_backing_size = 0;
3372 uint64_t offset;
3373 int64_t n;
3374 float local_progress = 0;
3376 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3377 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3379 size = blk_getlength(blk);
3380 if (size < 0) {
3381 error_report("Could not get size of '%s': %s",
3382 filename, strerror(-size));
3383 ret = -1;
3384 goto out;
3386 old_backing_size = blk_getlength(blk_old_backing);
3387 if (old_backing_size < 0) {
3388 char backing_name[PATH_MAX];
3390 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3391 error_report("Could not get size of '%s': %s",
3392 backing_name, strerror(-old_backing_size));
3393 ret = -1;
3394 goto out;
3396 if (blk_new_backing) {
3397 new_backing_size = blk_getlength(blk_new_backing);
3398 if (new_backing_size < 0) {
3399 error_report("Could not get size of '%s': %s",
3400 out_baseimg, strerror(-new_backing_size));
3401 ret = -1;
3402 goto out;
3406 if (size != 0) {
3407 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3410 for (offset = 0; offset < size; offset += n) {
3411 /* How many bytes can we handle with the next read? */
3412 n = MIN(IO_BUF_SIZE, size - offset);
3414 /* If the cluster is allocated, we don't need to take action */
3415 ret = bdrv_is_allocated(bs, offset, n, &n);
3416 if (ret < 0) {
3417 error_report("error while reading image metadata: %s",
3418 strerror(-ret));
3419 goto out;
3421 if (ret) {
3422 continue;
3426 * Read old and new backing file and take into consideration that
3427 * backing files may be smaller than the COW image.
3429 if (offset >= old_backing_size) {
3430 memset(buf_old, 0, n);
3431 } else {
3432 if (offset + n > old_backing_size) {
3433 n = old_backing_size - offset;
3436 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3437 if (ret < 0) {
3438 error_report("error while reading from old backing file");
3439 goto out;
3443 if (offset >= new_backing_size || !blk_new_backing) {
3444 memset(buf_new, 0, n);
3445 } else {
3446 if (offset + n > new_backing_size) {
3447 n = new_backing_size - offset;
3450 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3451 if (ret < 0) {
3452 error_report("error while reading from new backing file");
3453 goto out;
3457 /* If they differ, we need to write to the COW file */
3458 uint64_t written = 0;
3460 while (written < n) {
3461 int64_t pnum;
3463 if (compare_buffers(buf_old + written, buf_new + written,
3464 n - written, &pnum))
3466 ret = blk_pwrite(blk, offset + written,
3467 buf_old + written, pnum, 0);
3468 if (ret < 0) {
3469 error_report("Error while writing to COW image: %s",
3470 strerror(-ret));
3471 goto out;
3475 written += pnum;
3477 qemu_progress_print(local_progress, 100);
3482 * Change the backing file. All clusters that are different from the old
3483 * backing file are overwritten in the COW file now, so the visible content
3484 * doesn't change when we switch the backing file.
3486 if (out_baseimg && *out_baseimg) {
3487 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3488 } else {
3489 ret = bdrv_change_backing_file(bs, NULL, NULL);
3492 if (ret == -ENOSPC) {
3493 error_report("Could not change the backing file to '%s': No "
3494 "space left in the file header", out_baseimg);
3495 } else if (ret < 0) {
3496 error_report("Could not change the backing file to '%s': %s",
3497 out_baseimg, strerror(-ret));
3500 qemu_progress_print(100, 0);
3502 * TODO At this point it is possible to check if any clusters that are
3503 * allocated in the COW file are the same in the backing file. If so, they
3504 * could be dropped from the COW file. Don't do this before switching the
3505 * backing file, in case of a crash this would lead to corruption.
3507 out:
3508 qemu_progress_end();
3509 /* Cleanup */
3510 if (!unsafe) {
3511 blk_unref(blk_old_backing);
3512 blk_unref(blk_new_backing);
3514 qemu_vfree(buf_old);
3515 qemu_vfree(buf_new);
3517 blk_unref(blk);
3518 if (ret) {
3519 return 1;
3521 return 0;
3524 static int img_resize(int argc, char **argv)
3526 Error *err = NULL;
3527 int c, ret, relative;
3528 const char *filename, *fmt, *size;
3529 int64_t n, total_size, current_size, new_size;
3530 bool quiet = false;
3531 BlockBackend *blk = NULL;
3532 PreallocMode prealloc = PREALLOC_MODE_OFF;
3533 QemuOpts *param;
3535 static QemuOptsList resize_options = {
3536 .name = "resize_options",
3537 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3538 .desc = {
3540 .name = BLOCK_OPT_SIZE,
3541 .type = QEMU_OPT_SIZE,
3542 .help = "Virtual disk size"
3543 }, {
3544 /* end of list */
3548 bool image_opts = false;
3549 bool shrink = false;
3551 /* Remove size from argv manually so that negative numbers are not treated
3552 * as options by getopt. */
3553 if (argc < 3) {
3554 error_exit("Not enough arguments");
3555 return 1;
3558 size = argv[--argc];
3560 /* Parse getopt arguments */
3561 fmt = NULL;
3562 for(;;) {
3563 static const struct option long_options[] = {
3564 {"help", no_argument, 0, 'h'},
3565 {"object", required_argument, 0, OPTION_OBJECT},
3566 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3567 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3568 {"shrink", no_argument, 0, OPTION_SHRINK},
3569 {0, 0, 0, 0}
3571 c = getopt_long(argc, argv, ":f:hq",
3572 long_options, NULL);
3573 if (c == -1) {
3574 break;
3576 switch(c) {
3577 case ':':
3578 missing_argument(argv[optind - 1]);
3579 break;
3580 case '?':
3581 unrecognized_option(argv[optind - 1]);
3582 break;
3583 case 'h':
3584 help();
3585 break;
3586 case 'f':
3587 fmt = optarg;
3588 break;
3589 case 'q':
3590 quiet = true;
3591 break;
3592 case OPTION_OBJECT: {
3593 QemuOpts *opts;
3594 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3595 optarg, true);
3596 if (!opts) {
3597 return 1;
3599 } break;
3600 case OPTION_IMAGE_OPTS:
3601 image_opts = true;
3602 break;
3603 case OPTION_PREALLOCATION:
3604 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3605 PREALLOC_MODE__MAX, NULL);
3606 if (prealloc == PREALLOC_MODE__MAX) {
3607 error_report("Invalid preallocation mode '%s'", optarg);
3608 return 1;
3610 break;
3611 case OPTION_SHRINK:
3612 shrink = true;
3613 break;
3616 if (optind != argc - 1) {
3617 error_exit("Expecting image file name and size");
3619 filename = argv[optind++];
3621 if (qemu_opts_foreach(&qemu_object_opts,
3622 user_creatable_add_opts_foreach,
3623 NULL, NULL)) {
3624 return 1;
3627 /* Choose grow, shrink, or absolute resize mode */
3628 switch (size[0]) {
3629 case '+':
3630 relative = 1;
3631 size++;
3632 break;
3633 case '-':
3634 relative = -1;
3635 size++;
3636 break;
3637 default:
3638 relative = 0;
3639 break;
3642 /* Parse size */
3643 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3644 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3645 if (err) {
3646 error_report_err(err);
3647 ret = -1;
3648 qemu_opts_del(param);
3649 goto out;
3651 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3652 qemu_opts_del(param);
3654 blk = img_open(image_opts, filename, fmt,
3655 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3656 false);
3657 if (!blk) {
3658 ret = -1;
3659 goto out;
3662 current_size = blk_getlength(blk);
3663 if (current_size < 0) {
3664 error_report("Failed to inquire current image length: %s",
3665 strerror(-current_size));
3666 ret = -1;
3667 goto out;
3670 if (relative) {
3671 total_size = current_size + n * relative;
3672 } else {
3673 total_size = n;
3675 if (total_size <= 0) {
3676 error_report("New image size must be positive");
3677 ret = -1;
3678 goto out;
3681 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3682 error_report("Preallocation can only be used for growing images");
3683 ret = -1;
3684 goto out;
3687 if (total_size < current_size && !shrink) {
3688 warn_report("Shrinking an image will delete all data beyond the "
3689 "shrunken image's end. Before performing such an "
3690 "operation, make sure there is no important data there.");
3692 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3693 error_report(
3694 "Use the --shrink option to perform a shrink operation.");
3695 ret = -1;
3696 goto out;
3697 } else {
3698 warn_report("Using the --shrink option will suppress this message. "
3699 "Note that future versions of qemu-img may refuse to "
3700 "shrink images without this option.");
3704 ret = blk_truncate(blk, total_size, prealloc, &err);
3705 if (ret < 0) {
3706 error_report_err(err);
3707 goto out;
3710 new_size = blk_getlength(blk);
3711 if (new_size < 0) {
3712 error_report("Failed to verify truncated image length: %s",
3713 strerror(-new_size));
3714 ret = -1;
3715 goto out;
3718 /* Some block drivers implement a truncation method, but only so
3719 * the user can cause qemu to refresh the image's size from disk.
3720 * The idea is that the user resizes the image outside of qemu and
3721 * then invokes block_resize to inform qemu about it.
3722 * (This includes iscsi and file-posix for device files.)
3723 * Of course, that is not the behavior someone invoking
3724 * qemu-img resize would find useful, so we catch that behavior
3725 * here and tell the user. */
3726 if (new_size != total_size && new_size == current_size) {
3727 error_report("Image was not resized; resizing may not be supported "
3728 "for this image");
3729 ret = -1;
3730 goto out;
3733 if (new_size != total_size) {
3734 warn_report("Image should have been resized to %" PRIi64
3735 " bytes, but was resized to %" PRIi64 " bytes",
3736 total_size, new_size);
3739 qprintf(quiet, "Image resized.\n");
3741 out:
3742 blk_unref(blk);
3743 if (ret) {
3744 return 1;
3746 return 0;
3749 static void amend_status_cb(BlockDriverState *bs,
3750 int64_t offset, int64_t total_work_size,
3751 void *opaque)
3753 qemu_progress_print(100.f * offset / total_work_size, 0);
3756 static int print_amend_option_help(const char *format)
3758 BlockDriver *drv;
3760 /* Find driver and parse its options */
3761 drv = bdrv_find_format(format);
3762 if (!drv) {
3763 error_report("Unknown file format '%s'", format);
3764 return 1;
3767 if (!drv->bdrv_amend_options) {
3768 error_report("Format driver '%s' does not support option amendment",
3769 format);
3770 return 1;
3773 /* Every driver supporting amendment must have create_opts */
3774 assert(drv->create_opts);
3776 printf("Creation options for '%s':\n", format);
3777 qemu_opts_print_help(drv->create_opts, false);
3778 printf("\nNote that not all of these options may be amendable.\n");
3779 return 0;
3782 static int img_amend(int argc, char **argv)
3784 Error *err = NULL;
3785 int c, ret = 0;
3786 char *options = NULL;
3787 QemuOptsList *create_opts = NULL;
3788 QemuOpts *opts = NULL;
3789 const char *fmt = NULL, *filename, *cache;
3790 int flags;
3791 bool writethrough;
3792 bool quiet = false, progress = false;
3793 BlockBackend *blk = NULL;
3794 BlockDriverState *bs = NULL;
3795 bool image_opts = false;
3797 cache = BDRV_DEFAULT_CACHE;
3798 for (;;) {
3799 static const struct option long_options[] = {
3800 {"help", no_argument, 0, 'h'},
3801 {"object", required_argument, 0, OPTION_OBJECT},
3802 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3803 {0, 0, 0, 0}
3805 c = getopt_long(argc, argv, ":ho:f:t:pq",
3806 long_options, NULL);
3807 if (c == -1) {
3808 break;
3811 switch (c) {
3812 case ':':
3813 missing_argument(argv[optind - 1]);
3814 break;
3815 case '?':
3816 unrecognized_option(argv[optind - 1]);
3817 break;
3818 case 'h':
3819 help();
3820 break;
3821 case 'o':
3822 if (!is_valid_option_list(optarg)) {
3823 error_report("Invalid option list: %s", optarg);
3824 ret = -1;
3825 goto out_no_progress;
3827 if (!options) {
3828 options = g_strdup(optarg);
3829 } else {
3830 char *old_options = options;
3831 options = g_strdup_printf("%s,%s", options, optarg);
3832 g_free(old_options);
3834 break;
3835 case 'f':
3836 fmt = optarg;
3837 break;
3838 case 't':
3839 cache = optarg;
3840 break;
3841 case 'p':
3842 progress = true;
3843 break;
3844 case 'q':
3845 quiet = true;
3846 break;
3847 case OPTION_OBJECT:
3848 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3849 optarg, true);
3850 if (!opts) {
3851 ret = -1;
3852 goto out_no_progress;
3854 break;
3855 case OPTION_IMAGE_OPTS:
3856 image_opts = true;
3857 break;
3861 if (!options) {
3862 error_exit("Must specify options (-o)");
3865 if (qemu_opts_foreach(&qemu_object_opts,
3866 user_creatable_add_opts_foreach,
3867 NULL, NULL)) {
3868 ret = -1;
3869 goto out_no_progress;
3872 if (quiet) {
3873 progress = false;
3875 qemu_progress_init(progress, 1.0);
3877 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3878 if (fmt && has_help_option(options)) {
3879 /* If a format is explicitly specified (and possibly no filename is
3880 * given), print option help here */
3881 ret = print_amend_option_help(fmt);
3882 goto out;
3885 if (optind != argc - 1) {
3886 error_report("Expecting one image file name");
3887 ret = -1;
3888 goto out;
3891 flags = BDRV_O_RDWR;
3892 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3893 if (ret < 0) {
3894 error_report("Invalid cache option: %s", cache);
3895 goto out;
3898 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3899 false);
3900 if (!blk) {
3901 ret = -1;
3902 goto out;
3904 bs = blk_bs(blk);
3906 fmt = bs->drv->format_name;
3908 if (has_help_option(options)) {
3909 /* If the format was auto-detected, print option help here */
3910 ret = print_amend_option_help(fmt);
3911 goto out;
3914 if (!bs->drv->bdrv_amend_options) {
3915 error_report("Format driver '%s' does not support option amendment",
3916 fmt);
3917 ret = -1;
3918 goto out;
3921 /* Every driver supporting amendment must have create_opts */
3922 assert(bs->drv->create_opts);
3924 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3925 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3926 qemu_opts_do_parse(opts, options, NULL, &err);
3927 if (err) {
3928 error_report_err(err);
3929 ret = -1;
3930 goto out;
3933 /* In case the driver does not call amend_status_cb() */
3934 qemu_progress_print(0.f, 0);
3935 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
3936 qemu_progress_print(100.f, 0);
3937 if (ret < 0) {
3938 error_report_err(err);
3939 goto out;
3942 out:
3943 qemu_progress_end();
3945 out_no_progress:
3946 blk_unref(blk);
3947 qemu_opts_del(opts);
3948 qemu_opts_free(create_opts);
3949 g_free(options);
3951 if (ret) {
3952 return 1;
3954 return 0;
3957 typedef struct BenchData {
3958 BlockBackend *blk;
3959 uint64_t image_size;
3960 bool write;
3961 int bufsize;
3962 int step;
3963 int nrreq;
3964 int n;
3965 int flush_interval;
3966 bool drain_on_flush;
3967 uint8_t *buf;
3968 QEMUIOVector *qiov;
3970 int in_flight;
3971 bool in_flush;
3972 uint64_t offset;
3973 } BenchData;
3975 static void bench_undrained_flush_cb(void *opaque, int ret)
3977 if (ret < 0) {
3978 error_report("Failed flush request: %s", strerror(-ret));
3979 exit(EXIT_FAILURE);
3983 static void bench_cb(void *opaque, int ret)
3985 BenchData *b = opaque;
3986 BlockAIOCB *acb;
3988 if (ret < 0) {
3989 error_report("Failed request: %s", strerror(-ret));
3990 exit(EXIT_FAILURE);
3993 if (b->in_flush) {
3994 /* Just finished a flush with drained queue: Start next requests */
3995 assert(b->in_flight == 0);
3996 b->in_flush = false;
3997 } else if (b->in_flight > 0) {
3998 int remaining = b->n - b->in_flight;
4000 b->n--;
4001 b->in_flight--;
4003 /* Time for flush? Drain queue if requested, then flush */
4004 if (b->flush_interval && remaining % b->flush_interval == 0) {
4005 if (!b->in_flight || !b->drain_on_flush) {
4006 BlockCompletionFunc *cb;
4008 if (b->drain_on_flush) {
4009 b->in_flush = true;
4010 cb = bench_cb;
4011 } else {
4012 cb = bench_undrained_flush_cb;
4015 acb = blk_aio_flush(b->blk, cb, b);
4016 if (!acb) {
4017 error_report("Failed to issue flush request");
4018 exit(EXIT_FAILURE);
4021 if (b->drain_on_flush) {
4022 return;
4027 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4028 int64_t offset = b->offset;
4029 /* blk_aio_* might look for completed I/Os and kick bench_cb
4030 * again, so make sure this operation is counted by in_flight
4031 * and b->offset is ready for the next submission.
4033 b->in_flight++;
4034 b->offset += b->step;
4035 b->offset %= b->image_size;
4036 if (b->write) {
4037 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4038 } else {
4039 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4041 if (!acb) {
4042 error_report("Failed to issue request");
4043 exit(EXIT_FAILURE);
4048 static int img_bench(int argc, char **argv)
4050 int c, ret = 0;
4051 const char *fmt = NULL, *filename;
4052 bool quiet = false;
4053 bool image_opts = false;
4054 bool is_write = false;
4055 int count = 75000;
4056 int depth = 64;
4057 int64_t offset = 0;
4058 size_t bufsize = 4096;
4059 int pattern = 0;
4060 size_t step = 0;
4061 int flush_interval = 0;
4062 bool drain_on_flush = true;
4063 int64_t image_size;
4064 BlockBackend *blk = NULL;
4065 BenchData data = {};
4066 int flags = 0;
4067 bool writethrough = false;
4068 struct timeval t1, t2;
4069 int i;
4070 bool force_share = false;
4071 size_t buf_size;
4073 for (;;) {
4074 static const struct option long_options[] = {
4075 {"help", no_argument, 0, 'h'},
4076 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4077 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4078 {"pattern", required_argument, 0, OPTION_PATTERN},
4079 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4080 {"force-share", no_argument, 0, 'U'},
4081 {0, 0, 0, 0}
4083 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
4084 if (c == -1) {
4085 break;
4088 switch (c) {
4089 case ':':
4090 missing_argument(argv[optind - 1]);
4091 break;
4092 case '?':
4093 unrecognized_option(argv[optind - 1]);
4094 break;
4095 case 'h':
4096 help();
4097 break;
4098 case 'c':
4100 unsigned long res;
4102 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4103 error_report("Invalid request count specified");
4104 return 1;
4106 count = res;
4107 break;
4109 case 'd':
4111 unsigned long res;
4113 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4114 error_report("Invalid queue depth specified");
4115 return 1;
4117 depth = res;
4118 break;
4120 case 'f':
4121 fmt = optarg;
4122 break;
4123 case 'n':
4124 flags |= BDRV_O_NATIVE_AIO;
4125 break;
4126 case 'o':
4128 offset = cvtnum(optarg);
4129 if (offset < 0) {
4130 error_report("Invalid offset specified");
4131 return 1;
4133 break;
4135 break;
4136 case 'q':
4137 quiet = true;
4138 break;
4139 case 's':
4141 int64_t sval;
4143 sval = cvtnum(optarg);
4144 if (sval < 0 || sval > INT_MAX) {
4145 error_report("Invalid buffer size specified");
4146 return 1;
4149 bufsize = sval;
4150 break;
4152 case 'S':
4154 int64_t sval;
4156 sval = cvtnum(optarg);
4157 if (sval < 0 || sval > INT_MAX) {
4158 error_report("Invalid step size specified");
4159 return 1;
4162 step = sval;
4163 break;
4165 case 't':
4166 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4167 if (ret < 0) {
4168 error_report("Invalid cache mode");
4169 ret = -1;
4170 goto out;
4172 break;
4173 case 'w':
4174 flags |= BDRV_O_RDWR;
4175 is_write = true;
4176 break;
4177 case 'U':
4178 force_share = true;
4179 break;
4180 case OPTION_PATTERN:
4182 unsigned long res;
4184 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4185 error_report("Invalid pattern byte specified");
4186 return 1;
4188 pattern = res;
4189 break;
4191 case OPTION_FLUSH_INTERVAL:
4193 unsigned long res;
4195 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4196 error_report("Invalid flush interval specified");
4197 return 1;
4199 flush_interval = res;
4200 break;
4202 case OPTION_NO_DRAIN:
4203 drain_on_flush = false;
4204 break;
4205 case OPTION_IMAGE_OPTS:
4206 image_opts = true;
4207 break;
4211 if (optind != argc - 1) {
4212 error_exit("Expecting one image file name");
4214 filename = argv[argc - 1];
4216 if (!is_write && flush_interval) {
4217 error_report("--flush-interval is only available in write tests");
4218 ret = -1;
4219 goto out;
4221 if (flush_interval && flush_interval < depth) {
4222 error_report("Flush interval can't be smaller than depth");
4223 ret = -1;
4224 goto out;
4227 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4228 force_share);
4229 if (!blk) {
4230 ret = -1;
4231 goto out;
4234 image_size = blk_getlength(blk);
4235 if (image_size < 0) {
4236 ret = image_size;
4237 goto out;
4240 data = (BenchData) {
4241 .blk = blk,
4242 .image_size = image_size,
4243 .bufsize = bufsize,
4244 .step = step ?: bufsize,
4245 .nrreq = depth,
4246 .n = count,
4247 .offset = offset,
4248 .write = is_write,
4249 .flush_interval = flush_interval,
4250 .drain_on_flush = drain_on_flush,
4252 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4253 "(starting at offset %" PRId64 ", step size %d)\n",
4254 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4255 data.offset, data.step);
4256 if (flush_interval) {
4257 printf("Sending flush every %d requests\n", flush_interval);
4260 buf_size = data.nrreq * data.bufsize;
4261 data.buf = blk_blockalign(blk, buf_size);
4262 memset(data.buf, pattern, data.nrreq * data.bufsize);
4264 blk_register_buf(blk, data.buf, buf_size);
4266 data.qiov = g_new(QEMUIOVector, data.nrreq);
4267 for (i = 0; i < data.nrreq; i++) {
4268 qemu_iovec_init(&data.qiov[i], 1);
4269 qemu_iovec_add(&data.qiov[i],
4270 data.buf + i * data.bufsize, data.bufsize);
4273 gettimeofday(&t1, NULL);
4274 bench_cb(&data, 0);
4276 while (data.n > 0) {
4277 main_loop_wait(false);
4279 gettimeofday(&t2, NULL);
4281 printf("Run completed in %3.3f seconds.\n",
4282 (t2.tv_sec - t1.tv_sec)
4283 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4285 out:
4286 if (data.buf) {
4287 blk_unregister_buf(blk, data.buf);
4289 qemu_vfree(data.buf);
4290 blk_unref(blk);
4292 if (ret) {
4293 return 1;
4295 return 0;
4298 #define C_BS 01
4299 #define C_COUNT 02
4300 #define C_IF 04
4301 #define C_OF 010
4302 #define C_SKIP 020
4304 struct DdInfo {
4305 unsigned int flags;
4306 int64_t count;
4309 struct DdIo {
4310 int bsz; /* Block size */
4311 char *filename;
4312 uint8_t *buf;
4313 int64_t offset;
4316 struct DdOpts {
4317 const char *name;
4318 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4319 unsigned int flag;
4322 static int img_dd_bs(const char *arg,
4323 struct DdIo *in, struct DdIo *out,
4324 struct DdInfo *dd)
4326 int64_t res;
4328 res = cvtnum(arg);
4330 if (res <= 0 || res > INT_MAX) {
4331 error_report("invalid number: '%s'", arg);
4332 return 1;
4334 in->bsz = out->bsz = res;
4336 return 0;
4339 static int img_dd_count(const char *arg,
4340 struct DdIo *in, struct DdIo *out,
4341 struct DdInfo *dd)
4343 dd->count = cvtnum(arg);
4345 if (dd->count < 0) {
4346 error_report("invalid number: '%s'", arg);
4347 return 1;
4350 return 0;
4353 static int img_dd_if(const char *arg,
4354 struct DdIo *in, struct DdIo *out,
4355 struct DdInfo *dd)
4357 in->filename = g_strdup(arg);
4359 return 0;
4362 static int img_dd_of(const char *arg,
4363 struct DdIo *in, struct DdIo *out,
4364 struct DdInfo *dd)
4366 out->filename = g_strdup(arg);
4368 return 0;
4371 static int img_dd_skip(const char *arg,
4372 struct DdIo *in, struct DdIo *out,
4373 struct DdInfo *dd)
4375 in->offset = cvtnum(arg);
4377 if (in->offset < 0) {
4378 error_report("invalid number: '%s'", arg);
4379 return 1;
4382 return 0;
4385 static int img_dd(int argc, char **argv)
4387 int ret = 0;
4388 char *arg = NULL;
4389 char *tmp;
4390 BlockDriver *drv = NULL, *proto_drv = NULL;
4391 BlockBackend *blk1 = NULL, *blk2 = NULL;
4392 QemuOpts *opts = NULL;
4393 QemuOptsList *create_opts = NULL;
4394 Error *local_err = NULL;
4395 bool image_opts = false;
4396 int c, i;
4397 const char *out_fmt = "raw";
4398 const char *fmt = NULL;
4399 int64_t size = 0;
4400 int64_t block_count = 0, out_pos, in_pos;
4401 bool force_share = false;
4402 struct DdInfo dd = {
4403 .flags = 0,
4404 .count = 0,
4406 struct DdIo in = {
4407 .bsz = 512, /* Block size is by default 512 bytes */
4408 .filename = NULL,
4409 .buf = NULL,
4410 .offset = 0
4412 struct DdIo out = {
4413 .bsz = 512,
4414 .filename = NULL,
4415 .buf = NULL,
4416 .offset = 0
4419 const struct DdOpts options[] = {
4420 { "bs", img_dd_bs, C_BS },
4421 { "count", img_dd_count, C_COUNT },
4422 { "if", img_dd_if, C_IF },
4423 { "of", img_dd_of, C_OF },
4424 { "skip", img_dd_skip, C_SKIP },
4425 { NULL, NULL, 0 }
4427 const struct option long_options[] = {
4428 { "help", no_argument, 0, 'h'},
4429 { "object", required_argument, 0, OPTION_OBJECT},
4430 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4431 { "force-share", no_argument, 0, 'U'},
4432 { 0, 0, 0, 0 }
4435 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4436 if (c == EOF) {
4437 break;
4439 switch (c) {
4440 case 'O':
4441 out_fmt = optarg;
4442 break;
4443 case 'f':
4444 fmt = optarg;
4445 break;
4446 case ':':
4447 missing_argument(argv[optind - 1]);
4448 break;
4449 case '?':
4450 unrecognized_option(argv[optind - 1]);
4451 break;
4452 case 'h':
4453 help();
4454 break;
4455 case 'U':
4456 force_share = true;
4457 break;
4458 case OPTION_OBJECT:
4459 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4460 ret = -1;
4461 goto out;
4463 break;
4464 case OPTION_IMAGE_OPTS:
4465 image_opts = true;
4466 break;
4470 for (i = optind; i < argc; i++) {
4471 int j;
4472 arg = g_strdup(argv[i]);
4474 tmp = strchr(arg, '=');
4475 if (tmp == NULL) {
4476 error_report("unrecognized operand %s", arg);
4477 ret = -1;
4478 goto out;
4481 *tmp++ = '\0';
4483 for (j = 0; options[j].name != NULL; j++) {
4484 if (!strcmp(arg, options[j].name)) {
4485 break;
4488 if (options[j].name == NULL) {
4489 error_report("unrecognized operand %s", arg);
4490 ret = -1;
4491 goto out;
4494 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4495 ret = -1;
4496 goto out;
4498 dd.flags |= options[j].flag;
4499 g_free(arg);
4500 arg = NULL;
4503 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4504 error_report("Must specify both input and output files");
4505 ret = -1;
4506 goto out;
4509 if (qemu_opts_foreach(&qemu_object_opts,
4510 user_creatable_add_opts_foreach,
4511 NULL, NULL)) {
4512 ret = -1;
4513 goto out;
4516 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4517 force_share);
4519 if (!blk1) {
4520 ret = -1;
4521 goto out;
4524 drv = bdrv_find_format(out_fmt);
4525 if (!drv) {
4526 error_report("Unknown file format");
4527 ret = -1;
4528 goto out;
4530 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4532 if (!proto_drv) {
4533 error_report_err(local_err);
4534 ret = -1;
4535 goto out;
4537 if (!drv->create_opts) {
4538 error_report("Format driver '%s' does not support image creation",
4539 drv->format_name);
4540 ret = -1;
4541 goto out;
4543 if (!proto_drv->create_opts) {
4544 error_report("Protocol driver '%s' does not support image creation",
4545 proto_drv->format_name);
4546 ret = -1;
4547 goto out;
4549 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4550 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4552 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4554 size = blk_getlength(blk1);
4555 if (size < 0) {
4556 error_report("Failed to get size for '%s'", in.filename);
4557 ret = -1;
4558 goto out;
4561 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4562 dd.count * in.bsz < size) {
4563 size = dd.count * in.bsz;
4566 /* Overflow means the specified offset is beyond input image's size */
4567 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4568 size < in.bsz * in.offset)) {
4569 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4570 } else {
4571 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4572 size - in.bsz * in.offset, &error_abort);
4575 ret = bdrv_create(drv, out.filename, opts, &local_err);
4576 if (ret < 0) {
4577 error_reportf_err(local_err,
4578 "%s: error while creating output image: ",
4579 out.filename);
4580 ret = -1;
4581 goto out;
4584 /* TODO, we can't honour --image-opts for the target,
4585 * since it needs to be given in a format compatible
4586 * with the bdrv_create() call above which does not
4587 * support image-opts style.
4589 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4590 false, false, false);
4592 if (!blk2) {
4593 ret = -1;
4594 goto out;
4597 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4598 size < in.offset * in.bsz)) {
4599 /* We give a warning if the skip option is bigger than the input
4600 * size and create an empty output disk image (i.e. like dd(1)).
4602 error_report("%s: cannot skip to specified offset", in.filename);
4603 in_pos = size;
4604 } else {
4605 in_pos = in.offset * in.bsz;
4608 in.buf = g_new(uint8_t, in.bsz);
4610 for (out_pos = 0; in_pos < size; block_count++) {
4611 int in_ret, out_ret;
4613 if (in_pos + in.bsz > size) {
4614 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4615 } else {
4616 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4618 if (in_ret < 0) {
4619 error_report("error while reading from input image file: %s",
4620 strerror(-in_ret));
4621 ret = -1;
4622 goto out;
4624 in_pos += in_ret;
4626 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4628 if (out_ret < 0) {
4629 error_report("error while writing to output image file: %s",
4630 strerror(-out_ret));
4631 ret = -1;
4632 goto out;
4634 out_pos += out_ret;
4637 out:
4638 g_free(arg);
4639 qemu_opts_del(opts);
4640 qemu_opts_free(create_opts);
4641 blk_unref(blk1);
4642 blk_unref(blk2);
4643 g_free(in.filename);
4644 g_free(out.filename);
4645 g_free(in.buf);
4646 g_free(out.buf);
4648 if (ret) {
4649 return 1;
4651 return 0;
4654 static void dump_json_block_measure_info(BlockMeasureInfo *info)
4656 QString *str;
4657 QObject *obj;
4658 Visitor *v = qobject_output_visitor_new(&obj);
4660 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4661 visit_complete(v, &obj);
4662 str = qobject_to_json_pretty(obj);
4663 assert(str != NULL);
4664 printf("%s\n", qstring_get_str(str));
4665 qobject_unref(obj);
4666 visit_free(v);
4667 qobject_unref(str);
4670 static int img_measure(int argc, char **argv)
4672 static const struct option long_options[] = {
4673 {"help", no_argument, 0, 'h'},
4674 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4675 {"object", required_argument, 0, OPTION_OBJECT},
4676 {"output", required_argument, 0, OPTION_OUTPUT},
4677 {"size", required_argument, 0, OPTION_SIZE},
4678 {"force-share", no_argument, 0, 'U'},
4679 {0, 0, 0, 0}
4681 OutputFormat output_format = OFORMAT_HUMAN;
4682 BlockBackend *in_blk = NULL;
4683 BlockDriver *drv;
4684 const char *filename = NULL;
4685 const char *fmt = NULL;
4686 const char *out_fmt = "raw";
4687 char *options = NULL;
4688 char *snapshot_name = NULL;
4689 bool force_share = false;
4690 QemuOpts *opts = NULL;
4691 QemuOpts *object_opts = NULL;
4692 QemuOpts *sn_opts = NULL;
4693 QemuOptsList *create_opts = NULL;
4694 bool image_opts = false;
4695 uint64_t img_size = UINT64_MAX;
4696 BlockMeasureInfo *info = NULL;
4697 Error *local_err = NULL;
4698 int ret = 1;
4699 int c;
4701 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4702 long_options, NULL)) != -1) {
4703 switch (c) {
4704 case '?':
4705 case 'h':
4706 help();
4707 break;
4708 case 'f':
4709 fmt = optarg;
4710 break;
4711 case 'O':
4712 out_fmt = optarg;
4713 break;
4714 case 'o':
4715 if (!is_valid_option_list(optarg)) {
4716 error_report("Invalid option list: %s", optarg);
4717 goto out;
4719 if (!options) {
4720 options = g_strdup(optarg);
4721 } else {
4722 char *old_options = options;
4723 options = g_strdup_printf("%s,%s", options, optarg);
4724 g_free(old_options);
4726 break;
4727 case 'l':
4728 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4729 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4730 optarg, false);
4731 if (!sn_opts) {
4732 error_report("Failed in parsing snapshot param '%s'",
4733 optarg);
4734 goto out;
4736 } else {
4737 snapshot_name = optarg;
4739 break;
4740 case 'U':
4741 force_share = true;
4742 break;
4743 case OPTION_OBJECT:
4744 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4745 optarg, true);
4746 if (!object_opts) {
4747 goto out;
4749 break;
4750 case OPTION_IMAGE_OPTS:
4751 image_opts = true;
4752 break;
4753 case OPTION_OUTPUT:
4754 if (!strcmp(optarg, "json")) {
4755 output_format = OFORMAT_JSON;
4756 } else if (!strcmp(optarg, "human")) {
4757 output_format = OFORMAT_HUMAN;
4758 } else {
4759 error_report("--output must be used with human or json "
4760 "as argument.");
4761 goto out;
4763 break;
4764 case OPTION_SIZE:
4766 int64_t sval;
4768 sval = cvtnum(optarg);
4769 if (sval < 0) {
4770 if (sval == -ERANGE) {
4771 error_report("Image size must be less than 8 EiB!");
4772 } else {
4773 error_report("Invalid image size specified! You may use "
4774 "k, M, G, T, P or E suffixes for ");
4775 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4776 "petabytes and exabytes.");
4778 goto out;
4780 img_size = (uint64_t)sval;
4782 break;
4786 if (qemu_opts_foreach(&qemu_object_opts,
4787 user_creatable_add_opts_foreach,
4788 NULL, NULL)) {
4789 goto out;
4792 if (argc - optind > 1) {
4793 error_report("At most one filename argument is allowed.");
4794 goto out;
4795 } else if (argc - optind == 1) {
4796 filename = argv[optind];
4799 if (!filename &&
4800 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4801 error_report("--object, --image-opts, -f, and -l "
4802 "require a filename argument.");
4803 goto out;
4805 if (filename && img_size != UINT64_MAX) {
4806 error_report("--size N cannot be used together with a filename.");
4807 goto out;
4809 if (!filename && img_size == UINT64_MAX) {
4810 error_report("Either --size N or one filename must be specified.");
4811 goto out;
4814 if (filename) {
4815 in_blk = img_open(image_opts, filename, fmt, 0,
4816 false, false, force_share);
4817 if (!in_blk) {
4818 goto out;
4821 if (sn_opts) {
4822 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4823 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4824 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4825 &local_err);
4826 } else if (snapshot_name != NULL) {
4827 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4828 snapshot_name, &local_err);
4830 if (local_err) {
4831 error_reportf_err(local_err, "Failed to load snapshot: ");
4832 goto out;
4836 drv = bdrv_find_format(out_fmt);
4837 if (!drv) {
4838 error_report("Unknown file format '%s'", out_fmt);
4839 goto out;
4841 if (!drv->create_opts) {
4842 error_report("Format driver '%s' does not support image creation",
4843 drv->format_name);
4844 goto out;
4847 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4848 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4849 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4850 if (options) {
4851 qemu_opts_do_parse(opts, options, NULL, &local_err);
4852 if (local_err) {
4853 error_report_err(local_err);
4854 error_report("Invalid options for file format '%s'", out_fmt);
4855 goto out;
4858 if (img_size != UINT64_MAX) {
4859 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4862 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4863 if (local_err) {
4864 error_report_err(local_err);
4865 goto out;
4868 if (output_format == OFORMAT_HUMAN) {
4869 printf("required size: %" PRIu64 "\n", info->required);
4870 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4871 } else {
4872 dump_json_block_measure_info(info);
4875 ret = 0;
4877 out:
4878 qapi_free_BlockMeasureInfo(info);
4879 qemu_opts_del(object_opts);
4880 qemu_opts_del(opts);
4881 qemu_opts_del(sn_opts);
4882 qemu_opts_free(create_opts);
4883 g_free(options);
4884 blk_unref(in_blk);
4885 return ret;
4888 static const img_cmd_t img_cmds[] = {
4889 #define DEF(option, callback, arg_string) \
4890 { option, callback },
4891 #include "qemu-img-cmds.h"
4892 #undef DEF
4893 { NULL, NULL, },
4896 int main(int argc, char **argv)
4898 const img_cmd_t *cmd;
4899 const char *cmdname;
4900 Error *local_error = NULL;
4901 char *trace_file = NULL;
4902 int c;
4903 static const struct option long_options[] = {
4904 {"help", no_argument, 0, 'h'},
4905 {"version", no_argument, 0, 'V'},
4906 {"trace", required_argument, NULL, 'T'},
4907 {0, 0, 0, 0}
4910 #ifdef CONFIG_POSIX
4911 signal(SIGPIPE, SIG_IGN);
4912 #endif
4914 module_call_init(MODULE_INIT_TRACE);
4915 error_set_progname(argv[0]);
4916 qemu_init_exec_dir(argv[0]);
4918 if (qemu_init_main_loop(&local_error)) {
4919 error_report_err(local_error);
4920 exit(EXIT_FAILURE);
4923 qcrypto_init(&error_fatal);
4925 module_call_init(MODULE_INIT_QOM);
4926 bdrv_init();
4927 if (argc < 2) {
4928 error_exit("Not enough arguments");
4931 qemu_add_opts(&qemu_object_opts);
4932 qemu_add_opts(&qemu_source_opts);
4933 qemu_add_opts(&qemu_trace_opts);
4935 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4936 switch (c) {
4937 case ':':
4938 missing_argument(argv[optind - 1]);
4939 return 0;
4940 case '?':
4941 unrecognized_option(argv[optind - 1]);
4942 return 0;
4943 case 'h':
4944 help();
4945 return 0;
4946 case 'V':
4947 printf(QEMU_IMG_VERSION);
4948 return 0;
4949 case 'T':
4950 g_free(trace_file);
4951 trace_file = trace_opt_parse(optarg);
4952 break;
4956 cmdname = argv[optind];
4958 /* reset getopt_long scanning */
4959 argc -= optind;
4960 if (argc < 1) {
4961 return 0;
4963 argv += optind;
4964 optind = 0;
4966 if (!trace_init_backends()) {
4967 exit(1);
4969 trace_init_file(trace_file);
4970 qemu_set_log(LOG_TRACE);
4972 /* find the command */
4973 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4974 if (!strcmp(cmdname, cmd->name)) {
4975 return cmd->handler(argc, argv);
4979 /* not found */
4980 error_exit("Command not found: %s", cmdname);