block: Make bdrv_is_allocated() byte-based
[qemu/ar7.git] / qemu-img.c
blob86e24335fcbb233c0264c9f6a3822b66801c62d7
1 /*
2 * QEMU disk image utility
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-version.h"
26 #include "qapi/error.h"
27 #include "qapi-visit.h"
28 #include "qapi/qobject-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qemu/cutils.h"
33 #include "qemu/config-file.h"
34 #include "qemu/option.h"
35 #include "qemu/error-report.h"
36 #include "qemu/log.h"
37 #include "qom/object_interfaces.h"
38 #include "sysemu/sysemu.h"
39 #include "sysemu/block-backend.h"
40 #include "block/block_int.h"
41 #include "block/blockjob.h"
42 #include "block/qapi.h"
43 #include "crypto/init.h"
44 #include "trace/control.h"
45 #include <getopt.h>
47 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
48 "\n" QEMU_COPYRIGHT "\n"
50 typedef struct img_cmd_t {
51 const char *name;
52 int (*handler)(int argc, char **argv);
53 } img_cmd_t;
55 enum {
56 OPTION_OUTPUT = 256,
57 OPTION_BACKING_CHAIN = 257,
58 OPTION_OBJECT = 258,
59 OPTION_IMAGE_OPTS = 259,
60 OPTION_PATTERN = 260,
61 OPTION_FLUSH_INTERVAL = 261,
62 OPTION_NO_DRAIN = 262,
63 OPTION_TARGET_IMAGE_OPTS = 263,
66 typedef enum OutputFormat {
67 OFORMAT_JSON,
68 OFORMAT_HUMAN,
69 } OutputFormat;
71 /* Default to cache=writeback as data integrity is not important for qemu-img */
72 #define BDRV_DEFAULT_CACHE "writeback"
74 static void format_print(void *opaque, const char *name)
76 printf(" %s", name);
79 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
81 va_list ap;
83 error_printf("qemu-img: ");
85 va_start(ap, fmt);
86 error_vprintf(fmt, ap);
87 va_end(ap);
89 error_printf("\nTry 'qemu-img --help' for more information\n");
90 exit(EXIT_FAILURE);
93 static void QEMU_NORETURN missing_argument(const char *option)
95 error_exit("missing argument for option '%s'", option);
98 static void QEMU_NORETURN unrecognized_option(const char *option)
100 error_exit("unrecognized option '%s'", option);
103 /* Please keep in synch with qemu-img.texi */
104 static void QEMU_NORETURN help(void)
106 const char *help_msg =
107 QEMU_IMG_VERSION
108 "usage: qemu-img [standard options] command [command options]\n"
109 "QEMU disk image utility\n"
110 "\n"
111 " '-h', '--help' display this help and exit\n"
112 " '-V', '--version' output version information and exit\n"
113 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
114 " specify tracing options\n"
115 "\n"
116 "Command syntax:\n"
117 #define DEF(option, callback, arg_string) \
118 " " arg_string "\n"
119 #include "qemu-img-cmds.h"
120 #undef DEF
121 #undef GEN_DOCS
122 "\n"
123 "Command parameters:\n"
124 " 'filename' is a disk image filename\n"
125 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
126 " manual page for a description of the object properties. The most common\n"
127 " object type is a 'secret', which is used to supply passwords and/or\n"
128 " encryption keys.\n"
129 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
130 " 'cache' is the cache mode used to write the output disk image, the valid\n"
131 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
132 " 'directsync' and 'unsafe' (default for convert)\n"
133 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
134 " options are the same as for the 'cache' option\n"
135 " 'size' is the disk image size in bytes. Optional suffixes\n"
136 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
137 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
138 " supported. 'b' is ignored.\n"
139 " 'output_filename' is the destination disk image filename\n"
140 " 'output_fmt' is the destination format\n"
141 " 'options' is a comma separated list of format specific options in a\n"
142 " name=value format. Use -o ? for an overview of the options supported by the\n"
143 " used format\n"
144 " 'snapshot_param' is param used for internal snapshot, format\n"
145 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
146 " '[ID_OR_NAME]'\n"
147 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
148 " instead\n"
149 " '-c' indicates that target image must be compressed (qcow format only)\n"
150 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
151 " match exactly. The image doesn't need a working backing file before\n"
152 " rebasing in this case (useful for renaming the backing file)\n"
153 " '-h' with or without a command shows this help and lists the supported formats\n"
154 " '-p' show progress of command (only certain commands)\n"
155 " '-q' use Quiet mode - do not print any output (except errors)\n"
156 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
157 " contain only zeros for qemu-img to create a sparse image during\n"
158 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
159 " unallocated or zero sectors, and the destination image will always be\n"
160 " fully allocated\n"
161 " '--output' takes the format in which the output must be done (human or json)\n"
162 " '-n' skips the target volume creation (useful if the volume is created\n"
163 " prior to running qemu-img)\n"
164 "\n"
165 "Parameters to check subcommand:\n"
166 " '-r' tries to repair any inconsistencies that are found during the check.\n"
167 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
168 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
169 " hiding corruption that has already occurred.\n"
170 "\n"
171 "Parameters to convert subcommand:\n"
172 " '-m' specifies how many coroutines work in parallel during the convert\n"
173 " process (defaults to 8)\n"
174 " '-W' allow to write to the target out of order rather than sequential\n"
175 "\n"
176 "Parameters to snapshot subcommand:\n"
177 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
178 " '-a' applies a snapshot (revert disk to saved state)\n"
179 " '-c' creates a snapshot\n"
180 " '-d' deletes a snapshot\n"
181 " '-l' lists all snapshots in the given image\n"
182 "\n"
183 "Parameters to compare subcommand:\n"
184 " '-f' first image format\n"
185 " '-F' second image format\n"
186 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
187 "\n"
188 "Parameters to dd subcommand:\n"
189 " 'bs=BYTES' read and write up to BYTES bytes at a time "
190 "(default: 512)\n"
191 " 'count=N' copy only N input blocks\n"
192 " 'if=FILE' read from FILE\n"
193 " 'of=FILE' write to FILE\n"
194 " 'skip=N' skip N bs-sized blocks at the start of input\n";
196 printf("%s\nSupported formats:", help_msg);
197 bdrv_iterate_format(format_print, NULL);
198 printf("\n");
199 exit(EXIT_SUCCESS);
202 static QemuOptsList qemu_object_opts = {
203 .name = "object",
204 .implied_opt_name = "qom-type",
205 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
206 .desc = {
211 static QemuOptsList qemu_source_opts = {
212 .name = "source",
213 .implied_opt_name = "file",
214 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
215 .desc = {
220 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
222 int ret = 0;
223 if (!quiet) {
224 va_list args;
225 va_start(args, fmt);
226 ret = vprintf(fmt, args);
227 va_end(args);
229 return ret;
233 static int print_block_option_help(const char *filename, const char *fmt)
235 BlockDriver *drv, *proto_drv;
236 QemuOptsList *create_opts = NULL;
237 Error *local_err = NULL;
239 /* Find driver and parse its options */
240 drv = bdrv_find_format(fmt);
241 if (!drv) {
242 error_report("Unknown file format '%s'", fmt);
243 return 1;
246 create_opts = qemu_opts_append(create_opts, drv->create_opts);
247 if (filename) {
248 proto_drv = bdrv_find_protocol(filename, true, &local_err);
249 if (!proto_drv) {
250 error_report_err(local_err);
251 qemu_opts_free(create_opts);
252 return 1;
254 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
257 qemu_opts_print_help(create_opts);
258 qemu_opts_free(create_opts);
259 return 0;
263 static int img_open_password(BlockBackend *blk, const char *filename,
264 int flags, bool quiet)
266 BlockDriverState *bs;
267 char password[256];
269 bs = blk_bs(blk);
270 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
271 !(flags & BDRV_O_NO_IO)) {
272 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
273 if (qemu_read_password(password, sizeof(password)) < 0) {
274 error_report("No password given");
275 return -1;
277 if (bdrv_set_key(bs, password) < 0) {
278 error_report("invalid password");
279 return -1;
282 return 0;
286 static BlockBackend *img_open_opts(const char *optstr,
287 QemuOpts *opts, int flags, bool writethrough,
288 bool quiet, bool force_share)
290 QDict *options;
291 Error *local_err = NULL;
292 BlockBackend *blk;
293 options = qemu_opts_to_qdict(opts, NULL);
294 if (force_share) {
295 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
296 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
297 error_report("--force-share/-U conflicts with image options");
298 QDECREF(options);
299 return NULL;
301 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
303 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
304 if (!blk) {
305 error_reportf_err(local_err, "Could not open '%s': ", optstr);
306 return NULL;
308 blk_set_enable_write_cache(blk, !writethrough);
310 if (img_open_password(blk, optstr, flags, quiet) < 0) {
311 blk_unref(blk);
312 return NULL;
314 return blk;
317 static BlockBackend *img_open_file(const char *filename,
318 QDict *options,
319 const char *fmt, int flags,
320 bool writethrough, bool quiet,
321 bool force_share)
323 BlockBackend *blk;
324 Error *local_err = NULL;
326 if (!options) {
327 options = qdict_new();
329 if (fmt) {
330 qdict_put_str(options, "driver", fmt);
333 if (force_share) {
334 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
336 blk = blk_new_open(filename, NULL, options, flags, &local_err);
337 if (!blk) {
338 error_reportf_err(local_err, "Could not open '%s': ", filename);
339 return NULL;
341 blk_set_enable_write_cache(blk, !writethrough);
343 if (img_open_password(blk, filename, flags, quiet) < 0) {
344 blk_unref(blk);
345 return NULL;
347 return blk;
351 static int img_add_key_secrets(void *opaque,
352 const char *name, const char *value,
353 Error **errp)
355 QDict *options = opaque;
357 if (g_str_has_suffix(name, "key-secret")) {
358 qdict_put(options, name, qstring_from_str(value));
361 return 0;
364 static BlockBackend *img_open_new_file(const char *filename,
365 QemuOpts *create_opts,
366 const char *fmt, int flags,
367 bool writethrough, bool quiet,
368 bool force_share)
370 QDict *options = NULL;
372 options = qdict_new();
373 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
375 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
376 force_share);
380 static BlockBackend *img_open(bool image_opts,
381 const char *filename,
382 const char *fmt, int flags, bool writethrough,
383 bool quiet, bool force_share)
385 BlockBackend *blk;
386 if (image_opts) {
387 QemuOpts *opts;
388 if (fmt) {
389 error_report("--image-opts and --format are mutually exclusive");
390 return NULL;
392 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
393 filename, true);
394 if (!opts) {
395 return NULL;
397 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
398 force_share);
399 } else {
400 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
401 force_share);
403 return blk;
407 static int add_old_style_options(const char *fmt, QemuOpts *opts,
408 const char *base_filename,
409 const char *base_fmt)
411 Error *err = NULL;
413 if (base_filename) {
414 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
415 if (err) {
416 error_report("Backing file not supported for file format '%s'",
417 fmt);
418 error_free(err);
419 return -1;
422 if (base_fmt) {
423 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
424 if (err) {
425 error_report("Backing file format not supported for file "
426 "format '%s'", fmt);
427 error_free(err);
428 return -1;
431 return 0;
434 static int64_t cvtnum(const char *s)
436 int err;
437 uint64_t value;
439 err = qemu_strtosz(s, NULL, &value);
440 if (err < 0) {
441 return err;
443 if (value > INT64_MAX) {
444 return -ERANGE;
446 return value;
449 static int img_create(int argc, char **argv)
451 int c;
452 uint64_t img_size = -1;
453 const char *fmt = "raw";
454 const char *base_fmt = NULL;
455 const char *filename;
456 const char *base_filename = NULL;
457 char *options = NULL;
458 Error *local_err = NULL;
459 bool quiet = false;
461 for(;;) {
462 static const struct option long_options[] = {
463 {"help", no_argument, 0, 'h'},
464 {"object", required_argument, 0, OPTION_OBJECT},
465 {0, 0, 0, 0}
467 c = getopt_long(argc, argv, ":F:b:f:ho:q",
468 long_options, NULL);
469 if (c == -1) {
470 break;
472 switch(c) {
473 case ':':
474 missing_argument(argv[optind - 1]);
475 break;
476 case '?':
477 unrecognized_option(argv[optind - 1]);
478 break;
479 case 'h':
480 help();
481 break;
482 case 'F':
483 base_fmt = optarg;
484 break;
485 case 'b':
486 base_filename = optarg;
487 break;
488 case 'f':
489 fmt = optarg;
490 break;
491 case 'o':
492 if (!is_valid_option_list(optarg)) {
493 error_report("Invalid option list: %s", optarg);
494 goto fail;
496 if (!options) {
497 options = g_strdup(optarg);
498 } else {
499 char *old_options = options;
500 options = g_strdup_printf("%s,%s", options, optarg);
501 g_free(old_options);
503 break;
504 case 'q':
505 quiet = true;
506 break;
507 case OPTION_OBJECT: {
508 QemuOpts *opts;
509 opts = qemu_opts_parse_noisily(&qemu_object_opts,
510 optarg, true);
511 if (!opts) {
512 goto fail;
514 } break;
518 /* Get the filename */
519 filename = (optind < argc) ? argv[optind] : NULL;
520 if (options && has_help_option(options)) {
521 g_free(options);
522 return print_block_option_help(filename, fmt);
525 if (optind >= argc) {
526 error_exit("Expecting image file name");
528 optind++;
530 if (qemu_opts_foreach(&qemu_object_opts,
531 user_creatable_add_opts_foreach,
532 NULL, NULL)) {
533 goto fail;
536 /* Get image size, if specified */
537 if (optind < argc) {
538 int64_t sval;
540 sval = cvtnum(argv[optind++]);
541 if (sval < 0) {
542 if (sval == -ERANGE) {
543 error_report("Image size must be less than 8 EiB!");
544 } else {
545 error_report("Invalid image size specified! You may use k, M, "
546 "G, T, P or E suffixes for ");
547 error_report("kilobytes, megabytes, gigabytes, terabytes, "
548 "petabytes and exabytes.");
550 goto fail;
552 img_size = (uint64_t)sval;
554 if (optind != argc) {
555 error_exit("Unexpected argument: %s", argv[optind]);
558 bdrv_img_create(filename, fmt, base_filename, base_fmt,
559 options, img_size, 0, quiet, &local_err);
560 if (local_err) {
561 error_reportf_err(local_err, "%s: ", filename);
562 goto fail;
565 g_free(options);
566 return 0;
568 fail:
569 g_free(options);
570 return 1;
573 static void dump_json_image_check(ImageCheck *check, bool quiet)
575 QString *str;
576 QObject *obj;
577 Visitor *v = qobject_output_visitor_new(&obj);
579 visit_type_ImageCheck(v, NULL, &check, &error_abort);
580 visit_complete(v, &obj);
581 str = qobject_to_json_pretty(obj);
582 assert(str != NULL);
583 qprintf(quiet, "%s\n", qstring_get_str(str));
584 qobject_decref(obj);
585 visit_free(v);
586 QDECREF(str);
589 static void dump_human_image_check(ImageCheck *check, bool quiet)
591 if (!(check->corruptions || check->leaks || check->check_errors)) {
592 qprintf(quiet, "No errors were found on the image.\n");
593 } else {
594 if (check->corruptions) {
595 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
596 "Data may be corrupted, or further writes to the image "
597 "may corrupt it.\n",
598 check->corruptions);
601 if (check->leaks) {
602 qprintf(quiet,
603 "\n%" PRId64 " leaked clusters were found on the image.\n"
604 "This means waste of disk space, but no harm to data.\n",
605 check->leaks);
608 if (check->check_errors) {
609 qprintf(quiet,
610 "\n%" PRId64
611 " internal errors have occurred during the check.\n",
612 check->check_errors);
616 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
617 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
618 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
619 check->allocated_clusters, check->total_clusters,
620 check->allocated_clusters * 100.0 / check->total_clusters,
621 check->fragmented_clusters * 100.0 / check->allocated_clusters,
622 check->compressed_clusters * 100.0 /
623 check->allocated_clusters);
626 if (check->image_end_offset) {
627 qprintf(quiet,
628 "Image end offset: %" PRId64 "\n", check->image_end_offset);
632 static int collect_image_check(BlockDriverState *bs,
633 ImageCheck *check,
634 const char *filename,
635 const char *fmt,
636 int fix)
638 int ret;
639 BdrvCheckResult result;
641 ret = bdrv_check(bs, &result, fix);
642 if (ret < 0) {
643 return ret;
646 check->filename = g_strdup(filename);
647 check->format = g_strdup(bdrv_get_format_name(bs));
648 check->check_errors = result.check_errors;
649 check->corruptions = result.corruptions;
650 check->has_corruptions = result.corruptions != 0;
651 check->leaks = result.leaks;
652 check->has_leaks = result.leaks != 0;
653 check->corruptions_fixed = result.corruptions_fixed;
654 check->has_corruptions_fixed = result.corruptions != 0;
655 check->leaks_fixed = result.leaks_fixed;
656 check->has_leaks_fixed = result.leaks != 0;
657 check->image_end_offset = result.image_end_offset;
658 check->has_image_end_offset = result.image_end_offset != 0;
659 check->total_clusters = result.bfi.total_clusters;
660 check->has_total_clusters = result.bfi.total_clusters != 0;
661 check->allocated_clusters = result.bfi.allocated_clusters;
662 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
663 check->fragmented_clusters = result.bfi.fragmented_clusters;
664 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
665 check->compressed_clusters = result.bfi.compressed_clusters;
666 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
668 return 0;
672 * Checks an image for consistency. Exit codes:
674 * 0 - Check completed, image is good
675 * 1 - Check not completed because of internal errors
676 * 2 - Check completed, image is corrupted
677 * 3 - Check completed, image has leaked clusters, but is good otherwise
678 * 63 - Checks are not supported by the image format
680 static int img_check(int argc, char **argv)
682 int c, ret;
683 OutputFormat output_format = OFORMAT_HUMAN;
684 const char *filename, *fmt, *output, *cache;
685 BlockBackend *blk;
686 BlockDriverState *bs;
687 int fix = 0;
688 int flags = BDRV_O_CHECK;
689 bool writethrough;
690 ImageCheck *check;
691 bool quiet = false;
692 bool image_opts = false;
693 bool force_share = false;
695 fmt = NULL;
696 output = NULL;
697 cache = BDRV_DEFAULT_CACHE;
699 for(;;) {
700 int option_index = 0;
701 static const struct option long_options[] = {
702 {"help", no_argument, 0, 'h'},
703 {"format", required_argument, 0, 'f'},
704 {"repair", required_argument, 0, 'r'},
705 {"output", required_argument, 0, OPTION_OUTPUT},
706 {"object", required_argument, 0, OPTION_OBJECT},
707 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
708 {"force-share", no_argument, 0, 'U'},
709 {0, 0, 0, 0}
711 c = getopt_long(argc, argv, ":hf:r:T:qU",
712 long_options, &option_index);
713 if (c == -1) {
714 break;
716 switch(c) {
717 case ':':
718 missing_argument(argv[optind - 1]);
719 break;
720 case '?':
721 unrecognized_option(argv[optind - 1]);
722 break;
723 case 'h':
724 help();
725 break;
726 case 'f':
727 fmt = optarg;
728 break;
729 case 'r':
730 flags |= BDRV_O_RDWR;
732 if (!strcmp(optarg, "leaks")) {
733 fix = BDRV_FIX_LEAKS;
734 } else if (!strcmp(optarg, "all")) {
735 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
736 } else {
737 error_exit("Unknown option value for -r "
738 "(expecting 'leaks' or 'all'): %s", optarg);
740 break;
741 case OPTION_OUTPUT:
742 output = optarg;
743 break;
744 case 'T':
745 cache = optarg;
746 break;
747 case 'q':
748 quiet = true;
749 break;
750 case 'U':
751 force_share = true;
752 break;
753 case OPTION_OBJECT: {
754 QemuOpts *opts;
755 opts = qemu_opts_parse_noisily(&qemu_object_opts,
756 optarg, true);
757 if (!opts) {
758 return 1;
760 } break;
761 case OPTION_IMAGE_OPTS:
762 image_opts = true;
763 break;
766 if (optind != argc - 1) {
767 error_exit("Expecting one image file name");
769 filename = argv[optind++];
771 if (output && !strcmp(output, "json")) {
772 output_format = OFORMAT_JSON;
773 } else if (output && !strcmp(output, "human")) {
774 output_format = OFORMAT_HUMAN;
775 } else if (output) {
776 error_report("--output must be used with human or json as argument.");
777 return 1;
780 if (qemu_opts_foreach(&qemu_object_opts,
781 user_creatable_add_opts_foreach,
782 NULL, NULL)) {
783 return 1;
786 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
787 if (ret < 0) {
788 error_report("Invalid source cache option: %s", cache);
789 return 1;
792 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
793 force_share);
794 if (!blk) {
795 return 1;
797 bs = blk_bs(blk);
799 check = g_new0(ImageCheck, 1);
800 ret = collect_image_check(bs, check, filename, fmt, fix);
802 if (ret == -ENOTSUP) {
803 error_report("This image format does not support checks");
804 ret = 63;
805 goto fail;
808 if (check->corruptions_fixed || check->leaks_fixed) {
809 int corruptions_fixed, leaks_fixed;
811 leaks_fixed = check->leaks_fixed;
812 corruptions_fixed = check->corruptions_fixed;
814 if (output_format == OFORMAT_HUMAN) {
815 qprintf(quiet,
816 "The following inconsistencies were found and repaired:\n\n"
817 " %" PRId64 " leaked clusters\n"
818 " %" PRId64 " corruptions\n\n"
819 "Double checking the fixed image now...\n",
820 check->leaks_fixed,
821 check->corruptions_fixed);
824 ret = collect_image_check(bs, check, filename, fmt, 0);
826 check->leaks_fixed = leaks_fixed;
827 check->corruptions_fixed = corruptions_fixed;
830 if (!ret) {
831 switch (output_format) {
832 case OFORMAT_HUMAN:
833 dump_human_image_check(check, quiet);
834 break;
835 case OFORMAT_JSON:
836 dump_json_image_check(check, quiet);
837 break;
841 if (ret || check->check_errors) {
842 if (ret) {
843 error_report("Check failed: %s", strerror(-ret));
844 } else {
845 error_report("Check failed");
847 ret = 1;
848 goto fail;
851 if (check->corruptions) {
852 ret = 2;
853 } else if (check->leaks) {
854 ret = 3;
855 } else {
856 ret = 0;
859 fail:
860 qapi_free_ImageCheck(check);
861 blk_unref(blk);
862 return ret;
865 typedef struct CommonBlockJobCBInfo {
866 BlockDriverState *bs;
867 Error **errp;
868 } CommonBlockJobCBInfo;
870 static void common_block_job_cb(void *opaque, int ret)
872 CommonBlockJobCBInfo *cbi = opaque;
874 if (ret < 0) {
875 error_setg_errno(cbi->errp, -ret, "Block job failed");
879 static void run_block_job(BlockJob *job, Error **errp)
881 AioContext *aio_context = blk_get_aio_context(job->blk);
882 int ret = 0;
884 aio_context_acquire(aio_context);
885 block_job_ref(job);
886 do {
887 aio_poll(aio_context, true);
888 qemu_progress_print(job->len ?
889 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
890 } while (!job->ready && !job->completed);
892 if (!job->completed) {
893 ret = block_job_complete_sync(job, errp);
894 } else {
895 ret = job->ret;
897 block_job_unref(job);
898 aio_context_release(aio_context);
900 /* publish completion progress only when success */
901 if (!ret) {
902 qemu_progress_print(100.f, 0);
906 static int img_commit(int argc, char **argv)
908 int c, ret, flags;
909 const char *filename, *fmt, *cache, *base;
910 BlockBackend *blk;
911 BlockDriverState *bs, *base_bs;
912 BlockJob *job;
913 bool progress = false, quiet = false, drop = false;
914 bool writethrough;
915 Error *local_err = NULL;
916 CommonBlockJobCBInfo cbi;
917 bool image_opts = false;
918 AioContext *aio_context;
920 fmt = NULL;
921 cache = BDRV_DEFAULT_CACHE;
922 base = NULL;
923 for(;;) {
924 static const struct option long_options[] = {
925 {"help", no_argument, 0, 'h'},
926 {"object", required_argument, 0, OPTION_OBJECT},
927 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
928 {0, 0, 0, 0}
930 c = getopt_long(argc, argv, ":f:ht:b:dpq",
931 long_options, NULL);
932 if (c == -1) {
933 break;
935 switch(c) {
936 case ':':
937 missing_argument(argv[optind - 1]);
938 break;
939 case '?':
940 unrecognized_option(argv[optind - 1]);
941 break;
942 case 'h':
943 help();
944 break;
945 case 'f':
946 fmt = optarg;
947 break;
948 case 't':
949 cache = optarg;
950 break;
951 case 'b':
952 base = optarg;
953 /* -b implies -d */
954 drop = true;
955 break;
956 case 'd':
957 drop = true;
958 break;
959 case 'p':
960 progress = true;
961 break;
962 case 'q':
963 quiet = true;
964 break;
965 case OPTION_OBJECT: {
966 QemuOpts *opts;
967 opts = qemu_opts_parse_noisily(&qemu_object_opts,
968 optarg, true);
969 if (!opts) {
970 return 1;
972 } break;
973 case OPTION_IMAGE_OPTS:
974 image_opts = true;
975 break;
979 /* Progress is not shown in Quiet mode */
980 if (quiet) {
981 progress = false;
984 if (optind != argc - 1) {
985 error_exit("Expecting one image file name");
987 filename = argv[optind++];
989 if (qemu_opts_foreach(&qemu_object_opts,
990 user_creatable_add_opts_foreach,
991 NULL, NULL)) {
992 return 1;
995 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
996 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
997 if (ret < 0) {
998 error_report("Invalid cache option: %s", cache);
999 return 1;
1002 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1003 false);
1004 if (!blk) {
1005 return 1;
1007 bs = blk_bs(blk);
1009 qemu_progress_init(progress, 1.f);
1010 qemu_progress_print(0.f, 100);
1012 if (base) {
1013 base_bs = bdrv_find_backing_image(bs, base);
1014 if (!base_bs) {
1015 error_setg(&local_err,
1016 "Did not find '%s' in the backing chain of '%s'",
1017 base, filename);
1018 goto done;
1020 } else {
1021 /* This is different from QMP, which by default uses the deepest file in
1022 * the backing chain (i.e., the very base); however, the traditional
1023 * behavior of qemu-img commit is using the immediate backing file. */
1024 base_bs = backing_bs(bs);
1025 if (!base_bs) {
1026 error_setg(&local_err, "Image does not have a backing file");
1027 goto done;
1031 cbi = (CommonBlockJobCBInfo){
1032 .errp = &local_err,
1033 .bs = bs,
1036 aio_context = bdrv_get_aio_context(bs);
1037 aio_context_acquire(aio_context);
1038 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
1039 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1040 &cbi, false, &local_err);
1041 aio_context_release(aio_context);
1042 if (local_err) {
1043 goto done;
1046 /* When the block job completes, the BlockBackend reference will point to
1047 * the old backing file. In order to avoid that the top image is already
1048 * deleted, so we can still empty it afterwards, increment the reference
1049 * counter here preemptively. */
1050 if (!drop) {
1051 bdrv_ref(bs);
1054 job = block_job_get("commit");
1055 run_block_job(job, &local_err);
1056 if (local_err) {
1057 goto unref_backing;
1060 if (!drop && bs->drv->bdrv_make_empty) {
1061 ret = bs->drv->bdrv_make_empty(bs);
1062 if (ret) {
1063 error_setg_errno(&local_err, -ret, "Could not empty %s",
1064 filename);
1065 goto unref_backing;
1069 unref_backing:
1070 if (!drop) {
1071 bdrv_unref(bs);
1074 done:
1075 qemu_progress_end();
1077 blk_unref(blk);
1079 if (local_err) {
1080 error_report_err(local_err);
1081 return 1;
1084 qprintf(quiet, "Image committed.\n");
1085 return 0;
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.
1095 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1097 bool is_zero;
1098 int i;
1100 if (n <= 0) {
1101 *pnum = 0;
1102 return 0;
1104 is_zero = buffer_is_zero(buf, 512);
1105 for(i = 1; i < n; i++) {
1106 buf += 512;
1107 if (is_zero != buffer_is_zero(buf, 512)) {
1108 break;
1111 *pnum = i;
1112 return !is_zero;
1116 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1117 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1118 * breaking up write requests for only small sparse areas.
1120 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1121 int min)
1123 int ret;
1124 int num_checked, num_used;
1126 if (n < min) {
1127 min = n;
1130 ret = is_allocated_sectors(buf, n, pnum);
1131 if (!ret) {
1132 return ret;
1135 num_used = *pnum;
1136 buf += BDRV_SECTOR_SIZE * *pnum;
1137 n -= *pnum;
1138 num_checked = num_used;
1140 while (n > 0) {
1141 ret = is_allocated_sectors(buf, n, pnum);
1143 buf += BDRV_SECTOR_SIZE * *pnum;
1144 n -= *pnum;
1145 num_checked += *pnum;
1146 if (ret) {
1147 num_used = num_checked;
1148 } else if (*pnum >= min) {
1149 break;
1153 *pnum = num_used;
1154 return 1;
1158 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1159 * buffers matches, non-zero otherwise.
1161 * pnum is set to the number of sectors (including and immediately following
1162 * the first one) that are known to have the same comparison result
1164 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1165 int *pnum)
1167 bool res;
1168 int i;
1170 if (n <= 0) {
1171 *pnum = 0;
1172 return 0;
1175 res = !!memcmp(buf1, buf2, 512);
1176 for(i = 1; i < n; i++) {
1177 buf1 += 512;
1178 buf2 += 512;
1180 if (!!memcmp(buf1, buf2, 512) != res) {
1181 break;
1185 *pnum = i;
1186 return res;
1189 #define IO_BUF_SIZE (2 * 1024 * 1024)
1191 static int64_t sectors_to_bytes(int64_t sectors)
1193 return sectors << BDRV_SECTOR_BITS;
1196 static int64_t sectors_to_process(int64_t total, int64_t from)
1198 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1202 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1204 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1205 * data and negative value on error.
1207 * @param blk: BlockBackend for the image
1208 * @param sect_num: Number of first sector to check
1209 * @param sect_count: Number of sectors to check
1210 * @param filename: Name of disk file we are checking (logging purpose)
1211 * @param buffer: Allocated buffer for storing read data
1212 * @param quiet: Flag for quiet mode
1214 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1215 int sect_count, const char *filename,
1216 uint8_t *buffer, bool quiet)
1218 int pnum, ret = 0;
1219 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1220 sect_count << BDRV_SECTOR_BITS);
1221 if (ret < 0) {
1222 error_report("Error while reading offset %" PRId64 " of %s: %s",
1223 sectors_to_bytes(sect_num), filename, strerror(-ret));
1224 return ret;
1226 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1227 if (ret || pnum != sect_count) {
1228 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1229 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1230 return 1;
1233 return 0;
1237 * Compares two images. Exit codes:
1239 * 0 - Images are identical
1240 * 1 - Images differ
1241 * >1 - Error occurred
1243 static int img_compare(int argc, char **argv)
1245 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1246 BlockBackend *blk1, *blk2;
1247 BlockDriverState *bs1, *bs2;
1248 int64_t total_sectors1, total_sectors2;
1249 uint8_t *buf1 = NULL, *buf2 = NULL;
1250 int pnum1, pnum2;
1251 int allocated1, allocated2;
1252 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1253 bool progress = false, quiet = false, strict = false;
1254 int flags;
1255 bool writethrough;
1256 int64_t total_sectors;
1257 int64_t sector_num = 0;
1258 int64_t nb_sectors;
1259 int c, pnum;
1260 uint64_t progress_base;
1261 bool image_opts = false;
1262 bool force_share = false;
1264 cache = BDRV_DEFAULT_CACHE;
1265 for (;;) {
1266 static const struct option long_options[] = {
1267 {"help", no_argument, 0, 'h'},
1268 {"object", required_argument, 0, OPTION_OBJECT},
1269 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1270 {"force-share", no_argument, 0, 'U'},
1271 {0, 0, 0, 0}
1273 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1274 long_options, NULL);
1275 if (c == -1) {
1276 break;
1278 switch (c) {
1279 case ':':
1280 missing_argument(argv[optind - 1]);
1281 break;
1282 case '?':
1283 unrecognized_option(argv[optind - 1]);
1284 break;
1285 case 'h':
1286 help();
1287 break;
1288 case 'f':
1289 fmt1 = optarg;
1290 break;
1291 case 'F':
1292 fmt2 = optarg;
1293 break;
1294 case 'T':
1295 cache = optarg;
1296 break;
1297 case 'p':
1298 progress = true;
1299 break;
1300 case 'q':
1301 quiet = true;
1302 break;
1303 case 's':
1304 strict = true;
1305 break;
1306 case 'U':
1307 force_share = true;
1308 break;
1309 case OPTION_OBJECT: {
1310 QemuOpts *opts;
1311 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1312 optarg, true);
1313 if (!opts) {
1314 ret = 2;
1315 goto out4;
1317 } break;
1318 case OPTION_IMAGE_OPTS:
1319 image_opts = true;
1320 break;
1324 /* Progress is not shown in Quiet mode */
1325 if (quiet) {
1326 progress = false;
1330 if (optind != argc - 2) {
1331 error_exit("Expecting two image file names");
1333 filename1 = argv[optind++];
1334 filename2 = argv[optind++];
1336 if (qemu_opts_foreach(&qemu_object_opts,
1337 user_creatable_add_opts_foreach,
1338 NULL, NULL)) {
1339 ret = 2;
1340 goto out4;
1343 /* Initialize before goto out */
1344 qemu_progress_init(progress, 2.0);
1346 flags = 0;
1347 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1348 if (ret < 0) {
1349 error_report("Invalid source cache option: %s", cache);
1350 ret = 2;
1351 goto out3;
1354 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1355 force_share);
1356 if (!blk1) {
1357 ret = 2;
1358 goto out3;
1361 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1362 force_share);
1363 if (!blk2) {
1364 ret = 2;
1365 goto out2;
1367 bs1 = blk_bs(blk1);
1368 bs2 = blk_bs(blk2);
1370 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1371 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1372 total_sectors1 = blk_nb_sectors(blk1);
1373 if (total_sectors1 < 0) {
1374 error_report("Can't get size of %s: %s",
1375 filename1, strerror(-total_sectors1));
1376 ret = 4;
1377 goto out;
1379 total_sectors2 = blk_nb_sectors(blk2);
1380 if (total_sectors2 < 0) {
1381 error_report("Can't get size of %s: %s",
1382 filename2, strerror(-total_sectors2));
1383 ret = 4;
1384 goto out;
1386 total_sectors = MIN(total_sectors1, total_sectors2);
1387 progress_base = MAX(total_sectors1, total_sectors2);
1389 qemu_progress_print(0, 100);
1391 if (strict && total_sectors1 != total_sectors2) {
1392 ret = 1;
1393 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1394 goto out;
1397 for (;;) {
1398 int64_t status1, status2;
1399 BlockDriverState *file;
1401 nb_sectors = sectors_to_process(total_sectors, sector_num);
1402 if (nb_sectors <= 0) {
1403 break;
1405 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1406 total_sectors1 - sector_num,
1407 &pnum1, &file);
1408 if (status1 < 0) {
1409 ret = 3;
1410 error_report("Sector allocation test failed for %s", filename1);
1411 goto out;
1413 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1415 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1416 total_sectors2 - sector_num,
1417 &pnum2, &file);
1418 if (status2 < 0) {
1419 ret = 3;
1420 error_report("Sector allocation test failed for %s", filename2);
1421 goto out;
1423 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1424 if (pnum1) {
1425 nb_sectors = MIN(nb_sectors, pnum1);
1427 if (pnum2) {
1428 nb_sectors = MIN(nb_sectors, pnum2);
1431 if (strict) {
1432 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1433 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1434 ret = 1;
1435 qprintf(quiet, "Strict mode: Offset %" PRId64
1436 " block status mismatch!\n",
1437 sectors_to_bytes(sector_num));
1438 goto out;
1441 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1442 nb_sectors = MIN(pnum1, pnum2);
1443 } else if (allocated1 == allocated2) {
1444 if (allocated1) {
1445 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1446 nb_sectors << BDRV_SECTOR_BITS);
1447 if (ret < 0) {
1448 error_report("Error while reading offset %" PRId64 " of %s:"
1449 " %s", sectors_to_bytes(sector_num), filename1,
1450 strerror(-ret));
1451 ret = 4;
1452 goto out;
1454 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1455 nb_sectors << BDRV_SECTOR_BITS);
1456 if (ret < 0) {
1457 error_report("Error while reading offset %" PRId64
1458 " of %s: %s", sectors_to_bytes(sector_num),
1459 filename2, strerror(-ret));
1460 ret = 4;
1461 goto out;
1463 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1464 if (ret || pnum != nb_sectors) {
1465 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1466 sectors_to_bytes(
1467 ret ? sector_num : sector_num + pnum));
1468 ret = 1;
1469 goto out;
1472 } else {
1474 if (allocated1) {
1475 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1476 filename1, buf1, quiet);
1477 } else {
1478 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1479 filename2, buf1, quiet);
1481 if (ret) {
1482 if (ret < 0) {
1483 error_report("Error while reading offset %" PRId64 ": %s",
1484 sectors_to_bytes(sector_num), strerror(-ret));
1485 ret = 4;
1487 goto out;
1490 sector_num += nb_sectors;
1491 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1494 if (total_sectors1 != total_sectors2) {
1495 BlockBackend *blk_over;
1496 int64_t total_sectors_over;
1497 const char *filename_over;
1499 qprintf(quiet, "Warning: Image size mismatch!\n");
1500 if (total_sectors1 > total_sectors2) {
1501 total_sectors_over = total_sectors1;
1502 blk_over = blk1;
1503 filename_over = filename1;
1504 } else {
1505 total_sectors_over = total_sectors2;
1506 blk_over = blk2;
1507 filename_over = filename2;
1510 for (;;) {
1511 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1512 if (nb_sectors <= 0) {
1513 break;
1515 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1516 nb_sectors, &pnum);
1517 if (ret < 0) {
1518 ret = 3;
1519 error_report("Sector allocation test failed for %s",
1520 filename_over);
1521 goto out;
1524 nb_sectors = pnum;
1525 if (ret) {
1526 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1527 filename_over, buf1, quiet);
1528 if (ret) {
1529 if (ret < 0) {
1530 error_report("Error while reading offset %" PRId64
1531 " of %s: %s", sectors_to_bytes(sector_num),
1532 filename_over, strerror(-ret));
1533 ret = 4;
1535 goto out;
1538 sector_num += nb_sectors;
1539 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1543 qprintf(quiet, "Images are identical.\n");
1544 ret = 0;
1546 out:
1547 qemu_vfree(buf1);
1548 qemu_vfree(buf2);
1549 blk_unref(blk2);
1550 out2:
1551 blk_unref(blk1);
1552 out3:
1553 qemu_progress_end();
1554 out4:
1555 return ret;
1558 enum ImgConvertBlockStatus {
1559 BLK_DATA,
1560 BLK_ZERO,
1561 BLK_BACKING_FILE,
1564 #define MAX_COROUTINES 16
1566 typedef struct ImgConvertState {
1567 BlockBackend **src;
1568 int64_t *src_sectors;
1569 int src_num;
1570 int64_t total_sectors;
1571 int64_t allocated_sectors;
1572 int64_t allocated_done;
1573 int64_t sector_num;
1574 int64_t wr_offs;
1575 enum ImgConvertBlockStatus status;
1576 int64_t sector_next_status;
1577 BlockBackend *target;
1578 bool has_zero_init;
1579 bool compressed;
1580 bool target_has_backing;
1581 bool wr_in_order;
1582 int min_sparse;
1583 size_t cluster_sectors;
1584 size_t buf_sectors;
1585 long num_coroutines;
1586 int running_coroutines;
1587 Coroutine *co[MAX_COROUTINES];
1588 int64_t wait_sector_num[MAX_COROUTINES];
1589 CoMutex lock;
1590 int ret;
1591 } ImgConvertState;
1593 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1594 int *src_cur, int64_t *src_cur_offset)
1596 *src_cur = 0;
1597 *src_cur_offset = 0;
1598 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1599 *src_cur_offset += s->src_sectors[*src_cur];
1600 (*src_cur)++;
1601 assert(*src_cur < s->src_num);
1605 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1607 int64_t ret, src_cur_offset;
1608 int n, src_cur;
1610 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1612 assert(s->total_sectors > sector_num);
1613 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1615 if (s->sector_next_status <= sector_num) {
1616 BlockDriverState *file;
1617 if (s->target_has_backing) {
1618 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1619 sector_num - src_cur_offset,
1620 n, &n, &file);
1621 } else {
1622 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1623 sector_num - src_cur_offset,
1624 n, &n, &file);
1626 if (ret < 0) {
1627 return ret;
1630 if (ret & BDRV_BLOCK_ZERO) {
1631 s->status = BLK_ZERO;
1632 } else if (ret & BDRV_BLOCK_DATA) {
1633 s->status = BLK_DATA;
1634 } else {
1635 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1638 s->sector_next_status = sector_num + n;
1641 n = MIN(n, s->sector_next_status - sector_num);
1642 if (s->status == BLK_DATA) {
1643 n = MIN(n, s->buf_sectors);
1646 /* We need to write complete clusters for compressed images, so if an
1647 * unallocated area is shorter than that, we must consider the whole
1648 * cluster allocated. */
1649 if (s->compressed) {
1650 if (n < s->cluster_sectors) {
1651 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1652 s->status = BLK_DATA;
1653 } else {
1654 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1658 return n;
1661 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1662 int nb_sectors, uint8_t *buf)
1664 int n, ret;
1665 QEMUIOVector qiov;
1666 struct iovec iov;
1668 assert(nb_sectors <= s->buf_sectors);
1669 while (nb_sectors > 0) {
1670 BlockBackend *blk;
1671 int src_cur;
1672 int64_t bs_sectors, src_cur_offset;
1674 /* In the case of compression with multiple source files, we can get a
1675 * nb_sectors that spreads into the next part. So we must be able to
1676 * read across multiple BDSes for one convert_read() call. */
1677 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1678 blk = s->src[src_cur];
1679 bs_sectors = s->src_sectors[src_cur];
1681 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1682 iov.iov_base = buf;
1683 iov.iov_len = n << BDRV_SECTOR_BITS;
1684 qemu_iovec_init_external(&qiov, &iov, 1);
1686 ret = blk_co_preadv(
1687 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1688 n << BDRV_SECTOR_BITS, &qiov, 0);
1689 if (ret < 0) {
1690 return ret;
1693 sector_num += n;
1694 nb_sectors -= n;
1695 buf += n * BDRV_SECTOR_SIZE;
1698 return 0;
1702 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1703 int nb_sectors, uint8_t *buf,
1704 enum ImgConvertBlockStatus status)
1706 int ret;
1707 QEMUIOVector qiov;
1708 struct iovec iov;
1710 while (nb_sectors > 0) {
1711 int n = nb_sectors;
1712 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1714 switch (status) {
1715 case BLK_BACKING_FILE:
1716 /* If we have a backing file, leave clusters unallocated that are
1717 * unallocated in the source image, so that the backing file is
1718 * visible at the respective offset. */
1719 assert(s->target_has_backing);
1720 break;
1722 case BLK_DATA:
1723 /* If we're told to keep the target fully allocated (-S 0) or there
1724 * is real non-zero data, we must write it. Otherwise we can treat
1725 * it as zero sectors.
1726 * Compressed clusters need to be written as a whole, so in that
1727 * case we can only save the write if the buffer is completely
1728 * zeroed. */
1729 if (!s->min_sparse ||
1730 (!s->compressed &&
1731 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1732 (s->compressed &&
1733 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1735 iov.iov_base = buf;
1736 iov.iov_len = n << BDRV_SECTOR_BITS;
1737 qemu_iovec_init_external(&qiov, &iov, 1);
1739 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1740 n << BDRV_SECTOR_BITS, &qiov, flags);
1741 if (ret < 0) {
1742 return ret;
1744 break;
1746 /* fall-through */
1748 case BLK_ZERO:
1749 if (s->has_zero_init) {
1750 assert(!s->target_has_backing);
1751 break;
1753 ret = blk_co_pwrite_zeroes(s->target,
1754 sector_num << BDRV_SECTOR_BITS,
1755 n << BDRV_SECTOR_BITS, 0);
1756 if (ret < 0) {
1757 return ret;
1759 break;
1762 sector_num += n;
1763 nb_sectors -= n;
1764 buf += n * BDRV_SECTOR_SIZE;
1767 return 0;
1770 static void coroutine_fn convert_co_do_copy(void *opaque)
1772 ImgConvertState *s = opaque;
1773 uint8_t *buf = NULL;
1774 int ret, i;
1775 int index = -1;
1777 for (i = 0; i < s->num_coroutines; i++) {
1778 if (s->co[i] == qemu_coroutine_self()) {
1779 index = i;
1780 break;
1783 assert(index >= 0);
1785 s->running_coroutines++;
1786 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1788 while (1) {
1789 int n;
1790 int64_t sector_num;
1791 enum ImgConvertBlockStatus status;
1793 qemu_co_mutex_lock(&s->lock);
1794 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1795 qemu_co_mutex_unlock(&s->lock);
1796 break;
1798 n = convert_iteration_sectors(s, s->sector_num);
1799 if (n < 0) {
1800 qemu_co_mutex_unlock(&s->lock);
1801 s->ret = n;
1802 break;
1804 /* save current sector and allocation status to local variables */
1805 sector_num = s->sector_num;
1806 status = s->status;
1807 if (!s->min_sparse && s->status == BLK_ZERO) {
1808 n = MIN(n, s->buf_sectors);
1810 /* increment global sector counter so that other coroutines can
1811 * already continue reading beyond this request */
1812 s->sector_num += n;
1813 qemu_co_mutex_unlock(&s->lock);
1815 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1816 s->allocated_done += n;
1817 qemu_progress_print(100.0 * s->allocated_done /
1818 s->allocated_sectors, 0);
1821 if (status == BLK_DATA) {
1822 ret = convert_co_read(s, sector_num, n, buf);
1823 if (ret < 0) {
1824 error_report("error while reading sector %" PRId64
1825 ": %s", sector_num, strerror(-ret));
1826 s->ret = ret;
1828 } else if (!s->min_sparse && status == BLK_ZERO) {
1829 status = BLK_DATA;
1830 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1833 if (s->wr_in_order) {
1834 /* keep writes in order */
1835 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1836 s->wait_sector_num[index] = sector_num;
1837 qemu_coroutine_yield();
1839 s->wait_sector_num[index] = -1;
1842 if (s->ret == -EINPROGRESS) {
1843 ret = convert_co_write(s, sector_num, n, buf, status);
1844 if (ret < 0) {
1845 error_report("error while writing sector %" PRId64
1846 ": %s", sector_num, strerror(-ret));
1847 s->ret = ret;
1851 if (s->wr_in_order) {
1852 /* reenter the coroutine that might have waited
1853 * for this write to complete */
1854 s->wr_offs = sector_num + n;
1855 for (i = 0; i < s->num_coroutines; i++) {
1856 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1858 * A -> B -> A cannot occur because A has
1859 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1860 * B will never enter A during this time window.
1862 qemu_coroutine_enter(s->co[i]);
1863 break;
1869 qemu_vfree(buf);
1870 s->co[index] = NULL;
1871 s->running_coroutines--;
1872 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1873 /* the convert job finished successfully */
1874 s->ret = 0;
1878 static int convert_do_copy(ImgConvertState *s)
1880 int ret, i, n;
1881 int64_t sector_num = 0;
1883 /* Check whether we have zero initialisation or can get it efficiently */
1884 s->has_zero_init = s->min_sparse && !s->target_has_backing
1885 ? bdrv_has_zero_init(blk_bs(s->target))
1886 : false;
1888 if (!s->has_zero_init && !s->target_has_backing &&
1889 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1891 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1892 if (ret == 0) {
1893 s->has_zero_init = true;
1897 /* Allocate buffer for copied data. For compressed images, only one cluster
1898 * can be copied at a time. */
1899 if (s->compressed) {
1900 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1901 error_report("invalid cluster size");
1902 return -EINVAL;
1904 s->buf_sectors = s->cluster_sectors;
1907 while (sector_num < s->total_sectors) {
1908 n = convert_iteration_sectors(s, sector_num);
1909 if (n < 0) {
1910 return n;
1912 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1914 s->allocated_sectors += n;
1916 sector_num += n;
1919 /* Do the copy */
1920 s->sector_next_status = 0;
1921 s->ret = -EINPROGRESS;
1923 qemu_co_mutex_init(&s->lock);
1924 for (i = 0; i < s->num_coroutines; i++) {
1925 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1926 s->wait_sector_num[i] = -1;
1927 qemu_coroutine_enter(s->co[i]);
1930 while (s->running_coroutines) {
1931 main_loop_wait(false);
1934 if (s->compressed && !s->ret) {
1935 /* signal EOF to align */
1936 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1937 if (ret < 0) {
1938 return ret;
1942 return s->ret;
1945 static int img_convert(int argc, char **argv)
1947 int c, bs_i, flags, src_flags = 0;
1948 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
1949 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1950 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1951 BlockDriver *drv = NULL, *proto_drv = NULL;
1952 BlockDriverInfo bdi;
1953 BlockDriverState *out_bs;
1954 QemuOpts *opts = NULL, *sn_opts = NULL;
1955 QemuOptsList *create_opts = NULL;
1956 char *options = NULL;
1957 Error *local_err = NULL;
1958 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1959 skip_create = false, progress = false, tgt_image_opts = false;
1960 int64_t ret = -EINVAL;
1961 bool force_share = false;
1963 ImgConvertState s = (ImgConvertState) {
1964 /* Need at least 4k of zeros for sparse detection */
1965 .min_sparse = 8,
1966 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1967 .wr_in_order = true,
1968 .num_coroutines = 8,
1971 for(;;) {
1972 static const struct option long_options[] = {
1973 {"help", no_argument, 0, 'h'},
1974 {"object", required_argument, 0, OPTION_OBJECT},
1975 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1976 {"force-share", no_argument, 0, 'U'},
1977 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
1978 {0, 0, 0, 0}
1980 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
1981 long_options, NULL);
1982 if (c == -1) {
1983 break;
1985 switch(c) {
1986 case ':':
1987 missing_argument(argv[optind - 1]);
1988 break;
1989 case '?':
1990 unrecognized_option(argv[optind - 1]);
1991 break;
1992 case 'h':
1993 help();
1994 break;
1995 case 'f':
1996 fmt = optarg;
1997 break;
1998 case 'O':
1999 out_fmt = optarg;
2000 break;
2001 case 'B':
2002 out_baseimg = optarg;
2003 break;
2004 case 'c':
2005 s.compressed = true;
2006 break;
2007 case 'o':
2008 if (!is_valid_option_list(optarg)) {
2009 error_report("Invalid option list: %s", optarg);
2010 goto fail_getopt;
2012 if (!options) {
2013 options = g_strdup(optarg);
2014 } else {
2015 char *old_options = options;
2016 options = g_strdup_printf("%s,%s", options, optarg);
2017 g_free(old_options);
2019 break;
2020 case 's':
2021 snapshot_name = optarg;
2022 break;
2023 case 'l':
2024 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2025 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2026 optarg, false);
2027 if (!sn_opts) {
2028 error_report("Failed in parsing snapshot param '%s'",
2029 optarg);
2030 goto fail_getopt;
2032 } else {
2033 snapshot_name = optarg;
2035 break;
2036 case 'S':
2038 int64_t sval;
2040 sval = cvtnum(optarg);
2041 if (sval < 0) {
2042 error_report("Invalid minimum zero buffer size for sparse output specified");
2043 goto fail_getopt;
2046 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2047 break;
2049 case 'p':
2050 progress = true;
2051 break;
2052 case 't':
2053 cache = optarg;
2054 break;
2055 case 'T':
2056 src_cache = optarg;
2057 break;
2058 case 'q':
2059 quiet = true;
2060 break;
2061 case 'n':
2062 skip_create = true;
2063 break;
2064 case 'm':
2065 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2066 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2067 error_report("Invalid number of coroutines. Allowed number of"
2068 " coroutines is between 1 and %d", MAX_COROUTINES);
2069 goto fail_getopt;
2071 break;
2072 case 'W':
2073 s.wr_in_order = false;
2074 break;
2075 case 'U':
2076 force_share = true;
2077 break;
2078 case OPTION_OBJECT: {
2079 QemuOpts *object_opts;
2080 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2081 optarg, true);
2082 if (!object_opts) {
2083 goto fail_getopt;
2085 break;
2087 case OPTION_IMAGE_OPTS:
2088 image_opts = true;
2089 break;
2090 case OPTION_TARGET_IMAGE_OPTS:
2091 tgt_image_opts = true;
2092 break;
2096 if (!out_fmt && !tgt_image_opts) {
2097 out_fmt = "raw";
2100 if (qemu_opts_foreach(&qemu_object_opts,
2101 user_creatable_add_opts_foreach,
2102 NULL, NULL)) {
2103 goto fail_getopt;
2106 if (!s.wr_in_order && s.compressed) {
2107 error_report("Out of order write and compress are mutually exclusive");
2108 goto fail_getopt;
2111 if (tgt_image_opts && !skip_create) {
2112 error_report("--target-image-opts requires use of -n flag");
2113 goto fail_getopt;
2116 s.src_num = argc - optind - 1;
2117 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2119 if (options && has_help_option(options)) {
2120 if (out_fmt) {
2121 ret = print_block_option_help(out_filename, out_fmt);
2122 goto fail_getopt;
2123 } else {
2124 error_report("Option help requires a format be specified");
2125 goto fail_getopt;
2129 if (s.src_num < 1) {
2130 error_report("Must specify image file name");
2131 goto fail_getopt;
2135 /* ret is still -EINVAL until here */
2136 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2137 if (ret < 0) {
2138 error_report("Invalid source cache option: %s", src_cache);
2139 goto fail_getopt;
2142 /* Initialize before goto out */
2143 if (quiet) {
2144 progress = false;
2146 qemu_progress_init(progress, 1.0);
2147 qemu_progress_print(0, 100);
2149 s.src = g_new0(BlockBackend *, s.src_num);
2150 s.src_sectors = g_new(int64_t, s.src_num);
2152 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2153 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2154 fmt, src_flags, src_writethrough, quiet,
2155 force_share);
2156 if (!s.src[bs_i]) {
2157 ret = -1;
2158 goto out;
2160 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2161 if (s.src_sectors[bs_i] < 0) {
2162 error_report("Could not get size of %s: %s",
2163 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2164 ret = -1;
2165 goto out;
2167 s.total_sectors += s.src_sectors[bs_i];
2170 if (sn_opts) {
2171 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2172 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2173 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2174 &local_err);
2175 } else if (snapshot_name != NULL) {
2176 if (s.src_num > 1) {
2177 error_report("No support for concatenating multiple snapshot");
2178 ret = -1;
2179 goto out;
2182 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2183 &local_err);
2185 if (local_err) {
2186 error_reportf_err(local_err, "Failed to load snapshot: ");
2187 ret = -1;
2188 goto out;
2191 if (!skip_create) {
2192 /* Find driver and parse its options */
2193 drv = bdrv_find_format(out_fmt);
2194 if (!drv) {
2195 error_report("Unknown file format '%s'", out_fmt);
2196 ret = -1;
2197 goto out;
2200 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2201 if (!proto_drv) {
2202 error_report_err(local_err);
2203 ret = -1;
2204 goto out;
2207 if (!drv->create_opts) {
2208 error_report("Format driver '%s' does not support image creation",
2209 drv->format_name);
2210 ret = -1;
2211 goto out;
2214 if (!proto_drv->create_opts) {
2215 error_report("Protocol driver '%s' does not support image creation",
2216 proto_drv->format_name);
2217 ret = -1;
2218 goto out;
2221 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2222 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2224 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2225 if (options) {
2226 qemu_opts_do_parse(opts, options, NULL, &local_err);
2227 if (local_err) {
2228 error_report_err(local_err);
2229 ret = -1;
2230 goto out;
2234 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2235 &error_abort);
2236 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2237 if (ret < 0) {
2238 goto out;
2242 /* Get backing file name if -o backing_file was used */
2243 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2244 if (out_baseimg_param) {
2245 out_baseimg = out_baseimg_param;
2247 s.target_has_backing = (bool) out_baseimg;
2249 if (s.src_num > 1 && out_baseimg) {
2250 error_report("Having a backing file for the target makes no sense when "
2251 "concatenating multiple input images");
2252 ret = -1;
2253 goto out;
2256 /* Check if compression is supported */
2257 if (s.compressed) {
2258 bool encryption =
2259 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2260 const char *preallocation =
2261 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2263 if (drv && !drv->bdrv_co_pwritev_compressed) {
2264 error_report("Compression not supported for this file format");
2265 ret = -1;
2266 goto out;
2269 if (encryption) {
2270 error_report("Compression and encryption not supported at "
2271 "the same time");
2272 ret = -1;
2273 goto out;
2276 if (preallocation
2277 && strcmp(preallocation, "off"))
2279 error_report("Compression and preallocation not supported at "
2280 "the same time");
2281 ret = -1;
2282 goto out;
2286 if (!skip_create) {
2287 /* Create the new image */
2288 ret = bdrv_create(drv, out_filename, opts, &local_err);
2289 if (ret < 0) {
2290 error_reportf_err(local_err, "%s: error while converting %s: ",
2291 out_filename, out_fmt);
2292 goto out;
2296 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2297 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2298 if (ret < 0) {
2299 error_report("Invalid cache option: %s", cache);
2300 goto out;
2303 if (skip_create) {
2304 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2305 flags, writethrough, quiet, false);
2306 } else {
2307 /* TODO ultimately we should allow --target-image-opts
2308 * to be used even when -n is not given.
2309 * That has to wait for bdrv_create to be improved
2310 * to allow filenames in option syntax
2312 s.target = img_open_new_file(out_filename, opts, out_fmt,
2313 flags, writethrough, quiet, false);
2315 if (!s.target) {
2316 ret = -1;
2317 goto out;
2319 out_bs = blk_bs(s.target);
2321 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2322 error_report("Compression not supported for this file format");
2323 ret = -1;
2324 goto out;
2327 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2328 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2329 * as maximum. */
2330 s.buf_sectors = MIN(32768,
2331 MAX(s.buf_sectors,
2332 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2333 out_bs->bl.pdiscard_alignment >>
2334 BDRV_SECTOR_BITS)));
2336 if (skip_create) {
2337 int64_t output_sectors = blk_nb_sectors(s.target);
2338 if (output_sectors < 0) {
2339 error_report("unable to get output image length: %s",
2340 strerror(-output_sectors));
2341 ret = -1;
2342 goto out;
2343 } else if (output_sectors < s.total_sectors) {
2344 error_report("output file is smaller than input file");
2345 ret = -1;
2346 goto out;
2350 ret = bdrv_get_info(out_bs, &bdi);
2351 if (ret < 0) {
2352 if (s.compressed) {
2353 error_report("could not get block driver info");
2354 goto out;
2356 } else {
2357 s.compressed = s.compressed || bdi.needs_compressed_writes;
2358 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2361 ret = convert_do_copy(&s);
2362 out:
2363 if (!ret) {
2364 qemu_progress_print(100, 0);
2366 qemu_progress_end();
2367 qemu_opts_del(opts);
2368 qemu_opts_free(create_opts);
2369 qemu_opts_del(sn_opts);
2370 blk_unref(s.target);
2371 if (s.src) {
2372 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2373 blk_unref(s.src[bs_i]);
2375 g_free(s.src);
2377 g_free(s.src_sectors);
2378 fail_getopt:
2379 g_free(options);
2381 return !!ret;
2385 static void dump_snapshots(BlockDriverState *bs)
2387 QEMUSnapshotInfo *sn_tab, *sn;
2388 int nb_sns, i;
2390 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2391 if (nb_sns <= 0)
2392 return;
2393 printf("Snapshot list:\n");
2394 bdrv_snapshot_dump(fprintf, stdout, NULL);
2395 printf("\n");
2396 for(i = 0; i < nb_sns; i++) {
2397 sn = &sn_tab[i];
2398 bdrv_snapshot_dump(fprintf, stdout, sn);
2399 printf("\n");
2401 g_free(sn_tab);
2404 static void dump_json_image_info_list(ImageInfoList *list)
2406 QString *str;
2407 QObject *obj;
2408 Visitor *v = qobject_output_visitor_new(&obj);
2410 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2411 visit_complete(v, &obj);
2412 str = qobject_to_json_pretty(obj);
2413 assert(str != NULL);
2414 printf("%s\n", qstring_get_str(str));
2415 qobject_decref(obj);
2416 visit_free(v);
2417 QDECREF(str);
2420 static void dump_json_image_info(ImageInfo *info)
2422 QString *str;
2423 QObject *obj;
2424 Visitor *v = qobject_output_visitor_new(&obj);
2426 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2427 visit_complete(v, &obj);
2428 str = qobject_to_json_pretty(obj);
2429 assert(str != NULL);
2430 printf("%s\n", qstring_get_str(str));
2431 qobject_decref(obj);
2432 visit_free(v);
2433 QDECREF(str);
2436 static void dump_human_image_info_list(ImageInfoList *list)
2438 ImageInfoList *elem;
2439 bool delim = false;
2441 for (elem = list; elem; elem = elem->next) {
2442 if (delim) {
2443 printf("\n");
2445 delim = true;
2447 bdrv_image_info_dump(fprintf, stdout, elem->value);
2451 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2453 return strcmp(a, b) == 0;
2457 * Open an image file chain and return an ImageInfoList
2459 * @filename: topmost image filename
2460 * @fmt: topmost image format (may be NULL to autodetect)
2461 * @chain: true - enumerate entire backing file chain
2462 * false - only topmost image file
2464 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2465 * image file. If there was an error a message will have been printed to
2466 * stderr.
2468 static ImageInfoList *collect_image_info_list(bool image_opts,
2469 const char *filename,
2470 const char *fmt,
2471 bool chain, bool force_share)
2473 ImageInfoList *head = NULL;
2474 ImageInfoList **last = &head;
2475 GHashTable *filenames;
2476 Error *err = NULL;
2478 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2480 while (filename) {
2481 BlockBackend *blk;
2482 BlockDriverState *bs;
2483 ImageInfo *info;
2484 ImageInfoList *elem;
2486 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2487 error_report("Backing file '%s' creates an infinite loop.",
2488 filename);
2489 goto err;
2491 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2493 blk = img_open(image_opts, filename, fmt,
2494 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2495 force_share);
2496 if (!blk) {
2497 goto err;
2499 bs = blk_bs(blk);
2501 bdrv_query_image_info(bs, &info, &err);
2502 if (err) {
2503 error_report_err(err);
2504 blk_unref(blk);
2505 goto err;
2508 elem = g_new0(ImageInfoList, 1);
2509 elem->value = info;
2510 *last = elem;
2511 last = &elem->next;
2513 blk_unref(blk);
2515 filename = fmt = NULL;
2516 if (chain) {
2517 if (info->has_full_backing_filename) {
2518 filename = info->full_backing_filename;
2519 } else if (info->has_backing_filename) {
2520 error_report("Could not determine absolute backing filename,"
2521 " but backing filename '%s' present",
2522 info->backing_filename);
2523 goto err;
2525 if (info->has_backing_filename_format) {
2526 fmt = info->backing_filename_format;
2530 g_hash_table_destroy(filenames);
2531 return head;
2533 err:
2534 qapi_free_ImageInfoList(head);
2535 g_hash_table_destroy(filenames);
2536 return NULL;
2539 static int img_info(int argc, char **argv)
2541 int c;
2542 OutputFormat output_format = OFORMAT_HUMAN;
2543 bool chain = false;
2544 const char *filename, *fmt, *output;
2545 ImageInfoList *list;
2546 bool image_opts = false;
2547 bool force_share = false;
2549 fmt = NULL;
2550 output = NULL;
2551 for(;;) {
2552 int option_index = 0;
2553 static const struct option long_options[] = {
2554 {"help", no_argument, 0, 'h'},
2555 {"format", required_argument, 0, 'f'},
2556 {"output", required_argument, 0, OPTION_OUTPUT},
2557 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2558 {"object", required_argument, 0, OPTION_OBJECT},
2559 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2560 {"force-share", no_argument, 0, 'U'},
2561 {0, 0, 0, 0}
2563 c = getopt_long(argc, argv, ":f:hU",
2564 long_options, &option_index);
2565 if (c == -1) {
2566 break;
2568 switch(c) {
2569 case ':':
2570 missing_argument(argv[optind - 1]);
2571 break;
2572 case '?':
2573 unrecognized_option(argv[optind - 1]);
2574 break;
2575 case 'h':
2576 help();
2577 break;
2578 case 'f':
2579 fmt = optarg;
2580 break;
2581 case 'U':
2582 force_share = true;
2583 break;
2584 case OPTION_OUTPUT:
2585 output = optarg;
2586 break;
2587 case OPTION_BACKING_CHAIN:
2588 chain = true;
2589 break;
2590 case OPTION_OBJECT: {
2591 QemuOpts *opts;
2592 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2593 optarg, true);
2594 if (!opts) {
2595 return 1;
2597 } break;
2598 case OPTION_IMAGE_OPTS:
2599 image_opts = true;
2600 break;
2603 if (optind != argc - 1) {
2604 error_exit("Expecting one image file name");
2606 filename = argv[optind++];
2608 if (output && !strcmp(output, "json")) {
2609 output_format = OFORMAT_JSON;
2610 } else if (output && !strcmp(output, "human")) {
2611 output_format = OFORMAT_HUMAN;
2612 } else if (output) {
2613 error_report("--output must be used with human or json as argument.");
2614 return 1;
2617 if (qemu_opts_foreach(&qemu_object_opts,
2618 user_creatable_add_opts_foreach,
2619 NULL, NULL)) {
2620 return 1;
2623 list = collect_image_info_list(image_opts, filename, fmt, chain,
2624 force_share);
2625 if (!list) {
2626 return 1;
2629 switch (output_format) {
2630 case OFORMAT_HUMAN:
2631 dump_human_image_info_list(list);
2632 break;
2633 case OFORMAT_JSON:
2634 if (chain) {
2635 dump_json_image_info_list(list);
2636 } else {
2637 dump_json_image_info(list->value);
2639 break;
2642 qapi_free_ImageInfoList(list);
2643 return 0;
2646 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2647 MapEntry *next)
2649 switch (output_format) {
2650 case OFORMAT_HUMAN:
2651 if (e->data && !e->has_offset) {
2652 error_report("File contains external, encrypted or compressed clusters.");
2653 exit(1);
2655 if (e->data && !e->zero) {
2656 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2657 e->start, e->length,
2658 e->has_offset ? e->offset : 0,
2659 e->has_filename ? e->filename : "");
2661 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2662 * Modify the flags here to allow more coalescing.
2664 if (next && (!next->data || next->zero)) {
2665 next->data = false;
2666 next->zero = true;
2668 break;
2669 case OFORMAT_JSON:
2670 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2671 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2672 (e->start == 0 ? "[" : ",\n"),
2673 e->start, e->length, e->depth,
2674 e->zero ? "true" : "false",
2675 e->data ? "true" : "false");
2676 if (e->has_offset) {
2677 printf(", \"offset\": %"PRId64"", e->offset);
2679 putchar('}');
2681 if (!next) {
2682 printf("]\n");
2684 break;
2688 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2689 int nb_sectors, MapEntry *e)
2691 int64_t ret;
2692 int depth;
2693 BlockDriverState *file;
2694 bool has_offset;
2696 /* As an optimization, we could cache the current range of unallocated
2697 * clusters in each file of the chain, and avoid querying the same
2698 * range repeatedly.
2701 depth = 0;
2702 for (;;) {
2703 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2704 &file);
2705 if (ret < 0) {
2706 return ret;
2708 assert(nb_sectors);
2709 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2710 break;
2712 bs = backing_bs(bs);
2713 if (bs == NULL) {
2714 ret = 0;
2715 break;
2718 depth++;
2721 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2723 *e = (MapEntry) {
2724 .start = sector_num * BDRV_SECTOR_SIZE,
2725 .length = nb_sectors * BDRV_SECTOR_SIZE,
2726 .data = !!(ret & BDRV_BLOCK_DATA),
2727 .zero = !!(ret & BDRV_BLOCK_ZERO),
2728 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2729 .has_offset = has_offset,
2730 .depth = depth,
2731 .has_filename = file && has_offset,
2732 .filename = file && has_offset ? file->filename : NULL,
2735 return 0;
2738 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2740 if (curr->length == 0) {
2741 return false;
2743 if (curr->zero != next->zero ||
2744 curr->data != next->data ||
2745 curr->depth != next->depth ||
2746 curr->has_filename != next->has_filename ||
2747 curr->has_offset != next->has_offset) {
2748 return false;
2750 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2751 return false;
2753 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2754 return false;
2756 return true;
2759 static int img_map(int argc, char **argv)
2761 int c;
2762 OutputFormat output_format = OFORMAT_HUMAN;
2763 BlockBackend *blk;
2764 BlockDriverState *bs;
2765 const char *filename, *fmt, *output;
2766 int64_t length;
2767 MapEntry curr = { .length = 0 }, next;
2768 int ret = 0;
2769 bool image_opts = false;
2770 bool force_share = false;
2772 fmt = NULL;
2773 output = NULL;
2774 for (;;) {
2775 int option_index = 0;
2776 static const struct option long_options[] = {
2777 {"help", no_argument, 0, 'h'},
2778 {"format", required_argument, 0, 'f'},
2779 {"output", required_argument, 0, OPTION_OUTPUT},
2780 {"object", required_argument, 0, OPTION_OBJECT},
2781 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2782 {"force-share", no_argument, 0, 'U'},
2783 {0, 0, 0, 0}
2785 c = getopt_long(argc, argv, ":f:hU",
2786 long_options, &option_index);
2787 if (c == -1) {
2788 break;
2790 switch (c) {
2791 case ':':
2792 missing_argument(argv[optind - 1]);
2793 break;
2794 case '?':
2795 unrecognized_option(argv[optind - 1]);
2796 break;
2797 case 'h':
2798 help();
2799 break;
2800 case 'f':
2801 fmt = optarg;
2802 break;
2803 case 'U':
2804 force_share = true;
2805 break;
2806 case OPTION_OUTPUT:
2807 output = optarg;
2808 break;
2809 case OPTION_OBJECT: {
2810 QemuOpts *opts;
2811 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2812 optarg, true);
2813 if (!opts) {
2814 return 1;
2816 } break;
2817 case OPTION_IMAGE_OPTS:
2818 image_opts = true;
2819 break;
2822 if (optind != argc - 1) {
2823 error_exit("Expecting one image file name");
2825 filename = argv[optind];
2827 if (output && !strcmp(output, "json")) {
2828 output_format = OFORMAT_JSON;
2829 } else if (output && !strcmp(output, "human")) {
2830 output_format = OFORMAT_HUMAN;
2831 } else if (output) {
2832 error_report("--output must be used with human or json as argument.");
2833 return 1;
2836 if (qemu_opts_foreach(&qemu_object_opts,
2837 user_creatable_add_opts_foreach,
2838 NULL, NULL)) {
2839 return 1;
2842 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
2843 if (!blk) {
2844 return 1;
2846 bs = blk_bs(blk);
2848 if (output_format == OFORMAT_HUMAN) {
2849 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2852 length = blk_getlength(blk);
2853 while (curr.start + curr.length < length) {
2854 int64_t nsectors_left;
2855 int64_t sector_num;
2856 int n;
2858 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2860 /* Probe up to 1 GiB at a time. */
2861 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2862 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2863 ret = get_block_status(bs, sector_num, n, &next);
2865 if (ret < 0) {
2866 error_report("Could not read file metadata: %s", strerror(-ret));
2867 goto out;
2870 if (entry_mergeable(&curr, &next)) {
2871 curr.length += next.length;
2872 continue;
2875 if (curr.length > 0) {
2876 dump_map_entry(output_format, &curr, &next);
2878 curr = next;
2881 dump_map_entry(output_format, &curr, NULL);
2883 out:
2884 blk_unref(blk);
2885 return ret < 0;
2888 #define SNAPSHOT_LIST 1
2889 #define SNAPSHOT_CREATE 2
2890 #define SNAPSHOT_APPLY 3
2891 #define SNAPSHOT_DELETE 4
2893 static int img_snapshot(int argc, char **argv)
2895 BlockBackend *blk;
2896 BlockDriverState *bs;
2897 QEMUSnapshotInfo sn;
2898 char *filename, *snapshot_name = NULL;
2899 int c, ret = 0, bdrv_oflags;
2900 int action = 0;
2901 qemu_timeval tv;
2902 bool quiet = false;
2903 Error *err = NULL;
2904 bool image_opts = false;
2905 bool force_share = false;
2907 bdrv_oflags = BDRV_O_RDWR;
2908 /* Parse commandline parameters */
2909 for(;;) {
2910 static const struct option long_options[] = {
2911 {"help", no_argument, 0, 'h'},
2912 {"object", required_argument, 0, OPTION_OBJECT},
2913 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2914 {"force-share", no_argument, 0, 'U'},
2915 {0, 0, 0, 0}
2917 c = getopt_long(argc, argv, ":la:c:d:hqU",
2918 long_options, NULL);
2919 if (c == -1) {
2920 break;
2922 switch(c) {
2923 case ':':
2924 missing_argument(argv[optind - 1]);
2925 break;
2926 case '?':
2927 unrecognized_option(argv[optind - 1]);
2928 break;
2929 case 'h':
2930 help();
2931 return 0;
2932 case 'l':
2933 if (action) {
2934 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2935 return 0;
2937 action = SNAPSHOT_LIST;
2938 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2939 break;
2940 case 'a':
2941 if (action) {
2942 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2943 return 0;
2945 action = SNAPSHOT_APPLY;
2946 snapshot_name = optarg;
2947 break;
2948 case 'c':
2949 if (action) {
2950 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2951 return 0;
2953 action = SNAPSHOT_CREATE;
2954 snapshot_name = optarg;
2955 break;
2956 case 'd':
2957 if (action) {
2958 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2959 return 0;
2961 action = SNAPSHOT_DELETE;
2962 snapshot_name = optarg;
2963 break;
2964 case 'q':
2965 quiet = true;
2966 break;
2967 case 'U':
2968 force_share = true;
2969 break;
2970 case OPTION_OBJECT: {
2971 QemuOpts *opts;
2972 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2973 optarg, true);
2974 if (!opts) {
2975 return 1;
2977 } break;
2978 case OPTION_IMAGE_OPTS:
2979 image_opts = true;
2980 break;
2984 if (optind != argc - 1) {
2985 error_exit("Expecting one image file name");
2987 filename = argv[optind++];
2989 if (qemu_opts_foreach(&qemu_object_opts,
2990 user_creatable_add_opts_foreach,
2991 NULL, NULL)) {
2992 return 1;
2995 /* Open the image */
2996 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2997 force_share);
2998 if (!blk) {
2999 return 1;
3001 bs = blk_bs(blk);
3003 /* Perform the requested action */
3004 switch(action) {
3005 case SNAPSHOT_LIST:
3006 dump_snapshots(bs);
3007 break;
3009 case SNAPSHOT_CREATE:
3010 memset(&sn, 0, sizeof(sn));
3011 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3013 qemu_gettimeofday(&tv);
3014 sn.date_sec = tv.tv_sec;
3015 sn.date_nsec = tv.tv_usec * 1000;
3017 ret = bdrv_snapshot_create(bs, &sn);
3018 if (ret) {
3019 error_report("Could not create snapshot '%s': %d (%s)",
3020 snapshot_name, ret, strerror(-ret));
3022 break;
3024 case SNAPSHOT_APPLY:
3025 ret = bdrv_snapshot_goto(bs, snapshot_name);
3026 if (ret) {
3027 error_report("Could not apply snapshot '%s': %d (%s)",
3028 snapshot_name, ret, strerror(-ret));
3030 break;
3032 case SNAPSHOT_DELETE:
3033 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
3034 if (err) {
3035 error_reportf_err(err, "Could not delete snapshot '%s': ",
3036 snapshot_name);
3037 ret = 1;
3039 break;
3042 /* Cleanup */
3043 blk_unref(blk);
3044 if (ret) {
3045 return 1;
3047 return 0;
3050 static int img_rebase(int argc, char **argv)
3052 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3053 uint8_t *buf_old = NULL;
3054 uint8_t *buf_new = NULL;
3055 BlockDriverState *bs = NULL;
3056 char *filename;
3057 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3058 int c, flags, src_flags, ret;
3059 bool writethrough, src_writethrough;
3060 int unsafe = 0;
3061 bool force_share = false;
3062 int progress = 0;
3063 bool quiet = false;
3064 Error *local_err = NULL;
3065 bool image_opts = false;
3067 /* Parse commandline parameters */
3068 fmt = NULL;
3069 cache = BDRV_DEFAULT_CACHE;
3070 src_cache = BDRV_DEFAULT_CACHE;
3071 out_baseimg = NULL;
3072 out_basefmt = NULL;
3073 for(;;) {
3074 static const struct option long_options[] = {
3075 {"help", no_argument, 0, 'h'},
3076 {"object", required_argument, 0, OPTION_OBJECT},
3077 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3078 {"force-share", no_argument, 0, 'U'},
3079 {0, 0, 0, 0}
3081 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3082 long_options, NULL);
3083 if (c == -1) {
3084 break;
3086 switch(c) {
3087 case ':':
3088 missing_argument(argv[optind - 1]);
3089 break;
3090 case '?':
3091 unrecognized_option(argv[optind - 1]);
3092 break;
3093 case 'h':
3094 help();
3095 return 0;
3096 case 'f':
3097 fmt = optarg;
3098 break;
3099 case 'F':
3100 out_basefmt = optarg;
3101 break;
3102 case 'b':
3103 out_baseimg = optarg;
3104 break;
3105 case 'u':
3106 unsafe = 1;
3107 break;
3108 case 'p':
3109 progress = 1;
3110 break;
3111 case 't':
3112 cache = optarg;
3113 break;
3114 case 'T':
3115 src_cache = optarg;
3116 break;
3117 case 'q':
3118 quiet = true;
3119 break;
3120 case OPTION_OBJECT: {
3121 QemuOpts *opts;
3122 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3123 optarg, true);
3124 if (!opts) {
3125 return 1;
3127 } break;
3128 case OPTION_IMAGE_OPTS:
3129 image_opts = true;
3130 break;
3131 case 'U':
3132 force_share = true;
3133 break;
3137 if (quiet) {
3138 progress = 0;
3141 if (optind != argc - 1) {
3142 error_exit("Expecting one image file name");
3144 if (!unsafe && !out_baseimg) {
3145 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3147 filename = argv[optind++];
3149 if (qemu_opts_foreach(&qemu_object_opts,
3150 user_creatable_add_opts_foreach,
3151 NULL, NULL)) {
3152 return 1;
3155 qemu_progress_init(progress, 2.0);
3156 qemu_progress_print(0, 100);
3158 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3159 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3160 if (ret < 0) {
3161 error_report("Invalid cache option: %s", cache);
3162 goto out;
3165 src_flags = 0;
3166 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3167 if (ret < 0) {
3168 error_report("Invalid source cache option: %s", src_cache);
3169 goto out;
3172 /* The source files are opened read-only, don't care about WCE */
3173 assert((src_flags & BDRV_O_RDWR) == 0);
3174 (void) src_writethrough;
3177 * Open the images.
3179 * Ignore the old backing file for unsafe rebase in case we want to correct
3180 * the reference to a renamed or moved backing file.
3182 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3183 false);
3184 if (!blk) {
3185 ret = -1;
3186 goto out;
3188 bs = blk_bs(blk);
3190 if (out_basefmt != NULL) {
3191 if (bdrv_find_format(out_basefmt) == NULL) {
3192 error_report("Invalid format name: '%s'", out_basefmt);
3193 ret = -1;
3194 goto out;
3198 /* For safe rebasing we need to compare old and new backing file */
3199 if (!unsafe) {
3200 char backing_name[PATH_MAX];
3201 QDict *options = NULL;
3203 if (bs->backing_format[0] != '\0') {
3204 options = qdict_new();
3205 qdict_put_str(options, "driver", bs->backing_format);
3208 if (force_share) {
3209 if (!options) {
3210 options = qdict_new();
3212 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3214 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3215 blk_old_backing = blk_new_open(backing_name, NULL,
3216 options, src_flags, &local_err);
3217 if (!blk_old_backing) {
3218 error_reportf_err(local_err,
3219 "Could not open old backing file '%s': ",
3220 backing_name);
3221 ret = -1;
3222 goto out;
3225 if (out_baseimg[0]) {
3226 options = qdict_new();
3227 if (out_basefmt) {
3228 qdict_put_str(options, "driver", out_basefmt);
3230 if (force_share) {
3231 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3234 blk_new_backing = blk_new_open(out_baseimg, NULL,
3235 options, src_flags, &local_err);
3236 if (!blk_new_backing) {
3237 error_reportf_err(local_err,
3238 "Could not open new backing file '%s': ",
3239 out_baseimg);
3240 ret = -1;
3241 goto out;
3247 * Check each unallocated cluster in the COW file. If it is unallocated,
3248 * accesses go to the backing file. We must therefore compare this cluster
3249 * in the old and new backing file, and if they differ we need to copy it
3250 * from the old backing file into the COW file.
3252 * If qemu-img crashes during this step, no harm is done. The content of
3253 * the image is the same as the original one at any time.
3255 if (!unsafe) {
3256 int64_t num_sectors;
3257 int64_t old_backing_num_sectors;
3258 int64_t new_backing_num_sectors = 0;
3259 uint64_t sector;
3260 int n;
3261 int64_t count;
3262 float local_progress = 0;
3264 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3265 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3267 num_sectors = blk_nb_sectors(blk);
3268 if (num_sectors < 0) {
3269 error_report("Could not get size of '%s': %s",
3270 filename, strerror(-num_sectors));
3271 ret = -1;
3272 goto out;
3274 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
3275 if (old_backing_num_sectors < 0) {
3276 char backing_name[PATH_MAX];
3278 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3279 error_report("Could not get size of '%s': %s",
3280 backing_name, strerror(-old_backing_num_sectors));
3281 ret = -1;
3282 goto out;
3284 if (blk_new_backing) {
3285 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3286 if (new_backing_num_sectors < 0) {
3287 error_report("Could not get size of '%s': %s",
3288 out_baseimg, strerror(-new_backing_num_sectors));
3289 ret = -1;
3290 goto out;
3294 if (num_sectors != 0) {
3295 local_progress = (float)100 /
3296 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3299 for (sector = 0; sector < num_sectors; sector += n) {
3301 /* How many sectors can we handle with the next read? */
3302 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3303 n = (IO_BUF_SIZE / 512);
3304 } else {
3305 n = num_sectors - sector;
3308 /* If the cluster is allocated, we don't need to take action */
3309 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3310 n << BDRV_SECTOR_BITS, &count);
3311 if (ret < 0) {
3312 error_report("error while reading image metadata: %s",
3313 strerror(-ret));
3314 goto out;
3316 /* TODO relax this once bdrv_is_allocated does not enforce
3317 * sector alignment */
3318 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3319 n = count >> BDRV_SECTOR_BITS;
3320 if (ret) {
3321 continue;
3325 * Read old and new backing file and take into consideration that
3326 * backing files may be smaller than the COW image.
3328 if (sector >= old_backing_num_sectors) {
3329 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3330 } else {
3331 if (sector + n > old_backing_num_sectors) {
3332 n = old_backing_num_sectors - sector;
3335 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3336 buf_old, n << BDRV_SECTOR_BITS);
3337 if (ret < 0) {
3338 error_report("error while reading from old backing file");
3339 goto out;
3343 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3344 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3345 } else {
3346 if (sector + n > new_backing_num_sectors) {
3347 n = new_backing_num_sectors - sector;
3350 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3351 buf_new, n << BDRV_SECTOR_BITS);
3352 if (ret < 0) {
3353 error_report("error while reading from new backing file");
3354 goto out;
3358 /* If they differ, we need to write to the COW file */
3359 uint64_t written = 0;
3361 while (written < n) {
3362 int pnum;
3364 if (compare_sectors(buf_old + written * 512,
3365 buf_new + written * 512, n - written, &pnum))
3367 ret = blk_pwrite(blk,
3368 (sector + written) << BDRV_SECTOR_BITS,
3369 buf_old + written * 512,
3370 pnum << BDRV_SECTOR_BITS, 0);
3371 if (ret < 0) {
3372 error_report("Error while writing to COW image: %s",
3373 strerror(-ret));
3374 goto out;
3378 written += pnum;
3380 qemu_progress_print(local_progress, 100);
3385 * Change the backing file. All clusters that are different from the old
3386 * backing file are overwritten in the COW file now, so the visible content
3387 * doesn't change when we switch the backing file.
3389 if (out_baseimg && *out_baseimg) {
3390 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3391 } else {
3392 ret = bdrv_change_backing_file(bs, NULL, NULL);
3395 if (ret == -ENOSPC) {
3396 error_report("Could not change the backing file to '%s': No "
3397 "space left in the file header", out_baseimg);
3398 } else if (ret < 0) {
3399 error_report("Could not change the backing file to '%s': %s",
3400 out_baseimg, strerror(-ret));
3403 qemu_progress_print(100, 0);
3405 * TODO At this point it is possible to check if any clusters that are
3406 * allocated in the COW file are the same in the backing file. If so, they
3407 * could be dropped from the COW file. Don't do this before switching the
3408 * backing file, in case of a crash this would lead to corruption.
3410 out:
3411 qemu_progress_end();
3412 /* Cleanup */
3413 if (!unsafe) {
3414 blk_unref(blk_old_backing);
3415 blk_unref(blk_new_backing);
3417 qemu_vfree(buf_old);
3418 qemu_vfree(buf_new);
3420 blk_unref(blk);
3421 if (ret) {
3422 return 1;
3424 return 0;
3427 static int img_resize(int argc, char **argv)
3429 Error *err = NULL;
3430 int c, ret, relative;
3431 const char *filename, *fmt, *size;
3432 int64_t n, total_size;
3433 bool quiet = false;
3434 BlockBackend *blk = NULL;
3435 QemuOpts *param;
3437 static QemuOptsList resize_options = {
3438 .name = "resize_options",
3439 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3440 .desc = {
3442 .name = BLOCK_OPT_SIZE,
3443 .type = QEMU_OPT_SIZE,
3444 .help = "Virtual disk size"
3445 }, {
3446 /* end of list */
3450 bool image_opts = false;
3452 /* Remove size from argv manually so that negative numbers are not treated
3453 * as options by getopt. */
3454 if (argc < 3) {
3455 error_exit("Not enough arguments");
3456 return 1;
3459 size = argv[--argc];
3461 /* Parse getopt arguments */
3462 fmt = NULL;
3463 for(;;) {
3464 static const struct option long_options[] = {
3465 {"help", no_argument, 0, 'h'},
3466 {"object", required_argument, 0, OPTION_OBJECT},
3467 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3468 {0, 0, 0, 0}
3470 c = getopt_long(argc, argv, ":f:hq",
3471 long_options, NULL);
3472 if (c == -1) {
3473 break;
3475 switch(c) {
3476 case ':':
3477 missing_argument(argv[optind - 1]);
3478 break;
3479 case '?':
3480 unrecognized_option(argv[optind - 1]);
3481 break;
3482 case 'h':
3483 help();
3484 break;
3485 case 'f':
3486 fmt = optarg;
3487 break;
3488 case 'q':
3489 quiet = true;
3490 break;
3491 case OPTION_OBJECT: {
3492 QemuOpts *opts;
3493 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3494 optarg, true);
3495 if (!opts) {
3496 return 1;
3498 } break;
3499 case OPTION_IMAGE_OPTS:
3500 image_opts = true;
3501 break;
3504 if (optind != argc - 1) {
3505 error_exit("Expecting one image file name");
3507 filename = argv[optind++];
3509 if (qemu_opts_foreach(&qemu_object_opts,
3510 user_creatable_add_opts_foreach,
3511 NULL, NULL)) {
3512 return 1;
3515 /* Choose grow, shrink, or absolute resize mode */
3516 switch (size[0]) {
3517 case '+':
3518 relative = 1;
3519 size++;
3520 break;
3521 case '-':
3522 relative = -1;
3523 size++;
3524 break;
3525 default:
3526 relative = 0;
3527 break;
3530 /* Parse size */
3531 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3532 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3533 if (err) {
3534 error_report_err(err);
3535 ret = -1;
3536 qemu_opts_del(param);
3537 goto out;
3539 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3540 qemu_opts_del(param);
3542 blk = img_open(image_opts, filename, fmt,
3543 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3544 false);
3545 if (!blk) {
3546 ret = -1;
3547 goto out;
3550 if (relative) {
3551 total_size = blk_getlength(blk) + n * relative;
3552 } else {
3553 total_size = n;
3555 if (total_size <= 0) {
3556 error_report("New image size must be positive");
3557 ret = -1;
3558 goto out;
3561 ret = blk_truncate(blk, total_size, &err);
3562 if (!ret) {
3563 qprintf(quiet, "Image resized.\n");
3564 } else {
3565 error_report_err(err);
3567 out:
3568 blk_unref(blk);
3569 if (ret) {
3570 return 1;
3572 return 0;
3575 static void amend_status_cb(BlockDriverState *bs,
3576 int64_t offset, int64_t total_work_size,
3577 void *opaque)
3579 qemu_progress_print(100.f * offset / total_work_size, 0);
3582 static int img_amend(int argc, char **argv)
3584 Error *err = NULL;
3585 int c, ret = 0;
3586 char *options = NULL;
3587 QemuOptsList *create_opts = NULL;
3588 QemuOpts *opts = NULL;
3589 const char *fmt = NULL, *filename, *cache;
3590 int flags;
3591 bool writethrough;
3592 bool quiet = false, progress = false;
3593 BlockBackend *blk = NULL;
3594 BlockDriverState *bs = NULL;
3595 bool image_opts = false;
3597 cache = BDRV_DEFAULT_CACHE;
3598 for (;;) {
3599 static const struct option long_options[] = {
3600 {"help", no_argument, 0, 'h'},
3601 {"object", required_argument, 0, OPTION_OBJECT},
3602 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3603 {0, 0, 0, 0}
3605 c = getopt_long(argc, argv, ":ho:f:t:pq",
3606 long_options, NULL);
3607 if (c == -1) {
3608 break;
3611 switch (c) {
3612 case ':':
3613 missing_argument(argv[optind - 1]);
3614 break;
3615 case '?':
3616 unrecognized_option(argv[optind - 1]);
3617 break;
3618 case 'h':
3619 help();
3620 break;
3621 case 'o':
3622 if (!is_valid_option_list(optarg)) {
3623 error_report("Invalid option list: %s", optarg);
3624 ret = -1;
3625 goto out_no_progress;
3627 if (!options) {
3628 options = g_strdup(optarg);
3629 } else {
3630 char *old_options = options;
3631 options = g_strdup_printf("%s,%s", options, optarg);
3632 g_free(old_options);
3634 break;
3635 case 'f':
3636 fmt = optarg;
3637 break;
3638 case 't':
3639 cache = optarg;
3640 break;
3641 case 'p':
3642 progress = true;
3643 break;
3644 case 'q':
3645 quiet = true;
3646 break;
3647 case OPTION_OBJECT:
3648 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3649 optarg, true);
3650 if (!opts) {
3651 ret = -1;
3652 goto out_no_progress;
3654 break;
3655 case OPTION_IMAGE_OPTS:
3656 image_opts = true;
3657 break;
3661 if (!options) {
3662 error_exit("Must specify options (-o)");
3665 if (qemu_opts_foreach(&qemu_object_opts,
3666 user_creatable_add_opts_foreach,
3667 NULL, NULL)) {
3668 ret = -1;
3669 goto out_no_progress;
3672 if (quiet) {
3673 progress = false;
3675 qemu_progress_init(progress, 1.0);
3677 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3678 if (fmt && has_help_option(options)) {
3679 /* If a format is explicitly specified (and possibly no filename is
3680 * given), print option help here */
3681 ret = print_block_option_help(filename, fmt);
3682 goto out;
3685 if (optind != argc - 1) {
3686 error_report("Expecting one image file name");
3687 ret = -1;
3688 goto out;
3691 flags = BDRV_O_RDWR;
3692 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3693 if (ret < 0) {
3694 error_report("Invalid cache option: %s", cache);
3695 goto out;
3698 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3699 false);
3700 if (!blk) {
3701 ret = -1;
3702 goto out;
3704 bs = blk_bs(blk);
3706 fmt = bs->drv->format_name;
3708 if (has_help_option(options)) {
3709 /* If the format was auto-detected, print option help here */
3710 ret = print_block_option_help(filename, fmt);
3711 goto out;
3714 if (!bs->drv->create_opts) {
3715 error_report("Format driver '%s' does not support any options to amend",
3716 fmt);
3717 ret = -1;
3718 goto out;
3721 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3722 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3723 qemu_opts_do_parse(opts, options, NULL, &err);
3724 if (err) {
3725 error_report_err(err);
3726 ret = -1;
3727 goto out;
3730 /* In case the driver does not call amend_status_cb() */
3731 qemu_progress_print(0.f, 0);
3732 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3733 qemu_progress_print(100.f, 0);
3734 if (ret < 0) {
3735 error_report("Error while amending options: %s", strerror(-ret));
3736 goto out;
3739 out:
3740 qemu_progress_end();
3742 out_no_progress:
3743 blk_unref(blk);
3744 qemu_opts_del(opts);
3745 qemu_opts_free(create_opts);
3746 g_free(options);
3748 if (ret) {
3749 return 1;
3751 return 0;
3754 typedef struct BenchData {
3755 BlockBackend *blk;
3756 uint64_t image_size;
3757 bool write;
3758 int bufsize;
3759 int step;
3760 int nrreq;
3761 int n;
3762 int flush_interval;
3763 bool drain_on_flush;
3764 uint8_t *buf;
3765 QEMUIOVector *qiov;
3767 int in_flight;
3768 bool in_flush;
3769 uint64_t offset;
3770 } BenchData;
3772 static void bench_undrained_flush_cb(void *opaque, int ret)
3774 if (ret < 0) {
3775 error_report("Failed flush request: %s", strerror(-ret));
3776 exit(EXIT_FAILURE);
3780 static void bench_cb(void *opaque, int ret)
3782 BenchData *b = opaque;
3783 BlockAIOCB *acb;
3785 if (ret < 0) {
3786 error_report("Failed request: %s", strerror(-ret));
3787 exit(EXIT_FAILURE);
3790 if (b->in_flush) {
3791 /* Just finished a flush with drained queue: Start next requests */
3792 assert(b->in_flight == 0);
3793 b->in_flush = false;
3794 } else if (b->in_flight > 0) {
3795 int remaining = b->n - b->in_flight;
3797 b->n--;
3798 b->in_flight--;
3800 /* Time for flush? Drain queue if requested, then flush */
3801 if (b->flush_interval && remaining % b->flush_interval == 0) {
3802 if (!b->in_flight || !b->drain_on_flush) {
3803 BlockCompletionFunc *cb;
3805 if (b->drain_on_flush) {
3806 b->in_flush = true;
3807 cb = bench_cb;
3808 } else {
3809 cb = bench_undrained_flush_cb;
3812 acb = blk_aio_flush(b->blk, cb, b);
3813 if (!acb) {
3814 error_report("Failed to issue flush request");
3815 exit(EXIT_FAILURE);
3818 if (b->drain_on_flush) {
3819 return;
3824 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3825 int64_t offset = b->offset;
3826 /* blk_aio_* might look for completed I/Os and kick bench_cb
3827 * again, so make sure this operation is counted by in_flight
3828 * and b->offset is ready for the next submission.
3830 b->in_flight++;
3831 b->offset += b->step;
3832 b->offset %= b->image_size;
3833 if (b->write) {
3834 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3835 } else {
3836 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3838 if (!acb) {
3839 error_report("Failed to issue request");
3840 exit(EXIT_FAILURE);
3845 static int img_bench(int argc, char **argv)
3847 int c, ret = 0;
3848 const char *fmt = NULL, *filename;
3849 bool quiet = false;
3850 bool image_opts = false;
3851 bool is_write = false;
3852 int count = 75000;
3853 int depth = 64;
3854 int64_t offset = 0;
3855 size_t bufsize = 4096;
3856 int pattern = 0;
3857 size_t step = 0;
3858 int flush_interval = 0;
3859 bool drain_on_flush = true;
3860 int64_t image_size;
3861 BlockBackend *blk = NULL;
3862 BenchData data = {};
3863 int flags = 0;
3864 bool writethrough = false;
3865 struct timeval t1, t2;
3866 int i;
3867 bool force_share = false;
3869 for (;;) {
3870 static const struct option long_options[] = {
3871 {"help", no_argument, 0, 'h'},
3872 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3873 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3874 {"pattern", required_argument, 0, OPTION_PATTERN},
3875 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3876 {"force-share", no_argument, 0, 'U'},
3877 {0, 0, 0, 0}
3879 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
3880 if (c == -1) {
3881 break;
3884 switch (c) {
3885 case ':':
3886 missing_argument(argv[optind - 1]);
3887 break;
3888 case '?':
3889 unrecognized_option(argv[optind - 1]);
3890 break;
3891 case 'h':
3892 help();
3893 break;
3894 case 'c':
3896 unsigned long res;
3898 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3899 error_report("Invalid request count specified");
3900 return 1;
3902 count = res;
3903 break;
3905 case 'd':
3907 unsigned long res;
3909 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3910 error_report("Invalid queue depth specified");
3911 return 1;
3913 depth = res;
3914 break;
3916 case 'f':
3917 fmt = optarg;
3918 break;
3919 case 'n':
3920 flags |= BDRV_O_NATIVE_AIO;
3921 break;
3922 case 'o':
3924 offset = cvtnum(optarg);
3925 if (offset < 0) {
3926 error_report("Invalid offset specified");
3927 return 1;
3929 break;
3931 break;
3932 case 'q':
3933 quiet = true;
3934 break;
3935 case 's':
3937 int64_t sval;
3939 sval = cvtnum(optarg);
3940 if (sval < 0 || sval > INT_MAX) {
3941 error_report("Invalid buffer size specified");
3942 return 1;
3945 bufsize = sval;
3946 break;
3948 case 'S':
3950 int64_t sval;
3952 sval = cvtnum(optarg);
3953 if (sval < 0 || sval > INT_MAX) {
3954 error_report("Invalid step size specified");
3955 return 1;
3958 step = sval;
3959 break;
3961 case 't':
3962 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3963 if (ret < 0) {
3964 error_report("Invalid cache mode");
3965 ret = -1;
3966 goto out;
3968 break;
3969 case 'w':
3970 flags |= BDRV_O_RDWR;
3971 is_write = true;
3972 break;
3973 case 'U':
3974 force_share = true;
3975 break;
3976 case OPTION_PATTERN:
3978 unsigned long res;
3980 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
3981 error_report("Invalid pattern byte specified");
3982 return 1;
3984 pattern = res;
3985 break;
3987 case OPTION_FLUSH_INTERVAL:
3989 unsigned long res;
3991 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3992 error_report("Invalid flush interval specified");
3993 return 1;
3995 flush_interval = res;
3996 break;
3998 case OPTION_NO_DRAIN:
3999 drain_on_flush = false;
4000 break;
4001 case OPTION_IMAGE_OPTS:
4002 image_opts = true;
4003 break;
4007 if (optind != argc - 1) {
4008 error_exit("Expecting one image file name");
4010 filename = argv[argc - 1];
4012 if (!is_write && flush_interval) {
4013 error_report("--flush-interval is only available in write tests");
4014 ret = -1;
4015 goto out;
4017 if (flush_interval && flush_interval < depth) {
4018 error_report("Flush interval can't be smaller than depth");
4019 ret = -1;
4020 goto out;
4023 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4024 force_share);
4025 if (!blk) {
4026 ret = -1;
4027 goto out;
4030 image_size = blk_getlength(blk);
4031 if (image_size < 0) {
4032 ret = image_size;
4033 goto out;
4036 data = (BenchData) {
4037 .blk = blk,
4038 .image_size = image_size,
4039 .bufsize = bufsize,
4040 .step = step ?: bufsize,
4041 .nrreq = depth,
4042 .n = count,
4043 .offset = offset,
4044 .write = is_write,
4045 .flush_interval = flush_interval,
4046 .drain_on_flush = drain_on_flush,
4048 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4049 "(starting at offset %" PRId64 ", step size %d)\n",
4050 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4051 data.offset, data.step);
4052 if (flush_interval) {
4053 printf("Sending flush every %d requests\n", flush_interval);
4056 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
4057 memset(data.buf, pattern, data.nrreq * data.bufsize);
4059 data.qiov = g_new(QEMUIOVector, data.nrreq);
4060 for (i = 0; i < data.nrreq; i++) {
4061 qemu_iovec_init(&data.qiov[i], 1);
4062 qemu_iovec_add(&data.qiov[i],
4063 data.buf + i * data.bufsize, data.bufsize);
4066 gettimeofday(&t1, NULL);
4067 bench_cb(&data, 0);
4069 while (data.n > 0) {
4070 main_loop_wait(false);
4072 gettimeofday(&t2, NULL);
4074 printf("Run completed in %3.3f seconds.\n",
4075 (t2.tv_sec - t1.tv_sec)
4076 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4078 out:
4079 qemu_vfree(data.buf);
4080 blk_unref(blk);
4082 if (ret) {
4083 return 1;
4085 return 0;
4088 #define C_BS 01
4089 #define C_COUNT 02
4090 #define C_IF 04
4091 #define C_OF 010
4092 #define C_SKIP 020
4094 struct DdInfo {
4095 unsigned int flags;
4096 int64_t count;
4099 struct DdIo {
4100 int bsz; /* Block size */
4101 char *filename;
4102 uint8_t *buf;
4103 int64_t offset;
4106 struct DdOpts {
4107 const char *name;
4108 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4109 unsigned int flag;
4112 static int img_dd_bs(const char *arg,
4113 struct DdIo *in, struct DdIo *out,
4114 struct DdInfo *dd)
4116 int64_t res;
4118 res = cvtnum(arg);
4120 if (res <= 0 || res > INT_MAX) {
4121 error_report("invalid number: '%s'", arg);
4122 return 1;
4124 in->bsz = out->bsz = res;
4126 return 0;
4129 static int img_dd_count(const char *arg,
4130 struct DdIo *in, struct DdIo *out,
4131 struct DdInfo *dd)
4133 dd->count = cvtnum(arg);
4135 if (dd->count < 0) {
4136 error_report("invalid number: '%s'", arg);
4137 return 1;
4140 return 0;
4143 static int img_dd_if(const char *arg,
4144 struct DdIo *in, struct DdIo *out,
4145 struct DdInfo *dd)
4147 in->filename = g_strdup(arg);
4149 return 0;
4152 static int img_dd_of(const char *arg,
4153 struct DdIo *in, struct DdIo *out,
4154 struct DdInfo *dd)
4156 out->filename = g_strdup(arg);
4158 return 0;
4161 static int img_dd_skip(const char *arg,
4162 struct DdIo *in, struct DdIo *out,
4163 struct DdInfo *dd)
4165 in->offset = cvtnum(arg);
4167 if (in->offset < 0) {
4168 error_report("invalid number: '%s'", arg);
4169 return 1;
4172 return 0;
4175 static int img_dd(int argc, char **argv)
4177 int ret = 0;
4178 char *arg = NULL;
4179 char *tmp;
4180 BlockDriver *drv = NULL, *proto_drv = NULL;
4181 BlockBackend *blk1 = NULL, *blk2 = NULL;
4182 QemuOpts *opts = NULL;
4183 QemuOptsList *create_opts = NULL;
4184 Error *local_err = NULL;
4185 bool image_opts = false;
4186 int c, i;
4187 const char *out_fmt = "raw";
4188 const char *fmt = NULL;
4189 int64_t size = 0;
4190 int64_t block_count = 0, out_pos, in_pos;
4191 bool force_share = false;
4192 struct DdInfo dd = {
4193 .flags = 0,
4194 .count = 0,
4196 struct DdIo in = {
4197 .bsz = 512, /* Block size is by default 512 bytes */
4198 .filename = NULL,
4199 .buf = NULL,
4200 .offset = 0
4202 struct DdIo out = {
4203 .bsz = 512,
4204 .filename = NULL,
4205 .buf = NULL,
4206 .offset = 0
4209 const struct DdOpts options[] = {
4210 { "bs", img_dd_bs, C_BS },
4211 { "count", img_dd_count, C_COUNT },
4212 { "if", img_dd_if, C_IF },
4213 { "of", img_dd_of, C_OF },
4214 { "skip", img_dd_skip, C_SKIP },
4215 { NULL, NULL, 0 }
4217 const struct option long_options[] = {
4218 { "help", no_argument, 0, 'h'},
4219 { "object", required_argument, 0, OPTION_OBJECT},
4220 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4221 { "force-share", no_argument, 0, 'U'},
4222 { 0, 0, 0, 0 }
4225 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4226 if (c == EOF) {
4227 break;
4229 switch (c) {
4230 case 'O':
4231 out_fmt = optarg;
4232 break;
4233 case 'f':
4234 fmt = optarg;
4235 break;
4236 case ':':
4237 missing_argument(argv[optind - 1]);
4238 break;
4239 case '?':
4240 unrecognized_option(argv[optind - 1]);
4241 break;
4242 case 'h':
4243 help();
4244 break;
4245 case 'U':
4246 force_share = true;
4247 break;
4248 case OPTION_OBJECT:
4249 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
4250 ret = -1;
4251 goto out;
4253 break;
4254 case OPTION_IMAGE_OPTS:
4255 image_opts = true;
4256 break;
4260 for (i = optind; i < argc; i++) {
4261 int j;
4262 arg = g_strdup(argv[i]);
4264 tmp = strchr(arg, '=');
4265 if (tmp == NULL) {
4266 error_report("unrecognized operand %s", arg);
4267 ret = -1;
4268 goto out;
4271 *tmp++ = '\0';
4273 for (j = 0; options[j].name != NULL; j++) {
4274 if (!strcmp(arg, options[j].name)) {
4275 break;
4278 if (options[j].name == NULL) {
4279 error_report("unrecognized operand %s", arg);
4280 ret = -1;
4281 goto out;
4284 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4285 ret = -1;
4286 goto out;
4288 dd.flags |= options[j].flag;
4289 g_free(arg);
4290 arg = NULL;
4293 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4294 error_report("Must specify both input and output files");
4295 ret = -1;
4296 goto out;
4299 if (qemu_opts_foreach(&qemu_object_opts,
4300 user_creatable_add_opts_foreach,
4301 NULL, NULL)) {
4302 ret = -1;
4303 goto out;
4306 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4307 force_share);
4309 if (!blk1) {
4310 ret = -1;
4311 goto out;
4314 drv = bdrv_find_format(out_fmt);
4315 if (!drv) {
4316 error_report("Unknown file format");
4317 ret = -1;
4318 goto out;
4320 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4322 if (!proto_drv) {
4323 error_report_err(local_err);
4324 ret = -1;
4325 goto out;
4327 if (!drv->create_opts) {
4328 error_report("Format driver '%s' does not support image creation",
4329 drv->format_name);
4330 ret = -1;
4331 goto out;
4333 if (!proto_drv->create_opts) {
4334 error_report("Protocol driver '%s' does not support image creation",
4335 proto_drv->format_name);
4336 ret = -1;
4337 goto out;
4339 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4340 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4342 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4344 size = blk_getlength(blk1);
4345 if (size < 0) {
4346 error_report("Failed to get size for '%s'", in.filename);
4347 ret = -1;
4348 goto out;
4351 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4352 dd.count * in.bsz < size) {
4353 size = dd.count * in.bsz;
4356 /* Overflow means the specified offset is beyond input image's size */
4357 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4358 size < in.bsz * in.offset)) {
4359 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4360 } else {
4361 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4362 size - in.bsz * in.offset, &error_abort);
4365 ret = bdrv_create(drv, out.filename, opts, &local_err);
4366 if (ret < 0) {
4367 error_reportf_err(local_err,
4368 "%s: error while creating output image: ",
4369 out.filename);
4370 ret = -1;
4371 goto out;
4374 /* TODO, we can't honour --image-opts for the target,
4375 * since it needs to be given in a format compatible
4376 * with the bdrv_create() call above which does not
4377 * support image-opts style.
4379 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
4380 false, false, false);
4382 if (!blk2) {
4383 ret = -1;
4384 goto out;
4387 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4388 size < in.offset * in.bsz)) {
4389 /* We give a warning if the skip option is bigger than the input
4390 * size and create an empty output disk image (i.e. like dd(1)).
4392 error_report("%s: cannot skip to specified offset", in.filename);
4393 in_pos = size;
4394 } else {
4395 in_pos = in.offset * in.bsz;
4398 in.buf = g_new(uint8_t, in.bsz);
4400 for (out_pos = 0; in_pos < size; block_count++) {
4401 int in_ret, out_ret;
4403 if (in_pos + in.bsz > size) {
4404 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4405 } else {
4406 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4408 if (in_ret < 0) {
4409 error_report("error while reading from input image file: %s",
4410 strerror(-in_ret));
4411 ret = -1;
4412 goto out;
4414 in_pos += in_ret;
4416 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4418 if (out_ret < 0) {
4419 error_report("error while writing to output image file: %s",
4420 strerror(-out_ret));
4421 ret = -1;
4422 goto out;
4424 out_pos += out_ret;
4427 out:
4428 g_free(arg);
4429 qemu_opts_del(opts);
4430 qemu_opts_free(create_opts);
4431 blk_unref(blk1);
4432 blk_unref(blk2);
4433 g_free(in.filename);
4434 g_free(out.filename);
4435 g_free(in.buf);
4436 g_free(out.buf);
4438 if (ret) {
4439 return 1;
4441 return 0;
4445 static const img_cmd_t img_cmds[] = {
4446 #define DEF(option, callback, arg_string) \
4447 { option, callback },
4448 #include "qemu-img-cmds.h"
4449 #undef DEF
4450 #undef GEN_DOCS
4451 { NULL, NULL, },
4454 int main(int argc, char **argv)
4456 const img_cmd_t *cmd;
4457 const char *cmdname;
4458 Error *local_error = NULL;
4459 char *trace_file = NULL;
4460 int c;
4461 static const struct option long_options[] = {
4462 {"help", no_argument, 0, 'h'},
4463 {"version", no_argument, 0, 'V'},
4464 {"trace", required_argument, NULL, 'T'},
4465 {0, 0, 0, 0}
4468 #ifdef CONFIG_POSIX
4469 signal(SIGPIPE, SIG_IGN);
4470 #endif
4472 module_call_init(MODULE_INIT_TRACE);
4473 error_set_progname(argv[0]);
4474 qemu_init_exec_dir(argv[0]);
4476 if (qemu_init_main_loop(&local_error)) {
4477 error_report_err(local_error);
4478 exit(EXIT_FAILURE);
4481 qcrypto_init(&error_fatal);
4483 module_call_init(MODULE_INIT_QOM);
4484 bdrv_init();
4485 if (argc < 2) {
4486 error_exit("Not enough arguments");
4489 qemu_add_opts(&qemu_object_opts);
4490 qemu_add_opts(&qemu_source_opts);
4491 qemu_add_opts(&qemu_trace_opts);
4493 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4494 switch (c) {
4495 case ':':
4496 missing_argument(argv[optind - 1]);
4497 return 0;
4498 case '?':
4499 unrecognized_option(argv[optind - 1]);
4500 return 0;
4501 case 'h':
4502 help();
4503 return 0;
4504 case 'V':
4505 printf(QEMU_IMG_VERSION);
4506 return 0;
4507 case 'T':
4508 g_free(trace_file);
4509 trace_file = trace_opt_parse(optarg);
4510 break;
4514 cmdname = argv[optind];
4516 /* reset getopt_long scanning */
4517 argc -= optind;
4518 if (argc < 1) {
4519 return 0;
4521 argv += optind;
4522 optind = 0;
4524 if (!trace_init_backends()) {
4525 exit(1);
4527 trace_init_file(trace_file);
4528 qemu_set_log(LOG_TRACE);
4530 /* find the command */
4531 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4532 if (!strcmp(cmdname, cmd->name)) {
4533 return cmd->handler(argc, argv);
4537 /* not found */
4538 error_exit("Command not found: %s", cmdname);