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