]> git.proxmox.com Git - mirror_qemu.git/blob - qemu-img.c
qemu-img: Fail fast on convert --bitmaps with inconsistent bitmap
[mirror_qemu.git] / qemu-img.c
1 /*
2 * QEMU disk image utility
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24
25 #include "qemu/osdep.h"
26 #include <getopt.h>
27
28 #include "qemu-common.h"
29 #include "qemu-version.h"
30 #include "qapi/error.h"
31 #include "qapi/qapi-commands-block-core.h"
32 #include "qapi/qapi-visit-block-core.h"
33 #include "qapi/qobject-output-visitor.h"
34 #include "qapi/qmp/qjson.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qemu/cutils.h"
37 #include "qemu/config-file.h"
38 #include "qemu/option.h"
39 #include "qemu/error-report.h"
40 #include "qemu/log.h"
41 #include "qemu/main-loop.h"
42 #include "qemu/module.h"
43 #include "qemu/sockets.h"
44 #include "qemu/units.h"
45 #include "qom/object_interfaces.h"
46 #include "sysemu/block-backend.h"
47 #include "block/block_int.h"
48 #include "block/blockjob.h"
49 #include "block/qapi.h"
50 #include "crypto/init.h"
51 #include "trace/control.h"
52 #include "qemu/throttle.h"
53 #include "block/throttle-groups.h"
54
55 #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
56 "\n" QEMU_COPYRIGHT "\n"
57
58 typedef struct img_cmd_t {
59 const char *name;
60 int (*handler)(int argc, char **argv);
61 } img_cmd_t;
62
63 enum {
64 OPTION_OUTPUT = 256,
65 OPTION_BACKING_CHAIN = 257,
66 OPTION_OBJECT = 258,
67 OPTION_IMAGE_OPTS = 259,
68 OPTION_PATTERN = 260,
69 OPTION_FLUSH_INTERVAL = 261,
70 OPTION_NO_DRAIN = 262,
71 OPTION_TARGET_IMAGE_OPTS = 263,
72 OPTION_SIZE = 264,
73 OPTION_PREALLOCATION = 265,
74 OPTION_SHRINK = 266,
75 OPTION_SALVAGE = 267,
76 OPTION_TARGET_IS_ZERO = 268,
77 OPTION_ADD = 269,
78 OPTION_REMOVE = 270,
79 OPTION_CLEAR = 271,
80 OPTION_ENABLE = 272,
81 OPTION_DISABLE = 273,
82 OPTION_MERGE = 274,
83 OPTION_BITMAPS = 275,
84 OPTION_FORCE = 276,
85 };
86
87 typedef enum OutputFormat {
88 OFORMAT_JSON,
89 OFORMAT_HUMAN,
90 } OutputFormat;
91
92 /* Default to cache=writeback as data integrity is not important for qemu-img */
93 #define BDRV_DEFAULT_CACHE "writeback"
94
95 static void format_print(void *opaque, const char *name)
96 {
97 printf(" %s", name);
98 }
99
100 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
101 {
102 va_list ap;
103
104 va_start(ap, fmt);
105 error_vreport(fmt, ap);
106 va_end(ap);
107
108 error_printf("Try 'qemu-img --help' for more information\n");
109 exit(EXIT_FAILURE);
110 }
111
112 static void QEMU_NORETURN missing_argument(const char *option)
113 {
114 error_exit("missing argument for option '%s'", option);
115 }
116
117 static void QEMU_NORETURN unrecognized_option(const char *option)
118 {
119 error_exit("unrecognized option '%s'", option);
120 }
121
122 /* Please keep in synch with docs/tools/qemu-img.rst */
123 static void QEMU_NORETURN help(void)
124 {
125 const char *help_msg =
126 QEMU_IMG_VERSION
127 "usage: qemu-img [standard options] command [command options]\n"
128 "QEMU disk image utility\n"
129 "\n"
130 " '-h', '--help' display this help and exit\n"
131 " '-V', '--version' output version information and exit\n"
132 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
133 " specify tracing options\n"
134 "\n"
135 "Command syntax:\n"
136 #define DEF(option, callback, arg_string) \
137 " " arg_string "\n"
138 #include "qemu-img-cmds.h"
139 #undef DEF
140 "\n"
141 "Command parameters:\n"
142 " 'filename' is a disk image filename\n"
143 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
144 " manual page for a description of the object properties. The most common\n"
145 " object type is a 'secret', which is used to supply passwords and/or\n"
146 " encryption keys.\n"
147 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
148 " 'cache' is the cache mode used to write the output disk image, the valid\n"
149 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
150 " 'directsync' and 'unsafe' (default for convert)\n"
151 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
152 " options are the same as for the 'cache' option\n"
153 " 'size' is the disk image size in bytes. Optional suffixes\n"
154 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
155 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
156 " supported. 'b' is ignored.\n"
157 " 'output_filename' is the destination disk image filename\n"
158 " 'output_fmt' is the destination format\n"
159 " 'options' is a comma separated list of format specific options in a\n"
160 " name=value format. Use -o ? for an overview of the options supported by the\n"
161 " used format\n"
162 " 'snapshot_param' is param used for internal snapshot, format\n"
163 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
164 " '[ID_OR_NAME]'\n"
165 " '-c' indicates that target image must be compressed (qcow format only)\n"
166 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
167 " new backing file match exactly. The image doesn't need a working\n"
168 " backing file before rebasing in this case (useful for renaming the\n"
169 " backing file). For image creation, allow creating without attempting\n"
170 " to open the backing file.\n"
171 " '-h' with or without a command shows this help and lists the supported formats\n"
172 " '-p' show progress of command (only certain commands)\n"
173 " '-q' use Quiet mode - do not print any output (except errors)\n"
174 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
175 " contain only zeros for qemu-img to create a sparse image during\n"
176 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
177 " unallocated or zero sectors, and the destination image will always be\n"
178 " fully allocated\n"
179 " '--output' takes the format in which the output must be done (human or json)\n"
180 " '-n' skips the target volume creation (useful if the volume is created\n"
181 " prior to running qemu-img)\n"
182 "\n"
183 "Parameters to bitmap subcommand:\n"
184 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
185 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
186 " or '--merge source'\n"
187 " '-g granularity' sets the granularity for '--add' actions\n"
188 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
189 " bitmaps from an alternative file\n"
190 "\n"
191 "Parameters to check subcommand:\n"
192 " '-r' tries to repair any inconsistencies that are found during the check.\n"
193 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
194 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
195 " hiding corruption that has already occurred.\n"
196 "\n"
197 "Parameters to convert subcommand:\n"
198 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
199 " '-m' specifies how many coroutines work in parallel during the convert\n"
200 " process (defaults to 8)\n"
201 " '-W' allow to write to the target out of order rather than sequential\n"
202 "\n"
203 "Parameters to snapshot subcommand:\n"
204 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
205 " '-a' applies a snapshot (revert disk to saved state)\n"
206 " '-c' creates a snapshot\n"
207 " '-d' deletes a snapshot\n"
208 " '-l' lists all snapshots in the given image\n"
209 "\n"
210 "Parameters to compare subcommand:\n"
211 " '-f' first image format\n"
212 " '-F' second image format\n"
213 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
214 "\n"
215 "Parameters to dd subcommand:\n"
216 " 'bs=BYTES' read and write up to BYTES bytes at a time "
217 "(default: 512)\n"
218 " 'count=N' copy only N input blocks\n"
219 " 'if=FILE' read from FILE\n"
220 " 'of=FILE' write to FILE\n"
221 " 'skip=N' skip N bs-sized blocks at the start of input\n";
222
223 printf("%s\nSupported formats:", help_msg);
224 bdrv_iterate_format(format_print, NULL, false);
225 printf("\n\n" QEMU_HELP_BOTTOM "\n");
226 exit(EXIT_SUCCESS);
227 }
228
229 /*
230 * Is @optarg safe for accumulate_options()?
231 * It is when multiple of them can be joined together separated by ','.
232 * To make that work, @optarg must not start with ',' (or else a
233 * separating ',' preceding it gets escaped), and it must not end with
234 * an odd number of ',' (or else a separating ',' following it gets
235 * escaped), or be empty (or else a separating ',' preceding it can
236 * escape a separating ',' following it).
237 *
238 */
239 static bool is_valid_option_list(const char *optarg)
240 {
241 size_t len = strlen(optarg);
242 size_t i;
243
244 if (!optarg[0] || optarg[0] == ',') {
245 return false;
246 }
247
248 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
249 }
250 if ((len - i) % 2) {
251 return false;
252 }
253
254 return true;
255 }
256
257 static int accumulate_options(char **options, char *optarg)
258 {
259 char *new_options;
260
261 if (!is_valid_option_list(optarg)) {
262 error_report("Invalid option list: %s", optarg);
263 return -1;
264 }
265
266 if (!*options) {
267 *options = g_strdup(optarg);
268 } else {
269 new_options = g_strdup_printf("%s,%s", *options, optarg);
270 g_free(*options);
271 *options = new_options;
272 }
273 return 0;
274 }
275
276 static QemuOptsList qemu_source_opts = {
277 .name = "source",
278 .implied_opt_name = "file",
279 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
280 .desc = {
281 { }
282 },
283 };
284
285 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
286 {
287 int ret = 0;
288 if (!quiet) {
289 va_list args;
290 va_start(args, fmt);
291 ret = vprintf(fmt, args);
292 va_end(args);
293 }
294 return ret;
295 }
296
297
298 static int print_block_option_help(const char *filename, const char *fmt)
299 {
300 BlockDriver *drv, *proto_drv;
301 QemuOptsList *create_opts = NULL;
302 Error *local_err = NULL;
303
304 /* Find driver and parse its options */
305 drv = bdrv_find_format(fmt);
306 if (!drv) {
307 error_report("Unknown file format '%s'", fmt);
308 return 1;
309 }
310
311 if (!drv->create_opts) {
312 error_report("Format driver '%s' does not support image creation", fmt);
313 return 1;
314 }
315
316 create_opts = qemu_opts_append(create_opts, drv->create_opts);
317 if (filename) {
318 proto_drv = bdrv_find_protocol(filename, true, &local_err);
319 if (!proto_drv) {
320 error_report_err(local_err);
321 qemu_opts_free(create_opts);
322 return 1;
323 }
324 if (!proto_drv->create_opts) {
325 error_report("Protocol driver '%s' does not support image creation",
326 proto_drv->format_name);
327 qemu_opts_free(create_opts);
328 return 1;
329 }
330 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
331 }
332
333 if (filename) {
334 printf("Supported options:\n");
335 } else {
336 printf("Supported %s options:\n", fmt);
337 }
338 qemu_opts_print_help(create_opts, false);
339 qemu_opts_free(create_opts);
340
341 if (!filename) {
342 printf("\n"
343 "The protocol level may support further options.\n"
344 "Specify the target filename to include those options.\n");
345 }
346
347 return 0;
348 }
349
350
351 static BlockBackend *img_open_opts(const char *optstr,
352 QemuOpts *opts, int flags, bool writethrough,
353 bool quiet, bool force_share)
354 {
355 QDict *options;
356 Error *local_err = NULL;
357 BlockBackend *blk;
358 options = qemu_opts_to_qdict(opts, NULL);
359 if (force_share) {
360 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
361 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
362 error_report("--force-share/-U conflicts with image options");
363 qobject_unref(options);
364 return NULL;
365 }
366 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
367 }
368 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
369 if (!blk) {
370 error_reportf_err(local_err, "Could not open '%s': ", optstr);
371 return NULL;
372 }
373 blk_set_enable_write_cache(blk, !writethrough);
374
375 return blk;
376 }
377
378 static BlockBackend *img_open_file(const char *filename,
379 QDict *options,
380 const char *fmt, int flags,
381 bool writethrough, bool quiet,
382 bool force_share)
383 {
384 BlockBackend *blk;
385 Error *local_err = NULL;
386
387 if (!options) {
388 options = qdict_new();
389 }
390 if (fmt) {
391 qdict_put_str(options, "driver", fmt);
392 }
393
394 if (force_share) {
395 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
396 }
397 blk = blk_new_open(filename, NULL, options, flags, &local_err);
398 if (!blk) {
399 error_reportf_err(local_err, "Could not open '%s': ", filename);
400 return NULL;
401 }
402 blk_set_enable_write_cache(blk, !writethrough);
403
404 return blk;
405 }
406
407
408 static int img_add_key_secrets(void *opaque,
409 const char *name, const char *value,
410 Error **errp)
411 {
412 QDict *options = opaque;
413
414 if (g_str_has_suffix(name, "key-secret")) {
415 qdict_put_str(options, name, value);
416 }
417
418 return 0;
419 }
420
421
422 static BlockBackend *img_open(bool image_opts,
423 const char *filename,
424 const char *fmt, int flags, bool writethrough,
425 bool quiet, bool force_share)
426 {
427 BlockBackend *blk;
428 if (image_opts) {
429 QemuOpts *opts;
430 if (fmt) {
431 error_report("--image-opts and --format are mutually exclusive");
432 return NULL;
433 }
434 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
435 filename, true);
436 if (!opts) {
437 return NULL;
438 }
439 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
440 force_share);
441 } else {
442 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
443 force_share);
444 }
445 return blk;
446 }
447
448
449 static int add_old_style_options(const char *fmt, QemuOpts *opts,
450 const char *base_filename,
451 const char *base_fmt)
452 {
453 if (base_filename) {
454 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
455 NULL)) {
456 error_report("Backing file not supported for file format '%s'",
457 fmt);
458 return -1;
459 }
460 }
461 if (base_fmt) {
462 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
463 error_report("Backing file format not supported for file "
464 "format '%s'", fmt);
465 return -1;
466 }
467 }
468 return 0;
469 }
470
471 static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
472 int64_t max)
473 {
474 int err;
475 uint64_t res;
476
477 err = qemu_strtosz(value, NULL, &res);
478 if (err < 0 && err != -ERANGE) {
479 error_report("Invalid %s specified. You may use "
480 "k, M, G, T, P or E suffixes for", name);
481 error_report("kilobytes, megabytes, gigabytes, terabytes, "
482 "petabytes and exabytes.");
483 return err;
484 }
485 if (err == -ERANGE || res > max || res < min) {
486 error_report("Invalid %s specified. Must be between %" PRId64
487 " and %" PRId64 ".", name, min, max);
488 return -ERANGE;
489 }
490 return res;
491 }
492
493 static int64_t cvtnum(const char *name, const char *value)
494 {
495 return cvtnum_full(name, value, 0, INT64_MAX);
496 }
497
498 static int img_create(int argc, char **argv)
499 {
500 int c;
501 uint64_t img_size = -1;
502 const char *fmt = "raw";
503 const char *base_fmt = NULL;
504 const char *filename;
505 const char *base_filename = NULL;
506 char *options = NULL;
507 Error *local_err = NULL;
508 bool quiet = false;
509 int flags = 0;
510
511 for(;;) {
512 static const struct option long_options[] = {
513 {"help", no_argument, 0, 'h'},
514 {"object", required_argument, 0, OPTION_OBJECT},
515 {0, 0, 0, 0}
516 };
517 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
518 long_options, NULL);
519 if (c == -1) {
520 break;
521 }
522 switch(c) {
523 case ':':
524 missing_argument(argv[optind - 1]);
525 break;
526 case '?':
527 unrecognized_option(argv[optind - 1]);
528 break;
529 case 'h':
530 help();
531 break;
532 case 'F':
533 base_fmt = optarg;
534 break;
535 case 'b':
536 base_filename = optarg;
537 break;
538 case 'f':
539 fmt = optarg;
540 break;
541 case 'o':
542 if (accumulate_options(&options, optarg) < 0) {
543 goto fail;
544 }
545 break;
546 case 'q':
547 quiet = true;
548 break;
549 case 'u':
550 flags |= BDRV_O_NO_BACKING;
551 break;
552 case OPTION_OBJECT:
553 user_creatable_process_cmdline(optarg);
554 break;
555 }
556 }
557
558 /* Get the filename */
559 filename = (optind < argc) ? argv[optind] : NULL;
560 if (options && has_help_option(options)) {
561 g_free(options);
562 return print_block_option_help(filename, fmt);
563 }
564
565 if (optind >= argc) {
566 error_exit("Expecting image file name");
567 }
568 optind++;
569
570 /* Get image size, if specified */
571 if (optind < argc) {
572 int64_t sval;
573
574 sval = cvtnum("image size", argv[optind++]);
575 if (sval < 0) {
576 goto fail;
577 }
578 img_size = (uint64_t)sval;
579 }
580 if (optind != argc) {
581 error_exit("Unexpected argument: %s", argv[optind]);
582 }
583
584 bdrv_img_create(filename, fmt, base_filename, base_fmt,
585 options, img_size, flags, quiet, &local_err);
586 if (local_err) {
587 error_reportf_err(local_err, "%s: ", filename);
588 goto fail;
589 }
590
591 g_free(options);
592 return 0;
593
594 fail:
595 g_free(options);
596 return 1;
597 }
598
599 static void dump_json_image_check(ImageCheck *check, bool quiet)
600 {
601 GString *str;
602 QObject *obj;
603 Visitor *v = qobject_output_visitor_new(&obj);
604
605 visit_type_ImageCheck(v, NULL, &check, &error_abort);
606 visit_complete(v, &obj);
607 str = qobject_to_json_pretty(obj, true);
608 assert(str != NULL);
609 qprintf(quiet, "%s\n", str->str);
610 qobject_unref(obj);
611 visit_free(v);
612 g_string_free(str, true);
613 }
614
615 static void dump_human_image_check(ImageCheck *check, bool quiet)
616 {
617 if (!(check->corruptions || check->leaks || check->check_errors)) {
618 qprintf(quiet, "No errors were found on the image.\n");
619 } else {
620 if (check->corruptions) {
621 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
622 "Data may be corrupted, or further writes to the image "
623 "may corrupt it.\n",
624 check->corruptions);
625 }
626
627 if (check->leaks) {
628 qprintf(quiet,
629 "\n%" PRId64 " leaked clusters were found on the image.\n"
630 "This means waste of disk space, but no harm to data.\n",
631 check->leaks);
632 }
633
634 if (check->check_errors) {
635 qprintf(quiet,
636 "\n%" PRId64
637 " internal errors have occurred during the check.\n",
638 check->check_errors);
639 }
640 }
641
642 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
643 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
644 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
645 check->allocated_clusters, check->total_clusters,
646 check->allocated_clusters * 100.0 / check->total_clusters,
647 check->fragmented_clusters * 100.0 / check->allocated_clusters,
648 check->compressed_clusters * 100.0 /
649 check->allocated_clusters);
650 }
651
652 if (check->image_end_offset) {
653 qprintf(quiet,
654 "Image end offset: %" PRId64 "\n", check->image_end_offset);
655 }
656 }
657
658 static int collect_image_check(BlockDriverState *bs,
659 ImageCheck *check,
660 const char *filename,
661 const char *fmt,
662 int fix)
663 {
664 int ret;
665 BdrvCheckResult result;
666
667 ret = bdrv_check(bs, &result, fix);
668 if (ret < 0) {
669 return ret;
670 }
671
672 check->filename = g_strdup(filename);
673 check->format = g_strdup(bdrv_get_format_name(bs));
674 check->check_errors = result.check_errors;
675 check->corruptions = result.corruptions;
676 check->has_corruptions = result.corruptions != 0;
677 check->leaks = result.leaks;
678 check->has_leaks = result.leaks != 0;
679 check->corruptions_fixed = result.corruptions_fixed;
680 check->has_corruptions_fixed = result.corruptions_fixed != 0;
681 check->leaks_fixed = result.leaks_fixed;
682 check->has_leaks_fixed = result.leaks_fixed != 0;
683 check->image_end_offset = result.image_end_offset;
684 check->has_image_end_offset = result.image_end_offset != 0;
685 check->total_clusters = result.bfi.total_clusters;
686 check->has_total_clusters = result.bfi.total_clusters != 0;
687 check->allocated_clusters = result.bfi.allocated_clusters;
688 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
689 check->fragmented_clusters = result.bfi.fragmented_clusters;
690 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
691 check->compressed_clusters = result.bfi.compressed_clusters;
692 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
693
694 return 0;
695 }
696
697 /*
698 * Checks an image for consistency. Exit codes:
699 *
700 * 0 - Check completed, image is good
701 * 1 - Check not completed because of internal errors
702 * 2 - Check completed, image is corrupted
703 * 3 - Check completed, image has leaked clusters, but is good otherwise
704 * 63 - Checks are not supported by the image format
705 */
706 static int img_check(int argc, char **argv)
707 {
708 int c, ret;
709 OutputFormat output_format = OFORMAT_HUMAN;
710 const char *filename, *fmt, *output, *cache;
711 BlockBackend *blk;
712 BlockDriverState *bs;
713 int fix = 0;
714 int flags = BDRV_O_CHECK;
715 bool writethrough;
716 ImageCheck *check;
717 bool quiet = false;
718 bool image_opts = false;
719 bool force_share = false;
720
721 fmt = NULL;
722 output = NULL;
723 cache = BDRV_DEFAULT_CACHE;
724
725 for(;;) {
726 int option_index = 0;
727 static const struct option long_options[] = {
728 {"help", no_argument, 0, 'h'},
729 {"format", required_argument, 0, 'f'},
730 {"repair", required_argument, 0, 'r'},
731 {"output", required_argument, 0, OPTION_OUTPUT},
732 {"object", required_argument, 0, OPTION_OBJECT},
733 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
734 {"force-share", no_argument, 0, 'U'},
735 {0, 0, 0, 0}
736 };
737 c = getopt_long(argc, argv, ":hf:r:T:qU",
738 long_options, &option_index);
739 if (c == -1) {
740 break;
741 }
742 switch(c) {
743 case ':':
744 missing_argument(argv[optind - 1]);
745 break;
746 case '?':
747 unrecognized_option(argv[optind - 1]);
748 break;
749 case 'h':
750 help();
751 break;
752 case 'f':
753 fmt = optarg;
754 break;
755 case 'r':
756 flags |= BDRV_O_RDWR;
757
758 if (!strcmp(optarg, "leaks")) {
759 fix = BDRV_FIX_LEAKS;
760 } else if (!strcmp(optarg, "all")) {
761 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
762 } else {
763 error_exit("Unknown option value for -r "
764 "(expecting 'leaks' or 'all'): %s", optarg);
765 }
766 break;
767 case OPTION_OUTPUT:
768 output = optarg;
769 break;
770 case 'T':
771 cache = optarg;
772 break;
773 case 'q':
774 quiet = true;
775 break;
776 case 'U':
777 force_share = true;
778 break;
779 case OPTION_OBJECT:
780 user_creatable_process_cmdline(optarg);
781 break;
782 case OPTION_IMAGE_OPTS:
783 image_opts = true;
784 break;
785 }
786 }
787 if (optind != argc - 1) {
788 error_exit("Expecting one image file name");
789 }
790 filename = argv[optind++];
791
792 if (output && !strcmp(output, "json")) {
793 output_format = OFORMAT_JSON;
794 } else if (output && !strcmp(output, "human")) {
795 output_format = OFORMAT_HUMAN;
796 } else if (output) {
797 error_report("--output must be used with human or json as argument.");
798 return 1;
799 }
800
801 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
802 if (ret < 0) {
803 error_report("Invalid source cache option: %s", cache);
804 return 1;
805 }
806
807 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
808 force_share);
809 if (!blk) {
810 return 1;
811 }
812 bs = blk_bs(blk);
813
814 check = g_new0(ImageCheck, 1);
815 ret = collect_image_check(bs, check, filename, fmt, fix);
816
817 if (ret == -ENOTSUP) {
818 error_report("This image format does not support checks");
819 ret = 63;
820 goto fail;
821 }
822
823 if (check->corruptions_fixed || check->leaks_fixed) {
824 int corruptions_fixed, leaks_fixed;
825 bool has_leaks_fixed, has_corruptions_fixed;
826
827 leaks_fixed = check->leaks_fixed;
828 has_leaks_fixed = check->has_leaks_fixed;
829 corruptions_fixed = check->corruptions_fixed;
830 has_corruptions_fixed = check->has_corruptions_fixed;
831
832 if (output_format == OFORMAT_HUMAN) {
833 qprintf(quiet,
834 "The following inconsistencies were found and repaired:\n\n"
835 " %" PRId64 " leaked clusters\n"
836 " %" PRId64 " corruptions\n\n"
837 "Double checking the fixed image now...\n",
838 check->leaks_fixed,
839 check->corruptions_fixed);
840 }
841
842 qapi_free_ImageCheck(check);
843 check = g_new0(ImageCheck, 1);
844 ret = collect_image_check(bs, check, filename, fmt, 0);
845
846 check->leaks_fixed = leaks_fixed;
847 check->has_leaks_fixed = has_leaks_fixed;
848 check->corruptions_fixed = corruptions_fixed;
849 check->has_corruptions_fixed = has_corruptions_fixed;
850 }
851
852 if (!ret) {
853 switch (output_format) {
854 case OFORMAT_HUMAN:
855 dump_human_image_check(check, quiet);
856 break;
857 case OFORMAT_JSON:
858 dump_json_image_check(check, quiet);
859 break;
860 }
861 }
862
863 if (ret || check->check_errors) {
864 if (ret) {
865 error_report("Check failed: %s", strerror(-ret));
866 } else {
867 error_report("Check failed");
868 }
869 ret = 1;
870 goto fail;
871 }
872
873 if (check->corruptions) {
874 ret = 2;
875 } else if (check->leaks) {
876 ret = 3;
877 } else {
878 ret = 0;
879 }
880
881 fail:
882 qapi_free_ImageCheck(check);
883 blk_unref(blk);
884 return ret;
885 }
886
887 typedef struct CommonBlockJobCBInfo {
888 BlockDriverState *bs;
889 Error **errp;
890 } CommonBlockJobCBInfo;
891
892 static void common_block_job_cb(void *opaque, int ret)
893 {
894 CommonBlockJobCBInfo *cbi = opaque;
895
896 if (ret < 0) {
897 error_setg_errno(cbi->errp, -ret, "Block job failed");
898 }
899 }
900
901 static void run_block_job(BlockJob *job, Error **errp)
902 {
903 uint64_t progress_current, progress_total;
904 AioContext *aio_context = blk_get_aio_context(job->blk);
905 int ret = 0;
906
907 aio_context_acquire(aio_context);
908 job_ref(&job->job);
909 do {
910 float progress = 0.0f;
911 aio_poll(aio_context, true);
912
913 progress_get_snapshot(&job->job.progress, &progress_current,
914 &progress_total);
915 if (progress_total) {
916 progress = (float)progress_current / progress_total * 100.f;
917 }
918 qemu_progress_print(progress, 0);
919 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
920
921 if (!job_is_completed(&job->job)) {
922 ret = job_complete_sync(&job->job, errp);
923 } else {
924 ret = job->job.ret;
925 }
926 job_unref(&job->job);
927 aio_context_release(aio_context);
928
929 /* publish completion progress only when success */
930 if (!ret) {
931 qemu_progress_print(100.f, 0);
932 }
933 }
934
935 static int img_commit(int argc, char **argv)
936 {
937 int c, ret, flags;
938 const char *filename, *fmt, *cache, *base;
939 BlockBackend *blk;
940 BlockDriverState *bs, *base_bs;
941 BlockJob *job;
942 bool progress = false, quiet = false, drop = false;
943 bool writethrough;
944 Error *local_err = NULL;
945 CommonBlockJobCBInfo cbi;
946 bool image_opts = false;
947 AioContext *aio_context;
948 int64_t rate_limit = 0;
949
950 fmt = NULL;
951 cache = BDRV_DEFAULT_CACHE;
952 base = NULL;
953 for(;;) {
954 static const struct option long_options[] = {
955 {"help", no_argument, 0, 'h'},
956 {"object", required_argument, 0, OPTION_OBJECT},
957 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
958 {0, 0, 0, 0}
959 };
960 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
961 long_options, NULL);
962 if (c == -1) {
963 break;
964 }
965 switch(c) {
966 case ':':
967 missing_argument(argv[optind - 1]);
968 break;
969 case '?':
970 unrecognized_option(argv[optind - 1]);
971 break;
972 case 'h':
973 help();
974 break;
975 case 'f':
976 fmt = optarg;
977 break;
978 case 't':
979 cache = optarg;
980 break;
981 case 'b':
982 base = optarg;
983 /* -b implies -d */
984 drop = true;
985 break;
986 case 'd':
987 drop = true;
988 break;
989 case 'p':
990 progress = true;
991 break;
992 case 'q':
993 quiet = true;
994 break;
995 case 'r':
996 rate_limit = cvtnum("rate limit", optarg);
997 if (rate_limit < 0) {
998 return 1;
999 }
1000 break;
1001 case OPTION_OBJECT:
1002 user_creatable_process_cmdline(optarg);
1003 break;
1004 case OPTION_IMAGE_OPTS:
1005 image_opts = true;
1006 break;
1007 }
1008 }
1009
1010 /* Progress is not shown in Quiet mode */
1011 if (quiet) {
1012 progress = false;
1013 }
1014
1015 if (optind != argc - 1) {
1016 error_exit("Expecting one image file name");
1017 }
1018 filename = argv[optind++];
1019
1020 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
1021 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1022 if (ret < 0) {
1023 error_report("Invalid cache option: %s", cache);
1024 return 1;
1025 }
1026
1027 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1028 false);
1029 if (!blk) {
1030 return 1;
1031 }
1032 bs = blk_bs(blk);
1033
1034 qemu_progress_init(progress, 1.f);
1035 qemu_progress_print(0.f, 100);
1036
1037 if (base) {
1038 base_bs = bdrv_find_backing_image(bs, base);
1039 if (!base_bs) {
1040 error_setg(&local_err,
1041 "Did not find '%s' in the backing chain of '%s'",
1042 base, filename);
1043 goto done;
1044 }
1045 } else {
1046 /* This is different from QMP, which by default uses the deepest file in
1047 * the backing chain (i.e., the very base); however, the traditional
1048 * behavior of qemu-img commit is using the immediate backing file. */
1049 base_bs = bdrv_backing_chain_next(bs);
1050 if (!base_bs) {
1051 error_setg(&local_err, "Image does not have a backing file");
1052 goto done;
1053 }
1054 }
1055
1056 cbi = (CommonBlockJobCBInfo){
1057 .errp = &local_err,
1058 .bs = bs,
1059 };
1060
1061 aio_context = bdrv_get_aio_context(bs);
1062 aio_context_acquire(aio_context);
1063 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
1064 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
1065 &cbi, false, &local_err);
1066 aio_context_release(aio_context);
1067 if (local_err) {
1068 goto done;
1069 }
1070
1071 /* When the block job completes, the BlockBackend reference will point to
1072 * the old backing file. In order to avoid that the top image is already
1073 * deleted, so we can still empty it afterwards, increment the reference
1074 * counter here preemptively. */
1075 if (!drop) {
1076 bdrv_ref(bs);
1077 }
1078
1079 job = block_job_get("commit");
1080 assert(job);
1081 run_block_job(job, &local_err);
1082 if (local_err) {
1083 goto unref_backing;
1084 }
1085
1086 if (!drop) {
1087 BlockBackend *old_backing_blk;
1088
1089 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1090 &local_err);
1091 if (!old_backing_blk) {
1092 goto unref_backing;
1093 }
1094 ret = blk_make_empty(old_backing_blk, &local_err);
1095 blk_unref(old_backing_blk);
1096 if (ret == -ENOTSUP) {
1097 error_free(local_err);
1098 local_err = NULL;
1099 } else if (ret < 0) {
1100 goto unref_backing;
1101 }
1102 }
1103
1104 unref_backing:
1105 if (!drop) {
1106 bdrv_unref(bs);
1107 }
1108
1109 done:
1110 qemu_progress_end();
1111
1112 blk_unref(blk);
1113
1114 if (local_err) {
1115 error_report_err(local_err);
1116 return 1;
1117 }
1118
1119 qprintf(quiet, "Image committed.\n");
1120 return 0;
1121 }
1122
1123 /*
1124 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1125 * of the first sector boundary within buf where the sector contains a
1126 * non-zero byte. This function is robust to a buffer that is not
1127 * sector-aligned.
1128 */
1129 static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1130 {
1131 int64_t i;
1132 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1133
1134 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1135 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1136 return i;
1137 }
1138 }
1139 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1140 return i;
1141 }
1142 return -1;
1143 }
1144
1145 /*
1146 * Returns true iff the first sector pointed to by 'buf' contains at least
1147 * a non-NUL byte.
1148 *
1149 * 'pnum' is set to the number of sectors (including and immediately following
1150 * the first one) that are known to be in the same allocated/unallocated state.
1151 * The function will try to align the end offset to alignment boundaries so
1152 * that the request will at least end aligned and consecutive requests will
1153 * also start at an aligned offset.
1154 */
1155 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1156 int64_t sector_num, int alignment)
1157 {
1158 bool is_zero;
1159 int i, tail;
1160
1161 if (n <= 0) {
1162 *pnum = 0;
1163 return 0;
1164 }
1165 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
1166 for(i = 1; i < n; i++) {
1167 buf += BDRV_SECTOR_SIZE;
1168 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
1169 break;
1170 }
1171 }
1172
1173 tail = (sector_num + i) & (alignment - 1);
1174 if (tail) {
1175 if (is_zero && i <= tail) {
1176 /* treat unallocated areas which only consist
1177 * of a small tail as allocated. */
1178 is_zero = false;
1179 }
1180 if (!is_zero) {
1181 /* align up end offset of allocated areas. */
1182 i += alignment - tail;
1183 i = MIN(i, n);
1184 } else {
1185 /* align down end offset of zero areas. */
1186 i -= tail;
1187 }
1188 }
1189 *pnum = i;
1190 return !is_zero;
1191 }
1192
1193 /*
1194 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1195 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1196 * breaking up write requests for only small sparse areas.
1197 */
1198 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1199 int min, int64_t sector_num, int alignment)
1200 {
1201 int ret;
1202 int num_checked, num_used;
1203
1204 if (n < min) {
1205 min = n;
1206 }
1207
1208 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1209 if (!ret) {
1210 return ret;
1211 }
1212
1213 num_used = *pnum;
1214 buf += BDRV_SECTOR_SIZE * *pnum;
1215 n -= *pnum;
1216 sector_num += *pnum;
1217 num_checked = num_used;
1218
1219 while (n > 0) {
1220 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
1221
1222 buf += BDRV_SECTOR_SIZE * *pnum;
1223 n -= *pnum;
1224 sector_num += *pnum;
1225 num_checked += *pnum;
1226 if (ret) {
1227 num_used = num_checked;
1228 } else if (*pnum >= min) {
1229 break;
1230 }
1231 }
1232
1233 *pnum = num_used;
1234 return 1;
1235 }
1236
1237 /*
1238 * Compares two buffers sector by sector. Returns 0 if the first
1239 * sector of each buffer matches, non-zero otherwise.
1240 *
1241 * pnum is set to the sector-aligned size of the buffer prefix that
1242 * has the same matching status as the first sector.
1243 */
1244 static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1245 int64_t bytes, int64_t *pnum)
1246 {
1247 bool res;
1248 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
1249
1250 assert(bytes > 0);
1251
1252 res = !!memcmp(buf1, buf2, i);
1253 while (i < bytes) {
1254 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
1255
1256 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
1257 break;
1258 }
1259 i += len;
1260 }
1261
1262 *pnum = i;
1263 return res;
1264 }
1265
1266 #define IO_BUF_SIZE (2 * MiB)
1267
1268 /*
1269 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1270 *
1271 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1272 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1273 * failure), and 4 on error (the exit status for read errors), after emitting
1274 * an error message.
1275 *
1276 * @param blk: BlockBackend for the image
1277 * @param offset: Starting offset to check
1278 * @param bytes: Number of bytes to check
1279 * @param filename: Name of disk file we are checking (logging purpose)
1280 * @param buffer: Allocated buffer for storing read data
1281 * @param quiet: Flag for quiet mode
1282 */
1283 static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1284 int64_t bytes, const char *filename,
1285 uint8_t *buffer, bool quiet)
1286 {
1287 int ret = 0;
1288 int64_t idx;
1289
1290 ret = blk_pread(blk, offset, buffer, bytes);
1291 if (ret < 0) {
1292 error_report("Error while reading offset %" PRId64 " of %s: %s",
1293 offset, filename, strerror(-ret));
1294 return 4;
1295 }
1296 idx = find_nonzero(buffer, bytes);
1297 if (idx >= 0) {
1298 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1299 offset + idx);
1300 return 1;
1301 }
1302
1303 return 0;
1304 }
1305
1306 /*
1307 * Compares two images. Exit codes:
1308 *
1309 * 0 - Images are identical or the requested help was printed
1310 * 1 - Images differ
1311 * >1 - Error occurred
1312 */
1313 static int img_compare(int argc, char **argv)
1314 {
1315 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1316 BlockBackend *blk1, *blk2;
1317 BlockDriverState *bs1, *bs2;
1318 int64_t total_size1, total_size2;
1319 uint8_t *buf1 = NULL, *buf2 = NULL;
1320 int64_t pnum1, pnum2;
1321 int allocated1, allocated2;
1322 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1323 bool progress = false, quiet = false, strict = false;
1324 int flags;
1325 bool writethrough;
1326 int64_t total_size;
1327 int64_t offset = 0;
1328 int64_t chunk;
1329 int c;
1330 uint64_t progress_base;
1331 bool image_opts = false;
1332 bool force_share = false;
1333
1334 cache = BDRV_DEFAULT_CACHE;
1335 for (;;) {
1336 static const struct option long_options[] = {
1337 {"help", no_argument, 0, 'h'},
1338 {"object", required_argument, 0, OPTION_OBJECT},
1339 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1340 {"force-share", no_argument, 0, 'U'},
1341 {0, 0, 0, 0}
1342 };
1343 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
1344 long_options, NULL);
1345 if (c == -1) {
1346 break;
1347 }
1348 switch (c) {
1349 case ':':
1350 missing_argument(argv[optind - 1]);
1351 break;
1352 case '?':
1353 unrecognized_option(argv[optind - 1]);
1354 break;
1355 case 'h':
1356 help();
1357 break;
1358 case 'f':
1359 fmt1 = optarg;
1360 break;
1361 case 'F':
1362 fmt2 = optarg;
1363 break;
1364 case 'T':
1365 cache = optarg;
1366 break;
1367 case 'p':
1368 progress = true;
1369 break;
1370 case 'q':
1371 quiet = true;
1372 break;
1373 case 's':
1374 strict = true;
1375 break;
1376 case 'U':
1377 force_share = true;
1378 break;
1379 case OPTION_OBJECT:
1380 {
1381 Error *local_err = NULL;
1382
1383 if (!user_creatable_add_from_str(optarg, &local_err)) {
1384 if (local_err) {
1385 error_report_err(local_err);
1386 exit(2);
1387 } else {
1388 /* Help was printed */
1389 exit(EXIT_SUCCESS);
1390 }
1391 }
1392 break;
1393 }
1394 case OPTION_IMAGE_OPTS:
1395 image_opts = true;
1396 break;
1397 }
1398 }
1399
1400 /* Progress is not shown in Quiet mode */
1401 if (quiet) {
1402 progress = false;
1403 }
1404
1405
1406 if (optind != argc - 2) {
1407 error_exit("Expecting two image file names");
1408 }
1409 filename1 = argv[optind++];
1410 filename2 = argv[optind++];
1411
1412 /* Initialize before goto out */
1413 qemu_progress_init(progress, 2.0);
1414
1415 flags = 0;
1416 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1417 if (ret < 0) {
1418 error_report("Invalid source cache option: %s", cache);
1419 ret = 2;
1420 goto out3;
1421 }
1422
1423 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1424 force_share);
1425 if (!blk1) {
1426 ret = 2;
1427 goto out3;
1428 }
1429
1430 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1431 force_share);
1432 if (!blk2) {
1433 ret = 2;
1434 goto out2;
1435 }
1436 bs1 = blk_bs(blk1);
1437 bs2 = blk_bs(blk2);
1438
1439 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1440 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1441 total_size1 = blk_getlength(blk1);
1442 if (total_size1 < 0) {
1443 error_report("Can't get size of %s: %s",
1444 filename1, strerror(-total_size1));
1445 ret = 4;
1446 goto out;
1447 }
1448 total_size2 = blk_getlength(blk2);
1449 if (total_size2 < 0) {
1450 error_report("Can't get size of %s: %s",
1451 filename2, strerror(-total_size2));
1452 ret = 4;
1453 goto out;
1454 }
1455 total_size = MIN(total_size1, total_size2);
1456 progress_base = MAX(total_size1, total_size2);
1457
1458 qemu_progress_print(0, 100);
1459
1460 if (strict && total_size1 != total_size2) {
1461 ret = 1;
1462 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1463 goto out;
1464 }
1465
1466 while (offset < total_size) {
1467 int status1, status2;
1468
1469 status1 = bdrv_block_status_above(bs1, NULL, offset,
1470 total_size1 - offset, &pnum1, NULL,
1471 NULL);
1472 if (status1 < 0) {
1473 ret = 3;
1474 error_report("Sector allocation test failed for %s", filename1);
1475 goto out;
1476 }
1477 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1478
1479 status2 = bdrv_block_status_above(bs2, NULL, offset,
1480 total_size2 - offset, &pnum2, NULL,
1481 NULL);
1482 if (status2 < 0) {
1483 ret = 3;
1484 error_report("Sector allocation test failed for %s", filename2);
1485 goto out;
1486 }
1487 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1488
1489 assert(pnum1 && pnum2);
1490 chunk = MIN(pnum1, pnum2);
1491
1492 if (strict) {
1493 if (status1 != status2) {
1494 ret = 1;
1495 qprintf(quiet, "Strict mode: Offset %" PRId64
1496 " block status mismatch!\n", offset);
1497 goto out;
1498 }
1499 }
1500 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1501 /* nothing to do */
1502 } else if (allocated1 == allocated2) {
1503 if (allocated1) {
1504 int64_t pnum;
1505
1506 chunk = MIN(chunk, IO_BUF_SIZE);
1507 ret = blk_pread(blk1, offset, buf1, chunk);
1508 if (ret < 0) {
1509 error_report("Error while reading offset %" PRId64
1510 " of %s: %s",
1511 offset, filename1, strerror(-ret));
1512 ret = 4;
1513 goto out;
1514 }
1515 ret = blk_pread(blk2, offset, buf2, chunk);
1516 if (ret < 0) {
1517 error_report("Error while reading offset %" PRId64
1518 " of %s: %s",
1519 offset, filename2, strerror(-ret));
1520 ret = 4;
1521 goto out;
1522 }
1523 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1524 if (ret || pnum != chunk) {
1525 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1526 offset + (ret ? 0 : pnum));
1527 ret = 1;
1528 goto out;
1529 }
1530 }
1531 } else {
1532 chunk = MIN(chunk, IO_BUF_SIZE);
1533 if (allocated1) {
1534 ret = check_empty_sectors(blk1, offset, chunk,
1535 filename1, buf1, quiet);
1536 } else {
1537 ret = check_empty_sectors(blk2, offset, chunk,
1538 filename2, buf1, quiet);
1539 }
1540 if (ret) {
1541 goto out;
1542 }
1543 }
1544 offset += chunk;
1545 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1546 }
1547
1548 if (total_size1 != total_size2) {
1549 BlockBackend *blk_over;
1550 const char *filename_over;
1551
1552 qprintf(quiet, "Warning: Image size mismatch!\n");
1553 if (total_size1 > total_size2) {
1554 blk_over = blk1;
1555 filename_over = filename1;
1556 } else {
1557 blk_over = blk2;
1558 filename_over = filename2;
1559 }
1560
1561 while (offset < progress_base) {
1562 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1563 progress_base - offset, &chunk,
1564 NULL, NULL);
1565 if (ret < 0) {
1566 ret = 3;
1567 error_report("Sector allocation test failed for %s",
1568 filename_over);
1569 goto out;
1570
1571 }
1572 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
1573 chunk = MIN(chunk, IO_BUF_SIZE);
1574 ret = check_empty_sectors(blk_over, offset, chunk,
1575 filename_over, buf1, quiet);
1576 if (ret) {
1577 goto out;
1578 }
1579 }
1580 offset += chunk;
1581 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
1582 }
1583 }
1584
1585 qprintf(quiet, "Images are identical.\n");
1586 ret = 0;
1587
1588 out:
1589 qemu_vfree(buf1);
1590 qemu_vfree(buf2);
1591 blk_unref(blk2);
1592 out2:
1593 blk_unref(blk1);
1594 out3:
1595 qemu_progress_end();
1596 return ret;
1597 }
1598
1599 /* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1600 static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1601 const char *src_node, const char *src_name,
1602 Error **errp)
1603 {
1604 BlockDirtyBitmapMergeSource *merge_src;
1605 BlockDirtyBitmapMergeSourceList *list = NULL;
1606
1607 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1608 merge_src->type = QTYPE_QDICT;
1609 merge_src->u.external.node = g_strdup(src_node);
1610 merge_src->u.external.name = g_strdup(src_name);
1611 QAPI_LIST_PREPEND(list, merge_src);
1612 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1613 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1614 }
1615
1616 enum ImgConvertBlockStatus {
1617 BLK_DATA,
1618 BLK_ZERO,
1619 BLK_BACKING_FILE,
1620 };
1621
1622 #define MAX_COROUTINES 16
1623 #define CONVERT_THROTTLE_GROUP "img_convert"
1624
1625 typedef struct ImgConvertState {
1626 BlockBackend **src;
1627 int64_t *src_sectors;
1628 int *src_alignment;
1629 int src_num;
1630 int64_t total_sectors;
1631 int64_t allocated_sectors;
1632 int64_t allocated_done;
1633 int64_t sector_num;
1634 int64_t wr_offs;
1635 enum ImgConvertBlockStatus status;
1636 int64_t sector_next_status;
1637 BlockBackend *target;
1638 bool has_zero_init;
1639 bool compressed;
1640 bool target_is_new;
1641 bool target_has_backing;
1642 int64_t target_backing_sectors; /* negative if unknown */
1643 bool wr_in_order;
1644 bool copy_range;
1645 bool salvage;
1646 bool quiet;
1647 int min_sparse;
1648 int alignment;
1649 size_t cluster_sectors;
1650 size_t buf_sectors;
1651 long num_coroutines;
1652 int running_coroutines;
1653 Coroutine *co[MAX_COROUTINES];
1654 int64_t wait_sector_num[MAX_COROUTINES];
1655 CoMutex lock;
1656 int ret;
1657 } ImgConvertState;
1658
1659 static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1660 int *src_cur, int64_t *src_cur_offset)
1661 {
1662 *src_cur = 0;
1663 *src_cur_offset = 0;
1664 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1665 *src_cur_offset += s->src_sectors[*src_cur];
1666 (*src_cur)++;
1667 assert(*src_cur < s->src_num);
1668 }
1669 }
1670
1671 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1672 {
1673 int64_t src_cur_offset;
1674 int ret, n, src_cur;
1675 bool post_backing_zero = false;
1676
1677 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1678
1679 assert(s->total_sectors > sector_num);
1680 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1681
1682 if (s->target_backing_sectors >= 0) {
1683 if (sector_num >= s->target_backing_sectors) {
1684 post_backing_zero = true;
1685 } else if (sector_num + n > s->target_backing_sectors) {
1686 /* Split requests around target_backing_sectors (because
1687 * starting from there, zeros are handled differently) */
1688 n = s->target_backing_sectors - sector_num;
1689 }
1690 }
1691
1692 if (s->sector_next_status <= sector_num) {
1693 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1694 int64_t count;
1695 int tail;
1696 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1697 BlockDriverState *base;
1698
1699 if (s->target_has_backing) {
1700 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1701 } else {
1702 base = NULL;
1703 }
1704
1705 do {
1706 count = n * BDRV_SECTOR_SIZE;
1707
1708 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1709 NULL, NULL);
1710
1711 if (ret < 0) {
1712 if (s->salvage) {
1713 if (n == 1) {
1714 if (!s->quiet) {
1715 warn_report("error while reading block status at "
1716 "offset %" PRIu64 ": %s", offset,
1717 strerror(-ret));
1718 }
1719 /* Just try to read the data, then */
1720 ret = BDRV_BLOCK_DATA;
1721 count = BDRV_SECTOR_SIZE;
1722 } else {
1723 /* Retry on a shorter range */
1724 n = DIV_ROUND_UP(n, 4);
1725 }
1726 } else {
1727 error_report("error while reading block status at offset "
1728 "%" PRIu64 ": %s", offset, strerror(-ret));
1729 return ret;
1730 }
1731 }
1732 } while (ret < 0);
1733
1734 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
1735
1736 /*
1737 * Avoid that s->sector_next_status becomes unaligned to the source
1738 * request alignment and/or cluster size to avoid unnecessary read
1739 * cycles.
1740 */
1741 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1742 if (n > tail) {
1743 n -= tail;
1744 }
1745
1746 if (ret & BDRV_BLOCK_ZERO) {
1747 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
1748 } else if (ret & BDRV_BLOCK_DATA) {
1749 s->status = BLK_DATA;
1750 } else {
1751 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
1752 }
1753
1754 s->sector_next_status = sector_num + n;
1755 }
1756
1757 n = MIN(n, s->sector_next_status - sector_num);
1758 if (s->status == BLK_DATA) {
1759 n = MIN(n, s->buf_sectors);
1760 }
1761
1762 /* We need to write complete clusters for compressed images, so if an
1763 * unallocated area is shorter than that, we must consider the whole
1764 * cluster allocated. */
1765 if (s->compressed) {
1766 if (n < s->cluster_sectors) {
1767 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1768 s->status = BLK_DATA;
1769 } else {
1770 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1771 }
1772 }
1773
1774 return n;
1775 }
1776
1777 static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1778 int nb_sectors, uint8_t *buf)
1779 {
1780 uint64_t single_read_until = 0;
1781 int n, ret;
1782
1783 assert(nb_sectors <= s->buf_sectors);
1784 while (nb_sectors > 0) {
1785 BlockBackend *blk;
1786 int src_cur;
1787 int64_t bs_sectors, src_cur_offset;
1788 uint64_t offset;
1789
1790 /* In the case of compression with multiple source files, we can get a
1791 * nb_sectors that spreads into the next part. So we must be able to
1792 * read across multiple BDSes for one convert_read() call. */
1793 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1794 blk = s->src[src_cur];
1795 bs_sectors = s->src_sectors[src_cur];
1796
1797 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1798
1799 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1800 if (single_read_until > offset) {
1801 n = 1;
1802 }
1803
1804 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
1805 if (ret < 0) {
1806 if (s->salvage) {
1807 if (n > 1) {
1808 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1809 continue;
1810 } else {
1811 if (!s->quiet) {
1812 warn_report("error while reading offset %" PRIu64
1813 ": %s", offset, strerror(-ret));
1814 }
1815 memset(buf, 0, BDRV_SECTOR_SIZE);
1816 }
1817 } else {
1818 return ret;
1819 }
1820 }
1821
1822 sector_num += n;
1823 nb_sectors -= n;
1824 buf += n * BDRV_SECTOR_SIZE;
1825 }
1826
1827 return 0;
1828 }
1829
1830
1831 static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1832 int nb_sectors, uint8_t *buf,
1833 enum ImgConvertBlockStatus status)
1834 {
1835 int ret;
1836
1837 while (nb_sectors > 0) {
1838 int n = nb_sectors;
1839 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1840
1841 switch (status) {
1842 case BLK_BACKING_FILE:
1843 /* If we have a backing file, leave clusters unallocated that are
1844 * unallocated in the source image, so that the backing file is
1845 * visible at the respective offset. */
1846 assert(s->target_has_backing);
1847 break;
1848
1849 case BLK_DATA:
1850 /* If we're told to keep the target fully allocated (-S 0) or there
1851 * is real non-zero data, we must write it. Otherwise we can treat
1852 * it as zero sectors.
1853 * Compressed clusters need to be written as a whole, so in that
1854 * case we can only save the write if the buffer is completely
1855 * zeroed. */
1856 if (!s->min_sparse ||
1857 (!s->compressed &&
1858 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1859 sector_num, s->alignment)) ||
1860 (s->compressed &&
1861 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
1862 {
1863 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1864 n << BDRV_SECTOR_BITS, buf, flags);
1865 if (ret < 0) {
1866 return ret;
1867 }
1868 break;
1869 }
1870 /* fall-through */
1871
1872 case BLK_ZERO:
1873 if (s->has_zero_init) {
1874 assert(!s->target_has_backing);
1875 break;
1876 }
1877 ret = blk_co_pwrite_zeroes(s->target,
1878 sector_num << BDRV_SECTOR_BITS,
1879 n << BDRV_SECTOR_BITS,
1880 BDRV_REQ_MAY_UNMAP);
1881 if (ret < 0) {
1882 return ret;
1883 }
1884 break;
1885 }
1886
1887 sector_num += n;
1888 nb_sectors -= n;
1889 buf += n * BDRV_SECTOR_SIZE;
1890 }
1891
1892 return 0;
1893 }
1894
1895 static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1896 int nb_sectors)
1897 {
1898 int n, ret;
1899
1900 while (nb_sectors > 0) {
1901 BlockBackend *blk;
1902 int src_cur;
1903 int64_t bs_sectors, src_cur_offset;
1904 int64_t offset;
1905
1906 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1907 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1908 blk = s->src[src_cur];
1909 bs_sectors = s->src_sectors[src_cur];
1910
1911 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1912
1913 ret = blk_co_copy_range(blk, offset, s->target,
1914 sector_num << BDRV_SECTOR_BITS,
1915 n << BDRV_SECTOR_BITS, 0, 0);
1916 if (ret < 0) {
1917 return ret;
1918 }
1919
1920 sector_num += n;
1921 nb_sectors -= n;
1922 }
1923 return 0;
1924 }
1925
1926 static void coroutine_fn convert_co_do_copy(void *opaque)
1927 {
1928 ImgConvertState *s = opaque;
1929 uint8_t *buf = NULL;
1930 int ret, i;
1931 int index = -1;
1932
1933 for (i = 0; i < s->num_coroutines; i++) {
1934 if (s->co[i] == qemu_coroutine_self()) {
1935 index = i;
1936 break;
1937 }
1938 }
1939 assert(index >= 0);
1940
1941 s->running_coroutines++;
1942 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1943
1944 while (1) {
1945 int n;
1946 int64_t sector_num;
1947 enum ImgConvertBlockStatus status;
1948 bool copy_range;
1949
1950 qemu_co_mutex_lock(&s->lock);
1951 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1952 qemu_co_mutex_unlock(&s->lock);
1953 break;
1954 }
1955 n = convert_iteration_sectors(s, s->sector_num);
1956 if (n < 0) {
1957 qemu_co_mutex_unlock(&s->lock);
1958 s->ret = n;
1959 break;
1960 }
1961 /* save current sector and allocation status to local variables */
1962 sector_num = s->sector_num;
1963 status = s->status;
1964 if (!s->min_sparse && s->status == BLK_ZERO) {
1965 n = MIN(n, s->buf_sectors);
1966 }
1967 /* increment global sector counter so that other coroutines can
1968 * already continue reading beyond this request */
1969 s->sector_num += n;
1970 qemu_co_mutex_unlock(&s->lock);
1971
1972 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1973 s->allocated_done += n;
1974 qemu_progress_print(100.0 * s->allocated_done /
1975 s->allocated_sectors, 0);
1976 }
1977
1978 retry:
1979 copy_range = s->copy_range && s->status == BLK_DATA;
1980 if (status == BLK_DATA && !copy_range) {
1981 ret = convert_co_read(s, sector_num, n, buf);
1982 if (ret < 0) {
1983 error_report("error while reading at byte %lld: %s",
1984 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
1985 s->ret = ret;
1986 }
1987 } else if (!s->min_sparse && status == BLK_ZERO) {
1988 status = BLK_DATA;
1989 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1990 }
1991
1992 if (s->wr_in_order) {
1993 /* keep writes in order */
1994 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
1995 s->wait_sector_num[index] = sector_num;
1996 qemu_coroutine_yield();
1997 }
1998 s->wait_sector_num[index] = -1;
1999 }
2000
2001 if (s->ret == -EINPROGRESS) {
2002 if (copy_range) {
2003 ret = convert_co_copy_range(s, sector_num, n);
2004 if (ret) {
2005 s->copy_range = false;
2006 goto retry;
2007 }
2008 } else {
2009 ret = convert_co_write(s, sector_num, n, buf, status);
2010 }
2011 if (ret < 0) {
2012 error_report("error while writing at byte %lld: %s",
2013 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
2014 s->ret = ret;
2015 }
2016 }
2017
2018 if (s->wr_in_order) {
2019 /* reenter the coroutine that might have waited
2020 * for this write to complete */
2021 s->wr_offs = sector_num + n;
2022 for (i = 0; i < s->num_coroutines; i++) {
2023 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2024 /*
2025 * A -> B -> A cannot occur because A has
2026 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2027 * B will never enter A during this time window.
2028 */
2029 qemu_coroutine_enter(s->co[i]);
2030 break;
2031 }
2032 }
2033 }
2034 }
2035
2036 qemu_vfree(buf);
2037 s->co[index] = NULL;
2038 s->running_coroutines--;
2039 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2040 /* the convert job finished successfully */
2041 s->ret = 0;
2042 }
2043 }
2044
2045 static int convert_do_copy(ImgConvertState *s)
2046 {
2047 int ret, i, n;
2048 int64_t sector_num = 0;
2049
2050 /* Check whether we have zero initialisation or can get it efficiently */
2051 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2052 !s->target_has_backing) {
2053 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
2054 }
2055
2056 /* Allocate buffer for copied data. For compressed images, only one cluster
2057 * can be copied at a time. */
2058 if (s->compressed) {
2059 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2060 error_report("invalid cluster size");
2061 return -EINVAL;
2062 }
2063 s->buf_sectors = s->cluster_sectors;
2064 }
2065
2066 while (sector_num < s->total_sectors) {
2067 n = convert_iteration_sectors(s, sector_num);
2068 if (n < 0) {
2069 return n;
2070 }
2071 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2072 {
2073 s->allocated_sectors += n;
2074 }
2075 sector_num += n;
2076 }
2077
2078 /* Do the copy */
2079 s->sector_next_status = 0;
2080 s->ret = -EINPROGRESS;
2081
2082 qemu_co_mutex_init(&s->lock);
2083 for (i = 0; i < s->num_coroutines; i++) {
2084 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2085 s->wait_sector_num[i] = -1;
2086 qemu_coroutine_enter(s->co[i]);
2087 }
2088
2089 while (s->running_coroutines) {
2090 main_loop_wait(false);
2091 }
2092
2093 if (s->compressed && !s->ret) {
2094 /* signal EOF to align */
2095 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
2096 if (ret < 0) {
2097 return ret;
2098 }
2099 }
2100
2101 return s->ret;
2102 }
2103
2104 /* Check that bitmaps can be copied, or output an error */
2105 static int convert_check_bitmaps(BlockDriverState *src)
2106 {
2107 BdrvDirtyBitmap *bm;
2108
2109 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2110 error_report("Source lacks bitmap support");
2111 return -1;
2112 }
2113 FOR_EACH_DIRTY_BITMAP(src, bm) {
2114 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2115 continue;
2116 }
2117 if (bdrv_dirty_bitmap_inconsistent(bm)) {
2118 error_report("Cannot copy inconsistent bitmap '%s'",
2119 bdrv_dirty_bitmap_name(bm));
2120 error_printf("Try 'qemu-img bitmap --remove' to delete it\n");
2121 return -1;
2122 }
2123 }
2124 return 0;
2125 }
2126
2127 static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2128 {
2129 BdrvDirtyBitmap *bm;
2130 Error *err = NULL;
2131
2132 FOR_EACH_DIRTY_BITMAP(src, bm) {
2133 const char *name;
2134
2135 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2136 continue;
2137 }
2138 name = bdrv_dirty_bitmap_name(bm);
2139 qmp_block_dirty_bitmap_add(dst->node_name, name,
2140 true, bdrv_dirty_bitmap_granularity(bm),
2141 true, true,
2142 true, !bdrv_dirty_bitmap_enabled(bm),
2143 &err);
2144 if (err) {
2145 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2146 return -1;
2147 }
2148
2149 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2150 &err);
2151 if (err) {
2152 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2153 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
2154 return -1;
2155 }
2156 }
2157
2158 return 0;
2159 }
2160
2161 #define MAX_BUF_SECTORS 32768
2162
2163 static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2164 {
2165 ThrottleConfig cfg;
2166
2167 throttle_config_init(&cfg);
2168 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2169
2170 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2171 blk_set_io_limits(blk, &cfg);
2172 }
2173
2174 static int img_convert(int argc, char **argv)
2175 {
2176 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
2177 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
2178 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2179 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
2180 BlockDriver *drv = NULL, *proto_drv = NULL;
2181 BlockDriverInfo bdi;
2182 BlockDriverState *out_bs;
2183 QemuOpts *opts = NULL, *sn_opts = NULL;
2184 QemuOptsList *create_opts = NULL;
2185 QDict *open_opts = NULL;
2186 char *options = NULL;
2187 Error *local_err = NULL;
2188 bool writethrough, src_writethrough, image_opts = false,
2189 skip_create = false, progress = false, tgt_image_opts = false;
2190 int64_t ret = -EINVAL;
2191 bool force_share = false;
2192 bool explict_min_sparse = false;
2193 bool bitmaps = false;
2194 int64_t rate_limit = 0;
2195
2196 ImgConvertState s = (ImgConvertState) {
2197 /* Need at least 4k of zeros for sparse detection */
2198 .min_sparse = 8,
2199 .copy_range = false,
2200 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2201 .wr_in_order = true,
2202 .num_coroutines = 8,
2203 };
2204
2205 for(;;) {
2206 static const struct option long_options[] = {
2207 {"help", no_argument, 0, 'h'},
2208 {"object", required_argument, 0, OPTION_OBJECT},
2209 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2210 {"force-share", no_argument, 0, 'U'},
2211 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
2212 {"salvage", no_argument, 0, OPTION_SALVAGE},
2213 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
2214 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
2215 {0, 0, 0, 0}
2216 };
2217 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
2218 long_options, NULL);
2219 if (c == -1) {
2220 break;
2221 }
2222 switch(c) {
2223 case ':':
2224 missing_argument(argv[optind - 1]);
2225 break;
2226 case '?':
2227 unrecognized_option(argv[optind - 1]);
2228 break;
2229 case 'h':
2230 help();
2231 break;
2232 case 'f':
2233 fmt = optarg;
2234 break;
2235 case 'O':
2236 out_fmt = optarg;
2237 break;
2238 case 'B':
2239 out_baseimg = optarg;
2240 break;
2241 case 'C':
2242 s.copy_range = true;
2243 break;
2244 case 'c':
2245 s.compressed = true;
2246 break;
2247 case 'o':
2248 if (accumulate_options(&options, optarg) < 0) {
2249 goto fail_getopt;
2250 }
2251 break;
2252 case 'l':
2253 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
2254 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2255 optarg, false);
2256 if (!sn_opts) {
2257 error_report("Failed in parsing snapshot param '%s'",
2258 optarg);
2259 goto fail_getopt;
2260 }
2261 } else {
2262 snapshot_name = optarg;
2263 }
2264 break;
2265 case 'S':
2266 {
2267 int64_t sval;
2268
2269 sval = cvtnum("buffer size for sparse output", optarg);
2270 if (sval < 0) {
2271 goto fail_getopt;
2272 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
2273 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2274 error_report("Invalid buffer size for sparse output specified. "
2275 "Valid sizes are multiples of %llu up to %llu. Select "
2276 "0 to disable sparse detection (fully allocates output).",
2277 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
2278 goto fail_getopt;
2279 }
2280
2281 s.min_sparse = sval / BDRV_SECTOR_SIZE;
2282 explict_min_sparse = true;
2283 break;
2284 }
2285 case 'p':
2286 progress = true;
2287 break;
2288 case 't':
2289 cache = optarg;
2290 break;
2291 case 'T':
2292 src_cache = optarg;
2293 break;
2294 case 'q':
2295 s.quiet = true;
2296 break;
2297 case 'n':
2298 skip_create = true;
2299 break;
2300 case 'm':
2301 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2302 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2303 error_report("Invalid number of coroutines. Allowed number of"
2304 " coroutines is between 1 and %d", MAX_COROUTINES);
2305 goto fail_getopt;
2306 }
2307 break;
2308 case 'W':
2309 s.wr_in_order = false;
2310 break;
2311 case 'U':
2312 force_share = true;
2313 break;
2314 case 'r':
2315 rate_limit = cvtnum("rate limit", optarg);
2316 if (rate_limit < 0) {
2317 goto fail_getopt;
2318 }
2319 break;
2320 case OPTION_OBJECT:
2321 user_creatable_process_cmdline(optarg);
2322 break;
2323 case OPTION_IMAGE_OPTS:
2324 image_opts = true;
2325 break;
2326 case OPTION_SALVAGE:
2327 s.salvage = true;
2328 break;
2329 case OPTION_TARGET_IMAGE_OPTS:
2330 tgt_image_opts = true;
2331 break;
2332 case OPTION_TARGET_IS_ZERO:
2333 /*
2334 * The user asserting that the target is blank has the
2335 * same effect as the target driver supporting zero
2336 * initialisation.
2337 */
2338 s.has_zero_init = true;
2339 break;
2340 case OPTION_BITMAPS:
2341 bitmaps = true;
2342 break;
2343 }
2344 }
2345
2346 if (!out_fmt && !tgt_image_opts) {
2347 out_fmt = "raw";
2348 }
2349
2350 if (s.compressed && s.copy_range) {
2351 error_report("Cannot enable copy offloading when -c is used");
2352 goto fail_getopt;
2353 }
2354
2355 if (explict_min_sparse && s.copy_range) {
2356 error_report("Cannot enable copy offloading when -S is used");
2357 goto fail_getopt;
2358 }
2359
2360 if (s.copy_range && s.salvage) {
2361 error_report("Cannot use copy offloading in salvaging mode");
2362 goto fail_getopt;
2363 }
2364
2365 if (tgt_image_opts && !skip_create) {
2366 error_report("--target-image-opts requires use of -n flag");
2367 goto fail_getopt;
2368 }
2369
2370 if (skip_create && options) {
2371 error_report("-o has no effect when skipping image creation");
2372 goto fail_getopt;
2373 }
2374
2375 if (s.has_zero_init && !skip_create) {
2376 error_report("--target-is-zero requires use of -n flag");
2377 goto fail_getopt;
2378 }
2379
2380 s.src_num = argc - optind - 1;
2381 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2382
2383 if (options && has_help_option(options)) {
2384 if (out_fmt) {
2385 ret = print_block_option_help(out_filename, out_fmt);
2386 goto fail_getopt;
2387 } else {
2388 error_report("Option help requires a format be specified");
2389 goto fail_getopt;
2390 }
2391 }
2392
2393 if (s.src_num < 1) {
2394 error_report("Must specify image file name");
2395 goto fail_getopt;
2396 }
2397
2398 /* ret is still -EINVAL until here */
2399 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2400 if (ret < 0) {
2401 error_report("Invalid source cache option: %s", src_cache);
2402 goto fail_getopt;
2403 }
2404
2405 /* Initialize before goto out */
2406 if (s.quiet) {
2407 progress = false;
2408 }
2409 qemu_progress_init(progress, 1.0);
2410 qemu_progress_print(0, 100);
2411
2412 s.src = g_new0(BlockBackend *, s.src_num);
2413 s.src_sectors = g_new(int64_t, s.src_num);
2414 s.src_alignment = g_new(int, s.src_num);
2415
2416 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2417 BlockDriverState *src_bs;
2418 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
2419 fmt, src_flags, src_writethrough, s.quiet,
2420 force_share);
2421 if (!s.src[bs_i]) {
2422 ret = -1;
2423 goto out;
2424 }
2425 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2426 if (s.src_sectors[bs_i] < 0) {
2427 error_report("Could not get size of %s: %s",
2428 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
2429 ret = -1;
2430 goto out;
2431 }
2432 src_bs = blk_bs(s.src[bs_i]);
2433 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2434 BDRV_SECTOR_SIZE);
2435 if (!bdrv_get_info(src_bs, &bdi)) {
2436 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2437 bdi.cluster_size / BDRV_SECTOR_SIZE);
2438 }
2439 s.total_sectors += s.src_sectors[bs_i];
2440 }
2441
2442 if (sn_opts) {
2443 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
2444 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2445 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2446 &local_err);
2447 } else if (snapshot_name != NULL) {
2448 if (s.src_num > 1) {
2449 error_report("No support for concatenating multiple snapshot");
2450 ret = -1;
2451 goto out;
2452 }
2453
2454 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2455 &local_err);
2456 }
2457 if (local_err) {
2458 error_reportf_err(local_err, "Failed to load snapshot: ");
2459 ret = -1;
2460 goto out;
2461 }
2462
2463 if (!skip_create) {
2464 /* Find driver and parse its options */
2465 drv = bdrv_find_format(out_fmt);
2466 if (!drv) {
2467 error_report("Unknown file format '%s'", out_fmt);
2468 ret = -1;
2469 goto out;
2470 }
2471
2472 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2473 if (!proto_drv) {
2474 error_report_err(local_err);
2475 ret = -1;
2476 goto out;
2477 }
2478
2479 if (!drv->create_opts) {
2480 error_report("Format driver '%s' does not support image creation",
2481 drv->format_name);
2482 ret = -1;
2483 goto out;
2484 }
2485
2486 if (!proto_drv->create_opts) {
2487 error_report("Protocol driver '%s' does not support image creation",
2488 proto_drv->format_name);
2489 ret = -1;
2490 goto out;
2491 }
2492
2493 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2494 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
2495
2496 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2497 if (options) {
2498 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
2499 error_report_err(local_err);
2500 ret = -1;
2501 goto out;
2502 }
2503 }
2504
2505 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2506 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
2507 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2508 if (ret < 0) {
2509 goto out;
2510 }
2511 }
2512
2513 /* Get backing file name if -o backing_file was used */
2514 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2515 if (out_baseimg_param) {
2516 out_baseimg = out_baseimg_param;
2517 }
2518 s.target_has_backing = (bool) out_baseimg;
2519
2520 if (s.has_zero_init && s.target_has_backing) {
2521 error_report("Cannot use --target-is-zero when the destination "
2522 "image has a backing file");
2523 goto out;
2524 }
2525
2526 if (s.src_num > 1 && out_baseimg) {
2527 error_report("Having a backing file for the target makes no sense when "
2528 "concatenating multiple input images");
2529 ret = -1;
2530 goto out;
2531 }
2532
2533 if (out_baseimg_param) {
2534 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2535 error_report("Use of backing file requires explicit "
2536 "backing format");
2537 ret = -1;
2538 goto out;
2539 }
2540 }
2541
2542 /* Check if compression is supported */
2543 if (s.compressed) {
2544 bool encryption =
2545 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2546 const char *encryptfmt =
2547 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2548 const char *preallocation =
2549 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2550
2551 if (drv && !block_driver_can_compress(drv)) {
2552 error_report("Compression not supported for this file format");
2553 ret = -1;
2554 goto out;
2555 }
2556
2557 if (encryption || encryptfmt) {
2558 error_report("Compression and encryption not supported at "
2559 "the same time");
2560 ret = -1;
2561 goto out;
2562 }
2563
2564 if (preallocation
2565 && strcmp(preallocation, "off"))
2566 {
2567 error_report("Compression and preallocation not supported at "
2568 "the same time");
2569 ret = -1;
2570 goto out;
2571 }
2572 }
2573
2574 /* Determine if bitmaps need copying */
2575 if (bitmaps) {
2576 if (s.src_num > 1) {
2577 error_report("Copying bitmaps only possible with single source");
2578 ret = -1;
2579 goto out;
2580 }
2581 ret = convert_check_bitmaps(blk_bs(s.src[0]));
2582 if (ret < 0) {
2583 goto out;
2584 }
2585 }
2586
2587 /*
2588 * The later open call will need any decryption secrets, and
2589 * bdrv_create() will purge "opts", so extract them now before
2590 * they are lost.
2591 */
2592 if (!skip_create) {
2593 open_opts = qdict_new();
2594 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2595
2596 /* Create the new image */
2597 ret = bdrv_create(drv, out_filename, opts, &local_err);
2598 if (ret < 0) {
2599 error_reportf_err(local_err, "%s: error while converting %s: ",
2600 out_filename, out_fmt);
2601 goto out;
2602 }
2603 }
2604
2605 s.target_is_new = !skip_create;
2606
2607 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2608 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2609 if (ret < 0) {
2610 error_report("Invalid cache option: %s", cache);
2611 goto out;
2612 }
2613
2614 if (skip_create) {
2615 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2616 flags, writethrough, s.quiet, false);
2617 } else {
2618 /* TODO ultimately we should allow --target-image-opts
2619 * to be used even when -n is not given.
2620 * That has to wait for bdrv_create to be improved
2621 * to allow filenames in option syntax
2622 */
2623 s.target = img_open_file(out_filename, open_opts, out_fmt,
2624 flags, writethrough, s.quiet, false);
2625 open_opts = NULL; /* blk_new_open will have freed it */
2626 }
2627 if (!s.target) {
2628 ret = -1;
2629 goto out;
2630 }
2631 out_bs = blk_bs(s.target);
2632
2633 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2634 error_report("Format driver '%s' does not support bitmaps",
2635 out_bs->drv->format_name);
2636 ret = -1;
2637 goto out;
2638 }
2639
2640 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
2641 error_report("Compression not supported for this file format");
2642 ret = -1;
2643 goto out;
2644 }
2645
2646 /* increase bufsectors from the default 4096 (2M) if opt_transfer
2647 * or discard_alignment of the out_bs is greater. Limit to
2648 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2649 s.buf_sectors = MIN(MAX_BUF_SECTORS,
2650 MAX(s.buf_sectors,
2651 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2652 out_bs->bl.pdiscard_alignment >>
2653 BDRV_SECTOR_BITS)));
2654
2655 /* try to align the write requests to the destination to avoid unnecessary
2656 * RMW cycles. */
2657 s.alignment = MAX(pow2floor(s.min_sparse),
2658 DIV_ROUND_UP(out_bs->bl.request_alignment,
2659 BDRV_SECTOR_SIZE));
2660 assert(is_power_of_2(s.alignment));
2661
2662 if (skip_create) {
2663 int64_t output_sectors = blk_nb_sectors(s.target);
2664 if (output_sectors < 0) {
2665 error_report("unable to get output image length: %s",
2666 strerror(-output_sectors));
2667 ret = -1;
2668 goto out;
2669 } else if (output_sectors < s.total_sectors) {
2670 error_report("output file is smaller than input file");
2671 ret = -1;
2672 goto out;
2673 }
2674 }
2675
2676 if (s.target_has_backing && s.target_is_new) {
2677 /* Errors are treated as "backing length unknown" (which means
2678 * s.target_backing_sectors has to be negative, which it will
2679 * be automatically). The backing file length is used only
2680 * for optimizations, so such a case is not fatal. */
2681 s.target_backing_sectors =
2682 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
2683 } else {
2684 s.target_backing_sectors = -1;
2685 }
2686
2687 ret = bdrv_get_info(out_bs, &bdi);
2688 if (ret < 0) {
2689 if (s.compressed) {
2690 error_report("could not get block driver info");
2691 goto out;
2692 }
2693 } else {
2694 s.compressed = s.compressed || bdi.needs_compressed_writes;
2695 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2696 }
2697
2698 if (rate_limit) {
2699 set_rate_limit(s.target, rate_limit);
2700 }
2701
2702 ret = convert_do_copy(&s);
2703
2704 /* Now copy the bitmaps */
2705 if (bitmaps && ret == 0) {
2706 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2707 }
2708
2709 out:
2710 if (!ret) {
2711 qemu_progress_print(100, 0);
2712 }
2713 qemu_progress_end();
2714 qemu_opts_del(opts);
2715 qemu_opts_free(create_opts);
2716 qobject_unref(open_opts);
2717 blk_unref(s.target);
2718 if (s.src) {
2719 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2720 blk_unref(s.src[bs_i]);
2721 }
2722 g_free(s.src);
2723 }
2724 g_free(s.src_sectors);
2725 g_free(s.src_alignment);
2726 fail_getopt:
2727 qemu_opts_del(sn_opts);
2728 g_free(options);
2729
2730 return !!ret;
2731 }
2732
2733
2734 static void dump_snapshots(BlockDriverState *bs)
2735 {
2736 QEMUSnapshotInfo *sn_tab, *sn;
2737 int nb_sns, i;
2738
2739 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2740 if (nb_sns <= 0)
2741 return;
2742 printf("Snapshot list:\n");
2743 bdrv_snapshot_dump(NULL);
2744 printf("\n");
2745 for(i = 0; i < nb_sns; i++) {
2746 sn = &sn_tab[i];
2747 bdrv_snapshot_dump(sn);
2748 printf("\n");
2749 }
2750 g_free(sn_tab);
2751 }
2752
2753 static void dump_json_image_info_list(ImageInfoList *list)
2754 {
2755 GString *str;
2756 QObject *obj;
2757 Visitor *v = qobject_output_visitor_new(&obj);
2758
2759 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2760 visit_complete(v, &obj);
2761 str = qobject_to_json_pretty(obj, true);
2762 assert(str != NULL);
2763 printf("%s\n", str->str);
2764 qobject_unref(obj);
2765 visit_free(v);
2766 g_string_free(str, true);
2767 }
2768
2769 static void dump_json_image_info(ImageInfo *info)
2770 {
2771 GString *str;
2772 QObject *obj;
2773 Visitor *v = qobject_output_visitor_new(&obj);
2774
2775 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2776 visit_complete(v, &obj);
2777 str = qobject_to_json_pretty(obj, true);
2778 assert(str != NULL);
2779 printf("%s\n", str->str);
2780 qobject_unref(obj);
2781 visit_free(v);
2782 g_string_free(str, true);
2783 }
2784
2785 static void dump_human_image_info_list(ImageInfoList *list)
2786 {
2787 ImageInfoList *elem;
2788 bool delim = false;
2789
2790 for (elem = list; elem; elem = elem->next) {
2791 if (delim) {
2792 printf("\n");
2793 }
2794 delim = true;
2795
2796 bdrv_image_info_dump(elem->value);
2797 }
2798 }
2799
2800 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2801 {
2802 return strcmp(a, b) == 0;
2803 }
2804
2805 /**
2806 * Open an image file chain and return an ImageInfoList
2807 *
2808 * @filename: topmost image filename
2809 * @fmt: topmost image format (may be NULL to autodetect)
2810 * @chain: true - enumerate entire backing file chain
2811 * false - only topmost image file
2812 *
2813 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2814 * image file. If there was an error a message will have been printed to
2815 * stderr.
2816 */
2817 static ImageInfoList *collect_image_info_list(bool image_opts,
2818 const char *filename,
2819 const char *fmt,
2820 bool chain, bool force_share)
2821 {
2822 ImageInfoList *head = NULL;
2823 ImageInfoList **tail = &head;
2824 GHashTable *filenames;
2825 Error *err = NULL;
2826
2827 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2828
2829 while (filename) {
2830 BlockBackend *blk;
2831 BlockDriverState *bs;
2832 ImageInfo *info;
2833
2834 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2835 error_report("Backing file '%s' creates an infinite loop.",
2836 filename);
2837 goto err;
2838 }
2839 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2840
2841 blk = img_open(image_opts, filename, fmt,
2842 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2843 force_share);
2844 if (!blk) {
2845 goto err;
2846 }
2847 bs = blk_bs(blk);
2848
2849 bdrv_query_image_info(bs, &info, &err);
2850 if (err) {
2851 error_report_err(err);
2852 blk_unref(blk);
2853 goto err;
2854 }
2855
2856 QAPI_LIST_APPEND(tail, info);
2857
2858 blk_unref(blk);
2859
2860 /* Clear parameters that only apply to the topmost image */
2861 filename = fmt = NULL;
2862 image_opts = false;
2863
2864 if (chain) {
2865 if (info->has_full_backing_filename) {
2866 filename = info->full_backing_filename;
2867 } else if (info->has_backing_filename) {
2868 error_report("Could not determine absolute backing filename,"
2869 " but backing filename '%s' present",
2870 info->backing_filename);
2871 goto err;
2872 }
2873 if (info->has_backing_filename_format) {
2874 fmt = info->backing_filename_format;
2875 }
2876 }
2877 }
2878 g_hash_table_destroy(filenames);
2879 return head;
2880
2881 err:
2882 qapi_free_ImageInfoList(head);
2883 g_hash_table_destroy(filenames);
2884 return NULL;
2885 }
2886
2887 static int img_info(int argc, char **argv)
2888 {
2889 int c;
2890 OutputFormat output_format = OFORMAT_HUMAN;
2891 bool chain = false;
2892 const char *filename, *fmt, *output;
2893 ImageInfoList *list;
2894 bool image_opts = false;
2895 bool force_share = false;
2896
2897 fmt = NULL;
2898 output = NULL;
2899 for(;;) {
2900 int option_index = 0;
2901 static const struct option long_options[] = {
2902 {"help", no_argument, 0, 'h'},
2903 {"format", required_argument, 0, 'f'},
2904 {"output", required_argument, 0, OPTION_OUTPUT},
2905 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2906 {"object", required_argument, 0, OPTION_OBJECT},
2907 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2908 {"force-share", no_argument, 0, 'U'},
2909 {0, 0, 0, 0}
2910 };
2911 c = getopt_long(argc, argv, ":f:hU",
2912 long_options, &option_index);
2913 if (c == -1) {
2914 break;
2915 }
2916 switch(c) {
2917 case ':':
2918 missing_argument(argv[optind - 1]);
2919 break;
2920 case '?':
2921 unrecognized_option(argv[optind - 1]);
2922 break;
2923 case 'h':
2924 help();
2925 break;
2926 case 'f':
2927 fmt = optarg;
2928 break;
2929 case 'U':
2930 force_share = true;
2931 break;
2932 case OPTION_OUTPUT:
2933 output = optarg;
2934 break;
2935 case OPTION_BACKING_CHAIN:
2936 chain = true;
2937 break;
2938 case OPTION_OBJECT:
2939 user_creatable_process_cmdline(optarg);
2940 break;
2941 case OPTION_IMAGE_OPTS:
2942 image_opts = true;
2943 break;
2944 }
2945 }
2946 if (optind != argc - 1) {
2947 error_exit("Expecting one image file name");
2948 }
2949 filename = argv[optind++];
2950
2951 if (output && !strcmp(output, "json")) {
2952 output_format = OFORMAT_JSON;
2953 } else if (output && !strcmp(output, "human")) {
2954 output_format = OFORMAT_HUMAN;
2955 } else if (output) {
2956 error_report("--output must be used with human or json as argument.");
2957 return 1;
2958 }
2959
2960 list = collect_image_info_list(image_opts, filename, fmt, chain,
2961 force_share);
2962 if (!list) {
2963 return 1;
2964 }
2965
2966 switch (output_format) {
2967 case OFORMAT_HUMAN:
2968 dump_human_image_info_list(list);
2969 break;
2970 case OFORMAT_JSON:
2971 if (chain) {
2972 dump_json_image_info_list(list);
2973 } else {
2974 dump_json_image_info(list->value);
2975 }
2976 break;
2977 }
2978
2979 qapi_free_ImageInfoList(list);
2980 return 0;
2981 }
2982
2983 static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2984 MapEntry *next)
2985 {
2986 switch (output_format) {
2987 case OFORMAT_HUMAN:
2988 if (e->data && !e->has_offset) {
2989 error_report("File contains external, encrypted or compressed clusters.");
2990 return -1;
2991 }
2992 if (e->data && !e->zero) {
2993 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2994 e->start, e->length,
2995 e->has_offset ? e->offset : 0,
2996 e->has_filename ? e->filename : "");
2997 }
2998 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2999 * Modify the flags here to allow more coalescing.
3000 */
3001 if (next && (!next->data || next->zero)) {
3002 next->data = false;
3003 next->zero = true;
3004 }
3005 break;
3006 case OFORMAT_JSON:
3007 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
3008 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3009 " \"data\": %s", e->start, e->length, e->depth,
3010 e->present ? "true" : "false",
3011 e->zero ? "true" : "false",
3012 e->data ? "true" : "false");
3013 if (e->has_offset) {
3014 printf(", \"offset\": %"PRId64"", e->offset);
3015 }
3016 putchar('}');
3017
3018 if (next) {
3019 puts(",");
3020 }
3021 break;
3022 }
3023 return 0;
3024 }
3025
3026 static int get_block_status(BlockDriverState *bs, int64_t offset,
3027 int64_t bytes, MapEntry *e)
3028 {
3029 int ret;
3030 int depth;
3031 BlockDriverState *file;
3032 bool has_offset;
3033 int64_t map;
3034 char *filename = NULL;
3035
3036 /* As an optimization, we could cache the current range of unallocated
3037 * clusters in each file of the chain, and avoid querying the same
3038 * range repeatedly.
3039 */
3040
3041 depth = 0;
3042 for (;;) {
3043 bs = bdrv_skip_filters(bs);
3044 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
3045 if (ret < 0) {
3046 return ret;
3047 }
3048 assert(bytes);
3049 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3050 break;
3051 }
3052 bs = bdrv_cow_bs(bs);
3053 if (bs == NULL) {
3054 ret = 0;
3055 break;
3056 }
3057
3058 depth++;
3059 }
3060
3061 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3062
3063 if (file && has_offset) {
3064 bdrv_refresh_filename(file);
3065 filename = file->filename;
3066 }
3067
3068 *e = (MapEntry) {
3069 .start = offset,
3070 .length = bytes,
3071 .data = !!(ret & BDRV_BLOCK_DATA),
3072 .zero = !!(ret & BDRV_BLOCK_ZERO),
3073 .offset = map,
3074 .has_offset = has_offset,
3075 .depth = depth,
3076 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
3077 .has_filename = filename,
3078 .filename = filename,
3079 };
3080
3081 return 0;
3082 }
3083
3084 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3085 {
3086 if (curr->length == 0) {
3087 return false;
3088 }
3089 if (curr->zero != next->zero ||
3090 curr->data != next->data ||
3091 curr->depth != next->depth ||
3092 curr->present != next->present ||
3093 curr->has_filename != next->has_filename ||
3094 curr->has_offset != next->has_offset) {
3095 return false;
3096 }
3097 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3098 return false;
3099 }
3100 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3101 return false;
3102 }
3103 return true;
3104 }
3105
3106 static int img_map(int argc, char **argv)
3107 {
3108 int c;
3109 OutputFormat output_format = OFORMAT_HUMAN;
3110 BlockBackend *blk;
3111 BlockDriverState *bs;
3112 const char *filename, *fmt, *output;
3113 int64_t length;
3114 MapEntry curr = { .length = 0 }, next;
3115 int ret = 0;
3116 bool image_opts = false;
3117 bool force_share = false;
3118 int64_t start_offset = 0;
3119 int64_t max_length = -1;
3120
3121 fmt = NULL;
3122 output = NULL;
3123 for (;;) {
3124 int option_index = 0;
3125 static const struct option long_options[] = {
3126 {"help", no_argument, 0, 'h'},
3127 {"format", required_argument, 0, 'f'},
3128 {"output", required_argument, 0, OPTION_OUTPUT},
3129 {"object", required_argument, 0, OPTION_OBJECT},
3130 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3131 {"force-share", no_argument, 0, 'U'},
3132 {"start-offset", required_argument, 0, 's'},
3133 {"max-length", required_argument, 0, 'l'},
3134 {0, 0, 0, 0}
3135 };
3136 c = getopt_long(argc, argv, ":f:s:l:hU",
3137 long_options, &option_index);
3138 if (c == -1) {
3139 break;
3140 }
3141 switch (c) {
3142 case ':':
3143 missing_argument(argv[optind - 1]);
3144 break;
3145 case '?':
3146 unrecognized_option(argv[optind - 1]);
3147 break;
3148 case 'h':
3149 help();
3150 break;
3151 case 'f':
3152 fmt = optarg;
3153 break;
3154 case 'U':
3155 force_share = true;
3156 break;
3157 case OPTION_OUTPUT:
3158 output = optarg;
3159 break;
3160 case 's':
3161 start_offset = cvtnum("start offset", optarg);
3162 if (start_offset < 0) {
3163 return 1;
3164 }
3165 break;
3166 case 'l':
3167 max_length = cvtnum("max length", optarg);
3168 if (max_length < 0) {
3169 return 1;
3170 }
3171 break;
3172 case OPTION_OBJECT:
3173 user_creatable_process_cmdline(optarg);
3174 break;
3175 case OPTION_IMAGE_OPTS:
3176 image_opts = true;
3177 break;
3178 }
3179 }
3180 if (optind != argc - 1) {
3181 error_exit("Expecting one image file name");
3182 }
3183 filename = argv[optind];
3184
3185 if (output && !strcmp(output, "json")) {
3186 output_format = OFORMAT_JSON;
3187 } else if (output && !strcmp(output, "human")) {
3188 output_format = OFORMAT_HUMAN;
3189 } else if (output) {
3190 error_report("--output must be used with human or json as argument.");
3191 return 1;
3192 }
3193
3194 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
3195 if (!blk) {
3196 return 1;
3197 }
3198 bs = blk_bs(blk);
3199
3200 if (output_format == OFORMAT_HUMAN) {
3201 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3202 } else if (output_format == OFORMAT_JSON) {
3203 putchar('[');
3204 }
3205
3206 length = blk_getlength(blk);
3207 if (length < 0) {
3208 error_report("Failed to get size for '%s'", filename);
3209 return 1;
3210 }
3211 if (max_length != -1) {
3212 length = MIN(start_offset + max_length, length);
3213 }
3214
3215 curr.start = start_offset;
3216 while (curr.start + curr.length < length) {
3217 int64_t offset = curr.start + curr.length;
3218 int64_t n = length - offset;
3219
3220 ret = get_block_status(bs, offset, n, &next);
3221 if (ret < 0) {
3222 error_report("Could not read file metadata: %s", strerror(-ret));
3223 goto out;
3224 }
3225
3226 if (entry_mergeable(&curr, &next)) {
3227 curr.length += next.length;
3228 continue;
3229 }
3230
3231 if (curr.length > 0) {
3232 ret = dump_map_entry(output_format, &curr, &next);
3233 if (ret < 0) {
3234 goto out;
3235 }
3236 }
3237 curr = next;
3238 }
3239
3240 ret = dump_map_entry(output_format, &curr, NULL);
3241 if (output_format == OFORMAT_JSON) {
3242 puts("]");
3243 }
3244
3245 out:
3246 blk_unref(blk);
3247 return ret < 0;
3248 }
3249
3250 #define SNAPSHOT_LIST 1
3251 #define SNAPSHOT_CREATE 2
3252 #define SNAPSHOT_APPLY 3
3253 #define SNAPSHOT_DELETE 4
3254
3255 static int img_snapshot(int argc, char **argv)
3256 {
3257 BlockBackend *blk;
3258 BlockDriverState *bs;
3259 QEMUSnapshotInfo sn;
3260 char *filename, *snapshot_name = NULL;
3261 int c, ret = 0, bdrv_oflags;
3262 int action = 0;
3263 qemu_timeval tv;
3264 bool quiet = false;
3265 Error *err = NULL;
3266 bool image_opts = false;
3267 bool force_share = false;
3268
3269 bdrv_oflags = BDRV_O_RDWR;
3270 /* Parse commandline parameters */
3271 for(;;) {
3272 static const struct option long_options[] = {
3273 {"help", no_argument, 0, 'h'},
3274 {"object", required_argument, 0, OPTION_OBJECT},
3275 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3276 {"force-share", no_argument, 0, 'U'},
3277 {0, 0, 0, 0}
3278 };
3279 c = getopt_long(argc, argv, ":la:c:d:hqU",
3280 long_options, NULL);
3281 if (c == -1) {
3282 break;
3283 }
3284 switch(c) {
3285 case ':':
3286 missing_argument(argv[optind - 1]);
3287 break;
3288 case '?':
3289 unrecognized_option(argv[optind - 1]);
3290 break;
3291 case 'h':
3292 help();
3293 return 0;
3294 case 'l':
3295 if (action) {
3296 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3297 return 0;
3298 }
3299 action = SNAPSHOT_LIST;
3300 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
3301 break;
3302 case 'a':
3303 if (action) {
3304 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3305 return 0;
3306 }
3307 action = SNAPSHOT_APPLY;
3308 snapshot_name = optarg;
3309 break;
3310 case 'c':
3311 if (action) {
3312 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3313 return 0;
3314 }
3315 action = SNAPSHOT_CREATE;
3316 snapshot_name = optarg;
3317 break;
3318 case 'd':
3319 if (action) {
3320 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
3321 return 0;
3322 }
3323 action = SNAPSHOT_DELETE;
3324 snapshot_name = optarg;
3325 break;
3326 case 'q':
3327 quiet = true;
3328 break;
3329 case 'U':
3330 force_share = true;
3331 break;
3332 case OPTION_OBJECT:
3333 user_creatable_process_cmdline(optarg);
3334 break;
3335 case OPTION_IMAGE_OPTS:
3336 image_opts = true;
3337 break;
3338 }
3339 }
3340
3341 if (optind != argc - 1) {
3342 error_exit("Expecting one image file name");
3343 }
3344 filename = argv[optind++];
3345
3346 /* Open the image */
3347 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3348 force_share);
3349 if (!blk) {
3350 return 1;
3351 }
3352 bs = blk_bs(blk);
3353
3354 /* Perform the requested action */
3355 switch(action) {
3356 case SNAPSHOT_LIST:
3357 dump_snapshots(bs);
3358 break;
3359
3360 case SNAPSHOT_CREATE:
3361 memset(&sn, 0, sizeof(sn));
3362 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3363
3364 qemu_gettimeofday(&tv);
3365 sn.date_sec = tv.tv_sec;
3366 sn.date_nsec = tv.tv_usec * 1000;
3367
3368 ret = bdrv_snapshot_create(bs, &sn);
3369 if (ret) {
3370 error_report("Could not create snapshot '%s': %d (%s)",
3371 snapshot_name, ret, strerror(-ret));
3372 }
3373 break;
3374
3375 case SNAPSHOT_APPLY:
3376 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
3377 if (ret) {
3378 error_reportf_err(err, "Could not apply snapshot '%s': ",
3379 snapshot_name);
3380 }
3381 break;
3382
3383 case SNAPSHOT_DELETE:
3384 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3385 if (ret < 0) {
3386 error_report("Could not delete snapshot '%s': snapshot not "
3387 "found", snapshot_name);
3388 ret = 1;
3389 } else {
3390 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3391 if (ret < 0) {
3392 error_reportf_err(err, "Could not delete snapshot '%s': ",
3393 snapshot_name);
3394 ret = 1;
3395 }
3396 }
3397 break;
3398 }
3399
3400 /* Cleanup */
3401 blk_unref(blk);
3402 if (ret) {
3403 return 1;
3404 }
3405 return 0;
3406 }
3407
3408 static int img_rebase(int argc, char **argv)
3409 {
3410 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
3411 uint8_t *buf_old = NULL;
3412 uint8_t *buf_new = NULL;
3413 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3414 BlockDriverState *unfiltered_bs;
3415 char *filename;
3416 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3417 int c, flags, src_flags, ret;
3418 bool writethrough, src_writethrough;
3419 int unsafe = 0;
3420 bool force_share = false;
3421 int progress = 0;
3422 bool quiet = false;
3423 Error *local_err = NULL;
3424 bool image_opts = false;
3425
3426 /* Parse commandline parameters */
3427 fmt = NULL;
3428 cache = BDRV_DEFAULT_CACHE;
3429 src_cache = BDRV_DEFAULT_CACHE;
3430 out_baseimg = NULL;
3431 out_basefmt = NULL;
3432 for(;;) {
3433 static const struct option long_options[] = {
3434 {"help", no_argument, 0, 'h'},
3435 {"object", required_argument, 0, OPTION_OBJECT},
3436 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3437 {"force-share", no_argument, 0, 'U'},
3438 {0, 0, 0, 0}
3439 };
3440 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3441 long_options, NULL);
3442 if (c == -1) {
3443 break;
3444 }
3445 switch(c) {
3446 case ':':
3447 missing_argument(argv[optind - 1]);
3448 break;
3449 case '?':
3450 unrecognized_option(argv[optind - 1]);
3451 break;
3452 case 'h':
3453 help();
3454 return 0;
3455 case 'f':
3456 fmt = optarg;
3457 break;
3458 case 'F':
3459 out_basefmt = optarg;
3460 break;
3461 case 'b':
3462 out_baseimg = optarg;
3463 break;
3464 case 'u':
3465 unsafe = 1;
3466 break;
3467 case 'p':
3468 progress = 1;
3469 break;
3470 case 't':
3471 cache = optarg;
3472 break;
3473 case 'T':
3474 src_cache = optarg;
3475 break;
3476 case 'q':
3477 quiet = true;
3478 break;
3479 case OPTION_OBJECT:
3480 user_creatable_process_cmdline(optarg);
3481 break;
3482 case OPTION_IMAGE_OPTS:
3483 image_opts = true;
3484 break;
3485 case 'U':
3486 force_share = true;
3487 break;
3488 }
3489 }
3490
3491 if (quiet) {
3492 progress = 0;
3493 }
3494
3495 if (optind != argc - 1) {
3496 error_exit("Expecting one image file name");
3497 }
3498 if (!unsafe && !out_baseimg) {
3499 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
3500 }
3501 filename = argv[optind++];
3502
3503 qemu_progress_init(progress, 2.0);
3504 qemu_progress_print(0, 100);
3505
3506 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
3507 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3508 if (ret < 0) {
3509 error_report("Invalid cache option: %s", cache);
3510 goto out;
3511 }
3512
3513 src_flags = 0;
3514 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
3515 if (ret < 0) {
3516 error_report("Invalid source cache option: %s", src_cache);
3517 goto out;
3518 }
3519
3520 /* The source files are opened read-only, don't care about WCE */
3521 assert((src_flags & BDRV_O_RDWR) == 0);
3522 (void) src_writethrough;
3523
3524 /*
3525 * Open the images.
3526 *
3527 * Ignore the old backing file for unsafe rebase in case we want to correct
3528 * the reference to a renamed or moved backing file.
3529 */
3530 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3531 false);
3532 if (!blk) {
3533 ret = -1;
3534 goto out;
3535 }
3536 bs = blk_bs(blk);
3537
3538 unfiltered_bs = bdrv_skip_filters(bs);
3539
3540 if (out_basefmt != NULL) {
3541 if (bdrv_find_format(out_basefmt) == NULL) {
3542 error_report("Invalid format name: '%s'", out_basefmt);
3543 ret = -1;
3544 goto out;
3545 }
3546 }
3547
3548 /* For safe rebasing we need to compare old and new backing file */
3549 if (!unsafe) {
3550 QDict *options = NULL;
3551 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
3552
3553 if (base_bs) {
3554 blk_old_backing = blk_new(qemu_get_aio_context(),
3555 BLK_PERM_CONSISTENT_READ,
3556 BLK_PERM_ALL);
3557 ret = blk_insert_bs(blk_old_backing, base_bs,
3558 &local_err);
3559 if (ret < 0) {
3560 error_reportf_err(local_err,
3561 "Could not reuse old backing file '%s': ",
3562 base_bs->filename);
3563 goto out;
3564 }
3565 } else {
3566 blk_old_backing = NULL;
3567 }
3568
3569 if (out_baseimg[0]) {
3570 const char *overlay_filename;
3571 char *out_real_path;
3572
3573 options = qdict_new();
3574 if (out_basefmt) {
3575 qdict_put_str(options, "driver", out_basefmt);
3576 }
3577 if (force_share) {
3578 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
3579 }
3580
3581 bdrv_refresh_filename(bs);
3582 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3583 : bs->filename;
3584 out_real_path =
3585 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3586 out_baseimg,
3587 &local_err);
3588 if (local_err) {
3589 qobject_unref(options);
3590 error_reportf_err(local_err,
3591 "Could not resolve backing filename: ");
3592 ret = -1;
3593 goto out;
3594 }
3595
3596 /*
3597 * Find out whether we rebase an image on top of a previous image
3598 * in its chain.
3599 */
3600 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
3601 if (prefix_chain_bs) {
3602 qobject_unref(options);
3603 g_free(out_real_path);
3604
3605 blk_new_backing = blk_new(qemu_get_aio_context(),
3606 BLK_PERM_CONSISTENT_READ,
3607 BLK_PERM_ALL);
3608 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3609 &local_err);
3610 if (ret < 0) {
3611 error_reportf_err(local_err,
3612 "Could not reuse backing file '%s': ",
3613 out_baseimg);
3614 goto out;
3615 }
3616 } else {
3617 blk_new_backing = blk_new_open(out_real_path, NULL,
3618 options, src_flags, &local_err);
3619 g_free(out_real_path);
3620 if (!blk_new_backing) {
3621 error_reportf_err(local_err,
3622 "Could not open new backing file '%s': ",
3623 out_baseimg);
3624 ret = -1;
3625 goto out;
3626 }
3627 }
3628 }
3629 }
3630
3631 /*
3632 * Check each unallocated cluster in the COW file. If it is unallocated,
3633 * accesses go to the backing file. We must therefore compare this cluster
3634 * in the old and new backing file, and if they differ we need to copy it
3635 * from the old backing file into the COW file.
3636 *
3637 * If qemu-img crashes during this step, no harm is done. The content of
3638 * the image is the same as the original one at any time.
3639 */
3640 if (!unsafe) {
3641 int64_t size;
3642 int64_t old_backing_size = 0;
3643 int64_t new_backing_size = 0;
3644 uint64_t offset;
3645 int64_t n;
3646 float local_progress = 0;
3647
3648 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3649 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3650
3651 size = blk_getlength(blk);
3652 if (size < 0) {
3653 error_report("Could not get size of '%s': %s",
3654 filename, strerror(-size));
3655 ret = -1;
3656 goto out;
3657 }
3658 if (blk_old_backing) {
3659 old_backing_size = blk_getlength(blk_old_backing);
3660 if (old_backing_size < 0) {
3661 char backing_name[PATH_MAX];
3662
3663 bdrv_get_backing_filename(bs, backing_name,
3664 sizeof(backing_name));
3665 error_report("Could not get size of '%s': %s",
3666 backing_name, strerror(-old_backing_size));
3667 ret = -1;
3668 goto out;
3669 }
3670 }
3671 if (blk_new_backing) {
3672 new_backing_size = blk_getlength(blk_new_backing);
3673 if (new_backing_size < 0) {
3674 error_report("Could not get size of '%s': %s",
3675 out_baseimg, strerror(-new_backing_size));
3676 ret = -1;
3677 goto out;
3678 }
3679 }
3680
3681 if (size != 0) {
3682 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
3683 }
3684
3685 for (offset = 0; offset < size; offset += n) {
3686 bool buf_old_is_zero = false;
3687
3688 /* How many bytes can we handle with the next read? */
3689 n = MIN(IO_BUF_SIZE, size - offset);
3690
3691 /* If the cluster is allocated, we don't need to take action */
3692 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
3693 if (ret < 0) {
3694 error_report("error while reading image metadata: %s",
3695 strerror(-ret));
3696 goto out;
3697 }
3698 if (ret) {
3699 continue;
3700 }
3701
3702 if (prefix_chain_bs) {
3703 /*
3704 * If cluster wasn't changed since prefix_chain, we don't need
3705 * to take action
3706 */
3707 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3708 prefix_chain_bs, false,
3709 offset, n, &n);
3710 if (ret < 0) {
3711 error_report("error while reading image metadata: %s",
3712 strerror(-ret));
3713 goto out;
3714 }
3715 if (!ret) {
3716 continue;
3717 }
3718 }
3719
3720 /*
3721 * Read old and new backing file and take into consideration that
3722 * backing files may be smaller than the COW image.
3723 */
3724 if (offset >= old_backing_size) {
3725 memset(buf_old, 0, n);
3726 buf_old_is_zero = true;
3727 } else {
3728 if (offset + n > old_backing_size) {
3729 n = old_backing_size - offset;
3730 }
3731
3732 ret = blk_pread(blk_old_backing, offset, buf_old, n);
3733 if (ret < 0) {
3734 error_report("error while reading from old backing file");
3735 goto out;
3736 }
3737 }
3738
3739 if (offset >= new_backing_size || !blk_new_backing) {
3740 memset(buf_new, 0, n);
3741 } else {
3742 if (offset + n > new_backing_size) {
3743 n = new_backing_size - offset;
3744 }
3745
3746 ret = blk_pread(blk_new_backing, offset, buf_new, n);
3747 if (ret < 0) {
3748 error_report("error while reading from new backing file");
3749 goto out;
3750 }
3751 }
3752
3753 /* If they differ, we need to write to the COW file */
3754 uint64_t written = 0;
3755
3756 while (written < n) {
3757 int64_t pnum;
3758
3759 if (compare_buffers(buf_old + written, buf_new + written,
3760 n - written, &pnum))
3761 {
3762 if (buf_old_is_zero) {
3763 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3764 } else {
3765 ret = blk_pwrite(blk, offset + written,
3766 buf_old + written, pnum, 0);
3767 }
3768 if (ret < 0) {
3769 error_report("Error while writing to COW image: %s",
3770 strerror(-ret));
3771 goto out;
3772 }
3773 }
3774
3775 written += pnum;
3776 }
3777 qemu_progress_print(local_progress, 100);
3778 }
3779 }
3780
3781 /*
3782 * Change the backing file. All clusters that are different from the old
3783 * backing file are overwritten in the COW file now, so the visible content
3784 * doesn't change when we switch the backing file.
3785 */
3786 if (out_baseimg && *out_baseimg) {
3787 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3788 true);
3789 } else {
3790 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
3791 }
3792
3793 if (ret == -ENOSPC) {
3794 error_report("Could not change the backing file to '%s': No "
3795 "space left in the file header", out_baseimg);
3796 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3797 error_report("Could not change the backing file to '%s': backing "
3798 "format must be specified", out_baseimg);
3799 } else if (ret < 0) {
3800 error_report("Could not change the backing file to '%s': %s",
3801 out_baseimg, strerror(-ret));
3802 }
3803
3804 qemu_progress_print(100, 0);
3805 /*
3806 * TODO At this point it is possible to check if any clusters that are
3807 * allocated in the COW file are the same in the backing file. If so, they
3808 * could be dropped from the COW file. Don't do this before switching the
3809 * backing file, in case of a crash this would lead to corruption.
3810 */
3811 out:
3812 qemu_progress_end();
3813 /* Cleanup */
3814 if (!unsafe) {
3815 blk_unref(blk_old_backing);
3816 blk_unref(blk_new_backing);
3817 }
3818 qemu_vfree(buf_old);
3819 qemu_vfree(buf_new);
3820
3821 blk_unref(blk);
3822 if (ret) {
3823 return 1;
3824 }
3825 return 0;
3826 }
3827
3828 static int img_resize(int argc, char **argv)
3829 {
3830 Error *err = NULL;
3831 int c, ret, relative;
3832 const char *filename, *fmt, *size;
3833 int64_t n, total_size, current_size;
3834 bool quiet = false;
3835 BlockBackend *blk = NULL;
3836 PreallocMode prealloc = PREALLOC_MODE_OFF;
3837 QemuOpts *param;
3838
3839 static QemuOptsList resize_options = {
3840 .name = "resize_options",
3841 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3842 .desc = {
3843 {
3844 .name = BLOCK_OPT_SIZE,
3845 .type = QEMU_OPT_SIZE,
3846 .help = "Virtual disk size"
3847 }, {
3848 /* end of list */
3849 }
3850 },
3851 };
3852 bool image_opts = false;
3853 bool shrink = false;
3854
3855 /* Remove size from argv manually so that negative numbers are not treated
3856 * as options by getopt. */
3857 if (argc < 3) {
3858 error_exit("Not enough arguments");
3859 return 1;
3860 }
3861
3862 size = argv[--argc];
3863
3864 /* Parse getopt arguments */
3865 fmt = NULL;
3866 for(;;) {
3867 static const struct option long_options[] = {
3868 {"help", no_argument, 0, 'h'},
3869 {"object", required_argument, 0, OPTION_OBJECT},
3870 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3871 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
3872 {"shrink", no_argument, 0, OPTION_SHRINK},
3873 {0, 0, 0, 0}
3874 };
3875 c = getopt_long(argc, argv, ":f:hq",
3876 long_options, NULL);
3877 if (c == -1) {
3878 break;
3879 }
3880 switch(c) {
3881 case ':':
3882 missing_argument(argv[optind - 1]);
3883 break;
3884 case '?':
3885 unrecognized_option(argv[optind - 1]);
3886 break;
3887 case 'h':
3888 help();
3889 break;
3890 case 'f':
3891 fmt = optarg;
3892 break;
3893 case 'q':
3894 quiet = true;
3895 break;
3896 case OPTION_OBJECT:
3897 user_creatable_process_cmdline(optarg);
3898 break;
3899 case OPTION_IMAGE_OPTS:
3900 image_opts = true;
3901 break;
3902 case OPTION_PREALLOCATION:
3903 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
3904 PREALLOC_MODE__MAX, NULL);
3905 if (prealloc == PREALLOC_MODE__MAX) {
3906 error_report("Invalid preallocation mode '%s'", optarg);
3907 return 1;
3908 }
3909 break;
3910 case OPTION_SHRINK:
3911 shrink = true;
3912 break;
3913 }
3914 }
3915 if (optind != argc - 1) {
3916 error_exit("Expecting image file name and size");
3917 }
3918 filename = argv[optind++];
3919
3920 /* Choose grow, shrink, or absolute resize mode */
3921 switch (size[0]) {
3922 case '+':
3923 relative = 1;
3924 size++;
3925 break;
3926 case '-':
3927 relative = -1;
3928 size++;
3929 break;
3930 default:
3931 relative = 0;
3932 break;
3933 }
3934
3935 /* Parse size */
3936 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3937 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
3938 error_report_err(err);
3939 ret = -1;
3940 qemu_opts_del(param);
3941 goto out;
3942 }
3943 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3944 qemu_opts_del(param);
3945
3946 blk = img_open(image_opts, filename, fmt,
3947 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3948 false);
3949 if (!blk) {
3950 ret = -1;
3951 goto out;
3952 }
3953
3954 current_size = blk_getlength(blk);
3955 if (current_size < 0) {
3956 error_report("Failed to inquire current image length: %s",
3957 strerror(-current_size));
3958 ret = -1;
3959 goto out;
3960 }
3961
3962 if (relative) {
3963 total_size = current_size + n * relative;
3964 } else {
3965 total_size = n;
3966 }
3967 if (total_size <= 0) {
3968 error_report("New image size must be positive");
3969 ret = -1;
3970 goto out;
3971 }
3972
3973 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3974 error_report("Preallocation can only be used for growing images");
3975 ret = -1;
3976 goto out;
3977 }
3978
3979 if (total_size < current_size && !shrink) {
3980 error_report("Use the --shrink option to perform a shrink operation.");
3981 warn_report("Shrinking an image will delete all data beyond the "
3982 "shrunken image's end. Before performing such an "
3983 "operation, make sure there is no important data there.");
3984 ret = -1;
3985 goto out;
3986 }
3987
3988 /*
3989 * The user expects the image to have the desired size after
3990 * resizing, so pass @exact=true. It is of no use to report
3991 * success when the image has not actually been resized.
3992 */
3993 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
3994 if (!ret) {
3995 qprintf(quiet, "Image resized.\n");
3996 } else {
3997 error_report_err(err);
3998 }
3999 out:
4000 blk_unref(blk);
4001 if (ret) {
4002 return 1;
4003 }
4004 return 0;
4005 }
4006
4007 static void amend_status_cb(BlockDriverState *bs,
4008 int64_t offset, int64_t total_work_size,
4009 void *opaque)
4010 {
4011 qemu_progress_print(100.f * offset / total_work_size, 0);
4012 }
4013
4014 static int print_amend_option_help(const char *format)
4015 {
4016 BlockDriver *drv;
4017
4018 /* Find driver and parse its options */
4019 drv = bdrv_find_format(format);
4020 if (!drv) {
4021 error_report("Unknown file format '%s'", format);
4022 return 1;
4023 }
4024
4025 if (!drv->bdrv_amend_options) {
4026 error_report("Format driver '%s' does not support option amendment",
4027 format);
4028 return 1;
4029 }
4030
4031 /* Every driver supporting amendment must have amend_opts */
4032 assert(drv->amend_opts);
4033
4034 printf("Amend options for '%s':\n", format);
4035 qemu_opts_print_help(drv->amend_opts, false);
4036 return 0;
4037 }
4038
4039 static int img_amend(int argc, char **argv)
4040 {
4041 Error *err = NULL;
4042 int c, ret = 0;
4043 char *options = NULL;
4044 QemuOptsList *amend_opts = NULL;
4045 QemuOpts *opts = NULL;
4046 const char *fmt = NULL, *filename, *cache;
4047 int flags;
4048 bool writethrough;
4049 bool quiet = false, progress = false;
4050 BlockBackend *blk = NULL;
4051 BlockDriverState *bs = NULL;
4052 bool image_opts = false;
4053 bool force = false;
4054
4055 cache = BDRV_DEFAULT_CACHE;
4056 for (;;) {
4057 static const struct option long_options[] = {
4058 {"help", no_argument, 0, 'h'},
4059 {"object", required_argument, 0, OPTION_OBJECT},
4060 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4061 {"force", no_argument, 0, OPTION_FORCE},
4062 {0, 0, 0, 0}
4063 };
4064 c = getopt_long(argc, argv, ":ho:f:t:pq",
4065 long_options, NULL);
4066 if (c == -1) {
4067 break;
4068 }
4069
4070 switch (c) {
4071 case ':':
4072 missing_argument(argv[optind - 1]);
4073 break;
4074 case '?':
4075 unrecognized_option(argv[optind - 1]);
4076 break;
4077 case 'h':
4078 help();
4079 break;
4080 case 'o':
4081 if (accumulate_options(&options, optarg) < 0) {
4082 ret = -1;
4083 goto out_no_progress;
4084 }
4085 break;
4086 case 'f':
4087 fmt = optarg;
4088 break;
4089 case 't':
4090 cache = optarg;
4091 break;
4092 case 'p':
4093 progress = true;
4094 break;
4095 case 'q':
4096 quiet = true;
4097 break;
4098 case OPTION_OBJECT:
4099 user_creatable_process_cmdline(optarg);
4100 break;
4101 case OPTION_IMAGE_OPTS:
4102 image_opts = true;
4103 break;
4104 case OPTION_FORCE:
4105 force = true;
4106 break;
4107 }
4108 }
4109
4110 if (!options) {
4111 error_exit("Must specify options (-o)");
4112 }
4113
4114 if (quiet) {
4115 progress = false;
4116 }
4117 qemu_progress_init(progress, 1.0);
4118
4119 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4120 if (fmt && has_help_option(options)) {
4121 /* If a format is explicitly specified (and possibly no filename is
4122 * given), print option help here */
4123 ret = print_amend_option_help(fmt);
4124 goto out;
4125 }
4126
4127 if (optind != argc - 1) {
4128 error_report("Expecting one image file name");
4129 ret = -1;
4130 goto out;
4131 }
4132
4133 flags = BDRV_O_RDWR;
4134 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
4135 if (ret < 0) {
4136 error_report("Invalid cache option: %s", cache);
4137 goto out;
4138 }
4139
4140 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4141 false);
4142 if (!blk) {
4143 ret = -1;
4144 goto out;
4145 }
4146 bs = blk_bs(blk);
4147
4148 fmt = bs->drv->format_name;
4149
4150 if (has_help_option(options)) {
4151 /* If the format was auto-detected, print option help here */
4152 ret = print_amend_option_help(fmt);
4153 goto out;
4154 }
4155
4156 if (!bs->drv->bdrv_amend_options) {
4157 error_report("Format driver '%s' does not support option amendment",
4158 fmt);
4159 ret = -1;
4160 goto out;
4161 }
4162
4163 /* Every driver supporting amendment must have amend_opts */
4164 assert(bs->drv->amend_opts);
4165
4166 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4167 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4168 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
4169 /* Try to parse options using the create options */
4170 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4171 qemu_opts_del(opts);
4172 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4173 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
4174 error_append_hint(&err,
4175 "This option is only supported for image creation\n");
4176 }
4177
4178 error_report_err(err);
4179 ret = -1;
4180 goto out;
4181 }
4182
4183 /* In case the driver does not call amend_status_cb() */
4184 qemu_progress_print(0.f, 0);
4185 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
4186 qemu_progress_print(100.f, 0);
4187 if (ret < 0) {
4188 error_report_err(err);
4189 goto out;
4190 }
4191
4192 out:
4193 qemu_progress_end();
4194
4195 out_no_progress:
4196 blk_unref(blk);
4197 qemu_opts_del(opts);
4198 qemu_opts_free(amend_opts);
4199 g_free(options);
4200
4201 if (ret) {
4202 return 1;
4203 }
4204 return 0;
4205 }
4206
4207 typedef struct BenchData {
4208 BlockBackend *blk;
4209 uint64_t image_size;
4210 bool write;
4211 int bufsize;
4212 int step;
4213 int nrreq;
4214 int n;
4215 int flush_interval;
4216 bool drain_on_flush;
4217 uint8_t *buf;
4218 QEMUIOVector *qiov;
4219
4220 int in_flight;
4221 bool in_flush;
4222 uint64_t offset;
4223 } BenchData;
4224
4225 static void bench_undrained_flush_cb(void *opaque, int ret)
4226 {
4227 if (ret < 0) {
4228 error_report("Failed flush request: %s", strerror(-ret));
4229 exit(EXIT_FAILURE);
4230 }
4231 }
4232
4233 static void bench_cb(void *opaque, int ret)
4234 {
4235 BenchData *b = opaque;
4236 BlockAIOCB *acb;
4237
4238 if (ret < 0) {
4239 error_report("Failed request: %s", strerror(-ret));
4240 exit(EXIT_FAILURE);
4241 }
4242
4243 if (b->in_flush) {
4244 /* Just finished a flush with drained queue: Start next requests */
4245 assert(b->in_flight == 0);
4246 b->in_flush = false;
4247 } else if (b->in_flight > 0) {
4248 int remaining = b->n - b->in_flight;
4249
4250 b->n--;
4251 b->in_flight--;
4252
4253 /* Time for flush? Drain queue if requested, then flush */
4254 if (b->flush_interval && remaining % b->flush_interval == 0) {
4255 if (!b->in_flight || !b->drain_on_flush) {
4256 BlockCompletionFunc *cb;
4257
4258 if (b->drain_on_flush) {
4259 b->in_flush = true;
4260 cb = bench_cb;
4261 } else {
4262 cb = bench_undrained_flush_cb;
4263 }
4264
4265 acb = blk_aio_flush(b->blk, cb, b);
4266 if (!acb) {
4267 error_report("Failed to issue flush request");
4268 exit(EXIT_FAILURE);
4269 }
4270 }
4271 if (b->drain_on_flush) {
4272 return;
4273 }
4274 }
4275 }
4276
4277 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4278 int64_t offset = b->offset;
4279 /* blk_aio_* might look for completed I/Os and kick bench_cb
4280 * again, so make sure this operation is counted by in_flight
4281 * and b->offset is ready for the next submission.
4282 */
4283 b->in_flight++;
4284 b->offset += b->step;
4285 b->offset %= b->image_size;
4286 if (b->write) {
4287 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
4288 } else {
4289 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
4290 }
4291 if (!acb) {
4292 error_report("Failed to issue request");
4293 exit(EXIT_FAILURE);
4294 }
4295 }
4296 }
4297
4298 static int img_bench(int argc, char **argv)
4299 {
4300 int c, ret = 0;
4301 const char *fmt = NULL, *filename;
4302 bool quiet = false;
4303 bool image_opts = false;
4304 bool is_write = false;
4305 int count = 75000;
4306 int depth = 64;
4307 int64_t offset = 0;
4308 size_t bufsize = 4096;
4309 int pattern = 0;
4310 size_t step = 0;
4311 int flush_interval = 0;
4312 bool drain_on_flush = true;
4313 int64_t image_size;
4314 BlockBackend *blk = NULL;
4315 BenchData data = {};
4316 int flags = 0;
4317 bool writethrough = false;
4318 struct timeval t1, t2;
4319 int i;
4320 bool force_share = false;
4321 size_t buf_size;
4322
4323 for (;;) {
4324 static const struct option long_options[] = {
4325 {"help", no_argument, 0, 'h'},
4326 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
4327 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4328 {"pattern", required_argument, 0, OPTION_PATTERN},
4329 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
4330 {"force-share", no_argument, 0, 'U'},
4331 {0, 0, 0, 0}
4332 };
4333 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4334 NULL);
4335 if (c == -1) {
4336 break;
4337 }
4338
4339 switch (c) {
4340 case ':':
4341 missing_argument(argv[optind - 1]);
4342 break;
4343 case '?':
4344 unrecognized_option(argv[optind - 1]);
4345 break;
4346 case 'h':
4347 help();
4348 break;
4349 case 'c':
4350 {
4351 unsigned long res;
4352
4353 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4354 error_report("Invalid request count specified");
4355 return 1;
4356 }
4357 count = res;
4358 break;
4359 }
4360 case 'd':
4361 {
4362 unsigned long res;
4363
4364 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4365 error_report("Invalid queue depth specified");
4366 return 1;
4367 }
4368 depth = res;
4369 break;
4370 }
4371 case 'f':
4372 fmt = optarg;
4373 break;
4374 case 'n':
4375 flags |= BDRV_O_NATIVE_AIO;
4376 break;
4377 case 'i':
4378 ret = bdrv_parse_aio(optarg, &flags);
4379 if (ret < 0) {
4380 error_report("Invalid aio option: %s", optarg);
4381 ret = -1;
4382 goto out;
4383 }
4384 break;
4385 case 'o':
4386 {
4387 offset = cvtnum("offset", optarg);
4388 if (offset < 0) {
4389 return 1;
4390 }
4391 break;
4392 }
4393 break;
4394 case 'q':
4395 quiet = true;
4396 break;
4397 case 's':
4398 {
4399 int64_t sval;
4400
4401 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4402 if (sval < 0) {
4403 return 1;
4404 }
4405
4406 bufsize = sval;
4407 break;
4408 }
4409 case 'S':
4410 {
4411 int64_t sval;
4412
4413 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4414 if (sval < 0) {
4415 return 1;
4416 }
4417
4418 step = sval;
4419 break;
4420 }
4421 case 't':
4422 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4423 if (ret < 0) {
4424 error_report("Invalid cache mode");
4425 ret = -1;
4426 goto out;
4427 }
4428 break;
4429 case 'w':
4430 flags |= BDRV_O_RDWR;
4431 is_write = true;
4432 break;
4433 case 'U':
4434 force_share = true;
4435 break;
4436 case OPTION_PATTERN:
4437 {
4438 unsigned long res;
4439
4440 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
4441 error_report("Invalid pattern byte specified");
4442 return 1;
4443 }
4444 pattern = res;
4445 break;
4446 }
4447 case OPTION_FLUSH_INTERVAL:
4448 {
4449 unsigned long res;
4450
4451 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
4452 error_report("Invalid flush interval specified");
4453 return 1;
4454 }
4455 flush_interval = res;
4456 break;
4457 }
4458 case OPTION_NO_DRAIN:
4459 drain_on_flush = false;
4460 break;
4461 case OPTION_IMAGE_OPTS:
4462 image_opts = true;
4463 break;
4464 }
4465 }
4466
4467 if (optind != argc - 1) {
4468 error_exit("Expecting one image file name");
4469 }
4470 filename = argv[argc - 1];
4471
4472 if (!is_write && flush_interval) {
4473 error_report("--flush-interval is only available in write tests");
4474 ret = -1;
4475 goto out;
4476 }
4477 if (flush_interval && flush_interval < depth) {
4478 error_report("Flush interval can't be smaller than depth");
4479 ret = -1;
4480 goto out;
4481 }
4482
4483 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4484 force_share);
4485 if (!blk) {
4486 ret = -1;
4487 goto out;
4488 }
4489
4490 image_size = blk_getlength(blk);
4491 if (image_size < 0) {
4492 ret = image_size;
4493 goto out;
4494 }
4495
4496 data = (BenchData) {
4497 .blk = blk,
4498 .image_size = image_size,
4499 .bufsize = bufsize,
4500 .step = step ?: bufsize,
4501 .nrreq = depth,
4502 .n = count,
4503 .offset = offset,
4504 .write = is_write,
4505 .flush_interval = flush_interval,
4506 .drain_on_flush = drain_on_flush,
4507 };
4508 printf("Sending %d %s requests, %d bytes each, %d in parallel "
4509 "(starting at offset %" PRId64 ", step size %d)\n",
4510 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
4511 data.offset, data.step);
4512 if (flush_interval) {
4513 printf("Sending flush every %d requests\n", flush_interval);
4514 }
4515
4516 buf_size = data.nrreq * data.bufsize;
4517 data.buf = blk_blockalign(blk, buf_size);
4518 memset(data.buf, pattern, data.nrreq * data.bufsize);
4519
4520 blk_register_buf(blk, data.buf, buf_size);
4521
4522 data.qiov = g_new(QEMUIOVector, data.nrreq);
4523 for (i = 0; i < data.nrreq; i++) {
4524 qemu_iovec_init(&data.qiov[i], 1);
4525 qemu_iovec_add(&data.qiov[i],
4526 data.buf + i * data.bufsize, data.bufsize);
4527 }
4528
4529 gettimeofday(&t1, NULL);
4530 bench_cb(&data, 0);
4531
4532 while (data.n > 0) {
4533 main_loop_wait(false);
4534 }
4535 gettimeofday(&t2, NULL);
4536
4537 printf("Run completed in %3.3f seconds.\n",
4538 (t2.tv_sec - t1.tv_sec)
4539 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4540
4541 out:
4542 if (data.buf) {
4543 blk_unregister_buf(blk, data.buf);
4544 }
4545 qemu_vfree(data.buf);
4546 blk_unref(blk);
4547
4548 if (ret) {
4549 return 1;
4550 }
4551 return 0;
4552 }
4553
4554 enum ImgBitmapAct {
4555 BITMAP_ADD,
4556 BITMAP_REMOVE,
4557 BITMAP_CLEAR,
4558 BITMAP_ENABLE,
4559 BITMAP_DISABLE,
4560 BITMAP_MERGE,
4561 };
4562 typedef struct ImgBitmapAction {
4563 enum ImgBitmapAct act;
4564 const char *src; /* only used for merge */
4565 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4566 } ImgBitmapAction;
4567
4568 static int img_bitmap(int argc, char **argv)
4569 {
4570 Error *err = NULL;
4571 int c, ret = 1;
4572 QemuOpts *opts = NULL;
4573 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4574 const char *filename, *bitmap;
4575 BlockBackend *blk = NULL, *src = NULL;
4576 BlockDriverState *bs = NULL, *src_bs = NULL;
4577 bool image_opts = false;
4578 int64_t granularity = 0;
4579 bool add = false, merge = false;
4580 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4581 ImgBitmapAction *act, *act_next;
4582 const char *op;
4583
4584 QSIMPLEQ_INIT(&actions);
4585
4586 for (;;) {
4587 static const struct option long_options[] = {
4588 {"help", no_argument, 0, 'h'},
4589 {"object", required_argument, 0, OPTION_OBJECT},
4590 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4591 {"add", no_argument, 0, OPTION_ADD},
4592 {"remove", no_argument, 0, OPTION_REMOVE},
4593 {"clear", no_argument, 0, OPTION_CLEAR},
4594 {"enable", no_argument, 0, OPTION_ENABLE},
4595 {"disable", no_argument, 0, OPTION_DISABLE},
4596 {"merge", required_argument, 0, OPTION_MERGE},
4597 {"granularity", required_argument, 0, 'g'},
4598 {"source-file", required_argument, 0, 'b'},
4599 {"source-format", required_argument, 0, 'F'},
4600 {0, 0, 0, 0}
4601 };
4602 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4603 if (c == -1) {
4604 break;
4605 }
4606
4607 switch (c) {
4608 case ':':
4609 missing_argument(argv[optind - 1]);
4610 break;
4611 case '?':
4612 unrecognized_option(argv[optind - 1]);
4613 break;
4614 case 'h':
4615 help();
4616 break;
4617 case 'b':
4618 src_filename = optarg;
4619 break;
4620 case 'f':
4621 fmt = optarg;
4622 break;
4623 case 'F':
4624 src_fmt = optarg;
4625 break;
4626 case 'g':
4627 granularity = cvtnum("granularity", optarg);
4628 if (granularity < 0) {
4629 return 1;
4630 }
4631 break;
4632 case OPTION_ADD:
4633 act = g_new0(ImgBitmapAction, 1);
4634 act->act = BITMAP_ADD;
4635 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4636 add = true;
4637 break;
4638 case OPTION_REMOVE:
4639 act = g_new0(ImgBitmapAction, 1);
4640 act->act = BITMAP_REMOVE;
4641 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4642 break;
4643 case OPTION_CLEAR:
4644 act = g_new0(ImgBitmapAction, 1);
4645 act->act = BITMAP_CLEAR;
4646 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4647 break;
4648 case OPTION_ENABLE:
4649 act = g_new0(ImgBitmapAction, 1);
4650 act->act = BITMAP_ENABLE;
4651 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4652 break;
4653 case OPTION_DISABLE:
4654 act = g_new0(ImgBitmapAction, 1);
4655 act->act = BITMAP_DISABLE;
4656 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4657 break;
4658 case OPTION_MERGE:
4659 act = g_new0(ImgBitmapAction, 1);
4660 act->act = BITMAP_MERGE;
4661 act->src = optarg;
4662 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4663 merge = true;
4664 break;
4665 case OPTION_OBJECT:
4666 user_creatable_process_cmdline(optarg);
4667 break;
4668 case OPTION_IMAGE_OPTS:
4669 image_opts = true;
4670 break;
4671 }
4672 }
4673
4674 if (QSIMPLEQ_EMPTY(&actions)) {
4675 error_report("Need at least one of --add, --remove, --clear, "
4676 "--enable, --disable, or --merge");
4677 goto out;
4678 }
4679
4680 if (granularity && !add) {
4681 error_report("granularity only supported with --add");
4682 goto out;
4683 }
4684 if (src_fmt && !src_filename) {
4685 error_report("-F only supported with -b");
4686 goto out;
4687 }
4688 if (src_filename && !merge) {
4689 error_report("Merge bitmap source file only supported with "
4690 "--merge");
4691 goto out;
4692 }
4693
4694 if (optind != argc - 2) {
4695 error_report("Expecting filename and bitmap name");
4696 goto out;
4697 }
4698
4699 filename = argv[optind];
4700 bitmap = argv[optind + 1];
4701
4702 /*
4703 * No need to open backing chains; we will be manipulating bitmaps
4704 * directly in this image without reference to image contents.
4705 */
4706 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4707 false, false, false);
4708 if (!blk) {
4709 goto out;
4710 }
4711 bs = blk_bs(blk);
4712 if (src_filename) {
4713 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4714 false, false, false);
4715 if (!src) {
4716 goto out;
4717 }
4718 src_bs = blk_bs(src);
4719 } else {
4720 src_bs = bs;
4721 }
4722
4723 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4724 switch (act->act) {
4725 case BITMAP_ADD:
4726 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4727 !!granularity, granularity, true, true,
4728 false, false, &err);
4729 op = "add";
4730 break;
4731 case BITMAP_REMOVE:
4732 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4733 op = "remove";
4734 break;
4735 case BITMAP_CLEAR:
4736 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4737 op = "clear";
4738 break;
4739 case BITMAP_ENABLE:
4740 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4741 op = "enable";
4742 break;
4743 case BITMAP_DISABLE:
4744 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4745 op = "disable";
4746 break;
4747 case BITMAP_MERGE:
4748 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4749 act->src, &err);
4750 op = "merge";
4751 break;
4752 default:
4753 g_assert_not_reached();
4754 }
4755
4756 if (err) {
4757 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4758 op, bitmap);
4759 goto out;
4760 }
4761 g_free(act);
4762 }
4763
4764 ret = 0;
4765
4766 out:
4767 blk_unref(src);
4768 blk_unref(blk);
4769 qemu_opts_del(opts);
4770 return ret;
4771 }
4772
4773 #define C_BS 01
4774 #define C_COUNT 02
4775 #define C_IF 04
4776 #define C_OF 010
4777 #define C_SKIP 020
4778
4779 struct DdInfo {
4780 unsigned int flags;
4781 int64_t count;
4782 };
4783
4784 struct DdIo {
4785 int bsz; /* Block size */
4786 char *filename;
4787 uint8_t *buf;
4788 int64_t offset;
4789 };
4790
4791 struct DdOpts {
4792 const char *name;
4793 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4794 unsigned int flag;
4795 };
4796
4797 static int img_dd_bs(const char *arg,
4798 struct DdIo *in, struct DdIo *out,
4799 struct DdInfo *dd)
4800 {
4801 int64_t res;
4802
4803 res = cvtnum_full("bs", arg, 1, INT_MAX);
4804
4805 if (res < 0) {
4806 return 1;
4807 }
4808 in->bsz = out->bsz = res;
4809
4810 return 0;
4811 }
4812
4813 static int img_dd_count(const char *arg,
4814 struct DdIo *in, struct DdIo *out,
4815 struct DdInfo *dd)
4816 {
4817 dd->count = cvtnum("count", arg);
4818
4819 if (dd->count < 0) {
4820 return 1;
4821 }
4822
4823 return 0;
4824 }
4825
4826 static int img_dd_if(const char *arg,
4827 struct DdIo *in, struct DdIo *out,
4828 struct DdInfo *dd)
4829 {
4830 in->filename = g_strdup(arg);
4831
4832 return 0;
4833 }
4834
4835 static int img_dd_of(const char *arg,
4836 struct DdIo *in, struct DdIo *out,
4837 struct DdInfo *dd)
4838 {
4839 out->filename = g_strdup(arg);
4840
4841 return 0;
4842 }
4843
4844 static int img_dd_skip(const char *arg,
4845 struct DdIo *in, struct DdIo *out,
4846 struct DdInfo *dd)
4847 {
4848 in->offset = cvtnum("skip", arg);
4849
4850 if (in->offset < 0) {
4851 return 1;
4852 }
4853
4854 return 0;
4855 }
4856
4857 static int img_dd(int argc, char **argv)
4858 {
4859 int ret = 0;
4860 char *arg = NULL;
4861 char *tmp;
4862 BlockDriver *drv = NULL, *proto_drv = NULL;
4863 BlockBackend *blk1 = NULL, *blk2 = NULL;
4864 QemuOpts *opts = NULL;
4865 QemuOptsList *create_opts = NULL;
4866 Error *local_err = NULL;
4867 bool image_opts = false;
4868 int c, i;
4869 const char *out_fmt = "raw";
4870 const char *fmt = NULL;
4871 int64_t size = 0;
4872 int64_t block_count = 0, out_pos, in_pos;
4873 bool force_share = false;
4874 struct DdInfo dd = {
4875 .flags = 0,
4876 .count = 0,
4877 };
4878 struct DdIo in = {
4879 .bsz = 512, /* Block size is by default 512 bytes */
4880 .filename = NULL,
4881 .buf = NULL,
4882 .offset = 0
4883 };
4884 struct DdIo out = {
4885 .bsz = 512,
4886 .filename = NULL,
4887 .buf = NULL,
4888 .offset = 0
4889 };
4890
4891 const struct DdOpts options[] = {
4892 { "bs", img_dd_bs, C_BS },
4893 { "count", img_dd_count, C_COUNT },
4894 { "if", img_dd_if, C_IF },
4895 { "of", img_dd_of, C_OF },
4896 { "skip", img_dd_skip, C_SKIP },
4897 { NULL, NULL, 0 }
4898 };
4899 const struct option long_options[] = {
4900 { "help", no_argument, 0, 'h'},
4901 { "object", required_argument, 0, OPTION_OBJECT},
4902 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4903 { "force-share", no_argument, 0, 'U'},
4904 { 0, 0, 0, 0 }
4905 };
4906
4907 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
4908 if (c == EOF) {
4909 break;
4910 }
4911 switch (c) {
4912 case 'O':
4913 out_fmt = optarg;
4914 break;
4915 case 'f':
4916 fmt = optarg;
4917 break;
4918 case ':':
4919 missing_argument(argv[optind - 1]);
4920 break;
4921 case '?':
4922 unrecognized_option(argv[optind - 1]);
4923 break;
4924 case 'h':
4925 help();
4926 break;
4927 case 'U':
4928 force_share = true;
4929 break;
4930 case OPTION_OBJECT:
4931 user_creatable_process_cmdline(optarg);
4932 break;
4933 case OPTION_IMAGE_OPTS:
4934 image_opts = true;
4935 break;
4936 }
4937 }
4938
4939 for (i = optind; i < argc; i++) {
4940 int j;
4941 arg = g_strdup(argv[i]);
4942
4943 tmp = strchr(arg, '=');
4944 if (tmp == NULL) {
4945 error_report("unrecognized operand %s", arg);
4946 ret = -1;
4947 goto out;
4948 }
4949
4950 *tmp++ = '\0';
4951
4952 for (j = 0; options[j].name != NULL; j++) {
4953 if (!strcmp(arg, options[j].name)) {
4954 break;
4955 }
4956 }
4957 if (options[j].name == NULL) {
4958 error_report("unrecognized operand %s", arg);
4959 ret = -1;
4960 goto out;
4961 }
4962
4963 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4964 ret = -1;
4965 goto out;
4966 }
4967 dd.flags |= options[j].flag;
4968 g_free(arg);
4969 arg = NULL;
4970 }
4971
4972 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4973 error_report("Must specify both input and output files");
4974 ret = -1;
4975 goto out;
4976 }
4977
4978 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4979 force_share);
4980
4981 if (!blk1) {
4982 ret = -1;
4983 goto out;
4984 }
4985
4986 drv = bdrv_find_format(out_fmt);
4987 if (!drv) {
4988 error_report("Unknown file format");
4989 ret = -1;
4990 goto out;
4991 }
4992 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4993
4994 if (!proto_drv) {
4995 error_report_err(local_err);
4996 ret = -1;
4997 goto out;
4998 }
4999 if (!drv->create_opts) {
5000 error_report("Format driver '%s' does not support image creation",
5001 drv->format_name);
5002 ret = -1;
5003 goto out;
5004 }
5005 if (!proto_drv->create_opts) {
5006 error_report("Protocol driver '%s' does not support image creation",
5007 proto_drv->format_name);
5008 ret = -1;
5009 goto out;
5010 }
5011 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5012 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5013
5014 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5015
5016 size = blk_getlength(blk1);
5017 if (size < 0) {
5018 error_report("Failed to get size for '%s'", in.filename);
5019 ret = -1;
5020 goto out;
5021 }
5022
5023 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5024 dd.count * in.bsz < size) {
5025 size = dd.count * in.bsz;
5026 }
5027
5028 /* Overflow means the specified offset is beyond input image's size */
5029 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5030 size < in.bsz * in.offset)) {
5031 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5032 } else {
5033 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5034 size - in.bsz * in.offset, &error_abort);
5035 }
5036
5037 ret = bdrv_create(drv, out.filename, opts, &local_err);
5038 if (ret < 0) {
5039 error_reportf_err(local_err,
5040 "%s: error while creating output image: ",
5041 out.filename);
5042 ret = -1;
5043 goto out;
5044 }
5045
5046 /* TODO, we can't honour --image-opts for the target,
5047 * since it needs to be given in a format compatible
5048 * with the bdrv_create() call above which does not
5049 * support image-opts style.
5050 */
5051 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
5052 false, false, false);
5053
5054 if (!blk2) {
5055 ret = -1;
5056 goto out;
5057 }
5058
5059 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5060 size < in.offset * in.bsz)) {
5061 /* We give a warning if the skip option is bigger than the input
5062 * size and create an empty output disk image (i.e. like dd(1)).
5063 */
5064 error_report("%s: cannot skip to specified offset", in.filename);
5065 in_pos = size;
5066 } else {
5067 in_pos = in.offset * in.bsz;
5068 }
5069
5070 in.buf = g_new(uint8_t, in.bsz);
5071
5072 for (out_pos = 0; in_pos < size; block_count++) {
5073 int in_ret, out_ret;
5074
5075 if (in_pos + in.bsz > size) {
5076 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5077 } else {
5078 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5079 }
5080 if (in_ret < 0) {
5081 error_report("error while reading from input image file: %s",
5082 strerror(-in_ret));
5083 ret = -1;
5084 goto out;
5085 }
5086 in_pos += in_ret;
5087
5088 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5089
5090 if (out_ret < 0) {
5091 error_report("error while writing to output image file: %s",
5092 strerror(-out_ret));
5093 ret = -1;
5094 goto out;
5095 }
5096 out_pos += out_ret;
5097 }
5098
5099 out:
5100 g_free(arg);
5101 qemu_opts_del(opts);
5102 qemu_opts_free(create_opts);
5103 blk_unref(blk1);
5104 blk_unref(blk2);
5105 g_free(in.filename);
5106 g_free(out.filename);
5107 g_free(in.buf);
5108 g_free(out.buf);
5109
5110 if (ret) {
5111 return 1;
5112 }
5113 return 0;
5114 }
5115
5116 static void dump_json_block_measure_info(BlockMeasureInfo *info)
5117 {
5118 GString *str;
5119 QObject *obj;
5120 Visitor *v = qobject_output_visitor_new(&obj);
5121
5122 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5123 visit_complete(v, &obj);
5124 str = qobject_to_json_pretty(obj, true);
5125 assert(str != NULL);
5126 printf("%s\n", str->str);
5127 qobject_unref(obj);
5128 visit_free(v);
5129 g_string_free(str, true);
5130 }
5131
5132 static int img_measure(int argc, char **argv)
5133 {
5134 static const struct option long_options[] = {
5135 {"help", no_argument, 0, 'h'},
5136 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5137 {"object", required_argument, 0, OPTION_OBJECT},
5138 {"output", required_argument, 0, OPTION_OUTPUT},
5139 {"size", required_argument, 0, OPTION_SIZE},
5140 {"force-share", no_argument, 0, 'U'},
5141 {0, 0, 0, 0}
5142 };
5143 OutputFormat output_format = OFORMAT_HUMAN;
5144 BlockBackend *in_blk = NULL;
5145 BlockDriver *drv;
5146 const char *filename = NULL;
5147 const char *fmt = NULL;
5148 const char *out_fmt = "raw";
5149 char *options = NULL;
5150 char *snapshot_name = NULL;
5151 bool force_share = false;
5152 QemuOpts *opts = NULL;
5153 QemuOpts *object_opts = NULL;
5154 QemuOpts *sn_opts = NULL;
5155 QemuOptsList *create_opts = NULL;
5156 bool image_opts = false;
5157 uint64_t img_size = UINT64_MAX;
5158 BlockMeasureInfo *info = NULL;
5159 Error *local_err = NULL;
5160 int ret = 1;
5161 int c;
5162
5163 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5164 long_options, NULL)) != -1) {
5165 switch (c) {
5166 case '?':
5167 case 'h':
5168 help();
5169 break;
5170 case 'f':
5171 fmt = optarg;
5172 break;
5173 case 'O':
5174 out_fmt = optarg;
5175 break;
5176 case 'o':
5177 if (accumulate_options(&options, optarg) < 0) {
5178 goto out;
5179 }
5180 break;
5181 case 'l':
5182 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5183 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5184 optarg, false);
5185 if (!sn_opts) {
5186 error_report("Failed in parsing snapshot param '%s'",
5187 optarg);
5188 goto out;
5189 }
5190 } else {
5191 snapshot_name = optarg;
5192 }
5193 break;
5194 case 'U':
5195 force_share = true;
5196 break;
5197 case OPTION_OBJECT:
5198 user_creatable_process_cmdline(optarg);
5199 break;
5200 case OPTION_IMAGE_OPTS:
5201 image_opts = true;
5202 break;
5203 case OPTION_OUTPUT:
5204 if (!strcmp(optarg, "json")) {
5205 output_format = OFORMAT_JSON;
5206 } else if (!strcmp(optarg, "human")) {
5207 output_format = OFORMAT_HUMAN;
5208 } else {
5209 error_report("--output must be used with human or json "
5210 "as argument.");
5211 goto out;
5212 }
5213 break;
5214 case OPTION_SIZE:
5215 {
5216 int64_t sval;
5217
5218 sval = cvtnum("image size", optarg);
5219 if (sval < 0) {
5220 goto out;
5221 }
5222 img_size = (uint64_t)sval;
5223 }
5224 break;
5225 }
5226 }
5227
5228 if (argc - optind > 1) {
5229 error_report("At most one filename argument is allowed.");
5230 goto out;
5231 } else if (argc - optind == 1) {
5232 filename = argv[optind];
5233 }
5234
5235 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5236 error_report("--image-opts, -f, and -l require a filename argument.");
5237 goto out;
5238 }
5239 if (filename && img_size != UINT64_MAX) {
5240 error_report("--size N cannot be used together with a filename.");
5241 goto out;
5242 }
5243 if (!filename && img_size == UINT64_MAX) {
5244 error_report("Either --size N or one filename must be specified.");
5245 goto out;
5246 }
5247
5248 if (filename) {
5249 in_blk = img_open(image_opts, filename, fmt, 0,
5250 false, false, force_share);
5251 if (!in_blk) {
5252 goto out;
5253 }
5254
5255 if (sn_opts) {
5256 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5257 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5258 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5259 &local_err);
5260 } else if (snapshot_name != NULL) {
5261 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5262 snapshot_name, &local_err);
5263 }
5264 if (local_err) {
5265 error_reportf_err(local_err, "Failed to load snapshot: ");
5266 goto out;
5267 }
5268 }
5269
5270 drv = bdrv_find_format(out_fmt);
5271 if (!drv) {
5272 error_report("Unknown file format '%s'", out_fmt);
5273 goto out;
5274 }
5275 if (!drv->create_opts) {
5276 error_report("Format driver '%s' does not support image creation",
5277 drv->format_name);
5278 goto out;
5279 }
5280
5281 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5282 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5283 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5284 if (options) {
5285 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
5286 error_report_err(local_err);
5287 error_report("Invalid options for file format '%s'", out_fmt);
5288 goto out;
5289 }
5290 }
5291 if (img_size != UINT64_MAX) {
5292 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5293 }
5294
5295 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5296 if (local_err) {
5297 error_report_err(local_err);
5298 goto out;
5299 }
5300
5301 if (output_format == OFORMAT_HUMAN) {
5302 printf("required size: %" PRIu64 "\n", info->required);
5303 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5304 if (info->has_bitmaps) {
5305 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5306 }
5307 } else {
5308 dump_json_block_measure_info(info);
5309 }
5310
5311 ret = 0;
5312
5313 out:
5314 qapi_free_BlockMeasureInfo(info);
5315 qemu_opts_del(object_opts);
5316 qemu_opts_del(opts);
5317 qemu_opts_del(sn_opts);
5318 qemu_opts_free(create_opts);
5319 g_free(options);
5320 blk_unref(in_blk);
5321 return ret;
5322 }
5323
5324 static const img_cmd_t img_cmds[] = {
5325 #define DEF(option, callback, arg_string) \
5326 { option, callback },
5327 #include "qemu-img-cmds.h"
5328 #undef DEF
5329 { NULL, NULL, },
5330 };
5331
5332 int main(int argc, char **argv)
5333 {
5334 const img_cmd_t *cmd;
5335 const char *cmdname;
5336 Error *local_error = NULL;
5337 int c;
5338 static const struct option long_options[] = {
5339 {"help", no_argument, 0, 'h'},
5340 {"version", no_argument, 0, 'V'},
5341 {"trace", required_argument, NULL, 'T'},
5342 {0, 0, 0, 0}
5343 };
5344
5345 #ifdef CONFIG_POSIX
5346 signal(SIGPIPE, SIG_IGN);
5347 #endif
5348
5349 socket_init();
5350 error_init(argv[0]);
5351 module_call_init(MODULE_INIT_TRACE);
5352 qemu_init_exec_dir(argv[0]);
5353
5354 if (qemu_init_main_loop(&local_error)) {
5355 error_report_err(local_error);
5356 exit(EXIT_FAILURE);
5357 }
5358
5359 qcrypto_init(&error_fatal);
5360
5361 module_call_init(MODULE_INIT_QOM);
5362 bdrv_init();
5363 if (argc < 2) {
5364 error_exit("Not enough arguments");
5365 }
5366
5367 qemu_add_opts(&qemu_source_opts);
5368 qemu_add_opts(&qemu_trace_opts);
5369
5370 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
5371 switch (c) {
5372 case ':':
5373 missing_argument(argv[optind - 1]);
5374 return 0;
5375 case '?':
5376 unrecognized_option(argv[optind - 1]);
5377 return 0;
5378 case 'h':
5379 help();
5380 return 0;
5381 case 'V':
5382 printf(QEMU_IMG_VERSION);
5383 return 0;
5384 case 'T':
5385 trace_opt_parse(optarg);
5386 break;
5387 }
5388 }
5389
5390 cmdname = argv[optind];
5391
5392 /* reset getopt_long scanning */
5393 argc -= optind;
5394 if (argc < 1) {
5395 return 0;
5396 }
5397 argv += optind;
5398 qemu_reset_optind();
5399
5400 if (!trace_init_backends()) {
5401 exit(1);
5402 }
5403 trace_init_file();
5404 qemu_set_log(LOG_TRACE);
5405
5406 /* find the command */
5407 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5408 if (!strcmp(cmdname, cmd->name)) {
5409 return cmd->handler(argc, argv);
5410 }
5411 }
5412
5413 /* not found */
5414 error_exit("Command not found: %s", cmdname);
5415 }