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