iotests: 109: Filter out "len" of failed jobs
[qemu/ar7.git] / qemu-img.c
blobb94fc11e67f47a5e2e884e1ddc1d4b2650a06d9e
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 "qemu/cutils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
35 #include "qemu/log.h"
36 #include "qom/object_interfaces.h"
37 #include "sysemu/sysemu.h"
38 #include "sysemu/block-backend.h"
39 #include "block/block_int.h"
40 #include "block/blockjob.h"
41 #include "block/qapi.h"
42 #include "crypto/init.h"
43 #include "trace/control.h"
44 #include <getopt.h>
46 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
47 "\n" QEMU_COPYRIGHT "\n"
49 typedef struct img_cmd_t {
50 const char *name;
51 int (*handler)(int argc, char **argv);
52 } img_cmd_t;
54 enum {
55 OPTION_OUTPUT = 256,
56 OPTION_BACKING_CHAIN = 257,
57 OPTION_OBJECT = 258,
58 OPTION_IMAGE_OPTS = 259,
59 OPTION_PATTERN = 260,
60 OPTION_FLUSH_INTERVAL = 261,
61 OPTION_NO_DRAIN = 262,
64 typedef enum OutputFormat {
65 OFORMAT_JSON,
66 OFORMAT_HUMAN,
67 } OutputFormat;
69 /* Default to cache=writeback as data integrity is not important for qemu-img */
70 #define BDRV_DEFAULT_CACHE "writeback"
72 static void format_print(void *opaque, const char *name)
74 printf(" %s", name);
77 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
79 va_list ap;
81 error_printf("qemu-img: ");
83 va_start(ap, fmt);
84 error_vprintf(fmt, ap);
85 va_end(ap);
87 error_printf("\nTry 'qemu-img --help' for more information\n");
88 exit(EXIT_FAILURE);
91 static void QEMU_NORETURN missing_argument(const char *option)
93 error_exit("missing argument for option '%s'", option);
96 static void QEMU_NORETURN unrecognized_option(const char *option)
98 error_exit("unrecognized option '%s'", option);
101 /* Please keep in synch with qemu-img.texi */
102 static void QEMU_NORETURN help(void)
104 const char *help_msg =
105 QEMU_IMG_VERSION
106 "usage: qemu-img [standard options] command [command options]\n"
107 "QEMU disk image utility\n"
108 "\n"
109 " '-h', '--help' display this help and exit\n"
110 " '-V', '--version' output version information and exit\n"
111 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
112 " specify tracing options\n"
113 "\n"
114 "Command syntax:\n"
115 #define DEF(option, callback, arg_string) \
116 " " arg_string "\n"
117 #include "qemu-img-cmds.h"
118 #undef DEF
119 #undef GEN_DOCS
120 "\n"
121 "Command parameters:\n"
122 " 'filename' is a disk image filename\n"
123 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
124 " manual page for a description of the object properties. The most common\n"
125 " object type is a 'secret', which is used to supply passwords and/or\n"
126 " encryption keys.\n"
127 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
128 " 'cache' is the cache mode used to write the output disk image, the valid\n"
129 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
130 " 'directsync' and 'unsafe' (default for convert)\n"
131 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
132 " options are the same as for the 'cache' option\n"
133 " 'size' is the disk image size in bytes. Optional suffixes\n"
134 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
135 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
136 " supported. 'b' is ignored.\n"
137 " 'output_filename' is the destination disk image filename\n"
138 " 'output_fmt' is the destination format\n"
139 " 'options' is a comma separated list of format specific options in a\n"
140 " name=value format. Use -o ? for an overview of the options supported by the\n"
141 " used format\n"
142 " 'snapshot_param' is param used for internal snapshot, format\n"
143 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
144 " '[ID_OR_NAME]'\n"
145 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
146 " instead\n"
147 " '-c' indicates that target image must be compressed (qcow format only)\n"
148 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
149 " match exactly. The image doesn't need a working backing file before\n"
150 " rebasing in this case (useful for renaming the backing file)\n"
151 " '-h' with or without a command shows this help and lists the supported formats\n"
152 " '-p' show progress of command (only certain commands)\n"
153 " '-q' use Quiet mode - do not print any output (except errors)\n"
154 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
155 " contain only zeros for qemu-img to create a sparse image during\n"
156 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
157 " unallocated or zero sectors, and the destination image will always be\n"
158 " fully allocated\n"
159 " '--output' takes the format in which the output must be done (human or json)\n"
160 " '-n' skips the target volume creation (useful if the volume is created\n"
161 " prior to running qemu-img)\n"
162 "\n"
163 "Parameters to check subcommand:\n"
164 " '-r' tries to repair any inconsistencies that are found during the check.\n"
165 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
166 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
167 " hiding corruption that has already occurred.\n"
168 "\n"
169 "Parameters to convert subcommand:\n"
170 " '-m' specifies how many coroutines work in parallel during the convert\n"
171 " process (defaults to 8)\n"
172 " '-W' allow to write to the target out of order rather than sequential\n"
173 "\n"
174 "Parameters to snapshot subcommand:\n"
175 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
176 " '-a' applies a snapshot (revert disk to saved state)\n"
177 " '-c' creates a snapshot\n"
178 " '-d' deletes a snapshot\n"
179 " '-l' lists all snapshots in the given image\n"
180 "\n"
181 "Parameters to compare subcommand:\n"
182 " '-f' first image format\n"
183 " '-F' second image format\n"
184 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
185 "\n"
186 "Parameters to dd subcommand:\n"
187 " 'bs=BYTES' read and write up to BYTES bytes at a time "
188 "(default: 512)\n"
189 " 'count=N' copy only N input blocks\n"
190 " 'if=FILE' read from FILE\n"
191 " 'of=FILE' write to FILE\n"
192 " 'skip=N' skip N bs-sized blocks at the start of input\n";
194 printf("%s\nSupported formats:", help_msg);
195 bdrv_iterate_format(format_print, NULL);
196 printf("\n");
197 exit(EXIT_SUCCESS);
200 static QemuOptsList qemu_object_opts = {
201 .name = "object",
202 .implied_opt_name = "qom-type",
203 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
204 .desc = {
209 static QemuOptsList qemu_source_opts = {
210 .name = "source",
211 .implied_opt_name = "file",
212 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
213 .desc = {
218 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
220 int ret = 0;
221 if (!quiet) {
222 va_list args;
223 va_start(args, fmt);
224 ret = vprintf(fmt, args);
225 va_end(args);
227 return ret;
231 static int print_block_option_help(const char *filename, const char *fmt)
233 BlockDriver *drv, *proto_drv;
234 QemuOptsList *create_opts = NULL;
235 Error *local_err = NULL;
237 /* Find driver and parse its options */
238 drv = bdrv_find_format(fmt);
239 if (!drv) {
240 error_report("Unknown file format '%s'", fmt);
241 return 1;
244 create_opts = qemu_opts_append(create_opts, drv->create_opts);
245 if (filename) {
246 proto_drv = bdrv_find_protocol(filename, true, &local_err);
247 if (!proto_drv) {
248 error_report_err(local_err);
249 qemu_opts_free(create_opts);
250 return 1;
252 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
255 qemu_opts_print_help(create_opts);
256 qemu_opts_free(create_opts);
257 return 0;
261 static int img_open_password(BlockBackend *blk, const char *filename,
262 int flags, bool quiet)
264 BlockDriverState *bs;
265 char password[256];
267 bs = blk_bs(blk);
268 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
269 !(flags & BDRV_O_NO_IO)) {
270 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
271 if (qemu_read_password(password, sizeof(password)) < 0) {
272 error_report("No password given");
273 return -1;
275 if (bdrv_set_key(bs, password) < 0) {
276 error_report("invalid password");
277 return -1;
280 return 0;
284 static BlockBackend *img_open_opts(const char *optstr,
285 QemuOpts *opts, int flags, bool writethrough,
286 bool quiet)
288 QDict *options;
289 Error *local_err = NULL;
290 BlockBackend *blk;
291 options = qemu_opts_to_qdict(opts, NULL);
292 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
293 if (!blk) {
294 error_reportf_err(local_err, "Could not open '%s': ", optstr);
295 return NULL;
297 blk_set_enable_write_cache(blk, !writethrough);
299 if (img_open_password(blk, optstr, flags, quiet) < 0) {
300 blk_unref(blk);
301 return NULL;
303 return blk;
306 static BlockBackend *img_open_file(const char *filename,
307 const char *fmt, int flags,
308 bool writethrough, bool quiet)
310 BlockBackend *blk;
311 Error *local_err = NULL;
312 QDict *options = NULL;
314 if (fmt) {
315 options = qdict_new();
316 qdict_put(options, "driver", qstring_from_str(fmt));
319 blk = blk_new_open(filename, NULL, options, flags, &local_err);
320 if (!blk) {
321 error_reportf_err(local_err, "Could not open '%s': ", filename);
322 return NULL;
324 blk_set_enable_write_cache(blk, !writethrough);
326 if (img_open_password(blk, filename, flags, quiet) < 0) {
327 blk_unref(blk);
328 return NULL;
330 return blk;
334 static BlockBackend *img_open(bool image_opts,
335 const char *filename,
336 const char *fmt, int flags, bool writethrough,
337 bool quiet)
339 BlockBackend *blk;
340 if (image_opts) {
341 QemuOpts *opts;
342 if (fmt) {
343 error_report("--image-opts and --format are mutually exclusive");
344 return NULL;
346 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
347 filename, true);
348 if (!opts) {
349 return NULL;
351 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
352 } else {
353 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
355 return blk;
359 static int add_old_style_options(const char *fmt, QemuOpts *opts,
360 const char *base_filename,
361 const char *base_fmt)
363 Error *err = NULL;
365 if (base_filename) {
366 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
367 if (err) {
368 error_report("Backing file not supported for file format '%s'",
369 fmt);
370 error_free(err);
371 return -1;
374 if (base_fmt) {
375 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
376 if (err) {
377 error_report("Backing file format not supported for file "
378 "format '%s'", fmt);
379 error_free(err);
380 return -1;
383 return 0;
386 static int64_t cvtnum(const char *s)
388 int err;
389 uint64_t value;
391 err = qemu_strtosz(s, NULL, &value);
392 if (err < 0) {
393 return err;
395 if (value > INT64_MAX) {
396 return -ERANGE;
398 return value;
401 static int img_create(int argc, char **argv)
403 int c;
404 uint64_t img_size = -1;
405 const char *fmt = "raw";
406 const char *base_fmt = NULL;
407 const char *filename;
408 const char *base_filename = NULL;
409 char *options = NULL;
410 Error *local_err = NULL;
411 bool quiet = false;
413 for(;;) {
414 static const struct option long_options[] = {
415 {"help", no_argument, 0, 'h'},
416 {"object", required_argument, 0, OPTION_OBJECT},
417 {0, 0, 0, 0}
419 c = getopt_long(argc, argv, ":F:b:f:he6o:q",
420 long_options, NULL);
421 if (c == -1) {
422 break;
424 switch(c) {
425 case ':':
426 missing_argument(argv[optind - 1]);
427 break;
428 case '?':
429 unrecognized_option(argv[optind - 1]);
430 break;
431 case 'h':
432 help();
433 break;
434 case 'F':
435 base_fmt = optarg;
436 break;
437 case 'b':
438 base_filename = optarg;
439 break;
440 case 'f':
441 fmt = optarg;
442 break;
443 case 'e':
444 error_report("option -e is deprecated, please use \'-o "
445 "encryption\' instead!");
446 goto fail;
447 case '6':
448 error_report("option -6 is deprecated, please use \'-o "
449 "compat6\' instead!");
450 goto fail;
451 case 'o':
452 if (!is_valid_option_list(optarg)) {
453 error_report("Invalid option list: %s", optarg);
454 goto fail;
456 if (!options) {
457 options = g_strdup(optarg);
458 } else {
459 char *old_options = options;
460 options = g_strdup_printf("%s,%s", options, optarg);
461 g_free(old_options);
463 break;
464 case 'q':
465 quiet = true;
466 break;
467 case OPTION_OBJECT: {
468 QemuOpts *opts;
469 opts = qemu_opts_parse_noisily(&qemu_object_opts,
470 optarg, true);
471 if (!opts) {
472 goto fail;
474 } break;
478 /* Get the filename */
479 filename = (optind < argc) ? argv[optind] : NULL;
480 if (options && has_help_option(options)) {
481 g_free(options);
482 return print_block_option_help(filename, fmt);
485 if (optind >= argc) {
486 error_exit("Expecting image file name");
488 optind++;
490 if (qemu_opts_foreach(&qemu_object_opts,
491 user_creatable_add_opts_foreach,
492 NULL, NULL)) {
493 goto fail;
496 /* Get image size, if specified */
497 if (optind < argc) {
498 int64_t sval;
500 sval = cvtnum(argv[optind++]);
501 if (sval < 0) {
502 if (sval == -ERANGE) {
503 error_report("Image size must be less than 8 EiB!");
504 } else {
505 error_report("Invalid image size specified! You may use k, M, "
506 "G, T, P or E suffixes for ");
507 error_report("kilobytes, megabytes, gigabytes, terabytes, "
508 "petabytes and exabytes.");
510 goto fail;
512 img_size = (uint64_t)sval;
514 if (optind != argc) {
515 error_exit("Unexpected argument: %s", argv[optind]);
518 bdrv_img_create(filename, fmt, base_filename, base_fmt,
519 options, img_size, 0, quiet, &local_err);
520 if (local_err) {
521 error_reportf_err(local_err, "%s: ", filename);
522 goto fail;
525 g_free(options);
526 return 0;
528 fail:
529 g_free(options);
530 return 1;
533 static void dump_json_image_check(ImageCheck *check, bool quiet)
535 QString *str;
536 QObject *obj;
537 Visitor *v = qobject_output_visitor_new(&obj);
539 visit_type_ImageCheck(v, NULL, &check, &error_abort);
540 visit_complete(v, &obj);
541 str = qobject_to_json_pretty(obj);
542 assert(str != NULL);
543 qprintf(quiet, "%s\n", qstring_get_str(str));
544 qobject_decref(obj);
545 visit_free(v);
546 QDECREF(str);
549 static void dump_human_image_check(ImageCheck *check, bool quiet)
551 if (!(check->corruptions || check->leaks || check->check_errors)) {
552 qprintf(quiet, "No errors were found on the image.\n");
553 } else {
554 if (check->corruptions) {
555 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
556 "Data may be corrupted, or further writes to the image "
557 "may corrupt it.\n",
558 check->corruptions);
561 if (check->leaks) {
562 qprintf(quiet,
563 "\n%" PRId64 " leaked clusters were found on the image.\n"
564 "This means waste of disk space, but no harm to data.\n",
565 check->leaks);
568 if (check->check_errors) {
569 qprintf(quiet,
570 "\n%" PRId64
571 " internal errors have occurred during the check.\n",
572 check->check_errors);
576 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
577 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
578 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
579 check->allocated_clusters, check->total_clusters,
580 check->allocated_clusters * 100.0 / check->total_clusters,
581 check->fragmented_clusters * 100.0 / check->allocated_clusters,
582 check->compressed_clusters * 100.0 /
583 check->allocated_clusters);
586 if (check->image_end_offset) {
587 qprintf(quiet,
588 "Image end offset: %" PRId64 "\n", check->image_end_offset);
592 static int collect_image_check(BlockDriverState *bs,
593 ImageCheck *check,
594 const char *filename,
595 const char *fmt,
596 int fix)
598 int ret;
599 BdrvCheckResult result;
601 ret = bdrv_check(bs, &result, fix);
602 if (ret < 0) {
603 return ret;
606 check->filename = g_strdup(filename);
607 check->format = g_strdup(bdrv_get_format_name(bs));
608 check->check_errors = result.check_errors;
609 check->corruptions = result.corruptions;
610 check->has_corruptions = result.corruptions != 0;
611 check->leaks = result.leaks;
612 check->has_leaks = result.leaks != 0;
613 check->corruptions_fixed = result.corruptions_fixed;
614 check->has_corruptions_fixed = result.corruptions != 0;
615 check->leaks_fixed = result.leaks_fixed;
616 check->has_leaks_fixed = result.leaks != 0;
617 check->image_end_offset = result.image_end_offset;
618 check->has_image_end_offset = result.image_end_offset != 0;
619 check->total_clusters = result.bfi.total_clusters;
620 check->has_total_clusters = result.bfi.total_clusters != 0;
621 check->allocated_clusters = result.bfi.allocated_clusters;
622 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
623 check->fragmented_clusters = result.bfi.fragmented_clusters;
624 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
625 check->compressed_clusters = result.bfi.compressed_clusters;
626 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
628 return 0;
632 * Checks an image for consistency. Exit codes:
634 * 0 - Check completed, image is good
635 * 1 - Check not completed because of internal errors
636 * 2 - Check completed, image is corrupted
637 * 3 - Check completed, image has leaked clusters, but is good otherwise
638 * 63 - Checks are not supported by the image format
640 static int img_check(int argc, char **argv)
642 int c, ret;
643 OutputFormat output_format = OFORMAT_HUMAN;
644 const char *filename, *fmt, *output, *cache;
645 BlockBackend *blk;
646 BlockDriverState *bs;
647 int fix = 0;
648 int flags = BDRV_O_CHECK;
649 bool writethrough;
650 ImageCheck *check;
651 bool quiet = false;
652 bool image_opts = false;
654 fmt = NULL;
655 output = NULL;
656 cache = BDRV_DEFAULT_CACHE;
658 for(;;) {
659 int option_index = 0;
660 static const struct option long_options[] = {
661 {"help", no_argument, 0, 'h'},
662 {"format", required_argument, 0, 'f'},
663 {"repair", required_argument, 0, 'r'},
664 {"output", required_argument, 0, OPTION_OUTPUT},
665 {"object", required_argument, 0, OPTION_OBJECT},
666 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
667 {0, 0, 0, 0}
669 c = getopt_long(argc, argv, ":hf:r:T:q",
670 long_options, &option_index);
671 if (c == -1) {
672 break;
674 switch(c) {
675 case ':':
676 missing_argument(argv[optind - 1]);
677 break;
678 case '?':
679 unrecognized_option(argv[optind - 1]);
680 break;
681 case 'h':
682 help();
683 break;
684 case 'f':
685 fmt = optarg;
686 break;
687 case 'r':
688 flags |= BDRV_O_RDWR;
690 if (!strcmp(optarg, "leaks")) {
691 fix = BDRV_FIX_LEAKS;
692 } else if (!strcmp(optarg, "all")) {
693 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
694 } else {
695 error_exit("Unknown option value for -r "
696 "(expecting 'leaks' or 'all'): %s", optarg);
698 break;
699 case OPTION_OUTPUT:
700 output = optarg;
701 break;
702 case 'T':
703 cache = optarg;
704 break;
705 case 'q':
706 quiet = true;
707 break;
708 case OPTION_OBJECT: {
709 QemuOpts *opts;
710 opts = qemu_opts_parse_noisily(&qemu_object_opts,
711 optarg, true);
712 if (!opts) {
713 return 1;
715 } break;
716 case OPTION_IMAGE_OPTS:
717 image_opts = true;
718 break;
721 if (optind != argc - 1) {
722 error_exit("Expecting one image file name");
724 filename = argv[optind++];
726 if (output && !strcmp(output, "json")) {
727 output_format = OFORMAT_JSON;
728 } else if (output && !strcmp(output, "human")) {
729 output_format = OFORMAT_HUMAN;
730 } else if (output) {
731 error_report("--output must be used with human or json as argument.");
732 return 1;
735 if (qemu_opts_foreach(&qemu_object_opts,
736 user_creatable_add_opts_foreach,
737 NULL, NULL)) {
738 return 1;
741 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
742 if (ret < 0) {
743 error_report("Invalid source cache option: %s", cache);
744 return 1;
747 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
748 if (!blk) {
749 return 1;
751 bs = blk_bs(blk);
753 check = g_new0(ImageCheck, 1);
754 ret = collect_image_check(bs, check, filename, fmt, fix);
756 if (ret == -ENOTSUP) {
757 error_report("This image format does not support checks");
758 ret = 63;
759 goto fail;
762 if (check->corruptions_fixed || check->leaks_fixed) {
763 int corruptions_fixed, leaks_fixed;
765 leaks_fixed = check->leaks_fixed;
766 corruptions_fixed = check->corruptions_fixed;
768 if (output_format == OFORMAT_HUMAN) {
769 qprintf(quiet,
770 "The following inconsistencies were found and repaired:\n\n"
771 " %" PRId64 " leaked clusters\n"
772 " %" PRId64 " corruptions\n\n"
773 "Double checking the fixed image now...\n",
774 check->leaks_fixed,
775 check->corruptions_fixed);
778 ret = collect_image_check(bs, check, filename, fmt, 0);
780 check->leaks_fixed = leaks_fixed;
781 check->corruptions_fixed = corruptions_fixed;
784 if (!ret) {
785 switch (output_format) {
786 case OFORMAT_HUMAN:
787 dump_human_image_check(check, quiet);
788 break;
789 case OFORMAT_JSON:
790 dump_json_image_check(check, quiet);
791 break;
795 if (ret || check->check_errors) {
796 if (ret) {
797 error_report("Check failed: %s", strerror(-ret));
798 } else {
799 error_report("Check failed");
801 ret = 1;
802 goto fail;
805 if (check->corruptions) {
806 ret = 2;
807 } else if (check->leaks) {
808 ret = 3;
809 } else {
810 ret = 0;
813 fail:
814 qapi_free_ImageCheck(check);
815 blk_unref(blk);
816 return ret;
819 typedef struct CommonBlockJobCBInfo {
820 BlockDriverState *bs;
821 Error **errp;
822 } CommonBlockJobCBInfo;
824 static void common_block_job_cb(void *opaque, int ret)
826 CommonBlockJobCBInfo *cbi = opaque;
828 if (ret < 0) {
829 error_setg_errno(cbi->errp, -ret, "Block job failed");
833 static void run_block_job(BlockJob *job, Error **errp)
835 AioContext *aio_context = blk_get_aio_context(job->blk);
837 /* FIXME In error cases, the job simply goes away and we access a dangling
838 * pointer below. */
839 aio_context_acquire(aio_context);
840 do {
841 aio_poll(aio_context, true);
842 qemu_progress_print(job->len ?
843 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
844 } while (!job->ready);
846 block_job_complete_sync(job, errp);
847 aio_context_release(aio_context);
849 /* A block job may finish instantaneously without publishing any progress,
850 * so just signal completion here */
851 qemu_progress_print(100.f, 0);
854 static int img_commit(int argc, char **argv)
856 int c, ret, flags;
857 const char *filename, *fmt, *cache, *base;
858 BlockBackend *blk;
859 BlockDriverState *bs, *base_bs;
860 BlockJob *job;
861 bool progress = false, quiet = false, drop = false;
862 bool writethrough;
863 Error *local_err = NULL;
864 CommonBlockJobCBInfo cbi;
865 bool image_opts = false;
866 AioContext *aio_context;
868 fmt = NULL;
869 cache = BDRV_DEFAULT_CACHE;
870 base = NULL;
871 for(;;) {
872 static const struct option long_options[] = {
873 {"help", no_argument, 0, 'h'},
874 {"object", required_argument, 0, OPTION_OBJECT},
875 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
876 {0, 0, 0, 0}
878 c = getopt_long(argc, argv, ":f:ht:b:dpq",
879 long_options, NULL);
880 if (c == -1) {
881 break;
883 switch(c) {
884 case ':':
885 missing_argument(argv[optind - 1]);
886 break;
887 case '?':
888 unrecognized_option(argv[optind - 1]);
889 break;
890 case 'h':
891 help();
892 break;
893 case 'f':
894 fmt = optarg;
895 break;
896 case 't':
897 cache = optarg;
898 break;
899 case 'b':
900 base = optarg;
901 /* -b implies -d */
902 drop = true;
903 break;
904 case 'd':
905 drop = true;
906 break;
907 case 'p':
908 progress = true;
909 break;
910 case 'q':
911 quiet = true;
912 break;
913 case OPTION_OBJECT: {
914 QemuOpts *opts;
915 opts = qemu_opts_parse_noisily(&qemu_object_opts,
916 optarg, true);
917 if (!opts) {
918 return 1;
920 } break;
921 case OPTION_IMAGE_OPTS:
922 image_opts = true;
923 break;
927 /* Progress is not shown in Quiet mode */
928 if (quiet) {
929 progress = false;
932 if (optind != argc - 1) {
933 error_exit("Expecting one image file name");
935 filename = argv[optind++];
937 if (qemu_opts_foreach(&qemu_object_opts,
938 user_creatable_add_opts_foreach,
939 NULL, NULL)) {
940 return 1;
943 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
944 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
945 if (ret < 0) {
946 error_report("Invalid cache option: %s", cache);
947 return 1;
950 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
951 if (!blk) {
952 return 1;
954 bs = blk_bs(blk);
956 qemu_progress_init(progress, 1.f);
957 qemu_progress_print(0.f, 100);
959 if (base) {
960 base_bs = bdrv_find_backing_image(bs, base);
961 if (!base_bs) {
962 error_setg(&local_err,
963 "Did not find '%s' in the backing chain of '%s'",
964 base, filename);
965 goto done;
967 } else {
968 /* This is different from QMP, which by default uses the deepest file in
969 * the backing chain (i.e., the very base); however, the traditional
970 * behavior of qemu-img commit is using the immediate backing file. */
971 base_bs = backing_bs(bs);
972 if (!base_bs) {
973 error_setg(&local_err, "Image does not have a backing file");
974 goto done;
978 cbi = (CommonBlockJobCBInfo){
979 .errp = &local_err,
980 .bs = bs,
983 aio_context = bdrv_get_aio_context(bs);
984 aio_context_acquire(aio_context);
985 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
986 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
987 &cbi, false, &local_err);
988 aio_context_release(aio_context);
989 if (local_err) {
990 goto done;
993 /* When the block job completes, the BlockBackend reference will point to
994 * the old backing file. In order to avoid that the top image is already
995 * deleted, so we can still empty it afterwards, increment the reference
996 * counter here preemptively. */
997 if (!drop) {
998 bdrv_ref(bs);
1001 job = block_job_get("commit");
1002 run_block_job(job, &local_err);
1003 if (local_err) {
1004 goto unref_backing;
1007 if (!drop && bs->drv->bdrv_make_empty) {
1008 ret = bs->drv->bdrv_make_empty(bs);
1009 if (ret) {
1010 error_setg_errno(&local_err, -ret, "Could not empty %s",
1011 filename);
1012 goto unref_backing;
1016 unref_backing:
1017 if (!drop) {
1018 bdrv_unref(bs);
1021 done:
1022 qemu_progress_end();
1024 blk_unref(blk);
1026 if (local_err) {
1027 error_report_err(local_err);
1028 return 1;
1031 qprintf(quiet, "Image committed.\n");
1032 return 0;
1036 * Returns true iff the first sector pointed to by 'buf' contains at least
1037 * a non-NUL byte.
1039 * 'pnum' is set to the number of sectors (including and immediately following
1040 * the first one) that are known to be in the same allocated/unallocated state.
1042 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1044 bool is_zero;
1045 int i;
1047 if (n <= 0) {
1048 *pnum = 0;
1049 return 0;
1051 is_zero = buffer_is_zero(buf, 512);
1052 for(i = 1; i < n; i++) {
1053 buf += 512;
1054 if (is_zero != buffer_is_zero(buf, 512)) {
1055 break;
1058 *pnum = i;
1059 return !is_zero;
1063 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1064 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1065 * breaking up write requests for only small sparse areas.
1067 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1068 int min)
1070 int ret;
1071 int num_checked, num_used;
1073 if (n < min) {
1074 min = n;
1077 ret = is_allocated_sectors(buf, n, pnum);
1078 if (!ret) {
1079 return ret;
1082 num_used = *pnum;
1083 buf += BDRV_SECTOR_SIZE * *pnum;
1084 n -= *pnum;
1085 num_checked = num_used;
1087 while (n > 0) {
1088 ret = is_allocated_sectors(buf, n, pnum);
1090 buf += BDRV_SECTOR_SIZE * *pnum;
1091 n -= *pnum;
1092 num_checked += *pnum;
1093 if (ret) {
1094 num_used = num_checked;
1095 } else if (*pnum >= min) {
1096 break;
1100 *pnum = num_used;
1101 return 1;
1105 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1106 * buffers matches, non-zero otherwise.
1108 * pnum is set to the number of sectors (including and immediately following
1109 * the first one) that are known to have the same comparison result
1111 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1112 int *pnum)
1114 bool res;
1115 int i;
1117 if (n <= 0) {
1118 *pnum = 0;
1119 return 0;
1122 res = !!memcmp(buf1, buf2, 512);
1123 for(i = 1; i < n; i++) {
1124 buf1 += 512;
1125 buf2 += 512;
1127 if (!!memcmp(buf1, buf2, 512) != res) {
1128 break;
1132 *pnum = i;
1133 return res;
1136 #define IO_BUF_SIZE (2 * 1024 * 1024)
1138 static int64_t sectors_to_bytes(int64_t sectors)
1140 return sectors << BDRV_SECTOR_BITS;
1143 static int64_t sectors_to_process(int64_t total, int64_t from)
1145 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1149 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1151 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1152 * data and negative value on error.
1154 * @param blk: BlockBackend for the image
1155 * @param sect_num: Number of first sector to check
1156 * @param sect_count: Number of sectors to check
1157 * @param filename: Name of disk file we are checking (logging purpose)
1158 * @param buffer: Allocated buffer for storing read data
1159 * @param quiet: Flag for quiet mode
1161 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1162 int sect_count, const char *filename,
1163 uint8_t *buffer, bool quiet)
1165 int pnum, ret = 0;
1166 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1167 sect_count << BDRV_SECTOR_BITS);
1168 if (ret < 0) {
1169 error_report("Error while reading offset %" PRId64 " of %s: %s",
1170 sectors_to_bytes(sect_num), filename, strerror(-ret));
1171 return ret;
1173 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1174 if (ret || pnum != sect_count) {
1175 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1176 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1177 return 1;
1180 return 0;
1184 * Compares two images. Exit codes:
1186 * 0 - Images are identical
1187 * 1 - Images differ
1188 * >1 - Error occurred
1190 static int img_compare(int argc, char **argv)
1192 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1193 BlockBackend *blk1, *blk2;
1194 BlockDriverState *bs1, *bs2;
1195 int64_t total_sectors1, total_sectors2;
1196 uint8_t *buf1 = NULL, *buf2 = NULL;
1197 int pnum1, pnum2;
1198 int allocated1, allocated2;
1199 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1200 bool progress = false, quiet = false, strict = false;
1201 int flags;
1202 bool writethrough;
1203 int64_t total_sectors;
1204 int64_t sector_num = 0;
1205 int64_t nb_sectors;
1206 int c, pnum;
1207 uint64_t progress_base;
1208 bool image_opts = false;
1210 cache = BDRV_DEFAULT_CACHE;
1211 for (;;) {
1212 static const struct option long_options[] = {
1213 {"help", no_argument, 0, 'h'},
1214 {"object", required_argument, 0, OPTION_OBJECT},
1215 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1216 {0, 0, 0, 0}
1218 c = getopt_long(argc, argv, ":hf:F:T:pqs",
1219 long_options, NULL);
1220 if (c == -1) {
1221 break;
1223 switch (c) {
1224 case ':':
1225 missing_argument(argv[optind - 1]);
1226 break;
1227 case '?':
1228 unrecognized_option(argv[optind - 1]);
1229 break;
1230 case 'h':
1231 help();
1232 break;
1233 case 'f':
1234 fmt1 = optarg;
1235 break;
1236 case 'F':
1237 fmt2 = optarg;
1238 break;
1239 case 'T':
1240 cache = optarg;
1241 break;
1242 case 'p':
1243 progress = true;
1244 break;
1245 case 'q':
1246 quiet = true;
1247 break;
1248 case 's':
1249 strict = true;
1250 break;
1251 case OPTION_OBJECT: {
1252 QemuOpts *opts;
1253 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1254 optarg, true);
1255 if (!opts) {
1256 ret = 2;
1257 goto out4;
1259 } break;
1260 case OPTION_IMAGE_OPTS:
1261 image_opts = true;
1262 break;
1266 /* Progress is not shown in Quiet mode */
1267 if (quiet) {
1268 progress = false;
1272 if (optind != argc - 2) {
1273 error_exit("Expecting two image file names");
1275 filename1 = argv[optind++];
1276 filename2 = argv[optind++];
1278 if (qemu_opts_foreach(&qemu_object_opts,
1279 user_creatable_add_opts_foreach,
1280 NULL, NULL)) {
1281 ret = 2;
1282 goto out4;
1285 /* Initialize before goto out */
1286 qemu_progress_init(progress, 2.0);
1288 flags = 0;
1289 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1290 if (ret < 0) {
1291 error_report("Invalid source cache option: %s", cache);
1292 ret = 2;
1293 goto out3;
1296 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
1297 if (!blk1) {
1298 ret = 2;
1299 goto out3;
1302 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
1303 if (!blk2) {
1304 ret = 2;
1305 goto out2;
1307 bs1 = blk_bs(blk1);
1308 bs2 = blk_bs(blk2);
1310 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1311 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1312 total_sectors1 = blk_nb_sectors(blk1);
1313 if (total_sectors1 < 0) {
1314 error_report("Can't get size of %s: %s",
1315 filename1, strerror(-total_sectors1));
1316 ret = 4;
1317 goto out;
1319 total_sectors2 = blk_nb_sectors(blk2);
1320 if (total_sectors2 < 0) {
1321 error_report("Can't get size of %s: %s",
1322 filename2, strerror(-total_sectors2));
1323 ret = 4;
1324 goto out;
1326 total_sectors = MIN(total_sectors1, total_sectors2);
1327 progress_base = MAX(total_sectors1, total_sectors2);
1329 qemu_progress_print(0, 100);
1331 if (strict && total_sectors1 != total_sectors2) {
1332 ret = 1;
1333 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1334 goto out;
1337 for (;;) {
1338 int64_t status1, status2;
1339 BlockDriverState *file;
1341 nb_sectors = sectors_to_process(total_sectors, sector_num);
1342 if (nb_sectors <= 0) {
1343 break;
1345 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1346 total_sectors1 - sector_num,
1347 &pnum1, &file);
1348 if (status1 < 0) {
1349 ret = 3;
1350 error_report("Sector allocation test failed for %s", filename1);
1351 goto out;
1353 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1355 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1356 total_sectors2 - sector_num,
1357 &pnum2, &file);
1358 if (status2 < 0) {
1359 ret = 3;
1360 error_report("Sector allocation test failed for %s", filename2);
1361 goto out;
1363 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1364 if (pnum1) {
1365 nb_sectors = MIN(nb_sectors, pnum1);
1367 if (pnum2) {
1368 nb_sectors = MIN(nb_sectors, pnum2);
1371 if (strict) {
1372 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1373 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1374 ret = 1;
1375 qprintf(quiet, "Strict mode: Offset %" PRId64
1376 " block status mismatch!\n",
1377 sectors_to_bytes(sector_num));
1378 goto out;
1381 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1382 nb_sectors = MIN(pnum1, pnum2);
1383 } else if (allocated1 == allocated2) {
1384 if (allocated1) {
1385 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1386 nb_sectors << BDRV_SECTOR_BITS);
1387 if (ret < 0) {
1388 error_report("Error while reading offset %" PRId64 " of %s:"
1389 " %s", sectors_to_bytes(sector_num), filename1,
1390 strerror(-ret));
1391 ret = 4;
1392 goto out;
1394 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1395 nb_sectors << BDRV_SECTOR_BITS);
1396 if (ret < 0) {
1397 error_report("Error while reading offset %" PRId64
1398 " of %s: %s", sectors_to_bytes(sector_num),
1399 filename2, strerror(-ret));
1400 ret = 4;
1401 goto out;
1403 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1404 if (ret || pnum != nb_sectors) {
1405 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1406 sectors_to_bytes(
1407 ret ? sector_num : sector_num + pnum));
1408 ret = 1;
1409 goto out;
1412 } else {
1414 if (allocated1) {
1415 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1416 filename1, buf1, quiet);
1417 } else {
1418 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1419 filename2, buf1, quiet);
1421 if (ret) {
1422 if (ret < 0) {
1423 error_report("Error while reading offset %" PRId64 ": %s",
1424 sectors_to_bytes(sector_num), strerror(-ret));
1425 ret = 4;
1427 goto out;
1430 sector_num += nb_sectors;
1431 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1434 if (total_sectors1 != total_sectors2) {
1435 BlockBackend *blk_over;
1436 int64_t total_sectors_over;
1437 const char *filename_over;
1439 qprintf(quiet, "Warning: Image size mismatch!\n");
1440 if (total_sectors1 > total_sectors2) {
1441 total_sectors_over = total_sectors1;
1442 blk_over = blk1;
1443 filename_over = filename1;
1444 } else {
1445 total_sectors_over = total_sectors2;
1446 blk_over = blk2;
1447 filename_over = filename2;
1450 for (;;) {
1451 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1452 if (nb_sectors <= 0) {
1453 break;
1455 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1456 nb_sectors, &pnum);
1457 if (ret < 0) {
1458 ret = 3;
1459 error_report("Sector allocation test failed for %s",
1460 filename_over);
1461 goto out;
1464 nb_sectors = pnum;
1465 if (ret) {
1466 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1467 filename_over, buf1, quiet);
1468 if (ret) {
1469 if (ret < 0) {
1470 error_report("Error while reading offset %" PRId64
1471 " of %s: %s", sectors_to_bytes(sector_num),
1472 filename_over, strerror(-ret));
1473 ret = 4;
1475 goto out;
1478 sector_num += nb_sectors;
1479 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1483 qprintf(quiet, "Images are identical.\n");
1484 ret = 0;
1486 out:
1487 qemu_vfree(buf1);
1488 qemu_vfree(buf2);
1489 blk_unref(blk2);
1490 out2:
1491 blk_unref(blk1);
1492 out3:
1493 qemu_progress_end();
1494 out4:
1495 return ret;
1498 enum ImgConvertBlockStatus {
1499 BLK_DATA,
1500 BLK_ZERO,
1501 BLK_BACKING_FILE,
1504 #define MAX_COROUTINES 16
1506 typedef struct ImgConvertState {
1507 BlockBackend **src;
1508 int64_t *src_sectors;
1509 int src_num;
1510 int64_t total_sectors;
1511 int64_t allocated_sectors;
1512 int64_t allocated_done;
1513 int64_t sector_num;
1514 int64_t wr_offs;
1515 enum ImgConvertBlockStatus status;
1516 int64_t sector_next_status;
1517 BlockBackend *target;
1518 bool has_zero_init;
1519 bool compressed;
1520 bool target_has_backing;
1521 bool wr_in_order;
1522 int min_sparse;
1523 size_t cluster_sectors;
1524 size_t buf_sectors;
1525 long num_coroutines;
1526 int running_coroutines;
1527 Coroutine *co[MAX_COROUTINES];
1528 int64_t wait_sector_num[MAX_COROUTINES];
1529 CoMutex lock;
1530 int ret;
1531 } ImgConvertState;
1533 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1534 int *src_cur, int64_t *src_cur_offset)
1536 *src_cur = 0;
1537 *src_cur_offset = 0;
1538 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1539 *src_cur_offset += s->src_sectors[*src_cur];
1540 (*src_cur)++;
1541 assert(*src_cur < s->src_num);
1545 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1547 int64_t ret, src_cur_offset;
1548 int n, src_cur;
1550 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1552 assert(s->total_sectors > sector_num);
1553 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1555 if (s->sector_next_status <= sector_num) {
1556 BlockDriverState *file;
1557 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1558 sector_num - src_cur_offset,
1559 n, &n, &file);
1560 if (ret < 0) {
1561 return ret;
1564 if (ret & BDRV_BLOCK_ZERO) {
1565 s->status = BLK_ZERO;
1566 } else if (ret & BDRV_BLOCK_DATA) {
1567 s->status = BLK_DATA;
1568 } else if (!s->target_has_backing) {
1569 /* Without a target backing file we must copy over the contents of
1570 * the backing file as well. */
1571 /* Check block status of the backing file chain to avoid
1572 * needlessly reading zeroes and limiting the iteration to the
1573 * buffer size */
1574 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1575 sector_num - src_cur_offset,
1576 n, &n, &file);
1577 if (ret < 0) {
1578 return ret;
1581 if (ret & BDRV_BLOCK_ZERO) {
1582 s->status = BLK_ZERO;
1583 } else {
1584 s->status = BLK_DATA;
1586 } else {
1587 s->status = BLK_BACKING_FILE;
1590 s->sector_next_status = sector_num + n;
1593 n = MIN(n, s->sector_next_status - sector_num);
1594 if (s->status == BLK_DATA) {
1595 n = MIN(n, s->buf_sectors);
1598 /* We need to write complete clusters for compressed images, so if an
1599 * unallocated area is shorter than that, we must consider the whole
1600 * cluster allocated. */
1601 if (s->compressed) {
1602 if (n < s->cluster_sectors) {
1603 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1604 s->status = BLK_DATA;
1605 } else {
1606 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1610 return n;
1613 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1614 int nb_sectors, uint8_t *buf)
1616 int n, ret;
1617 QEMUIOVector qiov;
1618 struct iovec iov;
1620 assert(nb_sectors <= s->buf_sectors);
1621 while (nb_sectors > 0) {
1622 BlockBackend *blk;
1623 int src_cur;
1624 int64_t bs_sectors, src_cur_offset;
1626 /* In the case of compression with multiple source files, we can get a
1627 * nb_sectors that spreads into the next part. So we must be able to
1628 * read across multiple BDSes for one convert_read() call. */
1629 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1630 blk = s->src[src_cur];
1631 bs_sectors = s->src_sectors[src_cur];
1633 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1634 iov.iov_base = buf;
1635 iov.iov_len = n << BDRV_SECTOR_BITS;
1636 qemu_iovec_init_external(&qiov, &iov, 1);
1638 ret = blk_co_preadv(
1639 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1640 n << BDRV_SECTOR_BITS, &qiov, 0);
1641 if (ret < 0) {
1642 return ret;
1645 sector_num += n;
1646 nb_sectors -= n;
1647 buf += n * BDRV_SECTOR_SIZE;
1650 return 0;
1654 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1655 int nb_sectors, uint8_t *buf,
1656 enum ImgConvertBlockStatus status)
1658 int ret;
1659 QEMUIOVector qiov;
1660 struct iovec iov;
1662 while (nb_sectors > 0) {
1663 int n = nb_sectors;
1664 switch (status) {
1665 case BLK_BACKING_FILE:
1666 /* If we have a backing file, leave clusters unallocated that are
1667 * unallocated in the source image, so that the backing file is
1668 * visible at the respective offset. */
1669 assert(s->target_has_backing);
1670 break;
1672 case BLK_DATA:
1673 /* We must always write compressed clusters as a whole, so don't
1674 * try to find zeroed parts in the buffer. We can only save the
1675 * write if the buffer is completely zeroed and we're allowed to
1676 * keep the target sparse. */
1677 if (s->compressed) {
1678 if (s->has_zero_init && s->min_sparse &&
1679 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1681 assert(!s->target_has_backing);
1682 break;
1685 iov.iov_base = buf;
1686 iov.iov_len = n << BDRV_SECTOR_BITS;
1687 qemu_iovec_init_external(&qiov, &iov, 1);
1689 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1690 n << BDRV_SECTOR_BITS, &qiov,
1691 BDRV_REQ_WRITE_COMPRESSED);
1692 if (ret < 0) {
1693 return ret;
1695 break;
1698 /* If there is real non-zero data or we're told to keep the target
1699 * fully allocated (-S 0), we must write it. Otherwise we can treat
1700 * it as zero sectors. */
1701 if (!s->min_sparse ||
1702 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1704 iov.iov_base = buf;
1705 iov.iov_len = n << BDRV_SECTOR_BITS;
1706 qemu_iovec_init_external(&qiov, &iov, 1);
1708 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
1709 n << BDRV_SECTOR_BITS, &qiov, 0);
1710 if (ret < 0) {
1711 return ret;
1713 break;
1715 /* fall-through */
1717 case BLK_ZERO:
1718 if (s->has_zero_init) {
1719 break;
1721 ret = blk_co_pwrite_zeroes(s->target,
1722 sector_num << BDRV_SECTOR_BITS,
1723 n << BDRV_SECTOR_BITS, 0);
1724 if (ret < 0) {
1725 return ret;
1727 break;
1730 sector_num += n;
1731 nb_sectors -= n;
1732 buf += n * BDRV_SECTOR_SIZE;
1735 return 0;
1738 static void coroutine_fn convert_co_do_copy(void *opaque)
1740 ImgConvertState *s = opaque;
1741 uint8_t *buf = NULL;
1742 int ret, i;
1743 int index = -1;
1745 for (i = 0; i < s->num_coroutines; i++) {
1746 if (s->co[i] == qemu_coroutine_self()) {
1747 index = i;
1748 break;
1751 assert(index >= 0);
1753 s->running_coroutines++;
1754 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1756 while (1) {
1757 int n;
1758 int64_t sector_num;
1759 enum ImgConvertBlockStatus status;
1761 qemu_co_mutex_lock(&s->lock);
1762 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1763 qemu_co_mutex_unlock(&s->lock);
1764 goto out;
1766 n = convert_iteration_sectors(s, s->sector_num);
1767 if (n < 0) {
1768 qemu_co_mutex_unlock(&s->lock);
1769 s->ret = n;
1770 goto out;
1772 /* save current sector and allocation status to local variables */
1773 sector_num = s->sector_num;
1774 status = s->status;
1775 if (!s->min_sparse && s->status == BLK_ZERO) {
1776 n = MIN(n, s->buf_sectors);
1778 /* increment global sector counter so that other coroutines can
1779 * already continue reading beyond this request */
1780 s->sector_num += n;
1781 qemu_co_mutex_unlock(&s->lock);
1783 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1784 s->allocated_done += n;
1785 qemu_progress_print(100.0 * s->allocated_done /
1786 s->allocated_sectors, 0);
1789 if (status == BLK_DATA) {
1790 ret = convert_co_read(s, sector_num, n, buf);
1791 if (ret < 0) {
1792 error_report("error while reading sector %" PRId64
1793 ": %s", sector_num, strerror(-ret));
1794 s->ret = ret;
1795 goto out;
1797 } else if (!s->min_sparse && status == BLK_ZERO) {
1798 status = BLK_DATA;
1799 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1802 if (s->wr_in_order) {
1803 /* keep writes in order */
1804 while (s->wr_offs != sector_num) {
1805 if (s->ret != -EINPROGRESS) {
1806 goto out;
1808 s->wait_sector_num[index] = sector_num;
1809 qemu_coroutine_yield();
1811 s->wait_sector_num[index] = -1;
1814 ret = convert_co_write(s, sector_num, n, buf, status);
1815 if (ret < 0) {
1816 error_report("error while writing sector %" PRId64
1817 ": %s", sector_num, strerror(-ret));
1818 s->ret = ret;
1819 goto out;
1822 if (s->wr_in_order) {
1823 /* reenter the coroutine that might have waited
1824 * for this write to complete */
1825 s->wr_offs = sector_num + n;
1826 for (i = 0; i < s->num_coroutines; i++) {
1827 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1829 * A -> B -> A cannot occur because A has
1830 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1831 * B will never enter A during this time window.
1833 qemu_coroutine_enter(s->co[i]);
1834 break;
1840 out:
1841 qemu_vfree(buf);
1842 s->co[index] = NULL;
1843 s->running_coroutines--;
1844 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1845 /* the convert job finished successfully */
1846 s->ret = 0;
1850 static int convert_do_copy(ImgConvertState *s)
1852 int ret, i, n;
1853 int64_t sector_num = 0;
1855 /* Check whether we have zero initialisation or can get it efficiently */
1856 s->has_zero_init = s->min_sparse && !s->target_has_backing
1857 ? bdrv_has_zero_init(blk_bs(s->target))
1858 : false;
1860 if (!s->has_zero_init && !s->target_has_backing &&
1861 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1863 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
1864 if (ret == 0) {
1865 s->has_zero_init = true;
1869 /* Allocate buffer for copied data. For compressed images, only one cluster
1870 * can be copied at a time. */
1871 if (s->compressed) {
1872 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1873 error_report("invalid cluster size");
1874 return -EINVAL;
1876 s->buf_sectors = s->cluster_sectors;
1879 while (sector_num < s->total_sectors) {
1880 n = convert_iteration_sectors(s, sector_num);
1881 if (n < 0) {
1882 return n;
1884 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1886 s->allocated_sectors += n;
1888 sector_num += n;
1891 /* Do the copy */
1892 s->sector_next_status = 0;
1893 s->ret = -EINPROGRESS;
1895 qemu_co_mutex_init(&s->lock);
1896 for (i = 0; i < s->num_coroutines; i++) {
1897 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1898 s->wait_sector_num[i] = -1;
1899 qemu_coroutine_enter(s->co[i]);
1902 while (s->ret == -EINPROGRESS) {
1903 main_loop_wait(false);
1906 if (s->compressed && !s->ret) {
1907 /* signal EOF to align */
1908 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
1909 if (ret < 0) {
1910 return ret;
1914 return s->ret;
1917 static int img_convert(int argc, char **argv)
1919 int c, bs_i, flags, src_flags = 0;
1920 const char *fmt = NULL, *out_fmt = "raw", *cache = "unsafe",
1921 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1922 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
1923 BlockDriver *drv, *proto_drv;
1924 BlockDriverInfo bdi;
1925 BlockDriverState *out_bs;
1926 QemuOpts *opts = NULL, *sn_opts = NULL;
1927 QemuOptsList *create_opts = NULL;
1928 char *options = NULL;
1929 Error *local_err = NULL;
1930 bool writethrough, src_writethrough, quiet = false, image_opts = false,
1931 skip_create = false, progress = false;
1932 int64_t ret = -EINVAL;
1934 ImgConvertState s = (ImgConvertState) {
1935 /* Need at least 4k of zeros for sparse detection */
1936 .min_sparse = 8,
1937 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1938 .wr_in_order = true,
1939 .num_coroutines = 8,
1942 for(;;) {
1943 static const struct option long_options[] = {
1944 {"help", no_argument, 0, 'h'},
1945 {"object", required_argument, 0, OPTION_OBJECT},
1946 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1947 {0, 0, 0, 0}
1949 c = getopt_long(argc, argv, ":hf:O:B:ce6o:s:l:S:pt:T:qnm:W",
1950 long_options, NULL);
1951 if (c == -1) {
1952 break;
1954 switch(c) {
1955 case ':':
1956 missing_argument(argv[optind - 1]);
1957 break;
1958 case '?':
1959 unrecognized_option(argv[optind - 1]);
1960 break;
1961 case 'h':
1962 help();
1963 break;
1964 case 'f':
1965 fmt = optarg;
1966 break;
1967 case 'O':
1968 out_fmt = optarg;
1969 break;
1970 case 'B':
1971 out_baseimg = optarg;
1972 break;
1973 case 'c':
1974 s.compressed = true;
1975 break;
1976 case 'e':
1977 error_report("option -e is deprecated, please use \'-o "
1978 "encryption\' instead!");
1979 goto fail_getopt;
1980 case '6':
1981 error_report("option -6 is deprecated, please use \'-o "
1982 "compat6\' instead!");
1983 goto fail_getopt;
1984 case 'o':
1985 if (!is_valid_option_list(optarg)) {
1986 error_report("Invalid option list: %s", optarg);
1987 goto fail_getopt;
1989 if (!options) {
1990 options = g_strdup(optarg);
1991 } else {
1992 char *old_options = options;
1993 options = g_strdup_printf("%s,%s", options, optarg);
1994 g_free(old_options);
1996 break;
1997 case 's':
1998 snapshot_name = optarg;
1999 break;
2000 case 'l':
2001 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2002 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2003 optarg, false);
2004 if (!sn_opts) {
2005 error_report("Failed in parsing snapshot param '%s'",
2006 optarg);
2007 goto fail_getopt;
2009 } else {
2010 snapshot_name = optarg;
2012 break;
2013 case 'S':
2015 int64_t sval;
2017 sval = cvtnum(optarg);
2018 if (sval < 0) {
2019 error_report("Invalid minimum zero buffer size for sparse output specified");
2020 goto fail_getopt;
2023 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2024 break;
2026 case 'p':
2027 progress = true;
2028 break;
2029 case 't':
2030 cache = optarg;
2031 break;
2032 case 'T':
2033 src_cache = optarg;
2034 break;
2035 case 'q':
2036 quiet = true;
2037 break;
2038 case 'n':
2039 skip_create = true;
2040 break;
2041 case 'm':
2042 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2043 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2044 error_report("Invalid number of coroutines. Allowed number of"
2045 " coroutines is between 1 and %d", MAX_COROUTINES);
2046 goto fail_getopt;
2048 break;
2049 case 'W':
2050 s.wr_in_order = false;
2051 break;
2052 case OPTION_OBJECT:
2053 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2054 optarg, true);
2055 if (!opts) {
2056 goto fail_getopt;
2058 break;
2059 case OPTION_IMAGE_OPTS:
2060 image_opts = true;
2061 break;
2065 if (qemu_opts_foreach(&qemu_object_opts,
2066 user_creatable_add_opts_foreach,
2067 NULL, NULL)) {
2068 goto fail_getopt;
2071 if (!s.wr_in_order && s.compressed) {
2072 error_report("Out of order write and compress are mutually exclusive");
2073 goto fail_getopt;
2076 s.src_num = argc - optind - 1;
2077 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2079 if (options && has_help_option(options)) {
2080 ret = print_block_option_help(out_filename, out_fmt);
2081 goto fail_getopt;
2084 if (s.src_num < 1) {
2085 error_report("Must specify image file name");
2086 goto fail_getopt;
2090 if (s.src_num > 1 && out_baseimg) {
2091 error_report("-B makes no sense when concatenating multiple input "
2092 "images");
2093 goto fail_getopt;
2096 /* ret is still -EINVAL until here */
2097 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2098 if (ret < 0) {
2099 error_report("Invalid source cache option: %s", src_cache);
2100 goto fail_getopt;
2103 /* Initialize before goto out */
2104 if (quiet) {
2105 progress = false;
2107 qemu_progress_init(progress, 1.0);
2108 qemu_progress_print(0, 100);
2110 s.src = g_new0(BlockBackend *, s.src_num);
2111 s.src_sectors = g_new(int64_t, s.src_num);
2113 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2114 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2115 fmt, src_flags, src_writethrough, quiet);
2116 if (!s.src[bs_i]) {
2117 ret = -1;
2118 goto out;
2120 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2121 if (s.src_sectors[bs_i] < 0) {
2122 error_report("Could not get size of %s: %s",
2123 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2124 ret = -1;
2125 goto out;
2127 s.total_sectors += s.src_sectors[bs_i];
2130 if (sn_opts) {
2131 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2132 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2133 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2134 &local_err);
2135 } else if (snapshot_name != NULL) {
2136 if (s.src_num > 1) {
2137 error_report("No support for concatenating multiple snapshot");
2138 ret = -1;
2139 goto out;
2142 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2143 &local_err);
2145 if (local_err) {
2146 error_reportf_err(local_err, "Failed to load snapshot: ");
2147 ret = -1;
2148 goto out;
2151 /* Find driver and parse its options */
2152 drv = bdrv_find_format(out_fmt);
2153 if (!drv) {
2154 error_report("Unknown file format '%s'", out_fmt);
2155 ret = -1;
2156 goto out;
2159 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2160 if (!proto_drv) {
2161 error_report_err(local_err);
2162 ret = -1;
2163 goto out;
2166 if (!skip_create) {
2167 if (!drv->create_opts) {
2168 error_report("Format driver '%s' does not support image creation",
2169 drv->format_name);
2170 ret = -1;
2171 goto out;
2174 if (!proto_drv->create_opts) {
2175 error_report("Protocol driver '%s' does not support image creation",
2176 proto_drv->format_name);
2177 ret = -1;
2178 goto out;
2181 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2182 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2184 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2185 if (options) {
2186 qemu_opts_do_parse(opts, options, NULL, &local_err);
2187 if (local_err) {
2188 error_report_err(local_err);
2189 ret = -1;
2190 goto out;
2194 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
2195 &error_abort);
2196 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2197 if (ret < 0) {
2198 goto out;
2202 /* Get backing file name if -o backing_file was used */
2203 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2204 if (out_baseimg_param) {
2205 out_baseimg = out_baseimg_param;
2207 s.target_has_backing = (bool) out_baseimg;
2209 /* Check if compression is supported */
2210 if (s.compressed) {
2211 bool encryption =
2212 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2213 const char *preallocation =
2214 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2216 if (!drv->bdrv_co_pwritev_compressed) {
2217 error_report("Compression not supported for this file format");
2218 ret = -1;
2219 goto out;
2222 if (encryption) {
2223 error_report("Compression and encryption not supported at "
2224 "the same time");
2225 ret = -1;
2226 goto out;
2229 if (preallocation
2230 && strcmp(preallocation, "off"))
2232 error_report("Compression and preallocation not supported at "
2233 "the same time");
2234 ret = -1;
2235 goto out;
2239 if (!skip_create) {
2240 /* Create the new image */
2241 ret = bdrv_create(drv, out_filename, opts, &local_err);
2242 if (ret < 0) {
2243 error_reportf_err(local_err, "%s: error while converting %s: ",
2244 out_filename, out_fmt);
2245 goto out;
2249 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2250 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2251 if (ret < 0) {
2252 error_report("Invalid cache option: %s", cache);
2253 goto out;
2256 /* XXX we should allow --image-opts to trigger use of
2257 * img_open() here, but then we have trouble with
2258 * the bdrv_create() call which takes different params.
2259 * Not critical right now, so fix can wait...
2261 s.target = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
2262 if (!s.target) {
2263 ret = -1;
2264 goto out;
2266 out_bs = blk_bs(s.target);
2268 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2269 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2270 * as maximum. */
2271 s.buf_sectors = MIN(32768,
2272 MAX(s.buf_sectors,
2273 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2274 out_bs->bl.pdiscard_alignment >>
2275 BDRV_SECTOR_BITS)));
2277 if (skip_create) {
2278 int64_t output_sectors = blk_nb_sectors(s.target);
2279 if (output_sectors < 0) {
2280 error_report("unable to get output image length: %s",
2281 strerror(-output_sectors));
2282 ret = -1;
2283 goto out;
2284 } else if (output_sectors < s.total_sectors) {
2285 error_report("output file is smaller than input file");
2286 ret = -1;
2287 goto out;
2291 ret = bdrv_get_info(out_bs, &bdi);
2292 if (ret < 0) {
2293 if (s.compressed) {
2294 error_report("could not get block driver info");
2295 goto out;
2297 } else {
2298 s.compressed = s.compressed || bdi.needs_compressed_writes;
2299 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2302 ret = convert_do_copy(&s);
2303 out:
2304 if (!ret) {
2305 qemu_progress_print(100, 0);
2307 qemu_progress_end();
2308 qemu_opts_del(opts);
2309 qemu_opts_free(create_opts);
2310 qemu_opts_del(sn_opts);
2311 blk_unref(s.target);
2312 if (s.src) {
2313 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2314 blk_unref(s.src[bs_i]);
2316 g_free(s.src);
2318 g_free(s.src_sectors);
2319 fail_getopt:
2320 g_free(options);
2322 return !!ret;
2326 static void dump_snapshots(BlockDriverState *bs)
2328 QEMUSnapshotInfo *sn_tab, *sn;
2329 int nb_sns, i;
2331 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2332 if (nb_sns <= 0)
2333 return;
2334 printf("Snapshot list:\n");
2335 bdrv_snapshot_dump(fprintf, stdout, NULL);
2336 printf("\n");
2337 for(i = 0; i < nb_sns; i++) {
2338 sn = &sn_tab[i];
2339 bdrv_snapshot_dump(fprintf, stdout, sn);
2340 printf("\n");
2342 g_free(sn_tab);
2345 static void dump_json_image_info_list(ImageInfoList *list)
2347 QString *str;
2348 QObject *obj;
2349 Visitor *v = qobject_output_visitor_new(&obj);
2351 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2352 visit_complete(v, &obj);
2353 str = qobject_to_json_pretty(obj);
2354 assert(str != NULL);
2355 printf("%s\n", qstring_get_str(str));
2356 qobject_decref(obj);
2357 visit_free(v);
2358 QDECREF(str);
2361 static void dump_json_image_info(ImageInfo *info)
2363 QString *str;
2364 QObject *obj;
2365 Visitor *v = qobject_output_visitor_new(&obj);
2367 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2368 visit_complete(v, &obj);
2369 str = qobject_to_json_pretty(obj);
2370 assert(str != NULL);
2371 printf("%s\n", qstring_get_str(str));
2372 qobject_decref(obj);
2373 visit_free(v);
2374 QDECREF(str);
2377 static void dump_human_image_info_list(ImageInfoList *list)
2379 ImageInfoList *elem;
2380 bool delim = false;
2382 for (elem = list; elem; elem = elem->next) {
2383 if (delim) {
2384 printf("\n");
2386 delim = true;
2388 bdrv_image_info_dump(fprintf, stdout, elem->value);
2392 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2394 return strcmp(a, b) == 0;
2398 * Open an image file chain and return an ImageInfoList
2400 * @filename: topmost image filename
2401 * @fmt: topmost image format (may be NULL to autodetect)
2402 * @chain: true - enumerate entire backing file chain
2403 * false - only topmost image file
2405 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2406 * image file. If there was an error a message will have been printed to
2407 * stderr.
2409 static ImageInfoList *collect_image_info_list(bool image_opts,
2410 const char *filename,
2411 const char *fmt,
2412 bool chain)
2414 ImageInfoList *head = NULL;
2415 ImageInfoList **last = &head;
2416 GHashTable *filenames;
2417 Error *err = NULL;
2419 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2421 while (filename) {
2422 BlockBackend *blk;
2423 BlockDriverState *bs;
2424 ImageInfo *info;
2425 ImageInfoList *elem;
2427 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2428 error_report("Backing file '%s' creates an infinite loop.",
2429 filename);
2430 goto err;
2432 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2434 blk = img_open(image_opts, filename, fmt,
2435 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
2436 if (!blk) {
2437 goto err;
2439 bs = blk_bs(blk);
2441 bdrv_query_image_info(bs, &info, &err);
2442 if (err) {
2443 error_report_err(err);
2444 blk_unref(blk);
2445 goto err;
2448 elem = g_new0(ImageInfoList, 1);
2449 elem->value = info;
2450 *last = elem;
2451 last = &elem->next;
2453 blk_unref(blk);
2455 filename = fmt = NULL;
2456 if (chain) {
2457 if (info->has_full_backing_filename) {
2458 filename = info->full_backing_filename;
2459 } else if (info->has_backing_filename) {
2460 error_report("Could not determine absolute backing filename,"
2461 " but backing filename '%s' present",
2462 info->backing_filename);
2463 goto err;
2465 if (info->has_backing_filename_format) {
2466 fmt = info->backing_filename_format;
2470 g_hash_table_destroy(filenames);
2471 return head;
2473 err:
2474 qapi_free_ImageInfoList(head);
2475 g_hash_table_destroy(filenames);
2476 return NULL;
2479 static int img_info(int argc, char **argv)
2481 int c;
2482 OutputFormat output_format = OFORMAT_HUMAN;
2483 bool chain = false;
2484 const char *filename, *fmt, *output;
2485 ImageInfoList *list;
2486 bool image_opts = false;
2488 fmt = NULL;
2489 output = NULL;
2490 for(;;) {
2491 int option_index = 0;
2492 static const struct option long_options[] = {
2493 {"help", no_argument, 0, 'h'},
2494 {"format", required_argument, 0, 'f'},
2495 {"output", required_argument, 0, OPTION_OUTPUT},
2496 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2497 {"object", required_argument, 0, OPTION_OBJECT},
2498 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2499 {0, 0, 0, 0}
2501 c = getopt_long(argc, argv, ":f:h",
2502 long_options, &option_index);
2503 if (c == -1) {
2504 break;
2506 switch(c) {
2507 case ':':
2508 missing_argument(argv[optind - 1]);
2509 break;
2510 case '?':
2511 unrecognized_option(argv[optind - 1]);
2512 break;
2513 case 'h':
2514 help();
2515 break;
2516 case 'f':
2517 fmt = optarg;
2518 break;
2519 case OPTION_OUTPUT:
2520 output = optarg;
2521 break;
2522 case OPTION_BACKING_CHAIN:
2523 chain = true;
2524 break;
2525 case OPTION_OBJECT: {
2526 QemuOpts *opts;
2527 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2528 optarg, true);
2529 if (!opts) {
2530 return 1;
2532 } break;
2533 case OPTION_IMAGE_OPTS:
2534 image_opts = true;
2535 break;
2538 if (optind != argc - 1) {
2539 error_exit("Expecting one image file name");
2541 filename = argv[optind++];
2543 if (output && !strcmp(output, "json")) {
2544 output_format = OFORMAT_JSON;
2545 } else if (output && !strcmp(output, "human")) {
2546 output_format = OFORMAT_HUMAN;
2547 } else if (output) {
2548 error_report("--output must be used with human or json as argument.");
2549 return 1;
2552 if (qemu_opts_foreach(&qemu_object_opts,
2553 user_creatable_add_opts_foreach,
2554 NULL, NULL)) {
2555 return 1;
2558 list = collect_image_info_list(image_opts, filename, fmt, chain);
2559 if (!list) {
2560 return 1;
2563 switch (output_format) {
2564 case OFORMAT_HUMAN:
2565 dump_human_image_info_list(list);
2566 break;
2567 case OFORMAT_JSON:
2568 if (chain) {
2569 dump_json_image_info_list(list);
2570 } else {
2571 dump_json_image_info(list->value);
2573 break;
2576 qapi_free_ImageInfoList(list);
2577 return 0;
2580 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2581 MapEntry *next)
2583 switch (output_format) {
2584 case OFORMAT_HUMAN:
2585 if (e->data && !e->has_offset) {
2586 error_report("File contains external, encrypted or compressed clusters.");
2587 exit(1);
2589 if (e->data && !e->zero) {
2590 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2591 e->start, e->length,
2592 e->has_offset ? e->offset : 0,
2593 e->has_filename ? e->filename : "");
2595 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2596 * Modify the flags here to allow more coalescing.
2598 if (next && (!next->data || next->zero)) {
2599 next->data = false;
2600 next->zero = true;
2602 break;
2603 case OFORMAT_JSON:
2604 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2605 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2606 (e->start == 0 ? "[" : ",\n"),
2607 e->start, e->length, e->depth,
2608 e->zero ? "true" : "false",
2609 e->data ? "true" : "false");
2610 if (e->has_offset) {
2611 printf(", \"offset\": %"PRId64"", e->offset);
2613 putchar('}');
2615 if (!next) {
2616 printf("]\n");
2618 break;
2622 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2623 int nb_sectors, MapEntry *e)
2625 int64_t ret;
2626 int depth;
2627 BlockDriverState *file;
2628 bool has_offset;
2630 /* As an optimization, we could cache the current range of unallocated
2631 * clusters in each file of the chain, and avoid querying the same
2632 * range repeatedly.
2635 depth = 0;
2636 for (;;) {
2637 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2638 &file);
2639 if (ret < 0) {
2640 return ret;
2642 assert(nb_sectors);
2643 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2644 break;
2646 bs = backing_bs(bs);
2647 if (bs == NULL) {
2648 ret = 0;
2649 break;
2652 depth++;
2655 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2657 *e = (MapEntry) {
2658 .start = sector_num * BDRV_SECTOR_SIZE,
2659 .length = nb_sectors * BDRV_SECTOR_SIZE,
2660 .data = !!(ret & BDRV_BLOCK_DATA),
2661 .zero = !!(ret & BDRV_BLOCK_ZERO),
2662 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2663 .has_offset = has_offset,
2664 .depth = depth,
2665 .has_filename = file && has_offset,
2666 .filename = file && has_offset ? file->filename : NULL,
2669 return 0;
2672 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2674 if (curr->length == 0) {
2675 return false;
2677 if (curr->zero != next->zero ||
2678 curr->data != next->data ||
2679 curr->depth != next->depth ||
2680 curr->has_filename != next->has_filename ||
2681 curr->has_offset != next->has_offset) {
2682 return false;
2684 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2685 return false;
2687 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2688 return false;
2690 return true;
2693 static int img_map(int argc, char **argv)
2695 int c;
2696 OutputFormat output_format = OFORMAT_HUMAN;
2697 BlockBackend *blk;
2698 BlockDriverState *bs;
2699 const char *filename, *fmt, *output;
2700 int64_t length;
2701 MapEntry curr = { .length = 0 }, next;
2702 int ret = 0;
2703 bool image_opts = false;
2705 fmt = NULL;
2706 output = NULL;
2707 for (;;) {
2708 int option_index = 0;
2709 static const struct option long_options[] = {
2710 {"help", no_argument, 0, 'h'},
2711 {"format", required_argument, 0, 'f'},
2712 {"output", required_argument, 0, OPTION_OUTPUT},
2713 {"object", required_argument, 0, OPTION_OBJECT},
2714 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2715 {0, 0, 0, 0}
2717 c = getopt_long(argc, argv, ":f:h",
2718 long_options, &option_index);
2719 if (c == -1) {
2720 break;
2722 switch (c) {
2723 case ':':
2724 missing_argument(argv[optind - 1]);
2725 break;
2726 case '?':
2727 unrecognized_option(argv[optind - 1]);
2728 break;
2729 case 'h':
2730 help();
2731 break;
2732 case 'f':
2733 fmt = optarg;
2734 break;
2735 case OPTION_OUTPUT:
2736 output = optarg;
2737 break;
2738 case OPTION_OBJECT: {
2739 QemuOpts *opts;
2740 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2741 optarg, true);
2742 if (!opts) {
2743 return 1;
2745 } break;
2746 case OPTION_IMAGE_OPTS:
2747 image_opts = true;
2748 break;
2751 if (optind != argc - 1) {
2752 error_exit("Expecting one image file name");
2754 filename = argv[optind];
2756 if (output && !strcmp(output, "json")) {
2757 output_format = OFORMAT_JSON;
2758 } else if (output && !strcmp(output, "human")) {
2759 output_format = OFORMAT_HUMAN;
2760 } else if (output) {
2761 error_report("--output must be used with human or json as argument.");
2762 return 1;
2765 if (qemu_opts_foreach(&qemu_object_opts,
2766 user_creatable_add_opts_foreach,
2767 NULL, NULL)) {
2768 return 1;
2771 blk = img_open(image_opts, filename, fmt, 0, false, false);
2772 if (!blk) {
2773 return 1;
2775 bs = blk_bs(blk);
2777 if (output_format == OFORMAT_HUMAN) {
2778 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2781 length = blk_getlength(blk);
2782 while (curr.start + curr.length < length) {
2783 int64_t nsectors_left;
2784 int64_t sector_num;
2785 int n;
2787 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2789 /* Probe up to 1 GiB at a time. */
2790 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2791 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2792 ret = get_block_status(bs, sector_num, n, &next);
2794 if (ret < 0) {
2795 error_report("Could not read file metadata: %s", strerror(-ret));
2796 goto out;
2799 if (entry_mergeable(&curr, &next)) {
2800 curr.length += next.length;
2801 continue;
2804 if (curr.length > 0) {
2805 dump_map_entry(output_format, &curr, &next);
2807 curr = next;
2810 dump_map_entry(output_format, &curr, NULL);
2812 out:
2813 blk_unref(blk);
2814 return ret < 0;
2817 #define SNAPSHOT_LIST 1
2818 #define SNAPSHOT_CREATE 2
2819 #define SNAPSHOT_APPLY 3
2820 #define SNAPSHOT_DELETE 4
2822 static int img_snapshot(int argc, char **argv)
2824 BlockBackend *blk;
2825 BlockDriverState *bs;
2826 QEMUSnapshotInfo sn;
2827 char *filename, *snapshot_name = NULL;
2828 int c, ret = 0, bdrv_oflags;
2829 int action = 0;
2830 qemu_timeval tv;
2831 bool quiet = false;
2832 Error *err = NULL;
2833 bool image_opts = false;
2835 bdrv_oflags = BDRV_O_RDWR;
2836 /* Parse commandline parameters */
2837 for(;;) {
2838 static const struct option long_options[] = {
2839 {"help", no_argument, 0, 'h'},
2840 {"object", required_argument, 0, OPTION_OBJECT},
2841 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2842 {0, 0, 0, 0}
2844 c = getopt_long(argc, argv, ":la:c:d:hq",
2845 long_options, NULL);
2846 if (c == -1) {
2847 break;
2849 switch(c) {
2850 case ':':
2851 missing_argument(argv[optind - 1]);
2852 break;
2853 case '?':
2854 unrecognized_option(argv[optind - 1]);
2855 break;
2856 case 'h':
2857 help();
2858 return 0;
2859 case 'l':
2860 if (action) {
2861 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2862 return 0;
2864 action = SNAPSHOT_LIST;
2865 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2866 break;
2867 case 'a':
2868 if (action) {
2869 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2870 return 0;
2872 action = SNAPSHOT_APPLY;
2873 snapshot_name = optarg;
2874 break;
2875 case 'c':
2876 if (action) {
2877 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2878 return 0;
2880 action = SNAPSHOT_CREATE;
2881 snapshot_name = optarg;
2882 break;
2883 case 'd':
2884 if (action) {
2885 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2886 return 0;
2888 action = SNAPSHOT_DELETE;
2889 snapshot_name = optarg;
2890 break;
2891 case 'q':
2892 quiet = true;
2893 break;
2894 case OPTION_OBJECT: {
2895 QemuOpts *opts;
2896 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2897 optarg, true);
2898 if (!opts) {
2899 return 1;
2901 } break;
2902 case OPTION_IMAGE_OPTS:
2903 image_opts = true;
2904 break;
2908 if (optind != argc - 1) {
2909 error_exit("Expecting one image file name");
2911 filename = argv[optind++];
2913 if (qemu_opts_foreach(&qemu_object_opts,
2914 user_creatable_add_opts_foreach,
2915 NULL, NULL)) {
2916 return 1;
2919 /* Open the image */
2920 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
2921 if (!blk) {
2922 return 1;
2924 bs = blk_bs(blk);
2926 /* Perform the requested action */
2927 switch(action) {
2928 case SNAPSHOT_LIST:
2929 dump_snapshots(bs);
2930 break;
2932 case SNAPSHOT_CREATE:
2933 memset(&sn, 0, sizeof(sn));
2934 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2936 qemu_gettimeofday(&tv);
2937 sn.date_sec = tv.tv_sec;
2938 sn.date_nsec = tv.tv_usec * 1000;
2940 ret = bdrv_snapshot_create(bs, &sn);
2941 if (ret) {
2942 error_report("Could not create snapshot '%s': %d (%s)",
2943 snapshot_name, ret, strerror(-ret));
2945 break;
2947 case SNAPSHOT_APPLY:
2948 ret = bdrv_snapshot_goto(bs, snapshot_name);
2949 if (ret) {
2950 error_report("Could not apply snapshot '%s': %d (%s)",
2951 snapshot_name, ret, strerror(-ret));
2953 break;
2955 case SNAPSHOT_DELETE:
2956 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2957 if (err) {
2958 error_reportf_err(err, "Could not delete snapshot '%s': ",
2959 snapshot_name);
2960 ret = 1;
2962 break;
2965 /* Cleanup */
2966 blk_unref(blk);
2967 if (ret) {
2968 return 1;
2970 return 0;
2973 static int img_rebase(int argc, char **argv)
2975 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2976 uint8_t *buf_old = NULL;
2977 uint8_t *buf_new = NULL;
2978 BlockDriverState *bs = NULL;
2979 char *filename;
2980 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2981 int c, flags, src_flags, ret;
2982 bool writethrough, src_writethrough;
2983 int unsafe = 0;
2984 int progress = 0;
2985 bool quiet = false;
2986 Error *local_err = NULL;
2987 bool image_opts = false;
2989 /* Parse commandline parameters */
2990 fmt = NULL;
2991 cache = BDRV_DEFAULT_CACHE;
2992 src_cache = BDRV_DEFAULT_CACHE;
2993 out_baseimg = NULL;
2994 out_basefmt = NULL;
2995 for(;;) {
2996 static const struct option long_options[] = {
2997 {"help", no_argument, 0, 'h'},
2998 {"object", required_argument, 0, OPTION_OBJECT},
2999 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3000 {0, 0, 0, 0}
3002 c = getopt_long(argc, argv, ":hf:F:b:upt:T:q",
3003 long_options, NULL);
3004 if (c == -1) {
3005 break;
3007 switch(c) {
3008 case ':':
3009 missing_argument(argv[optind - 1]);
3010 break;
3011 case '?':
3012 unrecognized_option(argv[optind - 1]);
3013 break;
3014 case 'h':
3015 help();
3016 return 0;
3017 case 'f':
3018 fmt = optarg;
3019 break;
3020 case 'F':
3021 out_basefmt = optarg;
3022 break;
3023 case 'b':
3024 out_baseimg = optarg;
3025 break;
3026 case 'u':
3027 unsafe = 1;
3028 break;
3029 case 'p':
3030 progress = 1;
3031 break;
3032 case 't':
3033 cache = optarg;
3034 break;
3035 case 'T':
3036 src_cache = optarg;
3037 break;
3038 case 'q':
3039 quiet = true;
3040 break;
3041 case OPTION_OBJECT: {
3042 QemuOpts *opts;
3043 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3044 optarg, true);
3045 if (!opts) {
3046 return 1;
3048 } break;
3049 case OPTION_IMAGE_OPTS:
3050 image_opts = true;
3051 break;
3055 if (quiet) {
3056 progress = 0;
3059 if (optind != argc - 1) {
3060 error_exit("Expecting one image file name");
3062 if (!unsafe && !out_baseimg) {
3063 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3065 filename = argv[optind++];
3067 if (qemu_opts_foreach(&qemu_object_opts,
3068 user_creatable_add_opts_foreach,
3069 NULL, NULL)) {
3070 return 1;
3073 qemu_progress_init(progress, 2.0);
3074 qemu_progress_print(0, 100);
3076 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3077 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3078 if (ret < 0) {
3079 error_report("Invalid cache option: %s", cache);
3080 goto out;
3083 src_flags = 0;
3084 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3085 if (ret < 0) {
3086 error_report("Invalid source cache option: %s", src_cache);
3087 goto out;
3090 /* The source files are opened read-only, don't care about WCE */
3091 assert((src_flags & BDRV_O_RDWR) == 0);
3092 (void) src_writethrough;
3095 * Open the images.
3097 * Ignore the old backing file for unsafe rebase in case we want to correct
3098 * the reference to a renamed or moved backing file.
3100 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3101 if (!blk) {
3102 ret = -1;
3103 goto out;
3105 bs = blk_bs(blk);
3107 if (out_basefmt != NULL) {
3108 if (bdrv_find_format(out_basefmt) == NULL) {
3109 error_report("Invalid format name: '%s'", out_basefmt);
3110 ret = -1;
3111 goto out;
3115 /* For safe rebasing we need to compare old and new backing file */
3116 if (!unsafe) {
3117 char backing_name[PATH_MAX];
3118 QDict *options = NULL;
3120 if (bs->backing_format[0] != '\0') {
3121 options = qdict_new();
3122 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
3125 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3126 blk_old_backing = blk_new_open(backing_name, NULL,
3127 options, src_flags, &local_err);
3128 if (!blk_old_backing) {
3129 error_reportf_err(local_err,
3130 "Could not open old backing file '%s': ",
3131 backing_name);
3132 ret = -1;
3133 goto out;
3136 if (out_baseimg[0]) {
3137 if (out_basefmt) {
3138 options = qdict_new();
3139 qdict_put(options, "driver", qstring_from_str(out_basefmt));
3140 } else {
3141 options = NULL;
3144 blk_new_backing = blk_new_open(out_baseimg, NULL,
3145 options, src_flags, &local_err);
3146 if (!blk_new_backing) {
3147 error_reportf_err(local_err,
3148 "Could not open new backing file '%s': ",
3149 out_baseimg);
3150 ret = -1;
3151 goto out;
3157 * Check each unallocated cluster in the COW file. If it is unallocated,
3158 * accesses go to the backing file. We must therefore compare this cluster
3159 * in the old and new backing file, and if they differ we need to copy it
3160 * from the old backing file into the COW file.
3162 * If qemu-img crashes during this step, no harm is done. The content of
3163 * the image is the same as the original one at any time.
3165 if (!unsafe) {
3166 int64_t num_sectors;
3167 int64_t old_backing_num_sectors;
3168 int64_t new_backing_num_sectors = 0;
3169 uint64_t sector;
3170 int n;
3171 float local_progress = 0;
3173 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3174 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3176 num_sectors = blk_nb_sectors(blk);
3177 if (num_sectors < 0) {
3178 error_report("Could not get size of '%s': %s",
3179 filename, strerror(-num_sectors));
3180 ret = -1;
3181 goto out;
3183 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
3184 if (old_backing_num_sectors < 0) {
3185 char backing_name[PATH_MAX];
3187 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3188 error_report("Could not get size of '%s': %s",
3189 backing_name, strerror(-old_backing_num_sectors));
3190 ret = -1;
3191 goto out;
3193 if (blk_new_backing) {
3194 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3195 if (new_backing_num_sectors < 0) {
3196 error_report("Could not get size of '%s': %s",
3197 out_baseimg, strerror(-new_backing_num_sectors));
3198 ret = -1;
3199 goto out;
3203 if (num_sectors != 0) {
3204 local_progress = (float)100 /
3205 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3208 for (sector = 0; sector < num_sectors; sector += n) {
3210 /* How many sectors can we handle with the next read? */
3211 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3212 n = (IO_BUF_SIZE / 512);
3213 } else {
3214 n = num_sectors - sector;
3217 /* If the cluster is allocated, we don't need to take action */
3218 ret = bdrv_is_allocated(bs, sector, n, &n);
3219 if (ret < 0) {
3220 error_report("error while reading image metadata: %s",
3221 strerror(-ret));
3222 goto out;
3224 if (ret) {
3225 continue;
3229 * Read old and new backing file and take into consideration that
3230 * backing files may be smaller than the COW image.
3232 if (sector >= old_backing_num_sectors) {
3233 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3234 } else {
3235 if (sector + n > old_backing_num_sectors) {
3236 n = old_backing_num_sectors - sector;
3239 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3240 buf_old, n << BDRV_SECTOR_BITS);
3241 if (ret < 0) {
3242 error_report("error while reading from old backing file");
3243 goto out;
3247 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3248 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3249 } else {
3250 if (sector + n > new_backing_num_sectors) {
3251 n = new_backing_num_sectors - sector;
3254 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3255 buf_new, n << BDRV_SECTOR_BITS);
3256 if (ret < 0) {
3257 error_report("error while reading from new backing file");
3258 goto out;
3262 /* If they differ, we need to write to the COW file */
3263 uint64_t written = 0;
3265 while (written < n) {
3266 int pnum;
3268 if (compare_sectors(buf_old + written * 512,
3269 buf_new + written * 512, n - written, &pnum))
3271 ret = blk_pwrite(blk,
3272 (sector + written) << BDRV_SECTOR_BITS,
3273 buf_old + written * 512,
3274 pnum << BDRV_SECTOR_BITS, 0);
3275 if (ret < 0) {
3276 error_report("Error while writing to COW image: %s",
3277 strerror(-ret));
3278 goto out;
3282 written += pnum;
3284 qemu_progress_print(local_progress, 100);
3289 * Change the backing file. All clusters that are different from the old
3290 * backing file are overwritten in the COW file now, so the visible content
3291 * doesn't change when we switch the backing file.
3293 if (out_baseimg && *out_baseimg) {
3294 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3295 } else {
3296 ret = bdrv_change_backing_file(bs, NULL, NULL);
3299 if (ret == -ENOSPC) {
3300 error_report("Could not change the backing file to '%s': No "
3301 "space left in the file header", out_baseimg);
3302 } else if (ret < 0) {
3303 error_report("Could not change the backing file to '%s': %s",
3304 out_baseimg, strerror(-ret));
3307 qemu_progress_print(100, 0);
3309 * TODO At this point it is possible to check if any clusters that are
3310 * allocated in the COW file are the same in the backing file. If so, they
3311 * could be dropped from the COW file. Don't do this before switching the
3312 * backing file, in case of a crash this would lead to corruption.
3314 out:
3315 qemu_progress_end();
3316 /* Cleanup */
3317 if (!unsafe) {
3318 blk_unref(blk_old_backing);
3319 blk_unref(blk_new_backing);
3321 qemu_vfree(buf_old);
3322 qemu_vfree(buf_new);
3324 blk_unref(blk);
3325 if (ret) {
3326 return 1;
3328 return 0;
3331 static int img_resize(int argc, char **argv)
3333 Error *err = NULL;
3334 int c, ret, relative;
3335 const char *filename, *fmt, *size;
3336 int64_t n, total_size;
3337 bool quiet = false;
3338 BlockBackend *blk = NULL;
3339 QemuOpts *param;
3341 static QemuOptsList resize_options = {
3342 .name = "resize_options",
3343 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3344 .desc = {
3346 .name = BLOCK_OPT_SIZE,
3347 .type = QEMU_OPT_SIZE,
3348 .help = "Virtual disk size"
3349 }, {
3350 /* end of list */
3354 bool image_opts = false;
3356 /* Remove size from argv manually so that negative numbers are not treated
3357 * as options by getopt. */
3358 if (argc < 3) {
3359 error_exit("Not enough arguments");
3360 return 1;
3363 size = argv[--argc];
3365 /* Parse getopt arguments */
3366 fmt = NULL;
3367 for(;;) {
3368 static const struct option long_options[] = {
3369 {"help", no_argument, 0, 'h'},
3370 {"object", required_argument, 0, OPTION_OBJECT},
3371 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3372 {0, 0, 0, 0}
3374 c = getopt_long(argc, argv, ":f:hq",
3375 long_options, NULL);
3376 if (c == -1) {
3377 break;
3379 switch(c) {
3380 case ':':
3381 missing_argument(argv[optind - 1]);
3382 break;
3383 case '?':
3384 unrecognized_option(argv[optind - 1]);
3385 break;
3386 case 'h':
3387 help();
3388 break;
3389 case 'f':
3390 fmt = optarg;
3391 break;
3392 case 'q':
3393 quiet = true;
3394 break;
3395 case OPTION_OBJECT: {
3396 QemuOpts *opts;
3397 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3398 optarg, true);
3399 if (!opts) {
3400 return 1;
3402 } break;
3403 case OPTION_IMAGE_OPTS:
3404 image_opts = true;
3405 break;
3408 if (optind != argc - 1) {
3409 error_exit("Expecting one image file name");
3411 filename = argv[optind++];
3413 if (qemu_opts_foreach(&qemu_object_opts,
3414 user_creatable_add_opts_foreach,
3415 NULL, NULL)) {
3416 return 1;
3419 /* Choose grow, shrink, or absolute resize mode */
3420 switch (size[0]) {
3421 case '+':
3422 relative = 1;
3423 size++;
3424 break;
3425 case '-':
3426 relative = -1;
3427 size++;
3428 break;
3429 default:
3430 relative = 0;
3431 break;
3434 /* Parse size */
3435 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3436 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3437 if (err) {
3438 error_report_err(err);
3439 ret = -1;
3440 qemu_opts_del(param);
3441 goto out;
3443 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3444 qemu_opts_del(param);
3446 blk = img_open(image_opts, filename, fmt,
3447 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet);
3448 if (!blk) {
3449 ret = -1;
3450 goto out;
3453 if (relative) {
3454 total_size = blk_getlength(blk) + n * relative;
3455 } else {
3456 total_size = n;
3458 if (total_size <= 0) {
3459 error_report("New image size must be positive");
3460 ret = -1;
3461 goto out;
3464 ret = blk_truncate(blk, total_size);
3465 switch (ret) {
3466 case 0:
3467 qprintf(quiet, "Image resized.\n");
3468 break;
3469 case -ENOTSUP:
3470 error_report("This image does not support resize");
3471 break;
3472 case -EACCES:
3473 error_report("Image is read-only");
3474 break;
3475 default:
3476 error_report("Error resizing image: %s", strerror(-ret));
3477 break;
3479 out:
3480 blk_unref(blk);
3481 if (ret) {
3482 return 1;
3484 return 0;
3487 static void amend_status_cb(BlockDriverState *bs,
3488 int64_t offset, int64_t total_work_size,
3489 void *opaque)
3491 qemu_progress_print(100.f * offset / total_work_size, 0);
3494 static int img_amend(int argc, char **argv)
3496 Error *err = NULL;
3497 int c, ret = 0;
3498 char *options = NULL;
3499 QemuOptsList *create_opts = NULL;
3500 QemuOpts *opts = NULL;
3501 const char *fmt = NULL, *filename, *cache;
3502 int flags;
3503 bool writethrough;
3504 bool quiet = false, progress = false;
3505 BlockBackend *blk = NULL;
3506 BlockDriverState *bs = NULL;
3507 bool image_opts = false;
3509 cache = BDRV_DEFAULT_CACHE;
3510 for (;;) {
3511 static const struct option long_options[] = {
3512 {"help", no_argument, 0, 'h'},
3513 {"object", required_argument, 0, OPTION_OBJECT},
3514 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3515 {0, 0, 0, 0}
3517 c = getopt_long(argc, argv, ":ho:f:t:pq",
3518 long_options, NULL);
3519 if (c == -1) {
3520 break;
3523 switch (c) {
3524 case ':':
3525 missing_argument(argv[optind - 1]);
3526 break;
3527 case '?':
3528 unrecognized_option(argv[optind - 1]);
3529 break;
3530 case 'h':
3531 help();
3532 break;
3533 case 'o':
3534 if (!is_valid_option_list(optarg)) {
3535 error_report("Invalid option list: %s", optarg);
3536 ret = -1;
3537 goto out_no_progress;
3539 if (!options) {
3540 options = g_strdup(optarg);
3541 } else {
3542 char *old_options = options;
3543 options = g_strdup_printf("%s,%s", options, optarg);
3544 g_free(old_options);
3546 break;
3547 case 'f':
3548 fmt = optarg;
3549 break;
3550 case 't':
3551 cache = optarg;
3552 break;
3553 case 'p':
3554 progress = true;
3555 break;
3556 case 'q':
3557 quiet = true;
3558 break;
3559 case OPTION_OBJECT:
3560 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3561 optarg, true);
3562 if (!opts) {
3563 ret = -1;
3564 goto out_no_progress;
3566 break;
3567 case OPTION_IMAGE_OPTS:
3568 image_opts = true;
3569 break;
3573 if (!options) {
3574 error_exit("Must specify options (-o)");
3577 if (qemu_opts_foreach(&qemu_object_opts,
3578 user_creatable_add_opts_foreach,
3579 NULL, NULL)) {
3580 ret = -1;
3581 goto out_no_progress;
3584 if (quiet) {
3585 progress = false;
3587 qemu_progress_init(progress, 1.0);
3589 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3590 if (fmt && has_help_option(options)) {
3591 /* If a format is explicitly specified (and possibly no filename is
3592 * given), print option help here */
3593 ret = print_block_option_help(filename, fmt);
3594 goto out;
3597 if (optind != argc - 1) {
3598 error_report("Expecting one image file name");
3599 ret = -1;
3600 goto out;
3603 flags = BDRV_O_RDWR;
3604 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3605 if (ret < 0) {
3606 error_report("Invalid cache option: %s", cache);
3607 goto out;
3610 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3611 if (!blk) {
3612 ret = -1;
3613 goto out;
3615 bs = blk_bs(blk);
3617 fmt = bs->drv->format_name;
3619 if (has_help_option(options)) {
3620 /* If the format was auto-detected, print option help here */
3621 ret = print_block_option_help(filename, fmt);
3622 goto out;
3625 if (!bs->drv->create_opts) {
3626 error_report("Format driver '%s' does not support any options to amend",
3627 fmt);
3628 ret = -1;
3629 goto out;
3632 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3633 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3634 qemu_opts_do_parse(opts, options, NULL, &err);
3635 if (err) {
3636 error_report_err(err);
3637 ret = -1;
3638 goto out;
3641 /* In case the driver does not call amend_status_cb() */
3642 qemu_progress_print(0.f, 0);
3643 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3644 qemu_progress_print(100.f, 0);
3645 if (ret < 0) {
3646 error_report("Error while amending options: %s", strerror(-ret));
3647 goto out;
3650 out:
3651 qemu_progress_end();
3653 out_no_progress:
3654 blk_unref(blk);
3655 qemu_opts_del(opts);
3656 qemu_opts_free(create_opts);
3657 g_free(options);
3659 if (ret) {
3660 return 1;
3662 return 0;
3665 typedef struct BenchData {
3666 BlockBackend *blk;
3667 uint64_t image_size;
3668 bool write;
3669 int bufsize;
3670 int step;
3671 int nrreq;
3672 int n;
3673 int flush_interval;
3674 bool drain_on_flush;
3675 uint8_t *buf;
3676 QEMUIOVector *qiov;
3678 int in_flight;
3679 bool in_flush;
3680 uint64_t offset;
3681 } BenchData;
3683 static void bench_undrained_flush_cb(void *opaque, int ret)
3685 if (ret < 0) {
3686 error_report("Failed flush request: %s", strerror(-ret));
3687 exit(EXIT_FAILURE);
3691 static void bench_cb(void *opaque, int ret)
3693 BenchData *b = opaque;
3694 BlockAIOCB *acb;
3696 if (ret < 0) {
3697 error_report("Failed request: %s", strerror(-ret));
3698 exit(EXIT_FAILURE);
3701 if (b->in_flush) {
3702 /* Just finished a flush with drained queue: Start next requests */
3703 assert(b->in_flight == 0);
3704 b->in_flush = false;
3705 } else if (b->in_flight > 0) {
3706 int remaining = b->n - b->in_flight;
3708 b->n--;
3709 b->in_flight--;
3711 /* Time for flush? Drain queue if requested, then flush */
3712 if (b->flush_interval && remaining % b->flush_interval == 0) {
3713 if (!b->in_flight || !b->drain_on_flush) {
3714 BlockCompletionFunc *cb;
3716 if (b->drain_on_flush) {
3717 b->in_flush = true;
3718 cb = bench_cb;
3719 } else {
3720 cb = bench_undrained_flush_cb;
3723 acb = blk_aio_flush(b->blk, cb, b);
3724 if (!acb) {
3725 error_report("Failed to issue flush request");
3726 exit(EXIT_FAILURE);
3729 if (b->drain_on_flush) {
3730 return;
3735 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
3736 int64_t offset = b->offset;
3737 /* blk_aio_* might look for completed I/Os and kick bench_cb
3738 * again, so make sure this operation is counted by in_flight
3739 * and b->offset is ready for the next submission.
3741 b->in_flight++;
3742 b->offset += b->step;
3743 b->offset %= b->image_size;
3744 if (b->write) {
3745 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
3746 } else {
3747 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
3749 if (!acb) {
3750 error_report("Failed to issue request");
3751 exit(EXIT_FAILURE);
3756 static int img_bench(int argc, char **argv)
3758 int c, ret = 0;
3759 const char *fmt = NULL, *filename;
3760 bool quiet = false;
3761 bool image_opts = false;
3762 bool is_write = false;
3763 int count = 75000;
3764 int depth = 64;
3765 int64_t offset = 0;
3766 size_t bufsize = 4096;
3767 int pattern = 0;
3768 size_t step = 0;
3769 int flush_interval = 0;
3770 bool drain_on_flush = true;
3771 int64_t image_size;
3772 BlockBackend *blk = NULL;
3773 BenchData data = {};
3774 int flags = 0;
3775 bool writethrough = false;
3776 struct timeval t1, t2;
3777 int i;
3779 for (;;) {
3780 static const struct option long_options[] = {
3781 {"help", no_argument, 0, 'h'},
3782 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
3783 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3784 {"pattern", required_argument, 0, OPTION_PATTERN},
3785 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
3786 {0, 0, 0, 0}
3788 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:w", long_options, NULL);
3789 if (c == -1) {
3790 break;
3793 switch (c) {
3794 case ':':
3795 missing_argument(argv[optind - 1]);
3796 break;
3797 case '?':
3798 unrecognized_option(argv[optind - 1]);
3799 break;
3800 case 'h':
3801 help();
3802 break;
3803 case 'c':
3805 unsigned long res;
3807 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3808 error_report("Invalid request count specified");
3809 return 1;
3811 count = res;
3812 break;
3814 case 'd':
3816 unsigned long res;
3818 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3819 error_report("Invalid queue depth specified");
3820 return 1;
3822 depth = res;
3823 break;
3825 case 'f':
3826 fmt = optarg;
3827 break;
3828 case 'n':
3829 flags |= BDRV_O_NATIVE_AIO;
3830 break;
3831 case 'o':
3833 offset = cvtnum(optarg);
3834 if (offset < 0) {
3835 error_report("Invalid offset specified");
3836 return 1;
3838 break;
3840 break;
3841 case 'q':
3842 quiet = true;
3843 break;
3844 case 's':
3846 int64_t sval;
3848 sval = cvtnum(optarg);
3849 if (sval < 0 || sval > INT_MAX) {
3850 error_report("Invalid buffer size specified");
3851 return 1;
3854 bufsize = sval;
3855 break;
3857 case 'S':
3859 int64_t sval;
3861 sval = cvtnum(optarg);
3862 if (sval < 0 || sval > INT_MAX) {
3863 error_report("Invalid step size specified");
3864 return 1;
3867 step = sval;
3868 break;
3870 case 't':
3871 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3872 if (ret < 0) {
3873 error_report("Invalid cache mode");
3874 ret = -1;
3875 goto out;
3877 break;
3878 case 'w':
3879 flags |= BDRV_O_RDWR;
3880 is_write = true;
3881 break;
3882 case OPTION_PATTERN:
3884 unsigned long res;
3886 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
3887 error_report("Invalid pattern byte specified");
3888 return 1;
3890 pattern = res;
3891 break;
3893 case OPTION_FLUSH_INTERVAL:
3895 unsigned long res;
3897 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
3898 error_report("Invalid flush interval specified");
3899 return 1;
3901 flush_interval = res;
3902 break;
3904 case OPTION_NO_DRAIN:
3905 drain_on_flush = false;
3906 break;
3907 case OPTION_IMAGE_OPTS:
3908 image_opts = true;
3909 break;
3913 if (optind != argc - 1) {
3914 error_exit("Expecting one image file name");
3916 filename = argv[argc - 1];
3918 if (!is_write && flush_interval) {
3919 error_report("--flush-interval is only available in write tests");
3920 ret = -1;
3921 goto out;
3923 if (flush_interval && flush_interval < depth) {
3924 error_report("Flush interval can't be smaller than depth");
3925 ret = -1;
3926 goto out;
3929 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3930 if (!blk) {
3931 ret = -1;
3932 goto out;
3935 image_size = blk_getlength(blk);
3936 if (image_size < 0) {
3937 ret = image_size;
3938 goto out;
3941 data = (BenchData) {
3942 .blk = blk,
3943 .image_size = image_size,
3944 .bufsize = bufsize,
3945 .step = step ?: bufsize,
3946 .nrreq = depth,
3947 .n = count,
3948 .offset = offset,
3949 .write = is_write,
3950 .flush_interval = flush_interval,
3951 .drain_on_flush = drain_on_flush,
3953 printf("Sending %d %s requests, %d bytes each, %d in parallel "
3954 "(starting at offset %" PRId64 ", step size %d)\n",
3955 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
3956 data.offset, data.step);
3957 if (flush_interval) {
3958 printf("Sending flush every %d requests\n", flush_interval);
3961 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
3962 memset(data.buf, pattern, data.nrreq * data.bufsize);
3964 data.qiov = g_new(QEMUIOVector, data.nrreq);
3965 for (i = 0; i < data.nrreq; i++) {
3966 qemu_iovec_init(&data.qiov[i], 1);
3967 qemu_iovec_add(&data.qiov[i],
3968 data.buf + i * data.bufsize, data.bufsize);
3971 gettimeofday(&t1, NULL);
3972 bench_cb(&data, 0);
3974 while (data.n > 0) {
3975 main_loop_wait(false);
3977 gettimeofday(&t2, NULL);
3979 printf("Run completed in %3.3f seconds.\n",
3980 (t2.tv_sec - t1.tv_sec)
3981 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3983 out:
3984 qemu_vfree(data.buf);
3985 blk_unref(blk);
3987 if (ret) {
3988 return 1;
3990 return 0;
3993 #define C_BS 01
3994 #define C_COUNT 02
3995 #define C_IF 04
3996 #define C_OF 010
3997 #define C_SKIP 020
3999 struct DdInfo {
4000 unsigned int flags;
4001 int64_t count;
4004 struct DdIo {
4005 int bsz; /* Block size */
4006 char *filename;
4007 uint8_t *buf;
4008 int64_t offset;
4011 struct DdOpts {
4012 const char *name;
4013 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4014 unsigned int flag;
4017 static int img_dd_bs(const char *arg,
4018 struct DdIo *in, struct DdIo *out,
4019 struct DdInfo *dd)
4021 int64_t res;
4023 res = cvtnum(arg);
4025 if (res <= 0 || res > INT_MAX) {
4026 error_report("invalid number: '%s'", arg);
4027 return 1;
4029 in->bsz = out->bsz = res;
4031 return 0;
4034 static int img_dd_count(const char *arg,
4035 struct DdIo *in, struct DdIo *out,
4036 struct DdInfo *dd)
4038 dd->count = cvtnum(arg);
4040 if (dd->count < 0) {
4041 error_report("invalid number: '%s'", arg);
4042 return 1;
4045 return 0;
4048 static int img_dd_if(const char *arg,
4049 struct DdIo *in, struct DdIo *out,
4050 struct DdInfo *dd)
4052 in->filename = g_strdup(arg);
4054 return 0;
4057 static int img_dd_of(const char *arg,
4058 struct DdIo *in, struct DdIo *out,
4059 struct DdInfo *dd)
4061 out->filename = g_strdup(arg);
4063 return 0;
4066 static int img_dd_skip(const char *arg,
4067 struct DdIo *in, struct DdIo *out,
4068 struct DdInfo *dd)
4070 in->offset = cvtnum(arg);
4072 if (in->offset < 0) {
4073 error_report("invalid number: '%s'", arg);
4074 return 1;
4077 return 0;
4080 static int img_dd(int argc, char **argv)
4082 int ret = 0;
4083 char *arg = NULL;
4084 char *tmp;
4085 BlockDriver *drv = NULL, *proto_drv = NULL;
4086 BlockBackend *blk1 = NULL, *blk2 = NULL;
4087 QemuOpts *opts = NULL;
4088 QemuOptsList *create_opts = NULL;
4089 Error *local_err = NULL;
4090 bool image_opts = false;
4091 int c, i;
4092 const char *out_fmt = "raw";
4093 const char *fmt = NULL;
4094 int64_t size = 0;
4095 int64_t block_count = 0, out_pos, in_pos;
4096 struct DdInfo dd = {
4097 .flags = 0,
4098 .count = 0,
4100 struct DdIo in = {
4101 .bsz = 512, /* Block size is by default 512 bytes */
4102 .filename = NULL,
4103 .buf = NULL,
4104 .offset = 0
4106 struct DdIo out = {
4107 .bsz = 512,
4108 .filename = NULL,
4109 .buf = NULL,
4110 .offset = 0
4113 const struct DdOpts options[] = {
4114 { "bs", img_dd_bs, C_BS },
4115 { "count", img_dd_count, C_COUNT },
4116 { "if", img_dd_if, C_IF },
4117 { "of", img_dd_of, C_OF },
4118 { "skip", img_dd_skip, C_SKIP },
4119 { NULL, NULL, 0 }
4121 const struct option long_options[] = {
4122 { "help", no_argument, 0, 'h'},
4123 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4124 { 0, 0, 0, 0 }
4127 while ((c = getopt_long(argc, argv, ":hf:O:", long_options, NULL))) {
4128 if (c == EOF) {
4129 break;
4131 switch (c) {
4132 case 'O':
4133 out_fmt = optarg;
4134 break;
4135 case 'f':
4136 fmt = optarg;
4137 break;
4138 case ':':
4139 missing_argument(argv[optind - 1]);
4140 break;
4141 case '?':
4142 unrecognized_option(argv[optind - 1]);
4143 break;
4144 case 'h':
4145 help();
4146 break;
4147 case OPTION_IMAGE_OPTS:
4148 image_opts = true;
4149 break;
4153 for (i = optind; i < argc; i++) {
4154 int j;
4155 arg = g_strdup(argv[i]);
4157 tmp = strchr(arg, '=');
4158 if (tmp == NULL) {
4159 error_report("unrecognized operand %s", arg);
4160 ret = -1;
4161 goto out;
4164 *tmp++ = '\0';
4166 for (j = 0; options[j].name != NULL; j++) {
4167 if (!strcmp(arg, options[j].name)) {
4168 break;
4171 if (options[j].name == NULL) {
4172 error_report("unrecognized operand %s", arg);
4173 ret = -1;
4174 goto out;
4177 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4178 ret = -1;
4179 goto out;
4181 dd.flags |= options[j].flag;
4182 g_free(arg);
4183 arg = NULL;
4186 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4187 error_report("Must specify both input and output files");
4188 ret = -1;
4189 goto out;
4191 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false);
4193 if (!blk1) {
4194 ret = -1;
4195 goto out;
4198 drv = bdrv_find_format(out_fmt);
4199 if (!drv) {
4200 error_report("Unknown file format");
4201 ret = -1;
4202 goto out;
4204 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4206 if (!proto_drv) {
4207 error_report_err(local_err);
4208 ret = -1;
4209 goto out;
4211 if (!drv->create_opts) {
4212 error_report("Format driver '%s' does not support image creation",
4213 drv->format_name);
4214 ret = -1;
4215 goto out;
4217 if (!proto_drv->create_opts) {
4218 error_report("Protocol driver '%s' does not support image creation",
4219 proto_drv->format_name);
4220 ret = -1;
4221 goto out;
4223 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4224 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4226 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4228 size = blk_getlength(blk1);
4229 if (size < 0) {
4230 error_report("Failed to get size for '%s'", in.filename);
4231 ret = -1;
4232 goto out;
4235 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4236 dd.count * in.bsz < size) {
4237 size = dd.count * in.bsz;
4240 /* Overflow means the specified offset is beyond input image's size */
4241 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4242 size < in.bsz * in.offset)) {
4243 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4244 } else {
4245 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4246 size - in.bsz * in.offset, &error_abort);
4249 ret = bdrv_create(drv, out.filename, opts, &local_err);
4250 if (ret < 0) {
4251 error_reportf_err(local_err,
4252 "%s: error while creating output image: ",
4253 out.filename);
4254 ret = -1;
4255 goto out;
4258 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4259 false, false);
4261 if (!blk2) {
4262 ret = -1;
4263 goto out;
4266 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4267 size < in.offset * in.bsz)) {
4268 /* We give a warning if the skip option is bigger than the input
4269 * size and create an empty output disk image (i.e. like dd(1)).
4271 error_report("%s: cannot skip to specified offset", in.filename);
4272 in_pos = size;
4273 } else {
4274 in_pos = in.offset * in.bsz;
4277 in.buf = g_new(uint8_t, in.bsz);
4279 for (out_pos = 0; in_pos < size; block_count++) {
4280 int in_ret, out_ret;
4282 if (in_pos + in.bsz > size) {
4283 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4284 } else {
4285 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4287 if (in_ret < 0) {
4288 error_report("error while reading from input image file: %s",
4289 strerror(-in_ret));
4290 ret = -1;
4291 goto out;
4293 in_pos += in_ret;
4295 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4297 if (out_ret < 0) {
4298 error_report("error while writing to output image file: %s",
4299 strerror(-out_ret));
4300 ret = -1;
4301 goto out;
4303 out_pos += out_ret;
4306 out:
4307 g_free(arg);
4308 qemu_opts_del(opts);
4309 qemu_opts_free(create_opts);
4310 blk_unref(blk1);
4311 blk_unref(blk2);
4312 g_free(in.filename);
4313 g_free(out.filename);
4314 g_free(in.buf);
4315 g_free(out.buf);
4317 if (ret) {
4318 return 1;
4320 return 0;
4324 static const img_cmd_t img_cmds[] = {
4325 #define DEF(option, callback, arg_string) \
4326 { option, callback },
4327 #include "qemu-img-cmds.h"
4328 #undef DEF
4329 #undef GEN_DOCS
4330 { NULL, NULL, },
4333 int main(int argc, char **argv)
4335 const img_cmd_t *cmd;
4336 const char *cmdname;
4337 Error *local_error = NULL;
4338 char *trace_file = NULL;
4339 int c;
4340 static const struct option long_options[] = {
4341 {"help", no_argument, 0, 'h'},
4342 {"version", no_argument, 0, 'V'},
4343 {"trace", required_argument, NULL, 'T'},
4344 {0, 0, 0, 0}
4347 #ifdef CONFIG_POSIX
4348 signal(SIGPIPE, SIG_IGN);
4349 #endif
4351 module_call_init(MODULE_INIT_TRACE);
4352 error_set_progname(argv[0]);
4353 qemu_init_exec_dir(argv[0]);
4355 if (qemu_init_main_loop(&local_error)) {
4356 error_report_err(local_error);
4357 exit(EXIT_FAILURE);
4360 qcrypto_init(&error_fatal);
4362 module_call_init(MODULE_INIT_QOM);
4363 bdrv_init();
4364 if (argc < 2) {
4365 error_exit("Not enough arguments");
4368 qemu_add_opts(&qemu_object_opts);
4369 qemu_add_opts(&qemu_source_opts);
4370 qemu_add_opts(&qemu_trace_opts);
4372 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
4373 switch (c) {
4374 case ':':
4375 missing_argument(argv[optind - 1]);
4376 return 0;
4377 case '?':
4378 unrecognized_option(argv[optind - 1]);
4379 return 0;
4380 case 'h':
4381 help();
4382 return 0;
4383 case 'V':
4384 printf(QEMU_IMG_VERSION);
4385 return 0;
4386 case 'T':
4387 g_free(trace_file);
4388 trace_file = trace_opt_parse(optarg);
4389 break;
4393 cmdname = argv[optind];
4395 /* reset getopt_long scanning */
4396 argc -= optind;
4397 if (argc < 1) {
4398 return 0;
4400 argv += optind;
4401 optind = 0;
4403 if (!trace_init_backends()) {
4404 exit(1);
4406 trace_init_file(trace_file);
4407 qemu_set_log(LOG_TRACE);
4409 /* find the command */
4410 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4411 if (!strcmp(cmdname, cmd->name)) {
4412 return cmd->handler(argc, argv);
4416 /* not found */
4417 error_exit("Command not found: %s", cmdname);