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