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