]> git.proxmox.com Git - mirror_qemu.git/blob - qemu-img.c
Makefile: Derive "PKGVERSION" from "git describe" by default
[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/qmp-output-visitor.h"
29 #include "qapi/qmp/qerror.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qemu/cutils.h"
32 #include "qemu/config-file.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
35 #include "qom/object_interfaces.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/block-backend.h"
38 #include "block/block_int.h"
39 #include "block/blockjob.h"
40 #include "block/qapi.h"
41 #include "crypto/init.h"
42 #include <getopt.h>
43
44 #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
45 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
46
47 typedef struct img_cmd_t {
48 const char *name;
49 int (*handler)(int argc, char **argv);
50 } img_cmd_t;
51
52 enum {
53 OPTION_OUTPUT = 256,
54 OPTION_BACKING_CHAIN = 257,
55 OPTION_OBJECT = 258,
56 OPTION_IMAGE_OPTS = 259,
57 };
58
59 typedef enum OutputFormat {
60 OFORMAT_JSON,
61 OFORMAT_HUMAN,
62 } OutputFormat;
63
64 /* Default to cache=writeback as data integrity is not important for qemu-img */
65 #define BDRV_DEFAULT_CACHE "writeback"
66
67 static void format_print(void *opaque, const char *name)
68 {
69 printf(" %s", name);
70 }
71
72 static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
73 {
74 va_list ap;
75
76 error_printf("qemu-img: ");
77
78 va_start(ap, fmt);
79 error_vprintf(fmt, ap);
80 va_end(ap);
81
82 error_printf("\nTry 'qemu-img --help' for more information\n");
83 exit(EXIT_FAILURE);
84 }
85
86 /* Please keep in synch with qemu-img.texi */
87 static void QEMU_NORETURN help(void)
88 {
89 const char *help_msg =
90 QEMU_IMG_VERSION
91 "usage: qemu-img command [command options]\n"
92 "QEMU disk image utility\n"
93 "\n"
94 "Command syntax:\n"
95 #define DEF(option, callback, arg_string) \
96 " " arg_string "\n"
97 #include "qemu-img-cmds.h"
98 #undef DEF
99 #undef GEN_DOCS
100 "\n"
101 "Command parameters:\n"
102 " 'filename' is a disk image filename\n"
103 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
104 " manual page for a description of the object properties. The most common\n"
105 " object type is a 'secret', which is used to supply passwords and/or\n"
106 " encryption keys.\n"
107 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
108 " 'cache' is the cache mode used to write the output disk image, the valid\n"
109 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
110 " 'directsync' and 'unsafe' (default for convert)\n"
111 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
112 " options are the same as for the 'cache' option\n"
113 " 'size' is the disk image size in bytes. Optional suffixes\n"
114 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
115 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
116 " supported. 'b' is ignored.\n"
117 " 'output_filename' is the destination disk image filename\n"
118 " 'output_fmt' is the destination format\n"
119 " 'options' is a comma separated list of format specific options in a\n"
120 " name=value format. Use -o ? for an overview of the options supported by the\n"
121 " used format\n"
122 " 'snapshot_param' is param used for internal snapshot, format\n"
123 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
124 " '[ID_OR_NAME]'\n"
125 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
126 " instead\n"
127 " '-c' indicates that target image must be compressed (qcow format only)\n"
128 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
129 " match exactly. The image doesn't need a working backing file before\n"
130 " rebasing in this case (useful for renaming the backing file)\n"
131 " '-h' with or without a command shows this help and lists the supported formats\n"
132 " '-p' show progress of command (only certain commands)\n"
133 " '-q' use Quiet mode - do not print any output (except errors)\n"
134 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
135 " contain only zeros for qemu-img to create a sparse image during\n"
136 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
137 " unallocated or zero sectors, and the destination image will always be\n"
138 " fully allocated\n"
139 " '--output' takes the format in which the output must be done (human or json)\n"
140 " '-n' skips the target volume creation (useful if the volume is created\n"
141 " prior to running qemu-img)\n"
142 "\n"
143 "Parameters to check subcommand:\n"
144 " '-r' tries to repair any inconsistencies that are found during the check.\n"
145 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
146 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
147 " hiding corruption that has already occurred.\n"
148 "\n"
149 "Parameters to snapshot subcommand:\n"
150 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
151 " '-a' applies a snapshot (revert disk to saved state)\n"
152 " '-c' creates a snapshot\n"
153 " '-d' deletes a snapshot\n"
154 " '-l' lists all snapshots in the given image\n"
155 "\n"
156 "Parameters to compare subcommand:\n"
157 " '-f' first image format\n"
158 " '-F' second image format\n"
159 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
160
161 printf("%s\nSupported formats:", help_msg);
162 bdrv_iterate_format(format_print, NULL);
163 printf("\n");
164 exit(EXIT_SUCCESS);
165 }
166
167 static QemuOptsList qemu_object_opts = {
168 .name = "object",
169 .implied_opt_name = "qom-type",
170 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
171 .desc = {
172 { }
173 },
174 };
175
176 static QemuOptsList qemu_source_opts = {
177 .name = "source",
178 .implied_opt_name = "file",
179 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
180 .desc = {
181 { }
182 },
183 };
184
185 static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
186 {
187 int ret = 0;
188 if (!quiet) {
189 va_list args;
190 va_start(args, fmt);
191 ret = vprintf(fmt, args);
192 va_end(args);
193 }
194 return ret;
195 }
196
197
198 static int print_block_option_help(const char *filename, const char *fmt)
199 {
200 BlockDriver *drv, *proto_drv;
201 QemuOptsList *create_opts = NULL;
202 Error *local_err = NULL;
203
204 /* Find driver and parse its options */
205 drv = bdrv_find_format(fmt);
206 if (!drv) {
207 error_report("Unknown file format '%s'", fmt);
208 return 1;
209 }
210
211 create_opts = qemu_opts_append(create_opts, drv->create_opts);
212 if (filename) {
213 proto_drv = bdrv_find_protocol(filename, true, &local_err);
214 if (!proto_drv) {
215 error_report_err(local_err);
216 qemu_opts_free(create_opts);
217 return 1;
218 }
219 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
220 }
221
222 qemu_opts_print_help(create_opts);
223 qemu_opts_free(create_opts);
224 return 0;
225 }
226
227
228 static int img_open_password(BlockBackend *blk, const char *filename,
229 int flags, bool quiet)
230 {
231 BlockDriverState *bs;
232 char password[256];
233
234 bs = blk_bs(blk);
235 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
236 !(flags & BDRV_O_NO_IO)) {
237 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
238 if (qemu_read_password(password, sizeof(password)) < 0) {
239 error_report("No password given");
240 return -1;
241 }
242 if (bdrv_set_key(bs, password) < 0) {
243 error_report("invalid password");
244 return -1;
245 }
246 }
247 return 0;
248 }
249
250
251 static BlockBackend *img_open_opts(const char *optstr,
252 QemuOpts *opts, int flags, bool writethrough,
253 bool quiet)
254 {
255 QDict *options;
256 Error *local_err = NULL;
257 BlockBackend *blk;
258 options = qemu_opts_to_qdict(opts, NULL);
259 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
260 if (!blk) {
261 error_reportf_err(local_err, "Could not open '%s': ", optstr);
262 return NULL;
263 }
264 blk_set_enable_write_cache(blk, !writethrough);
265
266 if (img_open_password(blk, optstr, flags, quiet) < 0) {
267 blk_unref(blk);
268 return NULL;
269 }
270 return blk;
271 }
272
273 static BlockBackend *img_open_file(const char *filename,
274 const char *fmt, int flags,
275 bool writethrough, bool quiet)
276 {
277 BlockBackend *blk;
278 Error *local_err = NULL;
279 QDict *options = NULL;
280
281 if (fmt) {
282 options = qdict_new();
283 qdict_put(options, "driver", qstring_from_str(fmt));
284 }
285
286 blk = blk_new_open(filename, NULL, options, flags, &local_err);
287 if (!blk) {
288 error_reportf_err(local_err, "Could not open '%s': ", filename);
289 return NULL;
290 }
291 blk_set_enable_write_cache(blk, !writethrough);
292
293 if (img_open_password(blk, filename, flags, quiet) < 0) {
294 blk_unref(blk);
295 return NULL;
296 }
297 return blk;
298 }
299
300
301 static BlockBackend *img_open(bool image_opts,
302 const char *filename,
303 const char *fmt, int flags, bool writethrough,
304 bool quiet)
305 {
306 BlockBackend *blk;
307 if (image_opts) {
308 QemuOpts *opts;
309 if (fmt) {
310 error_report("--image-opts and --format are mutually exclusive");
311 return NULL;
312 }
313 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
314 filename, true);
315 if (!opts) {
316 return NULL;
317 }
318 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
319 } else {
320 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
321 }
322 return blk;
323 }
324
325
326 static int add_old_style_options(const char *fmt, QemuOpts *opts,
327 const char *base_filename,
328 const char *base_fmt)
329 {
330 Error *err = NULL;
331
332 if (base_filename) {
333 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
334 if (err) {
335 error_report("Backing file not supported for file format '%s'",
336 fmt);
337 error_free(err);
338 return -1;
339 }
340 }
341 if (base_fmt) {
342 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
343 if (err) {
344 error_report("Backing file format not supported for file "
345 "format '%s'", fmt);
346 error_free(err);
347 return -1;
348 }
349 }
350 return 0;
351 }
352
353 static int img_create(int argc, char **argv)
354 {
355 int c;
356 uint64_t img_size = -1;
357 const char *fmt = "raw";
358 const char *base_fmt = NULL;
359 const char *filename;
360 const char *base_filename = NULL;
361 char *options = NULL;
362 Error *local_err = NULL;
363 bool quiet = false;
364
365 for(;;) {
366 static const struct option long_options[] = {
367 {"help", no_argument, 0, 'h'},
368 {"object", required_argument, 0, OPTION_OBJECT},
369 {0, 0, 0, 0}
370 };
371 c = getopt_long(argc, argv, "F:b:f:he6o:q",
372 long_options, NULL);
373 if (c == -1) {
374 break;
375 }
376 switch(c) {
377 case '?':
378 case 'h':
379 help();
380 break;
381 case 'F':
382 base_fmt = optarg;
383 break;
384 case 'b':
385 base_filename = optarg;
386 break;
387 case 'f':
388 fmt = optarg;
389 break;
390 case 'e':
391 error_report("option -e is deprecated, please use \'-o "
392 "encryption\' instead!");
393 goto fail;
394 case '6':
395 error_report("option -6 is deprecated, please use \'-o "
396 "compat6\' instead!");
397 goto fail;
398 case 'o':
399 if (!is_valid_option_list(optarg)) {
400 error_report("Invalid option list: %s", optarg);
401 goto fail;
402 }
403 if (!options) {
404 options = g_strdup(optarg);
405 } else {
406 char *old_options = options;
407 options = g_strdup_printf("%s,%s", options, optarg);
408 g_free(old_options);
409 }
410 break;
411 case 'q':
412 quiet = true;
413 break;
414 case OPTION_OBJECT: {
415 QemuOpts *opts;
416 opts = qemu_opts_parse_noisily(&qemu_object_opts,
417 optarg, true);
418 if (!opts) {
419 goto fail;
420 }
421 } break;
422 }
423 }
424
425 /* Get the filename */
426 filename = (optind < argc) ? argv[optind] : NULL;
427 if (options && has_help_option(options)) {
428 g_free(options);
429 return print_block_option_help(filename, fmt);
430 }
431
432 if (optind >= argc) {
433 error_exit("Expecting image file name");
434 }
435 optind++;
436
437 if (qemu_opts_foreach(&qemu_object_opts,
438 user_creatable_add_opts_foreach,
439 NULL, NULL)) {
440 goto fail;
441 }
442
443 /* Get image size, if specified */
444 if (optind < argc) {
445 int64_t sval;
446 char *end;
447 sval = qemu_strtosz_suffix(argv[optind++], &end,
448 QEMU_STRTOSZ_DEFSUFFIX_B);
449 if (sval < 0 || *end) {
450 if (sval == -ERANGE) {
451 error_report("Image size must be less than 8 EiB!");
452 } else {
453 error_report("Invalid image size specified! You may use k, M, "
454 "G, T, P or E suffixes for ");
455 error_report("kilobytes, megabytes, gigabytes, terabytes, "
456 "petabytes and exabytes.");
457 }
458 goto fail;
459 }
460 img_size = (uint64_t)sval;
461 }
462 if (optind != argc) {
463 error_exit("Unexpected argument: %s", argv[optind]);
464 }
465
466 bdrv_img_create(filename, fmt, base_filename, base_fmt,
467 options, img_size, 0, &local_err, quiet);
468 if (local_err) {
469 error_reportf_err(local_err, "%s: ", filename);
470 goto fail;
471 }
472
473 g_free(options);
474 return 0;
475
476 fail:
477 g_free(options);
478 return 1;
479 }
480
481 static void dump_json_image_check(ImageCheck *check, bool quiet)
482 {
483 Error *local_err = NULL;
484 QString *str;
485 QmpOutputVisitor *ov = qmp_output_visitor_new();
486 QObject *obj;
487 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
488 &local_err);
489 obj = qmp_output_get_qobject(ov);
490 str = qobject_to_json_pretty(obj);
491 assert(str != NULL);
492 qprintf(quiet, "%s\n", qstring_get_str(str));
493 qobject_decref(obj);
494 qmp_output_visitor_cleanup(ov);
495 QDECREF(str);
496 }
497
498 static void dump_human_image_check(ImageCheck *check, bool quiet)
499 {
500 if (!(check->corruptions || check->leaks || check->check_errors)) {
501 qprintf(quiet, "No errors were found on the image.\n");
502 } else {
503 if (check->corruptions) {
504 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
505 "Data may be corrupted, or further writes to the image "
506 "may corrupt it.\n",
507 check->corruptions);
508 }
509
510 if (check->leaks) {
511 qprintf(quiet,
512 "\n%" PRId64 " leaked clusters were found on the image.\n"
513 "This means waste of disk space, but no harm to data.\n",
514 check->leaks);
515 }
516
517 if (check->check_errors) {
518 qprintf(quiet,
519 "\n%" PRId64
520 " internal errors have occurred during the check.\n",
521 check->check_errors);
522 }
523 }
524
525 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
526 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
527 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
528 check->allocated_clusters, check->total_clusters,
529 check->allocated_clusters * 100.0 / check->total_clusters,
530 check->fragmented_clusters * 100.0 / check->allocated_clusters,
531 check->compressed_clusters * 100.0 /
532 check->allocated_clusters);
533 }
534
535 if (check->image_end_offset) {
536 qprintf(quiet,
537 "Image end offset: %" PRId64 "\n", check->image_end_offset);
538 }
539 }
540
541 static int collect_image_check(BlockDriverState *bs,
542 ImageCheck *check,
543 const char *filename,
544 const char *fmt,
545 int fix)
546 {
547 int ret;
548 BdrvCheckResult result;
549
550 ret = bdrv_check(bs, &result, fix);
551 if (ret < 0) {
552 return ret;
553 }
554
555 check->filename = g_strdup(filename);
556 check->format = g_strdup(bdrv_get_format_name(bs));
557 check->check_errors = result.check_errors;
558 check->corruptions = result.corruptions;
559 check->has_corruptions = result.corruptions != 0;
560 check->leaks = result.leaks;
561 check->has_leaks = result.leaks != 0;
562 check->corruptions_fixed = result.corruptions_fixed;
563 check->has_corruptions_fixed = result.corruptions != 0;
564 check->leaks_fixed = result.leaks_fixed;
565 check->has_leaks_fixed = result.leaks != 0;
566 check->image_end_offset = result.image_end_offset;
567 check->has_image_end_offset = result.image_end_offset != 0;
568 check->total_clusters = result.bfi.total_clusters;
569 check->has_total_clusters = result.bfi.total_clusters != 0;
570 check->allocated_clusters = result.bfi.allocated_clusters;
571 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
572 check->fragmented_clusters = result.bfi.fragmented_clusters;
573 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
574 check->compressed_clusters = result.bfi.compressed_clusters;
575 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
576
577 return 0;
578 }
579
580 /*
581 * Checks an image for consistency. Exit codes:
582 *
583 * 0 - Check completed, image is good
584 * 1 - Check not completed because of internal errors
585 * 2 - Check completed, image is corrupted
586 * 3 - Check completed, image has leaked clusters, but is good otherwise
587 * 63 - Checks are not supported by the image format
588 */
589 static int img_check(int argc, char **argv)
590 {
591 int c, ret;
592 OutputFormat output_format = OFORMAT_HUMAN;
593 const char *filename, *fmt, *output, *cache;
594 BlockBackend *blk;
595 BlockDriverState *bs;
596 int fix = 0;
597 int flags = BDRV_O_CHECK;
598 bool writethrough;
599 ImageCheck *check;
600 bool quiet = false;
601 bool image_opts = false;
602
603 fmt = NULL;
604 output = NULL;
605 cache = BDRV_DEFAULT_CACHE;
606
607 for(;;) {
608 int option_index = 0;
609 static const struct option long_options[] = {
610 {"help", no_argument, 0, 'h'},
611 {"format", required_argument, 0, 'f'},
612 {"repair", required_argument, 0, 'r'},
613 {"output", required_argument, 0, OPTION_OUTPUT},
614 {"object", required_argument, 0, OPTION_OBJECT},
615 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
616 {0, 0, 0, 0}
617 };
618 c = getopt_long(argc, argv, "hf:r:T:q",
619 long_options, &option_index);
620 if (c == -1) {
621 break;
622 }
623 switch(c) {
624 case '?':
625 case 'h':
626 help();
627 break;
628 case 'f':
629 fmt = optarg;
630 break;
631 case 'r':
632 flags |= BDRV_O_RDWR;
633
634 if (!strcmp(optarg, "leaks")) {
635 fix = BDRV_FIX_LEAKS;
636 } else if (!strcmp(optarg, "all")) {
637 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
638 } else {
639 error_exit("Unknown option value for -r "
640 "(expecting 'leaks' or 'all'): %s", optarg);
641 }
642 break;
643 case OPTION_OUTPUT:
644 output = optarg;
645 break;
646 case 'T':
647 cache = optarg;
648 break;
649 case 'q':
650 quiet = true;
651 break;
652 case OPTION_OBJECT: {
653 QemuOpts *opts;
654 opts = qemu_opts_parse_noisily(&qemu_object_opts,
655 optarg, true);
656 if (!opts) {
657 return 1;
658 }
659 } break;
660 case OPTION_IMAGE_OPTS:
661 image_opts = true;
662 break;
663 }
664 }
665 if (optind != argc - 1) {
666 error_exit("Expecting one image file name");
667 }
668 filename = argv[optind++];
669
670 if (output && !strcmp(output, "json")) {
671 output_format = OFORMAT_JSON;
672 } else if (output && !strcmp(output, "human")) {
673 output_format = OFORMAT_HUMAN;
674 } else if (output) {
675 error_report("--output must be used with human or json as argument.");
676 return 1;
677 }
678
679 if (qemu_opts_foreach(&qemu_object_opts,
680 user_creatable_add_opts_foreach,
681 NULL, NULL)) {
682 return 1;
683 }
684
685 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
686 if (ret < 0) {
687 error_report("Invalid source cache option: %s", cache);
688 return 1;
689 }
690
691 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
692 if (!blk) {
693 return 1;
694 }
695 bs = blk_bs(blk);
696
697 check = g_new0(ImageCheck, 1);
698 ret = collect_image_check(bs, check, filename, fmt, fix);
699
700 if (ret == -ENOTSUP) {
701 error_report("This image format does not support checks");
702 ret = 63;
703 goto fail;
704 }
705
706 if (check->corruptions_fixed || check->leaks_fixed) {
707 int corruptions_fixed, leaks_fixed;
708
709 leaks_fixed = check->leaks_fixed;
710 corruptions_fixed = check->corruptions_fixed;
711
712 if (output_format == OFORMAT_HUMAN) {
713 qprintf(quiet,
714 "The following inconsistencies were found and repaired:\n\n"
715 " %" PRId64 " leaked clusters\n"
716 " %" PRId64 " corruptions\n\n"
717 "Double checking the fixed image now...\n",
718 check->leaks_fixed,
719 check->corruptions_fixed);
720 }
721
722 ret = collect_image_check(bs, check, filename, fmt, 0);
723
724 check->leaks_fixed = leaks_fixed;
725 check->corruptions_fixed = corruptions_fixed;
726 }
727
728 if (!ret) {
729 switch (output_format) {
730 case OFORMAT_HUMAN:
731 dump_human_image_check(check, quiet);
732 break;
733 case OFORMAT_JSON:
734 dump_json_image_check(check, quiet);
735 break;
736 }
737 }
738
739 if (ret || check->check_errors) {
740 if (ret) {
741 error_report("Check failed: %s", strerror(-ret));
742 } else {
743 error_report("Check failed");
744 }
745 ret = 1;
746 goto fail;
747 }
748
749 if (check->corruptions) {
750 ret = 2;
751 } else if (check->leaks) {
752 ret = 3;
753 } else {
754 ret = 0;
755 }
756
757 fail:
758 qapi_free_ImageCheck(check);
759 blk_unref(blk);
760 return ret;
761 }
762
763 typedef struct CommonBlockJobCBInfo {
764 BlockDriverState *bs;
765 Error **errp;
766 } CommonBlockJobCBInfo;
767
768 static void common_block_job_cb(void *opaque, int ret)
769 {
770 CommonBlockJobCBInfo *cbi = opaque;
771
772 if (ret < 0) {
773 error_setg_errno(cbi->errp, -ret, "Block job failed");
774 }
775 }
776
777 static void run_block_job(BlockJob *job, Error **errp)
778 {
779 AioContext *aio_context = blk_get_aio_context(job->blk);
780
781 do {
782 aio_poll(aio_context, true);
783 qemu_progress_print(job->len ?
784 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
785 } while (!job->ready);
786
787 block_job_complete_sync(job, errp);
788
789 /* A block job may finish instantaneously without publishing any progress,
790 * so just signal completion here */
791 qemu_progress_print(100.f, 0);
792 }
793
794 static int img_commit(int argc, char **argv)
795 {
796 int c, ret, flags;
797 const char *filename, *fmt, *cache, *base;
798 BlockBackend *blk;
799 BlockDriverState *bs, *base_bs;
800 bool progress = false, quiet = false, drop = false;
801 bool writethrough;
802 Error *local_err = NULL;
803 CommonBlockJobCBInfo cbi;
804 bool image_opts = false;
805
806 fmt = NULL;
807 cache = BDRV_DEFAULT_CACHE;
808 base = NULL;
809 for(;;) {
810 static const struct option long_options[] = {
811 {"help", no_argument, 0, 'h'},
812 {"object", required_argument, 0, OPTION_OBJECT},
813 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
814 {0, 0, 0, 0}
815 };
816 c = getopt_long(argc, argv, "f:ht:b:dpq",
817 long_options, NULL);
818 if (c == -1) {
819 break;
820 }
821 switch(c) {
822 case '?':
823 case 'h':
824 help();
825 break;
826 case 'f':
827 fmt = optarg;
828 break;
829 case 't':
830 cache = optarg;
831 break;
832 case 'b':
833 base = optarg;
834 /* -b implies -d */
835 drop = true;
836 break;
837 case 'd':
838 drop = true;
839 break;
840 case 'p':
841 progress = true;
842 break;
843 case 'q':
844 quiet = true;
845 break;
846 case OPTION_OBJECT: {
847 QemuOpts *opts;
848 opts = qemu_opts_parse_noisily(&qemu_object_opts,
849 optarg, true);
850 if (!opts) {
851 return 1;
852 }
853 } break;
854 case OPTION_IMAGE_OPTS:
855 image_opts = true;
856 break;
857 }
858 }
859
860 /* Progress is not shown in Quiet mode */
861 if (quiet) {
862 progress = false;
863 }
864
865 if (optind != argc - 1) {
866 error_exit("Expecting one image file name");
867 }
868 filename = argv[optind++];
869
870 if (qemu_opts_foreach(&qemu_object_opts,
871 user_creatable_add_opts_foreach,
872 NULL, NULL)) {
873 return 1;
874 }
875
876 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
877 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
878 if (ret < 0) {
879 error_report("Invalid cache option: %s", cache);
880 return 1;
881 }
882
883 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
884 if (!blk) {
885 return 1;
886 }
887 bs = blk_bs(blk);
888
889 qemu_progress_init(progress, 1.f);
890 qemu_progress_print(0.f, 100);
891
892 if (base) {
893 base_bs = bdrv_find_backing_image(bs, base);
894 if (!base_bs) {
895 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
896 goto done;
897 }
898 } else {
899 /* This is different from QMP, which by default uses the deepest file in
900 * the backing chain (i.e., the very base); however, the traditional
901 * behavior of qemu-img commit is using the immediate backing file. */
902 base_bs = backing_bs(bs);
903 if (!base_bs) {
904 error_setg(&local_err, "Image does not have a backing file");
905 goto done;
906 }
907 }
908
909 cbi = (CommonBlockJobCBInfo){
910 .errp = &local_err,
911 .bs = bs,
912 };
913
914 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
915 common_block_job_cb, &cbi, &local_err);
916 if (local_err) {
917 goto done;
918 }
919
920 /* When the block job completes, the BlockBackend reference will point to
921 * the old backing file. In order to avoid that the top image is already
922 * deleted, so we can still empty it afterwards, increment the reference
923 * counter here preemptively. */
924 if (!drop) {
925 bdrv_ref(bs);
926 }
927
928 run_block_job(bs->job, &local_err);
929 if (local_err) {
930 goto unref_backing;
931 }
932
933 if (!drop && bs->drv->bdrv_make_empty) {
934 ret = bs->drv->bdrv_make_empty(bs);
935 if (ret) {
936 error_setg_errno(&local_err, -ret, "Could not empty %s",
937 filename);
938 goto unref_backing;
939 }
940 }
941
942 unref_backing:
943 if (!drop) {
944 bdrv_unref(bs);
945 }
946
947 done:
948 qemu_progress_end();
949
950 blk_unref(blk);
951
952 if (local_err) {
953 error_report_err(local_err);
954 return 1;
955 }
956
957 qprintf(quiet, "Image committed.\n");
958 return 0;
959 }
960
961 /*
962 * Returns true iff the first sector pointed to by 'buf' contains at least
963 * a non-NUL byte.
964 *
965 * 'pnum' is set to the number of sectors (including and immediately following
966 * the first one) that are known to be in the same allocated/unallocated state.
967 */
968 static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
969 {
970 bool is_zero;
971 int i;
972
973 if (n <= 0) {
974 *pnum = 0;
975 return 0;
976 }
977 is_zero = buffer_is_zero(buf, 512);
978 for(i = 1; i < n; i++) {
979 buf += 512;
980 if (is_zero != buffer_is_zero(buf, 512)) {
981 break;
982 }
983 }
984 *pnum = i;
985 return !is_zero;
986 }
987
988 /*
989 * Like is_allocated_sectors, but if the buffer starts with a used sector,
990 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
991 * breaking up write requests for only small sparse areas.
992 */
993 static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
994 int min)
995 {
996 int ret;
997 int num_checked, num_used;
998
999 if (n < min) {
1000 min = n;
1001 }
1002
1003 ret = is_allocated_sectors(buf, n, pnum);
1004 if (!ret) {
1005 return ret;
1006 }
1007
1008 num_used = *pnum;
1009 buf += BDRV_SECTOR_SIZE * *pnum;
1010 n -= *pnum;
1011 num_checked = num_used;
1012
1013 while (n > 0) {
1014 ret = is_allocated_sectors(buf, n, pnum);
1015
1016 buf += BDRV_SECTOR_SIZE * *pnum;
1017 n -= *pnum;
1018 num_checked += *pnum;
1019 if (ret) {
1020 num_used = num_checked;
1021 } else if (*pnum >= min) {
1022 break;
1023 }
1024 }
1025
1026 *pnum = num_used;
1027 return 1;
1028 }
1029
1030 /*
1031 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1032 * buffers matches, non-zero otherwise.
1033 *
1034 * pnum is set to the number of sectors (including and immediately following
1035 * the first one) that are known to have the same comparison result
1036 */
1037 static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1038 int *pnum)
1039 {
1040 bool res;
1041 int i;
1042
1043 if (n <= 0) {
1044 *pnum = 0;
1045 return 0;
1046 }
1047
1048 res = !!memcmp(buf1, buf2, 512);
1049 for(i = 1; i < n; i++) {
1050 buf1 += 512;
1051 buf2 += 512;
1052
1053 if (!!memcmp(buf1, buf2, 512) != res) {
1054 break;
1055 }
1056 }
1057
1058 *pnum = i;
1059 return res;
1060 }
1061
1062 #define IO_BUF_SIZE (2 * 1024 * 1024)
1063
1064 static int64_t sectors_to_bytes(int64_t sectors)
1065 {
1066 return sectors << BDRV_SECTOR_BITS;
1067 }
1068
1069 static int64_t sectors_to_process(int64_t total, int64_t from)
1070 {
1071 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1072 }
1073
1074 /*
1075 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1076 *
1077 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1078 * data and negative value on error.
1079 *
1080 * @param blk: BlockBackend for the image
1081 * @param sect_num: Number of first sector to check
1082 * @param sect_count: Number of sectors to check
1083 * @param filename: Name of disk file we are checking (logging purpose)
1084 * @param buffer: Allocated buffer for storing read data
1085 * @param quiet: Flag for quiet mode
1086 */
1087 static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
1088 int sect_count, const char *filename,
1089 uint8_t *buffer, bool quiet)
1090 {
1091 int pnum, ret = 0;
1092 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1093 sect_count << BDRV_SECTOR_BITS);
1094 if (ret < 0) {
1095 error_report("Error while reading offset %" PRId64 " of %s: %s",
1096 sectors_to_bytes(sect_num), filename, strerror(-ret));
1097 return ret;
1098 }
1099 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1100 if (ret || pnum != sect_count) {
1101 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1102 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1103 return 1;
1104 }
1105
1106 return 0;
1107 }
1108
1109 /*
1110 * Compares two images. Exit codes:
1111 *
1112 * 0 - Images are identical
1113 * 1 - Images differ
1114 * >1 - Error occurred
1115 */
1116 static int img_compare(int argc, char **argv)
1117 {
1118 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
1119 BlockBackend *blk1, *blk2;
1120 BlockDriverState *bs1, *bs2;
1121 int64_t total_sectors1, total_sectors2;
1122 uint8_t *buf1 = NULL, *buf2 = NULL;
1123 int pnum1, pnum2;
1124 int allocated1, allocated2;
1125 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1126 bool progress = false, quiet = false, strict = false;
1127 int flags;
1128 bool writethrough;
1129 int64_t total_sectors;
1130 int64_t sector_num = 0;
1131 int64_t nb_sectors;
1132 int c, pnum;
1133 uint64_t progress_base;
1134 bool image_opts = false;
1135
1136 cache = BDRV_DEFAULT_CACHE;
1137 for (;;) {
1138 static const struct option long_options[] = {
1139 {"help", no_argument, 0, 'h'},
1140 {"object", required_argument, 0, OPTION_OBJECT},
1141 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1142 {0, 0, 0, 0}
1143 };
1144 c = getopt_long(argc, argv, "hf:F:T:pqs",
1145 long_options, NULL);
1146 if (c == -1) {
1147 break;
1148 }
1149 switch (c) {
1150 case '?':
1151 case 'h':
1152 help();
1153 break;
1154 case 'f':
1155 fmt1 = optarg;
1156 break;
1157 case 'F':
1158 fmt2 = optarg;
1159 break;
1160 case 'T':
1161 cache = optarg;
1162 break;
1163 case 'p':
1164 progress = true;
1165 break;
1166 case 'q':
1167 quiet = true;
1168 break;
1169 case 's':
1170 strict = true;
1171 break;
1172 case OPTION_OBJECT: {
1173 QemuOpts *opts;
1174 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1175 optarg, true);
1176 if (!opts) {
1177 ret = 2;
1178 goto out4;
1179 }
1180 } break;
1181 case OPTION_IMAGE_OPTS:
1182 image_opts = true;
1183 break;
1184 }
1185 }
1186
1187 /* Progress is not shown in Quiet mode */
1188 if (quiet) {
1189 progress = false;
1190 }
1191
1192
1193 if (optind != argc - 2) {
1194 error_exit("Expecting two image file names");
1195 }
1196 filename1 = argv[optind++];
1197 filename2 = argv[optind++];
1198
1199 if (qemu_opts_foreach(&qemu_object_opts,
1200 user_creatable_add_opts_foreach,
1201 NULL, NULL)) {
1202 ret = 2;
1203 goto out4;
1204 }
1205
1206 /* Initialize before goto out */
1207 qemu_progress_init(progress, 2.0);
1208
1209 flags = 0;
1210 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
1211 if (ret < 0) {
1212 error_report("Invalid source cache option: %s", cache);
1213 ret = 2;
1214 goto out3;
1215 }
1216
1217 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
1218 if (!blk1) {
1219 ret = 2;
1220 goto out3;
1221 }
1222
1223 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
1224 if (!blk2) {
1225 ret = 2;
1226 goto out2;
1227 }
1228 bs1 = blk_bs(blk1);
1229 bs2 = blk_bs(blk2);
1230
1231 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1232 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1233 total_sectors1 = blk_nb_sectors(blk1);
1234 if (total_sectors1 < 0) {
1235 error_report("Can't get size of %s: %s",
1236 filename1, strerror(-total_sectors1));
1237 ret = 4;
1238 goto out;
1239 }
1240 total_sectors2 = blk_nb_sectors(blk2);
1241 if (total_sectors2 < 0) {
1242 error_report("Can't get size of %s: %s",
1243 filename2, strerror(-total_sectors2));
1244 ret = 4;
1245 goto out;
1246 }
1247 total_sectors = MIN(total_sectors1, total_sectors2);
1248 progress_base = MAX(total_sectors1, total_sectors2);
1249
1250 qemu_progress_print(0, 100);
1251
1252 if (strict && total_sectors1 != total_sectors2) {
1253 ret = 1;
1254 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1255 goto out;
1256 }
1257
1258 for (;;) {
1259 int64_t status1, status2;
1260 BlockDriverState *file;
1261
1262 nb_sectors = sectors_to_process(total_sectors, sector_num);
1263 if (nb_sectors <= 0) {
1264 break;
1265 }
1266 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1267 total_sectors1 - sector_num,
1268 &pnum1, &file);
1269 if (status1 < 0) {
1270 ret = 3;
1271 error_report("Sector allocation test failed for %s", filename1);
1272 goto out;
1273 }
1274 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
1275
1276 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1277 total_sectors2 - sector_num,
1278 &pnum2, &file);
1279 if (status2 < 0) {
1280 ret = 3;
1281 error_report("Sector allocation test failed for %s", filename2);
1282 goto out;
1283 }
1284 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1285 if (pnum1) {
1286 nb_sectors = MIN(nb_sectors, pnum1);
1287 }
1288 if (pnum2) {
1289 nb_sectors = MIN(nb_sectors, pnum2);
1290 }
1291
1292 if (strict) {
1293 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1294 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1295 ret = 1;
1296 qprintf(quiet, "Strict mode: Offset %" PRId64
1297 " block status mismatch!\n",
1298 sectors_to_bytes(sector_num));
1299 goto out;
1300 }
1301 }
1302 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1303 nb_sectors = MIN(pnum1, pnum2);
1304 } else if (allocated1 == allocated2) {
1305 if (allocated1) {
1306 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1307 nb_sectors << BDRV_SECTOR_BITS);
1308 if (ret < 0) {
1309 error_report("Error while reading offset %" PRId64 " of %s:"
1310 " %s", sectors_to_bytes(sector_num), filename1,
1311 strerror(-ret));
1312 ret = 4;
1313 goto out;
1314 }
1315 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1316 nb_sectors << BDRV_SECTOR_BITS);
1317 if (ret < 0) {
1318 error_report("Error while reading offset %" PRId64
1319 " of %s: %s", sectors_to_bytes(sector_num),
1320 filename2, strerror(-ret));
1321 ret = 4;
1322 goto out;
1323 }
1324 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1325 if (ret || pnum != nb_sectors) {
1326 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1327 sectors_to_bytes(
1328 ret ? sector_num : sector_num + pnum));
1329 ret = 1;
1330 goto out;
1331 }
1332 }
1333 } else {
1334
1335 if (allocated1) {
1336 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
1337 filename1, buf1, quiet);
1338 } else {
1339 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
1340 filename2, buf1, quiet);
1341 }
1342 if (ret) {
1343 if (ret < 0) {
1344 error_report("Error while reading offset %" PRId64 ": %s",
1345 sectors_to_bytes(sector_num), strerror(-ret));
1346 ret = 4;
1347 }
1348 goto out;
1349 }
1350 }
1351 sector_num += nb_sectors;
1352 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1353 }
1354
1355 if (total_sectors1 != total_sectors2) {
1356 BlockBackend *blk_over;
1357 int64_t total_sectors_over;
1358 const char *filename_over;
1359
1360 qprintf(quiet, "Warning: Image size mismatch!\n");
1361 if (total_sectors1 > total_sectors2) {
1362 total_sectors_over = total_sectors1;
1363 blk_over = blk1;
1364 filename_over = filename1;
1365 } else {
1366 total_sectors_over = total_sectors2;
1367 blk_over = blk2;
1368 filename_over = filename2;
1369 }
1370
1371 for (;;) {
1372 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1373 if (nb_sectors <= 0) {
1374 break;
1375 }
1376 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
1377 nb_sectors, &pnum);
1378 if (ret < 0) {
1379 ret = 3;
1380 error_report("Sector allocation test failed for %s",
1381 filename_over);
1382 goto out;
1383
1384 }
1385 nb_sectors = pnum;
1386 if (ret) {
1387 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
1388 filename_over, buf1, quiet);
1389 if (ret) {
1390 if (ret < 0) {
1391 error_report("Error while reading offset %" PRId64
1392 " of %s: %s", sectors_to_bytes(sector_num),
1393 filename_over, strerror(-ret));
1394 ret = 4;
1395 }
1396 goto out;
1397 }
1398 }
1399 sector_num += nb_sectors;
1400 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1401 }
1402 }
1403
1404 qprintf(quiet, "Images are identical.\n");
1405 ret = 0;
1406
1407 out:
1408 qemu_vfree(buf1);
1409 qemu_vfree(buf2);
1410 blk_unref(blk2);
1411 out2:
1412 blk_unref(blk1);
1413 out3:
1414 qemu_progress_end();
1415 out4:
1416 return ret;
1417 }
1418
1419 enum ImgConvertBlockStatus {
1420 BLK_DATA,
1421 BLK_ZERO,
1422 BLK_BACKING_FILE,
1423 };
1424
1425 typedef struct ImgConvertState {
1426 BlockBackend **src;
1427 int64_t *src_sectors;
1428 int src_cur, src_num;
1429 int64_t src_cur_offset;
1430 int64_t total_sectors;
1431 int64_t allocated_sectors;
1432 enum ImgConvertBlockStatus status;
1433 int64_t sector_next_status;
1434 BlockBackend *target;
1435 bool has_zero_init;
1436 bool compressed;
1437 bool target_has_backing;
1438 int min_sparse;
1439 size_t cluster_sectors;
1440 size_t buf_sectors;
1441 } ImgConvertState;
1442
1443 static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1444 {
1445 assert(sector_num >= s->src_cur_offset);
1446 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1447 s->src_cur_offset += s->src_sectors[s->src_cur];
1448 s->src_cur++;
1449 assert(s->src_cur < s->src_num);
1450 }
1451 }
1452
1453 static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1454 {
1455 int64_t ret;
1456 int n;
1457
1458 convert_select_part(s, sector_num);
1459
1460 assert(s->total_sectors > sector_num);
1461 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1462
1463 if (s->sector_next_status <= sector_num) {
1464 BlockDriverState *file;
1465 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1466 sector_num - s->src_cur_offset,
1467 n, &n, &file);
1468 if (ret < 0) {
1469 return ret;
1470 }
1471
1472 if (ret & BDRV_BLOCK_ZERO) {
1473 s->status = BLK_ZERO;
1474 } else if (ret & BDRV_BLOCK_DATA) {
1475 s->status = BLK_DATA;
1476 } else if (!s->target_has_backing) {
1477 /* Without a target backing file we must copy over the contents of
1478 * the backing file as well. */
1479 /* Check block status of the backing file chain to avoid
1480 * needlessly reading zeroes and limiting the iteration to the
1481 * buffer size */
1482 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1483 sector_num - s->src_cur_offset,
1484 n, &n, &file);
1485 if (ret < 0) {
1486 return ret;
1487 }
1488
1489 if (ret & BDRV_BLOCK_ZERO) {
1490 s->status = BLK_ZERO;
1491 } else {
1492 s->status = BLK_DATA;
1493 }
1494 } else {
1495 s->status = BLK_BACKING_FILE;
1496 }
1497
1498 s->sector_next_status = sector_num + n;
1499 }
1500
1501 n = MIN(n, s->sector_next_status - sector_num);
1502 if (s->status == BLK_DATA) {
1503 n = MIN(n, s->buf_sectors);
1504 }
1505
1506 /* We need to write complete clusters for compressed images, so if an
1507 * unallocated area is shorter than that, we must consider the whole
1508 * cluster allocated. */
1509 if (s->compressed) {
1510 if (n < s->cluster_sectors) {
1511 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1512 s->status = BLK_DATA;
1513 } else {
1514 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1515 }
1516 }
1517
1518 return n;
1519 }
1520
1521 static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1522 uint8_t *buf)
1523 {
1524 int n;
1525 int ret;
1526
1527 assert(nb_sectors <= s->buf_sectors);
1528 while (nb_sectors > 0) {
1529 BlockBackend *blk;
1530 int64_t bs_sectors;
1531
1532 /* In the case of compression with multiple source files, we can get a
1533 * nb_sectors that spreads into the next part. So we must be able to
1534 * read across multiple BDSes for one convert_read() call. */
1535 convert_select_part(s, sector_num);
1536 blk = s->src[s->src_cur];
1537 bs_sectors = s->src_sectors[s->src_cur];
1538
1539 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1540 ret = blk_pread(blk,
1541 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1542 buf, n << BDRV_SECTOR_BITS);
1543 if (ret < 0) {
1544 return ret;
1545 }
1546
1547 sector_num += n;
1548 nb_sectors -= n;
1549 buf += n * BDRV_SECTOR_SIZE;
1550 }
1551
1552 return 0;
1553 }
1554
1555 static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1556 const uint8_t *buf)
1557 {
1558 int ret;
1559
1560 while (nb_sectors > 0) {
1561 int n = nb_sectors;
1562
1563 switch (s->status) {
1564 case BLK_BACKING_FILE:
1565 /* If we have a backing file, leave clusters unallocated that are
1566 * unallocated in the source image, so that the backing file is
1567 * visible at the respective offset. */
1568 assert(s->target_has_backing);
1569 break;
1570
1571 case BLK_DATA:
1572 /* We must always write compressed clusters as a whole, so don't
1573 * try to find zeroed parts in the buffer. We can only save the
1574 * write if the buffer is completely zeroed and we're allowed to
1575 * keep the target sparse. */
1576 if (s->compressed) {
1577 if (s->has_zero_init && s->min_sparse &&
1578 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1579 {
1580 assert(!s->target_has_backing);
1581 break;
1582 }
1583
1584 ret = blk_write_compressed(s->target, sector_num, buf, n);
1585 if (ret < 0) {
1586 return ret;
1587 }
1588 break;
1589 }
1590
1591 /* If there is real non-zero data or we're told to keep the target
1592 * fully allocated (-S 0), we must write it. Otherwise we can treat
1593 * it as zero sectors. */
1594 if (!s->min_sparse ||
1595 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1596 {
1597 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1598 buf, n << BDRV_SECTOR_BITS, 0);
1599 if (ret < 0) {
1600 return ret;
1601 }
1602 break;
1603 }
1604 /* fall-through */
1605
1606 case BLK_ZERO:
1607 if (s->has_zero_init) {
1608 break;
1609 }
1610 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1611 n << BDRV_SECTOR_BITS, 0);
1612 if (ret < 0) {
1613 return ret;
1614 }
1615 break;
1616 }
1617
1618 sector_num += n;
1619 nb_sectors -= n;
1620 buf += n * BDRV_SECTOR_SIZE;
1621 }
1622
1623 return 0;
1624 }
1625
1626 static int convert_do_copy(ImgConvertState *s)
1627 {
1628 uint8_t *buf = NULL;
1629 int64_t sector_num, allocated_done;
1630 int ret;
1631 int n;
1632
1633 /* Check whether we have zero initialisation or can get it efficiently */
1634 s->has_zero_init = s->min_sparse && !s->target_has_backing
1635 ? bdrv_has_zero_init(blk_bs(s->target))
1636 : false;
1637
1638 if (!s->has_zero_init && !s->target_has_backing &&
1639 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1640 {
1641 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1642 if (ret == 0) {
1643 s->has_zero_init = true;
1644 }
1645 }
1646
1647 /* Allocate buffer for copied data. For compressed images, only one cluster
1648 * can be copied at a time. */
1649 if (s->compressed) {
1650 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1651 error_report("invalid cluster size");
1652 ret = -EINVAL;
1653 goto fail;
1654 }
1655 s->buf_sectors = s->cluster_sectors;
1656 }
1657 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1658
1659 /* Calculate allocated sectors for progress */
1660 s->allocated_sectors = 0;
1661 sector_num = 0;
1662 while (sector_num < s->total_sectors) {
1663 n = convert_iteration_sectors(s, sector_num);
1664 if (n < 0) {
1665 ret = n;
1666 goto fail;
1667 }
1668 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1669 {
1670 s->allocated_sectors += n;
1671 }
1672 sector_num += n;
1673 }
1674
1675 /* Do the copy */
1676 s->src_cur = 0;
1677 s->src_cur_offset = 0;
1678 s->sector_next_status = 0;
1679
1680 sector_num = 0;
1681 allocated_done = 0;
1682
1683 while (sector_num < s->total_sectors) {
1684 n = convert_iteration_sectors(s, sector_num);
1685 if (n < 0) {
1686 ret = n;
1687 goto fail;
1688 }
1689 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1690 {
1691 allocated_done += n;
1692 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1693 0);
1694 }
1695
1696 if (s->status == BLK_DATA) {
1697 ret = convert_read(s, sector_num, n, buf);
1698 if (ret < 0) {
1699 error_report("error while reading sector %" PRId64
1700 ": %s", sector_num, strerror(-ret));
1701 goto fail;
1702 }
1703 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1704 n = MIN(n, s->buf_sectors);
1705 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1706 s->status = BLK_DATA;
1707 }
1708
1709 ret = convert_write(s, sector_num, n, buf);
1710 if (ret < 0) {
1711 error_report("error while writing sector %" PRId64
1712 ": %s", sector_num, strerror(-ret));
1713 goto fail;
1714 }
1715
1716 sector_num += n;
1717 }
1718
1719 if (s->compressed) {
1720 /* signal EOF to align */
1721 ret = blk_write_compressed(s->target, 0, NULL, 0);
1722 if (ret < 0) {
1723 goto fail;
1724 }
1725 }
1726
1727 ret = 0;
1728 fail:
1729 qemu_vfree(buf);
1730 return ret;
1731 }
1732
1733 static int img_convert(int argc, char **argv)
1734 {
1735 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
1736 int64_t ret = 0;
1737 int progress = 0, flags, src_flags;
1738 bool writethrough, src_writethrough;
1739 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
1740 BlockDriver *drv, *proto_drv;
1741 BlockBackend **blk = NULL, *out_blk = NULL;
1742 BlockDriverState **bs = NULL, *out_bs = NULL;
1743 int64_t total_sectors;
1744 int64_t *bs_sectors = NULL;
1745 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
1746 BlockDriverInfo bdi;
1747 QemuOpts *opts = NULL;
1748 QemuOptsList *create_opts = NULL;
1749 const char *out_baseimg_param;
1750 char *options = NULL;
1751 const char *snapshot_name = NULL;
1752 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
1753 bool quiet = false;
1754 Error *local_err = NULL;
1755 QemuOpts *sn_opts = NULL;
1756 ImgConvertState state;
1757 bool image_opts = false;
1758
1759 fmt = NULL;
1760 out_fmt = "raw";
1761 cache = "unsafe";
1762 src_cache = BDRV_DEFAULT_CACHE;
1763 out_baseimg = NULL;
1764 compress = 0;
1765 skip_create = 0;
1766 for(;;) {
1767 static const struct option long_options[] = {
1768 {"help", no_argument, 0, 'h'},
1769 {"object", required_argument, 0, OPTION_OBJECT},
1770 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
1771 {0, 0, 0, 0}
1772 };
1773 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1774 long_options, NULL);
1775 if (c == -1) {
1776 break;
1777 }
1778 switch(c) {
1779 case '?':
1780 case 'h':
1781 help();
1782 break;
1783 case 'f':
1784 fmt = optarg;
1785 break;
1786 case 'O':
1787 out_fmt = optarg;
1788 break;
1789 case 'B':
1790 out_baseimg = optarg;
1791 break;
1792 case 'c':
1793 compress = 1;
1794 break;
1795 case 'e':
1796 error_report("option -e is deprecated, please use \'-o "
1797 "encryption\' instead!");
1798 ret = -1;
1799 goto fail_getopt;
1800 case '6':
1801 error_report("option -6 is deprecated, please use \'-o "
1802 "compat6\' instead!");
1803 ret = -1;
1804 goto fail_getopt;
1805 case 'o':
1806 if (!is_valid_option_list(optarg)) {
1807 error_report("Invalid option list: %s", optarg);
1808 ret = -1;
1809 goto fail_getopt;
1810 }
1811 if (!options) {
1812 options = g_strdup(optarg);
1813 } else {
1814 char *old_options = options;
1815 options = g_strdup_printf("%s,%s", options, optarg);
1816 g_free(old_options);
1817 }
1818 break;
1819 case 's':
1820 snapshot_name = optarg;
1821 break;
1822 case 'l':
1823 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1824 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1825 optarg, false);
1826 if (!sn_opts) {
1827 error_report("Failed in parsing snapshot param '%s'",
1828 optarg);
1829 ret = -1;
1830 goto fail_getopt;
1831 }
1832 } else {
1833 snapshot_name = optarg;
1834 }
1835 break;
1836 case 'S':
1837 {
1838 int64_t sval;
1839 char *end;
1840 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
1841 if (sval < 0 || *end) {
1842 error_report("Invalid minimum zero buffer size for sparse output specified");
1843 ret = -1;
1844 goto fail_getopt;
1845 }
1846
1847 min_sparse = sval / BDRV_SECTOR_SIZE;
1848 break;
1849 }
1850 case 'p':
1851 progress = 1;
1852 break;
1853 case 't':
1854 cache = optarg;
1855 break;
1856 case 'T':
1857 src_cache = optarg;
1858 break;
1859 case 'q':
1860 quiet = true;
1861 break;
1862 case 'n':
1863 skip_create = 1;
1864 break;
1865 case OPTION_OBJECT:
1866 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1867 optarg, true);
1868 if (!opts) {
1869 goto fail_getopt;
1870 }
1871 break;
1872 case OPTION_IMAGE_OPTS:
1873 image_opts = true;
1874 break;
1875 }
1876 }
1877
1878 if (qemu_opts_foreach(&qemu_object_opts,
1879 user_creatable_add_opts_foreach,
1880 NULL, NULL)) {
1881 goto fail_getopt;
1882 }
1883
1884 /* Initialize before goto out */
1885 if (quiet) {
1886 progress = 0;
1887 }
1888 qemu_progress_init(progress, 1.0);
1889
1890 bs_n = argc - optind - 1;
1891 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
1892
1893 if (options && has_help_option(options)) {
1894 ret = print_block_option_help(out_filename, out_fmt);
1895 goto out;
1896 }
1897
1898 if (bs_n < 1) {
1899 error_exit("Must specify image file name");
1900 }
1901
1902
1903 if (bs_n > 1 && out_baseimg) {
1904 error_report("-B makes no sense when concatenating multiple input "
1905 "images");
1906 ret = -1;
1907 goto out;
1908 }
1909
1910 src_flags = 0;
1911 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
1912 if (ret < 0) {
1913 error_report("Invalid source cache option: %s", src_cache);
1914 goto out;
1915 }
1916
1917 qemu_progress_print(0, 100);
1918
1919 blk = g_new0(BlockBackend *, bs_n);
1920 bs = g_new0(BlockDriverState *, bs_n);
1921 bs_sectors = g_new(int64_t, bs_n);
1922
1923 total_sectors = 0;
1924 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1925 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
1926 fmt, src_flags, src_writethrough, quiet);
1927 if (!blk[bs_i]) {
1928 ret = -1;
1929 goto out;
1930 }
1931 bs[bs_i] = blk_bs(blk[bs_i]);
1932 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
1933 if (bs_sectors[bs_i] < 0) {
1934 error_report("Could not get size of %s: %s",
1935 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1936 ret = -1;
1937 goto out;
1938 }
1939 total_sectors += bs_sectors[bs_i];
1940 }
1941
1942 if (sn_opts) {
1943 ret = bdrv_snapshot_load_tmp(bs[0],
1944 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1945 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1946 &local_err);
1947 } else if (snapshot_name != NULL) {
1948 if (bs_n > 1) {
1949 error_report("No support for concatenating multiple snapshot");
1950 ret = -1;
1951 goto out;
1952 }
1953
1954 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
1955 }
1956 if (local_err) {
1957 error_reportf_err(local_err, "Failed to load snapshot: ");
1958 ret = -1;
1959 goto out;
1960 }
1961
1962 /* Find driver and parse its options */
1963 drv = bdrv_find_format(out_fmt);
1964 if (!drv) {
1965 error_report("Unknown file format '%s'", out_fmt);
1966 ret = -1;
1967 goto out;
1968 }
1969
1970 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
1971 if (!proto_drv) {
1972 error_report_err(local_err);
1973 ret = -1;
1974 goto out;
1975 }
1976
1977 if (!skip_create) {
1978 if (!drv->create_opts) {
1979 error_report("Format driver '%s' does not support image creation",
1980 drv->format_name);
1981 ret = -1;
1982 goto out;
1983 }
1984
1985 if (!proto_drv->create_opts) {
1986 error_report("Protocol driver '%s' does not support image creation",
1987 proto_drv->format_name);
1988 ret = -1;
1989 goto out;
1990 }
1991
1992 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1993 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
1994
1995 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1996 if (options) {
1997 qemu_opts_do_parse(opts, options, NULL, &local_err);
1998 if (local_err) {
1999 error_report_err(local_err);
2000 ret = -1;
2001 goto out;
2002 }
2003 }
2004
2005 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2006 &error_abort);
2007 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2008 if (ret < 0) {
2009 goto out;
2010 }
2011 }
2012
2013 /* Get backing file name if -o backing_file was used */
2014 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2015 if (out_baseimg_param) {
2016 out_baseimg = out_baseimg_param;
2017 }
2018
2019 /* Check if compression is supported */
2020 if (compress) {
2021 bool encryption =
2022 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2023 const char *preallocation =
2024 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
2025
2026 if (!drv->bdrv_write_compressed) {
2027 error_report("Compression not supported for this file format");
2028 ret = -1;
2029 goto out;
2030 }
2031
2032 if (encryption) {
2033 error_report("Compression and encryption not supported at "
2034 "the same time");
2035 ret = -1;
2036 goto out;
2037 }
2038
2039 if (preallocation
2040 && strcmp(preallocation, "off"))
2041 {
2042 error_report("Compression and preallocation not supported at "
2043 "the same time");
2044 ret = -1;
2045 goto out;
2046 }
2047 }
2048
2049 if (!skip_create) {
2050 /* Create the new image */
2051 ret = bdrv_create(drv, out_filename, opts, &local_err);
2052 if (ret < 0) {
2053 error_reportf_err(local_err, "%s: error while converting %s: ",
2054 out_filename, out_fmt);
2055 goto out;
2056 }
2057 }
2058
2059 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
2060 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2061 if (ret < 0) {
2062 error_report("Invalid cache option: %s", cache);
2063 goto out;
2064 }
2065
2066 /* XXX we should allow --image-opts to trigger use of
2067 * img_open() here, but then we have trouble with
2068 * the bdrv_create() call which takes different params.
2069 * Not critical right now, so fix can wait...
2070 */
2071 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
2072 if (!out_blk) {
2073 ret = -1;
2074 goto out;
2075 }
2076 out_bs = blk_bs(out_blk);
2077
2078 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2079 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2080 * as maximum. */
2081 bufsectors = MIN(32768,
2082 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2083 out_bs->bl.discard_alignment))
2084 );
2085
2086 if (skip_create) {
2087 int64_t output_sectors = blk_nb_sectors(out_blk);
2088 if (output_sectors < 0) {
2089 error_report("unable to get output image length: %s",
2090 strerror(-output_sectors));
2091 ret = -1;
2092 goto out;
2093 } else if (output_sectors < total_sectors) {
2094 error_report("output file is smaller than input file");
2095 ret = -1;
2096 goto out;
2097 }
2098 }
2099
2100 cluster_sectors = 0;
2101 ret = bdrv_get_info(out_bs, &bdi);
2102 if (ret < 0) {
2103 if (compress) {
2104 error_report("could not get block driver info");
2105 goto out;
2106 }
2107 } else {
2108 compress = compress || bdi.needs_compressed_writes;
2109 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2110 }
2111
2112 state = (ImgConvertState) {
2113 .src = blk,
2114 .src_sectors = bs_sectors,
2115 .src_num = bs_n,
2116 .total_sectors = total_sectors,
2117 .target = out_blk,
2118 .compressed = compress,
2119 .target_has_backing = (bool) out_baseimg,
2120 .min_sparse = min_sparse,
2121 .cluster_sectors = cluster_sectors,
2122 .buf_sectors = bufsectors,
2123 };
2124 ret = convert_do_copy(&state);
2125
2126 out:
2127 if (!ret) {
2128 qemu_progress_print(100, 0);
2129 }
2130 qemu_progress_end();
2131 qemu_opts_del(opts);
2132 qemu_opts_free(create_opts);
2133 qemu_opts_del(sn_opts);
2134 blk_unref(out_blk);
2135 g_free(bs);
2136 if (blk) {
2137 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2138 blk_unref(blk[bs_i]);
2139 }
2140 g_free(blk);
2141 }
2142 g_free(bs_sectors);
2143 fail_getopt:
2144 g_free(options);
2145
2146 if (ret) {
2147 return 1;
2148 }
2149 return 0;
2150 }
2151
2152
2153 static void dump_snapshots(BlockDriverState *bs)
2154 {
2155 QEMUSnapshotInfo *sn_tab, *sn;
2156 int nb_sns, i;
2157
2158 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2159 if (nb_sns <= 0)
2160 return;
2161 printf("Snapshot list:\n");
2162 bdrv_snapshot_dump(fprintf, stdout, NULL);
2163 printf("\n");
2164 for(i = 0; i < nb_sns; i++) {
2165 sn = &sn_tab[i];
2166 bdrv_snapshot_dump(fprintf, stdout, sn);
2167 printf("\n");
2168 }
2169 g_free(sn_tab);
2170 }
2171
2172 static void dump_json_image_info_list(ImageInfoList *list)
2173 {
2174 Error *local_err = NULL;
2175 QString *str;
2176 QmpOutputVisitor *ov = qmp_output_visitor_new();
2177 QObject *obj;
2178 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2179 &local_err);
2180 obj = qmp_output_get_qobject(ov);
2181 str = qobject_to_json_pretty(obj);
2182 assert(str != NULL);
2183 printf("%s\n", qstring_get_str(str));
2184 qobject_decref(obj);
2185 qmp_output_visitor_cleanup(ov);
2186 QDECREF(str);
2187 }
2188
2189 static void dump_json_image_info(ImageInfo *info)
2190 {
2191 Error *local_err = NULL;
2192 QString *str;
2193 QmpOutputVisitor *ov = qmp_output_visitor_new();
2194 QObject *obj;
2195 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
2196 obj = qmp_output_get_qobject(ov);
2197 str = qobject_to_json_pretty(obj);
2198 assert(str != NULL);
2199 printf("%s\n", qstring_get_str(str));
2200 qobject_decref(obj);
2201 qmp_output_visitor_cleanup(ov);
2202 QDECREF(str);
2203 }
2204
2205 static void dump_human_image_info_list(ImageInfoList *list)
2206 {
2207 ImageInfoList *elem;
2208 bool delim = false;
2209
2210 for (elem = list; elem; elem = elem->next) {
2211 if (delim) {
2212 printf("\n");
2213 }
2214 delim = true;
2215
2216 bdrv_image_info_dump(fprintf, stdout, elem->value);
2217 }
2218 }
2219
2220 static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2221 {
2222 return strcmp(a, b) == 0;
2223 }
2224
2225 /**
2226 * Open an image file chain and return an ImageInfoList
2227 *
2228 * @filename: topmost image filename
2229 * @fmt: topmost image format (may be NULL to autodetect)
2230 * @chain: true - enumerate entire backing file chain
2231 * false - only topmost image file
2232 *
2233 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2234 * image file. If there was an error a message will have been printed to
2235 * stderr.
2236 */
2237 static ImageInfoList *collect_image_info_list(bool image_opts,
2238 const char *filename,
2239 const char *fmt,
2240 bool chain)
2241 {
2242 ImageInfoList *head = NULL;
2243 ImageInfoList **last = &head;
2244 GHashTable *filenames;
2245 Error *err = NULL;
2246
2247 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2248
2249 while (filename) {
2250 BlockBackend *blk;
2251 BlockDriverState *bs;
2252 ImageInfo *info;
2253 ImageInfoList *elem;
2254
2255 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2256 error_report("Backing file '%s' creates an infinite loop.",
2257 filename);
2258 goto err;
2259 }
2260 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2261
2262 blk = img_open(image_opts, filename, fmt,
2263 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
2264 if (!blk) {
2265 goto err;
2266 }
2267 bs = blk_bs(blk);
2268
2269 bdrv_query_image_info(bs, &info, &err);
2270 if (err) {
2271 error_report_err(err);
2272 blk_unref(blk);
2273 goto err;
2274 }
2275
2276 elem = g_new0(ImageInfoList, 1);
2277 elem->value = info;
2278 *last = elem;
2279 last = &elem->next;
2280
2281 blk_unref(blk);
2282
2283 filename = fmt = NULL;
2284 if (chain) {
2285 if (info->has_full_backing_filename) {
2286 filename = info->full_backing_filename;
2287 } else if (info->has_backing_filename) {
2288 error_report("Could not determine absolute backing filename,"
2289 " but backing filename '%s' present",
2290 info->backing_filename);
2291 goto err;
2292 }
2293 if (info->has_backing_filename_format) {
2294 fmt = info->backing_filename_format;
2295 }
2296 }
2297 }
2298 g_hash_table_destroy(filenames);
2299 return head;
2300
2301 err:
2302 qapi_free_ImageInfoList(head);
2303 g_hash_table_destroy(filenames);
2304 return NULL;
2305 }
2306
2307 static int img_info(int argc, char **argv)
2308 {
2309 int c;
2310 OutputFormat output_format = OFORMAT_HUMAN;
2311 bool chain = false;
2312 const char *filename, *fmt, *output;
2313 ImageInfoList *list;
2314 bool image_opts = false;
2315
2316 fmt = NULL;
2317 output = NULL;
2318 for(;;) {
2319 int option_index = 0;
2320 static const struct option long_options[] = {
2321 {"help", no_argument, 0, 'h'},
2322 {"format", required_argument, 0, 'f'},
2323 {"output", required_argument, 0, OPTION_OUTPUT},
2324 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
2325 {"object", required_argument, 0, OPTION_OBJECT},
2326 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2327 {0, 0, 0, 0}
2328 };
2329 c = getopt_long(argc, argv, "f:h",
2330 long_options, &option_index);
2331 if (c == -1) {
2332 break;
2333 }
2334 switch(c) {
2335 case '?':
2336 case 'h':
2337 help();
2338 break;
2339 case 'f':
2340 fmt = optarg;
2341 break;
2342 case OPTION_OUTPUT:
2343 output = optarg;
2344 break;
2345 case OPTION_BACKING_CHAIN:
2346 chain = true;
2347 break;
2348 case OPTION_OBJECT: {
2349 QemuOpts *opts;
2350 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2351 optarg, true);
2352 if (!opts) {
2353 return 1;
2354 }
2355 } break;
2356 case OPTION_IMAGE_OPTS:
2357 image_opts = true;
2358 break;
2359 }
2360 }
2361 if (optind != argc - 1) {
2362 error_exit("Expecting one image file name");
2363 }
2364 filename = argv[optind++];
2365
2366 if (output && !strcmp(output, "json")) {
2367 output_format = OFORMAT_JSON;
2368 } else if (output && !strcmp(output, "human")) {
2369 output_format = OFORMAT_HUMAN;
2370 } else if (output) {
2371 error_report("--output must be used with human or json as argument.");
2372 return 1;
2373 }
2374
2375 if (qemu_opts_foreach(&qemu_object_opts,
2376 user_creatable_add_opts_foreach,
2377 NULL, NULL)) {
2378 return 1;
2379 }
2380
2381 list = collect_image_info_list(image_opts, filename, fmt, chain);
2382 if (!list) {
2383 return 1;
2384 }
2385
2386 switch (output_format) {
2387 case OFORMAT_HUMAN:
2388 dump_human_image_info_list(list);
2389 break;
2390 case OFORMAT_JSON:
2391 if (chain) {
2392 dump_json_image_info_list(list);
2393 } else {
2394 dump_json_image_info(list->value);
2395 }
2396 break;
2397 }
2398
2399 qapi_free_ImageInfoList(list);
2400 return 0;
2401 }
2402
2403 static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2404 MapEntry *next)
2405 {
2406 switch (output_format) {
2407 case OFORMAT_HUMAN:
2408 if (e->data && !e->has_offset) {
2409 error_report("File contains external, encrypted or compressed clusters.");
2410 exit(1);
2411 }
2412 if (e->data && !e->zero) {
2413 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2414 e->start, e->length,
2415 e->has_offset ? e->offset : 0,
2416 e->has_filename ? e->filename : "");
2417 }
2418 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2419 * Modify the flags here to allow more coalescing.
2420 */
2421 if (next && (!next->data || next->zero)) {
2422 next->data = false;
2423 next->zero = true;
2424 }
2425 break;
2426 case OFORMAT_JSON:
2427 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2428 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
2429 (e->start == 0 ? "[" : ",\n"),
2430 e->start, e->length, e->depth,
2431 e->zero ? "true" : "false",
2432 e->data ? "true" : "false");
2433 if (e->has_offset) {
2434 printf(", \"offset\": %"PRId64"", e->offset);
2435 }
2436 putchar('}');
2437
2438 if (!next) {
2439 printf("]\n");
2440 }
2441 break;
2442 }
2443 }
2444
2445 static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2446 int nb_sectors, MapEntry *e)
2447 {
2448 int64_t ret;
2449 int depth;
2450 BlockDriverState *file;
2451 bool has_offset;
2452
2453 /* As an optimization, we could cache the current range of unallocated
2454 * clusters in each file of the chain, and avoid querying the same
2455 * range repeatedly.
2456 */
2457
2458 depth = 0;
2459 for (;;) {
2460 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2461 &file);
2462 if (ret < 0) {
2463 return ret;
2464 }
2465 assert(nb_sectors);
2466 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2467 break;
2468 }
2469 bs = backing_bs(bs);
2470 if (bs == NULL) {
2471 ret = 0;
2472 break;
2473 }
2474
2475 depth++;
2476 }
2477
2478 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2479
2480 *e = (MapEntry) {
2481 .start = sector_num * BDRV_SECTOR_SIZE,
2482 .length = nb_sectors * BDRV_SECTOR_SIZE,
2483 .data = !!(ret & BDRV_BLOCK_DATA),
2484 .zero = !!(ret & BDRV_BLOCK_ZERO),
2485 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2486 .has_offset = has_offset,
2487 .depth = depth,
2488 .has_filename = file && has_offset,
2489 .filename = file && has_offset ? file->filename : NULL,
2490 };
2491
2492 return 0;
2493 }
2494
2495 static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2496 {
2497 if (curr->length == 0) {
2498 return false;
2499 }
2500 if (curr->zero != next->zero ||
2501 curr->data != next->data ||
2502 curr->depth != next->depth ||
2503 curr->has_filename != next->has_filename ||
2504 curr->has_offset != next->has_offset) {
2505 return false;
2506 }
2507 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2508 return false;
2509 }
2510 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2511 return false;
2512 }
2513 return true;
2514 }
2515
2516 static int img_map(int argc, char **argv)
2517 {
2518 int c;
2519 OutputFormat output_format = OFORMAT_HUMAN;
2520 BlockBackend *blk;
2521 BlockDriverState *bs;
2522 const char *filename, *fmt, *output;
2523 int64_t length;
2524 MapEntry curr = { .length = 0 }, next;
2525 int ret = 0;
2526 bool image_opts = false;
2527
2528 fmt = NULL;
2529 output = NULL;
2530 for (;;) {
2531 int option_index = 0;
2532 static const struct option long_options[] = {
2533 {"help", no_argument, 0, 'h'},
2534 {"format", required_argument, 0, 'f'},
2535 {"output", required_argument, 0, OPTION_OUTPUT},
2536 {"object", required_argument, 0, OPTION_OBJECT},
2537 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2538 {0, 0, 0, 0}
2539 };
2540 c = getopt_long(argc, argv, "f:h",
2541 long_options, &option_index);
2542 if (c == -1) {
2543 break;
2544 }
2545 switch (c) {
2546 case '?':
2547 case 'h':
2548 help();
2549 break;
2550 case 'f':
2551 fmt = optarg;
2552 break;
2553 case OPTION_OUTPUT:
2554 output = optarg;
2555 break;
2556 case OPTION_OBJECT: {
2557 QemuOpts *opts;
2558 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2559 optarg, true);
2560 if (!opts) {
2561 return 1;
2562 }
2563 } break;
2564 case OPTION_IMAGE_OPTS:
2565 image_opts = true;
2566 break;
2567 }
2568 }
2569 if (optind != argc - 1) {
2570 error_exit("Expecting one image file name");
2571 }
2572 filename = argv[optind];
2573
2574 if (output && !strcmp(output, "json")) {
2575 output_format = OFORMAT_JSON;
2576 } else if (output && !strcmp(output, "human")) {
2577 output_format = OFORMAT_HUMAN;
2578 } else if (output) {
2579 error_report("--output must be used with human or json as argument.");
2580 return 1;
2581 }
2582
2583 if (qemu_opts_foreach(&qemu_object_opts,
2584 user_creatable_add_opts_foreach,
2585 NULL, NULL)) {
2586 return 1;
2587 }
2588
2589 blk = img_open(image_opts, filename, fmt, 0, false, false);
2590 if (!blk) {
2591 return 1;
2592 }
2593 bs = blk_bs(blk);
2594
2595 if (output_format == OFORMAT_HUMAN) {
2596 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2597 }
2598
2599 length = blk_getlength(blk);
2600 while (curr.start + curr.length < length) {
2601 int64_t nsectors_left;
2602 int64_t sector_num;
2603 int n;
2604
2605 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2606
2607 /* Probe up to 1 GiB at a time. */
2608 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2609 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2610 ret = get_block_status(bs, sector_num, n, &next);
2611
2612 if (ret < 0) {
2613 error_report("Could not read file metadata: %s", strerror(-ret));
2614 goto out;
2615 }
2616
2617 if (entry_mergeable(&curr, &next)) {
2618 curr.length += next.length;
2619 continue;
2620 }
2621
2622 if (curr.length > 0) {
2623 dump_map_entry(output_format, &curr, &next);
2624 }
2625 curr = next;
2626 }
2627
2628 dump_map_entry(output_format, &curr, NULL);
2629
2630 out:
2631 blk_unref(blk);
2632 return ret < 0;
2633 }
2634
2635 #define SNAPSHOT_LIST 1
2636 #define SNAPSHOT_CREATE 2
2637 #define SNAPSHOT_APPLY 3
2638 #define SNAPSHOT_DELETE 4
2639
2640 static int img_snapshot(int argc, char **argv)
2641 {
2642 BlockBackend *blk;
2643 BlockDriverState *bs;
2644 QEMUSnapshotInfo sn;
2645 char *filename, *snapshot_name = NULL;
2646 int c, ret = 0, bdrv_oflags;
2647 int action = 0;
2648 qemu_timeval tv;
2649 bool quiet = false;
2650 Error *err = NULL;
2651 bool image_opts = false;
2652
2653 bdrv_oflags = BDRV_O_RDWR;
2654 /* Parse commandline parameters */
2655 for(;;) {
2656 static const struct option long_options[] = {
2657 {"help", no_argument, 0, 'h'},
2658 {"object", required_argument, 0, OPTION_OBJECT},
2659 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2660 {0, 0, 0, 0}
2661 };
2662 c = getopt_long(argc, argv, "la:c:d:hq",
2663 long_options, NULL);
2664 if (c == -1) {
2665 break;
2666 }
2667 switch(c) {
2668 case '?':
2669 case 'h':
2670 help();
2671 return 0;
2672 case 'l':
2673 if (action) {
2674 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2675 return 0;
2676 }
2677 action = SNAPSHOT_LIST;
2678 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
2679 break;
2680 case 'a':
2681 if (action) {
2682 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2683 return 0;
2684 }
2685 action = SNAPSHOT_APPLY;
2686 snapshot_name = optarg;
2687 break;
2688 case 'c':
2689 if (action) {
2690 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2691 return 0;
2692 }
2693 action = SNAPSHOT_CREATE;
2694 snapshot_name = optarg;
2695 break;
2696 case 'd':
2697 if (action) {
2698 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
2699 return 0;
2700 }
2701 action = SNAPSHOT_DELETE;
2702 snapshot_name = optarg;
2703 break;
2704 case 'q':
2705 quiet = true;
2706 break;
2707 case OPTION_OBJECT: {
2708 QemuOpts *opts;
2709 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2710 optarg, true);
2711 if (!opts) {
2712 return 1;
2713 }
2714 } break;
2715 case OPTION_IMAGE_OPTS:
2716 image_opts = true;
2717 break;
2718 }
2719 }
2720
2721 if (optind != argc - 1) {
2722 error_exit("Expecting one image file name");
2723 }
2724 filename = argv[optind++];
2725
2726 if (qemu_opts_foreach(&qemu_object_opts,
2727 user_creatable_add_opts_foreach,
2728 NULL, NULL)) {
2729 return 1;
2730 }
2731
2732 /* Open the image */
2733 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
2734 if (!blk) {
2735 return 1;
2736 }
2737 bs = blk_bs(blk);
2738
2739 /* Perform the requested action */
2740 switch(action) {
2741 case SNAPSHOT_LIST:
2742 dump_snapshots(bs);
2743 break;
2744
2745 case SNAPSHOT_CREATE:
2746 memset(&sn, 0, sizeof(sn));
2747 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2748
2749 qemu_gettimeofday(&tv);
2750 sn.date_sec = tv.tv_sec;
2751 sn.date_nsec = tv.tv_usec * 1000;
2752
2753 ret = bdrv_snapshot_create(bs, &sn);
2754 if (ret) {
2755 error_report("Could not create snapshot '%s': %d (%s)",
2756 snapshot_name, ret, strerror(-ret));
2757 }
2758 break;
2759
2760 case SNAPSHOT_APPLY:
2761 ret = bdrv_snapshot_goto(bs, snapshot_name);
2762 if (ret) {
2763 error_report("Could not apply snapshot '%s': %d (%s)",
2764 snapshot_name, ret, strerror(-ret));
2765 }
2766 break;
2767
2768 case SNAPSHOT_DELETE:
2769 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
2770 if (err) {
2771 error_reportf_err(err, "Could not delete snapshot '%s': ",
2772 snapshot_name);
2773 ret = 1;
2774 }
2775 break;
2776 }
2777
2778 /* Cleanup */
2779 blk_unref(blk);
2780 if (ret) {
2781 return 1;
2782 }
2783 return 0;
2784 }
2785
2786 static int img_rebase(int argc, char **argv)
2787 {
2788 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
2789 uint8_t *buf_old = NULL;
2790 uint8_t *buf_new = NULL;
2791 BlockDriverState *bs = NULL;
2792 char *filename;
2793 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2794 int c, flags, src_flags, ret;
2795 bool writethrough, src_writethrough;
2796 int unsafe = 0;
2797 int progress = 0;
2798 bool quiet = false;
2799 Error *local_err = NULL;
2800 bool image_opts = false;
2801
2802 /* Parse commandline parameters */
2803 fmt = NULL;
2804 cache = BDRV_DEFAULT_CACHE;
2805 src_cache = BDRV_DEFAULT_CACHE;
2806 out_baseimg = NULL;
2807 out_basefmt = NULL;
2808 for(;;) {
2809 static const struct option long_options[] = {
2810 {"help", no_argument, 0, 'h'},
2811 {"object", required_argument, 0, OPTION_OBJECT},
2812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
2813 {0, 0, 0, 0}
2814 };
2815 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2816 long_options, NULL);
2817 if (c == -1) {
2818 break;
2819 }
2820 switch(c) {
2821 case '?':
2822 case 'h':
2823 help();
2824 return 0;
2825 case 'f':
2826 fmt = optarg;
2827 break;
2828 case 'F':
2829 out_basefmt = optarg;
2830 break;
2831 case 'b':
2832 out_baseimg = optarg;
2833 break;
2834 case 'u':
2835 unsafe = 1;
2836 break;
2837 case 'p':
2838 progress = 1;
2839 break;
2840 case 't':
2841 cache = optarg;
2842 break;
2843 case 'T':
2844 src_cache = optarg;
2845 break;
2846 case 'q':
2847 quiet = true;
2848 break;
2849 case OPTION_OBJECT: {
2850 QemuOpts *opts;
2851 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2852 optarg, true);
2853 if (!opts) {
2854 return 1;
2855 }
2856 } break;
2857 case OPTION_IMAGE_OPTS:
2858 image_opts = true;
2859 break;
2860 }
2861 }
2862
2863 if (quiet) {
2864 progress = 0;
2865 }
2866
2867 if (optind != argc - 1) {
2868 error_exit("Expecting one image file name");
2869 }
2870 if (!unsafe && !out_baseimg) {
2871 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
2872 }
2873 filename = argv[optind++];
2874
2875 if (qemu_opts_foreach(&qemu_object_opts,
2876 user_creatable_add_opts_foreach,
2877 NULL, NULL)) {
2878 return 1;
2879 }
2880
2881 qemu_progress_init(progress, 2.0);
2882 qemu_progress_print(0, 100);
2883
2884 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
2885 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
2886 if (ret < 0) {
2887 error_report("Invalid cache option: %s", cache);
2888 goto out;
2889 }
2890
2891 src_flags = 0;
2892 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2893 if (ret < 0) {
2894 error_report("Invalid source cache option: %s", src_cache);
2895 goto out;
2896 }
2897
2898 /* The source files are opened read-only, don't care about WCE */
2899 assert((src_flags & BDRV_O_RDWR) == 0);
2900 (void) src_writethrough;
2901
2902 /*
2903 * Open the images.
2904 *
2905 * Ignore the old backing file for unsafe rebase in case we want to correct
2906 * the reference to a renamed or moved backing file.
2907 */
2908 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
2909 if (!blk) {
2910 ret = -1;
2911 goto out;
2912 }
2913 bs = blk_bs(blk);
2914
2915 if (out_basefmt != NULL) {
2916 if (bdrv_find_format(out_basefmt) == NULL) {
2917 error_report("Invalid format name: '%s'", out_basefmt);
2918 ret = -1;
2919 goto out;
2920 }
2921 }
2922
2923 /* For safe rebasing we need to compare old and new backing file */
2924 if (!unsafe) {
2925 char backing_name[PATH_MAX];
2926 QDict *options = NULL;
2927
2928 if (bs->backing_format[0] != '\0') {
2929 options = qdict_new();
2930 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2931 }
2932
2933 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2934 blk_old_backing = blk_new_open(backing_name, NULL,
2935 options, src_flags, &local_err);
2936 if (!blk_old_backing) {
2937 error_reportf_err(local_err,
2938 "Could not open old backing file '%s': ",
2939 backing_name);
2940 goto out;
2941 }
2942
2943 if (out_baseimg[0]) {
2944 if (out_basefmt) {
2945 options = qdict_new();
2946 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2947 } else {
2948 options = NULL;
2949 }
2950
2951 blk_new_backing = blk_new_open(out_baseimg, NULL,
2952 options, src_flags, &local_err);
2953 if (!blk_new_backing) {
2954 error_reportf_err(local_err,
2955 "Could not open new backing file '%s': ",
2956 out_baseimg);
2957 goto out;
2958 }
2959 }
2960 }
2961
2962 /*
2963 * Check each unallocated cluster in the COW file. If it is unallocated,
2964 * accesses go to the backing file. We must therefore compare this cluster
2965 * in the old and new backing file, and if they differ we need to copy it
2966 * from the old backing file into the COW file.
2967 *
2968 * If qemu-img crashes during this step, no harm is done. The content of
2969 * the image is the same as the original one at any time.
2970 */
2971 if (!unsafe) {
2972 int64_t num_sectors;
2973 int64_t old_backing_num_sectors;
2974 int64_t new_backing_num_sectors = 0;
2975 uint64_t sector;
2976 int n;
2977 float local_progress = 0;
2978
2979 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2980 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
2981
2982 num_sectors = blk_nb_sectors(blk);
2983 if (num_sectors < 0) {
2984 error_report("Could not get size of '%s': %s",
2985 filename, strerror(-num_sectors));
2986 ret = -1;
2987 goto out;
2988 }
2989 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
2990 if (old_backing_num_sectors < 0) {
2991 char backing_name[PATH_MAX];
2992
2993 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2994 error_report("Could not get size of '%s': %s",
2995 backing_name, strerror(-old_backing_num_sectors));
2996 ret = -1;
2997 goto out;
2998 }
2999 if (blk_new_backing) {
3000 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
3001 if (new_backing_num_sectors < 0) {
3002 error_report("Could not get size of '%s': %s",
3003 out_baseimg, strerror(-new_backing_num_sectors));
3004 ret = -1;
3005 goto out;
3006 }
3007 }
3008
3009 if (num_sectors != 0) {
3010 local_progress = (float)100 /
3011 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3012 }
3013
3014 for (sector = 0; sector < num_sectors; sector += n) {
3015
3016 /* How many sectors can we handle with the next read? */
3017 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3018 n = (IO_BUF_SIZE / 512);
3019 } else {
3020 n = num_sectors - sector;
3021 }
3022
3023 /* If the cluster is allocated, we don't need to take action */
3024 ret = bdrv_is_allocated(bs, sector, n, &n);
3025 if (ret < 0) {
3026 error_report("error while reading image metadata: %s",
3027 strerror(-ret));
3028 goto out;
3029 }
3030 if (ret) {
3031 continue;
3032 }
3033
3034 /*
3035 * Read old and new backing file and take into consideration that
3036 * backing files may be smaller than the COW image.
3037 */
3038 if (sector >= old_backing_num_sectors) {
3039 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3040 } else {
3041 if (sector + n > old_backing_num_sectors) {
3042 n = old_backing_num_sectors - sector;
3043 }
3044
3045 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3046 buf_old, n << BDRV_SECTOR_BITS);
3047 if (ret < 0) {
3048 error_report("error while reading from old backing file");
3049 goto out;
3050 }
3051 }
3052
3053 if (sector >= new_backing_num_sectors || !blk_new_backing) {
3054 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3055 } else {
3056 if (sector + n > new_backing_num_sectors) {
3057 n = new_backing_num_sectors - sector;
3058 }
3059
3060 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3061 buf_new, n << BDRV_SECTOR_BITS);
3062 if (ret < 0) {
3063 error_report("error while reading from new backing file");
3064 goto out;
3065 }
3066 }
3067
3068 /* If they differ, we need to write to the COW file */
3069 uint64_t written = 0;
3070
3071 while (written < n) {
3072 int pnum;
3073
3074 if (compare_sectors(buf_old + written * 512,
3075 buf_new + written * 512, n - written, &pnum))
3076 {
3077 ret = blk_pwrite(blk,
3078 (sector + written) << BDRV_SECTOR_BITS,
3079 buf_old + written * 512,
3080 pnum << BDRV_SECTOR_BITS, 0);
3081 if (ret < 0) {
3082 error_report("Error while writing to COW image: %s",
3083 strerror(-ret));
3084 goto out;
3085 }
3086 }
3087
3088 written += pnum;
3089 }
3090 qemu_progress_print(local_progress, 100);
3091 }
3092 }
3093
3094 /*
3095 * Change the backing file. All clusters that are different from the old
3096 * backing file are overwritten in the COW file now, so the visible content
3097 * doesn't change when we switch the backing file.
3098 */
3099 if (out_baseimg && *out_baseimg) {
3100 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3101 } else {
3102 ret = bdrv_change_backing_file(bs, NULL, NULL);
3103 }
3104
3105 if (ret == -ENOSPC) {
3106 error_report("Could not change the backing file to '%s': No "
3107 "space left in the file header", out_baseimg);
3108 } else if (ret < 0) {
3109 error_report("Could not change the backing file to '%s': %s",
3110 out_baseimg, strerror(-ret));
3111 }
3112
3113 qemu_progress_print(100, 0);
3114 /*
3115 * TODO At this point it is possible to check if any clusters that are
3116 * allocated in the COW file are the same in the backing file. If so, they
3117 * could be dropped from the COW file. Don't do this before switching the
3118 * backing file, in case of a crash this would lead to corruption.
3119 */
3120 out:
3121 qemu_progress_end();
3122 /* Cleanup */
3123 if (!unsafe) {
3124 blk_unref(blk_old_backing);
3125 blk_unref(blk_new_backing);
3126 }
3127 qemu_vfree(buf_old);
3128 qemu_vfree(buf_new);
3129
3130 blk_unref(blk);
3131 if (ret) {
3132 return 1;
3133 }
3134 return 0;
3135 }
3136
3137 static int img_resize(int argc, char **argv)
3138 {
3139 Error *err = NULL;
3140 int c, ret, relative;
3141 const char *filename, *fmt, *size;
3142 int64_t n, total_size;
3143 bool quiet = false;
3144 BlockBackend *blk = NULL;
3145 QemuOpts *param;
3146
3147 static QemuOptsList resize_options = {
3148 .name = "resize_options",
3149 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3150 .desc = {
3151 {
3152 .name = BLOCK_OPT_SIZE,
3153 .type = QEMU_OPT_SIZE,
3154 .help = "Virtual disk size"
3155 }, {
3156 /* end of list */
3157 }
3158 },
3159 };
3160 bool image_opts = false;
3161
3162 /* Remove size from argv manually so that negative numbers are not treated
3163 * as options by getopt. */
3164 if (argc < 3) {
3165 error_exit("Not enough arguments");
3166 return 1;
3167 }
3168
3169 size = argv[--argc];
3170
3171 /* Parse getopt arguments */
3172 fmt = NULL;
3173 for(;;) {
3174 static const struct option long_options[] = {
3175 {"help", no_argument, 0, 'h'},
3176 {"object", required_argument, 0, OPTION_OBJECT},
3177 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3178 {0, 0, 0, 0}
3179 };
3180 c = getopt_long(argc, argv, "f:hq",
3181 long_options, NULL);
3182 if (c == -1) {
3183 break;
3184 }
3185 switch(c) {
3186 case '?':
3187 case 'h':
3188 help();
3189 break;
3190 case 'f':
3191 fmt = optarg;
3192 break;
3193 case 'q':
3194 quiet = true;
3195 break;
3196 case OPTION_OBJECT: {
3197 QemuOpts *opts;
3198 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3199 optarg, true);
3200 if (!opts) {
3201 return 1;
3202 }
3203 } break;
3204 case OPTION_IMAGE_OPTS:
3205 image_opts = true;
3206 break;
3207 }
3208 }
3209 if (optind != argc - 1) {
3210 error_exit("Expecting one image file name");
3211 }
3212 filename = argv[optind++];
3213
3214 if (qemu_opts_foreach(&qemu_object_opts,
3215 user_creatable_add_opts_foreach,
3216 NULL, NULL)) {
3217 return 1;
3218 }
3219
3220 /* Choose grow, shrink, or absolute resize mode */
3221 switch (size[0]) {
3222 case '+':
3223 relative = 1;
3224 size++;
3225 break;
3226 case '-':
3227 relative = -1;
3228 size++;
3229 break;
3230 default:
3231 relative = 0;
3232 break;
3233 }
3234
3235 /* Parse size */
3236 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
3237 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
3238 if (err) {
3239 error_report_err(err);
3240 ret = -1;
3241 qemu_opts_del(param);
3242 goto out;
3243 }
3244 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3245 qemu_opts_del(param);
3246
3247 blk = img_open(image_opts, filename, fmt,
3248 BDRV_O_RDWR, false, quiet);
3249 if (!blk) {
3250 ret = -1;
3251 goto out;
3252 }
3253
3254 if (relative) {
3255 total_size = blk_getlength(blk) + n * relative;
3256 } else {
3257 total_size = n;
3258 }
3259 if (total_size <= 0) {
3260 error_report("New image size must be positive");
3261 ret = -1;
3262 goto out;
3263 }
3264
3265 ret = blk_truncate(blk, total_size);
3266 switch (ret) {
3267 case 0:
3268 qprintf(quiet, "Image resized.\n");
3269 break;
3270 case -ENOTSUP:
3271 error_report("This image does not support resize");
3272 break;
3273 case -EACCES:
3274 error_report("Image is read-only");
3275 break;
3276 default:
3277 error_report("Error resizing image (%d)", -ret);
3278 break;
3279 }
3280 out:
3281 blk_unref(blk);
3282 if (ret) {
3283 return 1;
3284 }
3285 return 0;
3286 }
3287
3288 static void amend_status_cb(BlockDriverState *bs,
3289 int64_t offset, int64_t total_work_size,
3290 void *opaque)
3291 {
3292 qemu_progress_print(100.f * offset / total_work_size, 0);
3293 }
3294
3295 static int img_amend(int argc, char **argv)
3296 {
3297 Error *err = NULL;
3298 int c, ret = 0;
3299 char *options = NULL;
3300 QemuOptsList *create_opts = NULL;
3301 QemuOpts *opts = NULL;
3302 const char *fmt = NULL, *filename, *cache;
3303 int flags;
3304 bool writethrough;
3305 bool quiet = false, progress = false;
3306 BlockBackend *blk = NULL;
3307 BlockDriverState *bs = NULL;
3308 bool image_opts = false;
3309
3310 cache = BDRV_DEFAULT_CACHE;
3311 for (;;) {
3312 static const struct option long_options[] = {
3313 {"help", no_argument, 0, 'h'},
3314 {"object", required_argument, 0, OPTION_OBJECT},
3315 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3316 {0, 0, 0, 0}
3317 };
3318 c = getopt_long(argc, argv, "ho:f:t:pq",
3319 long_options, NULL);
3320 if (c == -1) {
3321 break;
3322 }
3323
3324 switch (c) {
3325 case 'h':
3326 case '?':
3327 help();
3328 break;
3329 case 'o':
3330 if (!is_valid_option_list(optarg)) {
3331 error_report("Invalid option list: %s", optarg);
3332 ret = -1;
3333 goto out_no_progress;
3334 }
3335 if (!options) {
3336 options = g_strdup(optarg);
3337 } else {
3338 char *old_options = options;
3339 options = g_strdup_printf("%s,%s", options, optarg);
3340 g_free(old_options);
3341 }
3342 break;
3343 case 'f':
3344 fmt = optarg;
3345 break;
3346 case 't':
3347 cache = optarg;
3348 break;
3349 case 'p':
3350 progress = true;
3351 break;
3352 case 'q':
3353 quiet = true;
3354 break;
3355 case OPTION_OBJECT:
3356 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3357 optarg, true);
3358 if (!opts) {
3359 ret = -1;
3360 goto out_no_progress;
3361 }
3362 break;
3363 case OPTION_IMAGE_OPTS:
3364 image_opts = true;
3365 break;
3366 }
3367 }
3368
3369 if (!options) {
3370 error_exit("Must specify options (-o)");
3371 }
3372
3373 if (qemu_opts_foreach(&qemu_object_opts,
3374 user_creatable_add_opts_foreach,
3375 NULL, NULL)) {
3376 ret = -1;
3377 goto out_no_progress;
3378 }
3379
3380 if (quiet) {
3381 progress = false;
3382 }
3383 qemu_progress_init(progress, 1.0);
3384
3385 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3386 if (fmt && has_help_option(options)) {
3387 /* If a format is explicitly specified (and possibly no filename is
3388 * given), print option help here */
3389 ret = print_block_option_help(filename, fmt);
3390 goto out;
3391 }
3392
3393 if (optind != argc - 1) {
3394 error_report("Expecting one image file name");
3395 ret = -1;
3396 goto out;
3397 }
3398
3399 flags = BDRV_O_RDWR;
3400 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
3401 if (ret < 0) {
3402 error_report("Invalid cache option: %s", cache);
3403 goto out;
3404 }
3405
3406 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3407 if (!blk) {
3408 ret = -1;
3409 goto out;
3410 }
3411 bs = blk_bs(blk);
3412
3413 fmt = bs->drv->format_name;
3414
3415 if (has_help_option(options)) {
3416 /* If the format was auto-detected, print option help here */
3417 ret = print_block_option_help(filename, fmt);
3418 goto out;
3419 }
3420
3421 if (!bs->drv->create_opts) {
3422 error_report("Format driver '%s' does not support any options to amend",
3423 fmt);
3424 ret = -1;
3425 goto out;
3426 }
3427
3428 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
3429 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3430 if (options) {
3431 qemu_opts_do_parse(opts, options, NULL, &err);
3432 if (err) {
3433 error_report_err(err);
3434 ret = -1;
3435 goto out;
3436 }
3437 }
3438
3439 /* In case the driver does not call amend_status_cb() */
3440 qemu_progress_print(0.f, 0);
3441 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
3442 qemu_progress_print(100.f, 0);
3443 if (ret < 0) {
3444 error_report("Error while amending options: %s", strerror(-ret));
3445 goto out;
3446 }
3447
3448 out:
3449 qemu_progress_end();
3450
3451 out_no_progress:
3452 blk_unref(blk);
3453 qemu_opts_del(opts);
3454 qemu_opts_free(create_opts);
3455 g_free(options);
3456
3457 if (ret) {
3458 return 1;
3459 }
3460 return 0;
3461 }
3462
3463 static const img_cmd_t img_cmds[] = {
3464 #define DEF(option, callback, arg_string) \
3465 { option, callback },
3466 #include "qemu-img-cmds.h"
3467 #undef DEF
3468 #undef GEN_DOCS
3469 { NULL, NULL, },
3470 };
3471
3472 int main(int argc, char **argv)
3473 {
3474 const img_cmd_t *cmd;
3475 const char *cmdname;
3476 Error *local_error = NULL;
3477 int c;
3478 static const struct option long_options[] = {
3479 {"help", no_argument, 0, 'h'},
3480 {"version", no_argument, 0, 'v'},
3481 {0, 0, 0, 0}
3482 };
3483
3484 #ifdef CONFIG_POSIX
3485 signal(SIGPIPE, SIG_IGN);
3486 #endif
3487
3488 error_set_progname(argv[0]);
3489 qemu_init_exec_dir(argv[0]);
3490
3491 if (qemu_init_main_loop(&local_error)) {
3492 error_report_err(local_error);
3493 exit(EXIT_FAILURE);
3494 }
3495
3496 qcrypto_init(&error_fatal);
3497
3498 module_call_init(MODULE_INIT_QOM);
3499 bdrv_init();
3500 if (argc < 2) {
3501 error_exit("Not enough arguments");
3502 }
3503 cmdname = argv[1];
3504
3505 qemu_add_opts(&qemu_object_opts);
3506 qemu_add_opts(&qemu_source_opts);
3507
3508 /* find the command */
3509 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
3510 if (!strcmp(cmdname, cmd->name)) {
3511 return cmd->handler(argc - 1, argv + 1);
3512 }
3513 }
3514
3515 c = getopt_long(argc, argv, "h", long_options, NULL);
3516
3517 if (c == 'h') {
3518 help();
3519 }
3520 if (c == 'v') {
3521 printf(QEMU_IMG_VERSION);
3522 return 0;
3523 }
3524
3525 /* not found */
3526 error_exit("Command not found: %s", cmdname);
3527 }