]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-img.c
Makefile: Derive "PKGVERSION" from "git describe" by default
[mirror_qemu.git] / qemu-img.c
CommitLineData
ea2384d3 1/*
fb43f4dd 2 * QEMU disk image utility
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
ea2384d3
FB
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 */
80c71a24 24#include "qemu/osdep.h"
67a1de0d 25#include "qemu-version.h"
da34e65c 26#include "qapi/error.h"
c054b3fd
BC
27#include "qapi-visit.h"
28#include "qapi/qmp-output-visitor.h"
cc7a8ea7 29#include "qapi/qmp/qerror.h"
7b1b5d19 30#include "qapi/qmp/qjson.h"
f348b6d1 31#include "qemu/cutils.h"
3babeb15 32#include "qemu/config-file.h"
1de7afc9
PB
33#include "qemu/option.h"
34#include "qemu/error-report.h"
3babeb15 35#include "qom/object_interfaces.h"
9c17d615 36#include "sysemu/sysemu.h"
26f54e9a 37#include "sysemu/block-backend.h"
737e150e 38#include "block/block_int.h"
d4a3238a 39#include "block/blockjob.h"
f364ec65 40#include "block/qapi.h"
c2297088 41#include "crypto/init.h"
c054b3fd 42#include <getopt.h>
e8445331 43
61979a6a 44#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
5f6979cb
JC
45 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
46
c227f099 47typedef struct img_cmd_t {
153859be
SB
48 const char *name;
49 int (*handler)(int argc, char **argv);
c227f099 50} img_cmd_t;
153859be 51
8599ea4c
FS
52enum {
53 OPTION_OUTPUT = 256,
54 OPTION_BACKING_CHAIN = 257,
3babeb15 55 OPTION_OBJECT = 258,
eb769f74 56 OPTION_IMAGE_OPTS = 259,
8599ea4c
FS
57};
58
59typedef enum OutputFormat {
60 OFORMAT_JSON,
61 OFORMAT_HUMAN,
62} OutputFormat;
63
e6996143 64/* Default to cache=writeback as data integrity is not important for qemu-img */
661a0f71 65#define BDRV_DEFAULT_CACHE "writeback"
137519ce 66
00c6d403 67static void format_print(void *opaque, const char *name)
ea2384d3 68{
00c6d403 69 printf(" %s", name);
ea2384d3
FB
70}
71
ac1307ab
FZ
72static 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
d2c639d6 86/* Please keep in synch with qemu-img.texi */
ac1307ab 87static void QEMU_NORETURN help(void)
ea2384d3 88{
e00291c0 89 const char *help_msg =
5f6979cb 90 QEMU_IMG_VERSION
3f020d70 91 "usage: qemu-img command [command options]\n"
92 "QEMU disk image utility\n"
93 "\n"
94 "Command syntax:\n"
153859be
SB
95#define DEF(option, callback, arg_string) \
96 " " arg_string "\n"
97#include "qemu-img-cmds.h"
98#undef DEF
99#undef GEN_DOCS
3f020d70 100 "\n"
101 "Command parameters:\n"
102 " 'filename' is a disk image filename\n"
3babeb15
DB
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"
3f020d70 107 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
661a0f71 108 " 'cache' is the cache mode used to write the output disk image, the valid\n"
80ccf93b
LY
109 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
110 " 'directsync' and 'unsafe' (default for convert)\n"
bb87fdf8
SH
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"
3f020d70 113 " 'size' is the disk image size in bytes. Optional suffixes\n"
5e00984a
KW
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"
3f020d70 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"
ef80654d
WX
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"
3f020d70 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"
6b837bc4 132 " '-p' show progress of command (only certain commands)\n"
f382d43a 133 " '-q' use Quiet mode - do not print any output (except errors)\n"
11b6699a
PL
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"
c054b3fd 139 " '--output' takes the format in which the output must be done (human or json)\n"
b2e10493
AD
140 " '-n' skips the target volume creation (useful if the volume is created\n"
141 " prior to running qemu-img)\n"
3f020d70 142 "\n"
4534ff54
KW
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"
0546b8c2 147 " hiding corruption that has already occurred.\n"
4534ff54 148 "\n"
3f020d70 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"
d14ed18c
MR
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";
e00291c0
PB
160
161 printf("%s\nSupported formats:", help_msg);
00c6d403 162 bdrv_iterate_format(format_print, NULL);
ea2384d3 163 printf("\n");
ac1307ab 164 exit(EXIT_SUCCESS);
ea2384d3
FB
165}
166
3babeb15
DB
167static 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
eb769f74
DB
176static 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
7c30f657 185static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
f382d43a
MR
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
ea2384d3 197
4ac8aacd
JS
198static int print_block_option_help(const char *filename, const char *fmt)
199{
200 BlockDriver *drv, *proto_drv;
83d0521a 201 QemuOptsList *create_opts = NULL;
b65a5e12 202 Error *local_err = NULL;
4ac8aacd
JS
203
204 /* Find driver and parse its options */
205 drv = bdrv_find_format(fmt);
206 if (!drv) {
15654a6d 207 error_report("Unknown file format '%s'", fmt);
4ac8aacd
JS
208 return 1;
209 }
210
c282e1fd 211 create_opts = qemu_opts_append(create_opts, drv->create_opts);
a283cb6e 212 if (filename) {
b65a5e12 213 proto_drv = bdrv_find_protocol(filename, true, &local_err);
a283cb6e 214 if (!proto_drv) {
2867ce4a 215 error_report_err(local_err);
83d0521a 216 qemu_opts_free(create_opts);
a283cb6e
KW
217 return 1;
218 }
c282e1fd 219 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
a283cb6e
KW
220 }
221
83d0521a
CL
222 qemu_opts_print_help(create_opts);
223 qemu_opts_free(create_opts);
4ac8aacd
JS
224 return 0;
225}
226
eb769f74
DB
227
228static int img_open_password(BlockBackend *blk, const char *filename,
abb06c5a 229 int flags, bool quiet)
75c23805
FB
230{
231 BlockDriverState *bs;
75c23805 232 char password[256];
eb769f74
DB
233
234 bs = blk_bs(blk);
4ef130fc
DB
235 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
236 !(flags & BDRV_O_NO_IO)) {
eb769f74
DB
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
efaa7c4e 251static BlockBackend *img_open_opts(const char *optstr,
ce099547 252 QemuOpts *opts, int flags, bool writethrough,
abb06c5a 253 bool quiet)
eb769f74
DB
254{
255 QDict *options;
256 Error *local_err = NULL;
257 BlockBackend *blk;
258 options = qemu_opts_to_qdict(opts, NULL);
efaa7c4e 259 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
eb769f74 260 if (!blk) {
143605a2 261 error_reportf_err(local_err, "Could not open '%s': ", optstr);
eb769f74
DB
262 return NULL;
263 }
ce099547 264 blk_set_enable_write_cache(blk, !writethrough);
eb769f74 265
abb06c5a 266 if (img_open_password(blk, optstr, flags, quiet) < 0) {
eb769f74
DB
267 blk_unref(blk);
268 return NULL;
269 }
270 return blk;
271}
272
efaa7c4e 273static BlockBackend *img_open_file(const char *filename,
eb769f74 274 const char *fmt, int flags,
ce099547 275 bool writethrough, bool quiet)
eb769f74
DB
276{
277 BlockBackend *blk;
34b5d2c6 278 Error *local_err = NULL;
5bd31326 279 QDict *options = NULL;
ad717139 280
75c23805 281 if (fmt) {
5bd31326
HR
282 options = qdict_new();
283 qdict_put(options, "driver", qstring_from_str(fmt));
75c23805 284 }
b9eaf9ec 285
efaa7c4e 286 blk = blk_new_open(filename, NULL, options, flags, &local_err);
5bd31326 287 if (!blk) {
c29b77f9 288 error_reportf_err(local_err, "Could not open '%s': ", filename);
eb769f74 289 return NULL;
75c23805 290 }
ce099547 291 blk_set_enable_write_cache(blk, !writethrough);
b9eaf9ec 292
abb06c5a 293 if (img_open_password(blk, filename, flags, quiet) < 0) {
eb769f74
DB
294 blk_unref(blk);
295 return NULL;
296 }
297 return blk;
298}
299
300
efaa7c4e 301static BlockBackend *img_open(bool image_opts,
eb769f74 302 const char *filename,
ce099547 303 const char *fmt, int flags, bool writethrough,
abb06c5a 304 bool quiet)
eb769f74
DB
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 }
ce099547 318 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
eb769f74 319 } else {
ce099547 320 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
75c23805 321 }
7e7d56d9 322 return blk;
75c23805
FB
323}
324
eb769f74 325
83d0521a 326static int add_old_style_options(const char *fmt, QemuOpts *opts,
eec77d9e
JS
327 const char *base_filename,
328 const char *base_fmt)
efa84d43 329{
6750e795
MA
330 Error *err = NULL;
331
efa84d43 332 if (base_filename) {
f43e47db 333 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
6750e795 334 if (err) {
15654a6d
JS
335 error_report("Backing file not supported for file format '%s'",
336 fmt);
6750e795 337 error_free(err);
c2abccec 338 return -1;
efa84d43
KW
339 }
340 }
341 if (base_fmt) {
f43e47db 342 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
6750e795 343 if (err) {
15654a6d
JS
344 error_report("Backing file format not supported for file "
345 "format '%s'", fmt);
6750e795 346 error_free(err);
c2abccec 347 return -1;
efa84d43
KW
348 }
349 }
c2abccec 350 return 0;
efa84d43
KW
351}
352
ea2384d3
FB
353static int img_create(int argc, char **argv)
354{
a9300911 355 int c;
1da7cfbd 356 uint64_t img_size = -1;
ea2384d3 357 const char *fmt = "raw";
9230eaf6 358 const char *base_fmt = NULL;
ea2384d3
FB
359 const char *filename;
360 const char *base_filename = NULL;
9ea2ea71 361 char *options = NULL;
9b37525a 362 Error *local_err = NULL;
f382d43a 363 bool quiet = false;
3b46e624 364
ea2384d3 365 for(;;) {
3babeb15
DB
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);
b8fb60da 373 if (c == -1) {
ea2384d3 374 break;
b8fb60da 375 }
ea2384d3 376 switch(c) {
ef87394c 377 case '?':
ea2384d3
FB
378 case 'h':
379 help();
380 break;
9230eaf6
AL
381 case 'F':
382 base_fmt = optarg;
383 break;
ea2384d3
FB
384 case 'b':
385 base_filename = optarg;
386 break;
387 case 'f':
388 fmt = optarg;
389 break;
390 case 'e':
9d42e15d 391 error_report("option -e is deprecated, please use \'-o "
eec77d9e 392 "encryption\' instead!");
77386bf6 393 goto fail;
d8871c5a 394 case '6':
9d42e15d 395 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 396 "compat6\' instead!");
77386bf6 397 goto fail;
9ea2ea71 398 case 'o':
77386bf6
KW
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 }
9ea2ea71 410 break;
f382d43a
MR
411 case 'q':
412 quiet = true;
413 break;
3babeb15
DB
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;
ea2384d3
FB
422 }
423 }
9230eaf6 424
b50cbabc 425 /* Get the filename */
a283cb6e
KW
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
b8fb60da 432 if (optind >= argc) {
ac1307ab 433 error_exit("Expecting image file name");
b8fb60da 434 }
a283cb6e 435 optind++;
b50cbabc 436
3babeb15
DB
437 if (qemu_opts_foreach(&qemu_object_opts,
438 user_creatable_add_opts_foreach,
51b9b478 439 NULL, NULL)) {
3babeb15
DB
440 goto fail;
441 }
442
1da7cfbd
JS
443 /* Get image size, if specified */
444 if (optind < argc) {
70b4f4bb 445 int64_t sval;
e36b3695 446 char *end;
4677bb40
MAL
447 sval = qemu_strtosz_suffix(argv[optind++], &end,
448 QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 449 if (sval < 0 || *end) {
79443397
LG
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, "
5e00984a
KW
454 "G, T, P or E suffixes for ");
455 error_report("kilobytes, megabytes, gigabytes, terabytes, "
456 "petabytes and exabytes.");
79443397 457 }
77386bf6 458 goto fail;
1da7cfbd
JS
459 }
460 img_size = (uint64_t)sval;
461 }
fc11eb26 462 if (optind != argc) {
ac1307ab 463 error_exit("Unexpected argument: %s", argv[optind]);
fc11eb26 464 }
1da7cfbd 465
9b37525a 466 bdrv_img_create(filename, fmt, base_filename, base_fmt,
61de4c68 467 options, img_size, 0, &local_err, quiet);
84d18f06 468 if (local_err) {
c29b77f9 469 error_reportf_err(local_err, "%s: ", filename);
77386bf6 470 goto fail;
c2abccec 471 }
a9300911 472
77386bf6 473 g_free(options);
ea2384d3 474 return 0;
77386bf6
KW
475
476fail:
477 g_free(options);
478 return 1;
ea2384d3
FB
479}
480
f382d43a 481static void dump_json_image_check(ImageCheck *check, bool quiet)
8599ea4c 482{
4399c438 483 Error *local_err = NULL;
8599ea4c
FS
484 QString *str;
485 QmpOutputVisitor *ov = qmp_output_visitor_new();
486 QObject *obj;
51e72bc1
EB
487 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
488 &local_err);
8599ea4c
FS
489 obj = qmp_output_get_qobject(ov);
490 str = qobject_to_json_pretty(obj);
491 assert(str != NULL);
f382d43a 492 qprintf(quiet, "%s\n", qstring_get_str(str));
8599ea4c
FS
493 qobject_decref(obj);
494 qmp_output_visitor_cleanup(ov);
495 QDECREF(str);
496}
497
f382d43a 498static void dump_human_image_check(ImageCheck *check, bool quiet)
8599ea4c
FS
499{
500 if (!(check->corruptions || check->leaks || check->check_errors)) {
f382d43a 501 qprintf(quiet, "No errors were found on the image.\n");
8599ea4c
FS
502 } else {
503 if (check->corruptions) {
f382d43a
MR
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);
8599ea4c
FS
508 }
509
510 if (check->leaks) {
f382d43a
MR
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);
8599ea4c
FS
515 }
516
517 if (check->check_errors) {
f382d43a
MR
518 qprintf(quiet,
519 "\n%" PRId64
520 " internal errors have occurred during the check.\n",
521 check->check_errors);
8599ea4c
FS
522 }
523 }
524
525 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
f382d43a
MR
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);
8599ea4c
FS
533 }
534
535 if (check->image_end_offset) {
f382d43a
MR
536 qprintf(quiet,
537 "Image end offset: %" PRId64 "\n", check->image_end_offset);
8599ea4c
FS
538 }
539}
540
541static 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;
e6439d78
SH
574 check->compressed_clusters = result.bfi.compressed_clusters;
575 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
8599ea4c
FS
576
577 return 0;
578}
579
e076f338
KW
580/*
581 * Checks an image for consistency. Exit codes:
582 *
d6635c4d
HR
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
e076f338 588 */
1585969c
AL
589static int img_check(int argc, char **argv)
590{
591 int c, ret;
8599ea4c 592 OutputFormat output_format = OFORMAT_HUMAN;
40055951 593 const char *filename, *fmt, *output, *cache;
26f54e9a 594 BlockBackend *blk;
1585969c 595 BlockDriverState *bs;
4534ff54 596 int fix = 0;
ce099547
KW
597 int flags = BDRV_O_CHECK;
598 bool writethrough;
7e7d56d9 599 ImageCheck *check;
f382d43a 600 bool quiet = false;
eb769f74 601 bool image_opts = false;
1585969c
AL
602
603 fmt = NULL;
8599ea4c 604 output = NULL;
40055951 605 cache = BDRV_DEFAULT_CACHE;
ce099547 606
1585969c 607 for(;;) {
8599ea4c
FS
608 int option_index = 0;
609 static const struct option long_options[] = {
610 {"help", no_argument, 0, 'h'},
611 {"format", required_argument, 0, 'f'},
4fd6a984 612 {"repair", required_argument, 0, 'r'},
8599ea4c 613 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 614 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 615 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
8599ea4c
FS
616 {0, 0, 0, 0}
617 };
40055951 618 c = getopt_long(argc, argv, "hf:r:T:q",
8599ea4c 619 long_options, &option_index);
b8fb60da 620 if (c == -1) {
1585969c 621 break;
b8fb60da 622 }
1585969c 623 switch(c) {
ef87394c 624 case '?':
1585969c
AL
625 case 'h':
626 help();
627 break;
628 case 'f':
629 fmt = optarg;
630 break;
4534ff54
KW
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 {
ac1307ab
FZ
639 error_exit("Unknown option value for -r "
640 "(expecting 'leaks' or 'all'): %s", optarg);
4534ff54
KW
641 }
642 break;
8599ea4c
FS
643 case OPTION_OUTPUT:
644 output = optarg;
645 break;
40055951
HR
646 case 'T':
647 cache = optarg;
648 break;
f382d43a
MR
649 case 'q':
650 quiet = true;
651 break;
3babeb15
DB
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;
eb769f74
DB
660 case OPTION_IMAGE_OPTS:
661 image_opts = true;
662 break;
1585969c
AL
663 }
664 }
fc11eb26 665 if (optind != argc - 1) {
ac1307ab 666 error_exit("Expecting one image file name");
b8fb60da 667 }
1585969c
AL
668 filename = argv[optind++];
669
8599ea4c
FS
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
3babeb15
DB
679 if (qemu_opts_foreach(&qemu_object_opts,
680 user_creatable_add_opts_foreach,
51b9b478 681 NULL, NULL)) {
3babeb15
DB
682 return 1;
683 }
684
ce099547 685 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
686 if (ret < 0) {
687 error_report("Invalid source cache option: %s", cache);
688 return 1;
689 }
690
ce099547 691 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
692 if (!blk) {
693 return 1;
c2abccec 694 }
7e7d56d9 695 bs = blk_bs(blk);
8599ea4c
FS
696
697 check = g_new0(ImageCheck, 1);
698 ret = collect_image_check(bs, check, filename, fmt, fix);
e076f338
KW
699
700 if (ret == -ENOTSUP) {
55d492d7 701 error_report("This image format does not support checks");
fefddf95 702 ret = 63;
8599ea4c 703 goto fail;
e076f338
KW
704 }
705
8599ea4c
FS
706 if (check->corruptions_fixed || check->leaks_fixed) {
707 int corruptions_fixed, leaks_fixed;
ccf34716 708
8599ea4c
FS
709 leaks_fixed = check->leaks_fixed;
710 corruptions_fixed = check->corruptions_fixed;
e076f338 711
8599ea4c 712 if (output_format == OFORMAT_HUMAN) {
f382d43a
MR
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);
e076f338
KW
720 }
721
8599ea4c 722 ret = collect_image_check(bs, check, filename, fmt, 0);
1585969c 723
8599ea4c
FS
724 check->leaks_fixed = leaks_fixed;
725 check->corruptions_fixed = corruptions_fixed;
f8111c24
DXW
726 }
727
832390a5
HR
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 }
c6bb9ad1
FS
737 }
738
8599ea4c 739 if (ret || check->check_errors) {
832390a5
HR
740 if (ret) {
741 error_report("Check failed: %s", strerror(-ret));
742 } else {
743 error_report("Check failed");
744 }
8599ea4c
FS
745 ret = 1;
746 goto fail;
c2abccec 747 }
e076f338 748
8599ea4c
FS
749 if (check->corruptions) {
750 ret = 2;
751 } else if (check->leaks) {
752 ret = 3;
e076f338 753 } else {
8599ea4c 754 ret = 0;
e076f338 755 }
8599ea4c
FS
756
757fail:
758 qapi_free_ImageCheck(check);
26f54e9a 759 blk_unref(blk);
8599ea4c 760 return ret;
1585969c
AL
761}
762
d4a3238a
HR
763typedef struct CommonBlockJobCBInfo {
764 BlockDriverState *bs;
765 Error **errp;
766} CommonBlockJobCBInfo;
767
768static 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 }
d4a3238a
HR
775}
776
777static void run_block_job(BlockJob *job, Error **errp)
778{
b75536c9 779 AioContext *aio_context = blk_get_aio_context(job->blk);
d4a3238a
HR
780
781 do {
782 aio_poll(aio_context, true);
62547b8a
JS
783 qemu_progress_print(job->len ?
784 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
d4a3238a
HR
785 } while (!job->ready);
786
787 block_job_complete_sync(job, errp);
687fa1d8
HR
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);
d4a3238a
HR
792}
793
ea2384d3
FB
794static int img_commit(int argc, char **argv)
795{
661a0f71 796 int c, ret, flags;
1b22bffd 797 const char *filename, *fmt, *cache, *base;
26f54e9a 798 BlockBackend *blk;
d4a3238a 799 BlockDriverState *bs, *base_bs;
687fa1d8 800 bool progress = false, quiet = false, drop = false;
ce099547 801 bool writethrough;
d4a3238a
HR
802 Error *local_err = NULL;
803 CommonBlockJobCBInfo cbi;
eb769f74 804 bool image_opts = false;
ea2384d3
FB
805
806 fmt = NULL;
661a0f71 807 cache = BDRV_DEFAULT_CACHE;
1b22bffd 808 base = NULL;
ea2384d3 809 for(;;) {
3babeb15
DB
810 static const struct option long_options[] = {
811 {"help", no_argument, 0, 'h'},
812 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 813 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
814 {0, 0, 0, 0}
815 };
816 c = getopt_long(argc, argv, "f:ht:b:dpq",
817 long_options, NULL);
b8fb60da 818 if (c == -1) {
ea2384d3 819 break;
b8fb60da 820 }
ea2384d3 821 switch(c) {
ef87394c 822 case '?':
ea2384d3
FB
823 case 'h':
824 help();
825 break;
826 case 'f':
827 fmt = optarg;
828 break;
661a0f71
FS
829 case 't':
830 cache = optarg;
831 break;
1b22bffd
HR
832 case 'b':
833 base = optarg;
834 /* -b implies -d */
835 drop = true;
836 break;
9a86fe48
HR
837 case 'd':
838 drop = true;
839 break;
687fa1d8
HR
840 case 'p':
841 progress = true;
842 break;
f382d43a
MR
843 case 'q':
844 quiet = true;
845 break;
3babeb15
DB
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;
eb769f74
DB
854 case OPTION_IMAGE_OPTS:
855 image_opts = true;
856 break;
ea2384d3
FB
857 }
858 }
687fa1d8
HR
859
860 /* Progress is not shown in Quiet mode */
861 if (quiet) {
862 progress = false;
863 }
864
fc11eb26 865 if (optind != argc - 1) {
ac1307ab 866 error_exit("Expecting one image file name");
b8fb60da 867 }
ea2384d3
FB
868 filename = argv[optind++];
869
3babeb15
DB
870 if (qemu_opts_foreach(&qemu_object_opts,
871 user_creatable_add_opts_foreach,
51b9b478 872 NULL, NULL)) {
3babeb15
DB
873 return 1;
874 }
875
9a86fe48 876 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
ce099547 877 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
878 if (ret < 0) {
879 error_report("Invalid cache option: %s", cache);
a3981eb9 880 return 1;
661a0f71
FS
881 }
882
ce099547 883 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
884 if (!blk) {
885 return 1;
c2abccec 886 }
7e7d56d9
MA
887 bs = blk_bs(blk);
888
687fa1d8
HR
889 qemu_progress_init(progress, 1.f);
890 qemu_progress_print(0.f, 100);
891
1b22bffd
HR
892 if (base) {
893 base_bs = bdrv_find_backing_image(bs, base);
894 if (!base_bs) {
c6bd8c70 895 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
1b22bffd
HR
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. */
760e0063 902 base_bs = backing_bs(bs);
1b22bffd
HR
903 if (!base_bs) {
904 error_setg(&local_err, "Image does not have a backing file");
905 goto done;
906 }
d4a3238a
HR
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;
ea2384d3
FB
918 }
919
3f09bfbc
KW
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. */
9a86fe48 924 if (!drop) {
3f09bfbc 925 bdrv_ref(bs);
9a86fe48
HR
926 }
927
d4a3238a 928 run_block_job(bs->job, &local_err);
9a86fe48
HR
929 if (local_err) {
930 goto unref_backing;
931 }
932
3f09bfbc
KW
933 if (!drop && bs->drv->bdrv_make_empty) {
934 ret = bs->drv->bdrv_make_empty(bs);
9a86fe48
HR
935 if (ret) {
936 error_setg_errno(&local_err, -ret, "Could not empty %s",
937 filename);
938 goto unref_backing;
939 }
940 }
941
942unref_backing:
943 if (!drop) {
3f09bfbc 944 bdrv_unref(bs);
9a86fe48 945 }
d4a3238a
HR
946
947done:
687fa1d8
HR
948 qemu_progress_end();
949
26f54e9a 950 blk_unref(blk);
d4a3238a
HR
951
952 if (local_err) {
6936f299 953 error_report_err(local_err);
c2abccec
MK
954 return 1;
955 }
d4a3238a
HR
956
957 qprintf(quiet, "Image committed.\n");
ea2384d3
FB
958 return 0;
959}
960
f58c7b35
TS
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 */
ea2384d3
FB
968static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
969{
1a6d39fd
SH
970 bool is_zero;
971 int i;
ea2384d3
FB
972
973 if (n <= 0) {
974 *pnum = 0;
975 return 0;
976 }
1a6d39fd 977 is_zero = buffer_is_zero(buf, 512);
ea2384d3
FB
978 for(i = 1; i < n; i++) {
979 buf += 512;
1a6d39fd 980 if (is_zero != buffer_is_zero(buf, 512)) {
ea2384d3 981 break;
1a6d39fd 982 }
ea2384d3
FB
983 }
984 *pnum = i;
1a6d39fd 985 return !is_zero;
ea2384d3
FB
986}
987
a22f123c
KW
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 */
993static 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
3e85c6fd
KW
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 */
1037static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1038 int *pnum)
1039{
8c1ac475
RK
1040 bool res;
1041 int i;
3e85c6fd
KW
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
80ee15a6 1062#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3 1063
d14ed18c
MR
1064static int64_t sectors_to_bytes(int64_t sectors)
1065{
1066 return sectors << BDRV_SECTOR_BITS;
1067}
1068
1069static 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 *
f1d3cd79 1080 * @param blk: BlockBackend for the image
d14ed18c
MR
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 */
f1d3cd79 1087static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
d14ed18c
MR
1088 int sect_count, const char *filename,
1089 uint8_t *buffer, bool quiet)
1090{
1091 int pnum, ret = 0;
9166920a
EB
1092 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1093 sect_count << BDRV_SECTOR_BITS);
d14ed18c
MR
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 */
1116static int img_compare(int argc, char **argv)
1117{
40055951 1118 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
26f54e9a 1119 BlockBackend *blk1, *blk2;
d14ed18c
MR
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;
40055951 1127 int flags;
ce099547 1128 bool writethrough;
d14ed18c
MR
1129 int64_t total_sectors;
1130 int64_t sector_num = 0;
1131 int64_t nb_sectors;
1132 int c, pnum;
d14ed18c 1133 uint64_t progress_base;
eb769f74 1134 bool image_opts = false;
d14ed18c 1135
40055951 1136 cache = BDRV_DEFAULT_CACHE;
d14ed18c 1137 for (;;) {
3babeb15
DB
1138 static const struct option long_options[] = {
1139 {"help", no_argument, 0, 'h'},
1140 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1141 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
1142 {0, 0, 0, 0}
1143 };
1144 c = getopt_long(argc, argv, "hf:F:T:pqs",
1145 long_options, NULL);
d14ed18c
MR
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;
40055951
HR
1160 case 'T':
1161 cache = optarg;
1162 break;
d14ed18c
MR
1163 case 'p':
1164 progress = true;
1165 break;
1166 case 'q':
1167 quiet = true;
1168 break;
1169 case 's':
1170 strict = true;
1171 break;
3babeb15
DB
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;
eb769f74
DB
1181 case OPTION_IMAGE_OPTS:
1182 image_opts = true;
1183 break;
d14ed18c
MR
1184 }
1185 }
1186
1187 /* Progress is not shown in Quiet mode */
1188 if (quiet) {
1189 progress = false;
1190 }
1191
1192
fc11eb26 1193 if (optind != argc - 2) {
ac1307ab 1194 error_exit("Expecting two image file names");
d14ed18c
MR
1195 }
1196 filename1 = argv[optind++];
1197 filename2 = argv[optind++];
1198
3babeb15
DB
1199 if (qemu_opts_foreach(&qemu_object_opts,
1200 user_creatable_add_opts_foreach,
51b9b478 1201 NULL, NULL)) {
3babeb15
DB
1202 ret = 2;
1203 goto out4;
1204 }
1205
cbda016d
SH
1206 /* Initialize before goto out */
1207 qemu_progress_init(progress, 2.0);
1208
ce099547
KW
1209 flags = 0;
1210 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
1211 if (ret < 0) {
1212 error_report("Invalid source cache option: %s", cache);
1213 ret = 2;
1214 goto out3;
1215 }
1216
ce099547 1217 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
7e7d56d9 1218 if (!blk1) {
d14ed18c 1219 ret = 2;
7e7d56d9 1220 goto out3;
d14ed18c
MR
1221 }
1222
ce099547 1223 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
7e7d56d9 1224 if (!blk2) {
d14ed18c 1225 ret = 2;
7e7d56d9 1226 goto out2;
d14ed18c 1227 }
eb769f74 1228 bs1 = blk_bs(blk1);
7e7d56d9 1229 bs2 = blk_bs(blk2);
d14ed18c 1230
f1d3cd79
HR
1231 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1232 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1233 total_sectors1 = blk_nb_sectors(blk1);
52bf1e72
MA
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 }
f1d3cd79 1240 total_sectors2 = blk_nb_sectors(blk2);
52bf1e72
MA
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 }
d14ed18c
MR
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 (;;) {
25ad8e6e 1259 int64_t status1, status2;
67a0fd2a
FZ
1260 BlockDriverState *file;
1261
d14ed18c
MR
1262 nb_sectors = sectors_to_process(total_sectors, sector_num);
1263 if (nb_sectors <= 0) {
1264 break;
1265 }
25ad8e6e
FZ
1266 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1267 total_sectors1 - sector_num,
67a0fd2a 1268 &pnum1, &file);
25ad8e6e 1269 if (status1 < 0) {
d14ed18c
MR
1270 ret = 3;
1271 error_report("Sector allocation test failed for %s", filename1);
1272 goto out;
1273 }
25ad8e6e 1274 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
d14ed18c 1275
25ad8e6e
FZ
1276 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1277 total_sectors2 - sector_num,
67a0fd2a 1278 &pnum2, &file);
25ad8e6e 1279 if (status2 < 0) {
d14ed18c
MR
1280 ret = 3;
1281 error_report("Sector allocation test failed for %s", filename2);
1282 goto out;
1283 }
25ad8e6e
FZ
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 }
d14ed18c 1291
25ad8e6e
FZ
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) {
d14ed18c 1305 if (allocated1) {
9166920a
EB
1306 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1307 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
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 }
9166920a
EB
1315 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1316 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
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) {
d14ed18c
MR
1326 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1327 sectors_to_bytes(
1328 ret ? sector_num : sector_num + pnum));
36452f12 1329 ret = 1;
d14ed18c
MR
1330 goto out;
1331 }
1332 }
1333 } else {
d14ed18c
MR
1334
1335 if (allocated1) {
f1d3cd79 1336 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
d14ed18c
MR
1337 filename1, buf1, quiet);
1338 } else {
f1d3cd79 1339 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
d14ed18c
MR
1340 filename2, buf1, quiet);
1341 }
1342 if (ret) {
1343 if (ret < 0) {
d14ed18c
MR
1344 error_report("Error while reading offset %" PRId64 ": %s",
1345 sectors_to_bytes(sector_num), strerror(-ret));
36452f12 1346 ret = 4;
d14ed18c
MR
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) {
f1d3cd79 1356 BlockBackend *blk_over;
d14ed18c
MR
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;
f1d3cd79 1363 blk_over = blk1;
d14ed18c
MR
1364 filename_over = filename1;
1365 } else {
1366 total_sectors_over = total_sectors2;
f1d3cd79 1367 blk_over = blk2;
d14ed18c
MR
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 }
f1d3cd79 1376 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
d14ed18c
MR
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) {
f1d3cd79 1387 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
d14ed18c
MR
1388 filename_over, buf1, quiet);
1389 if (ret) {
1390 if (ret < 0) {
d14ed18c
MR
1391 error_report("Error while reading offset %" PRId64
1392 " of %s: %s", sectors_to_bytes(sector_num),
1393 filename_over, strerror(-ret));
36452f12 1394 ret = 4;
d14ed18c
MR
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
1407out:
d14ed18c
MR
1408 qemu_vfree(buf1);
1409 qemu_vfree(buf2);
26f54e9a 1410 blk_unref(blk2);
d14ed18c 1411out2:
26f54e9a 1412 blk_unref(blk1);
d14ed18c
MR
1413out3:
1414 qemu_progress_end();
3babeb15 1415out4:
d14ed18c
MR
1416 return ret;
1417}
1418
690c7301
KW
1419enum ImgConvertBlockStatus {
1420 BLK_DATA,
1421 BLK_ZERO,
1422 BLK_BACKING_FILE,
1423};
1424
1425typedef 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
1443static 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
1453static 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) {
67a0fd2a 1464 BlockDriverState *file;
690c7301
KW
1465 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1466 sector_num - s->src_cur_offset,
67a0fd2a 1467 n, &n, &file);
690c7301
KW
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. */
263a6f4c 1479 /* Check block status of the backing file chain to avoid
690c7301
KW
1480 * needlessly reading zeroes and limiting the iteration to the
1481 * buffer size */
263a6f4c
RK
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 }
690c7301
KW
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
1521static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1522 uint8_t *buf)
1523{
1524 int n;
1525 int ret;
1526
690c7301
KW
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));
9166920a
EB
1540 ret = blk_pread(blk,
1541 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1542 buf, n << BDRV_SECTOR_BITS);
690c7301
KW
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
1555static 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 {
9166920a
EB
1597 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1598 buf, n << BDRV_SECTOR_BITS, 0);
690c7301
KW
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 }
d004bd52
EB
1610 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1611 n << BDRV_SECTOR_BITS, 0);
690c7301
KW
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
1626static 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 }
aad15de4
HR
1668 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1669 {
690c7301
KW
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 }
aad15de4
HR
1689 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1690 {
690c7301
KW
1691 allocated_done += n;
1692 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1693 0);
1694 }
1695
aad15de4
HR
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;
690c7301
KW
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;
1728fail:
1729 qemu_vfree(buf);
1730 return ret;
1731}
1732
ea2384d3
FB
1733static int img_convert(int argc, char **argv)
1734{
690c7301 1735 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
13c28af8 1736 int64_t ret = 0;
40055951 1737 int progress = 0, flags, src_flags;
ce099547 1738 bool writethrough, src_writethrough;
40055951 1739 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
b50cbabc 1740 BlockDriver *drv, *proto_drv;
26f54e9a 1741 BlockBackend **blk = NULL, *out_blk = NULL;
c2abccec 1742 BlockDriverState **bs = NULL, *out_bs = NULL;
690c7301 1743 int64_t total_sectors;
52bf1e72 1744 int64_t *bs_sectors = NULL;
f2521c90 1745 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
faea38e7 1746 BlockDriverInfo bdi;
83d0521a
CL
1747 QemuOpts *opts = NULL;
1748 QemuOptsList *create_opts = NULL;
1749 const char *out_baseimg_param;
efa84d43 1750 char *options = NULL;
51ef6727 1751 const char *snapshot_name = NULL;
a22f123c 1752 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
f382d43a 1753 bool quiet = false;
cc84d90f 1754 Error *local_err = NULL;
ef80654d 1755 QemuOpts *sn_opts = NULL;
690c7301 1756 ImgConvertState state;
eb769f74 1757 bool image_opts = false;
ea2384d3
FB
1758
1759 fmt = NULL;
1760 out_fmt = "raw";
661a0f71 1761 cache = "unsafe";
40055951 1762 src_cache = BDRV_DEFAULT_CACHE;
f58c7b35 1763 out_baseimg = NULL;
eec77d9e 1764 compress = 0;
b2e10493 1765 skip_create = 0;
ea2384d3 1766 for(;;) {
3babeb15
DB
1767 static const struct option long_options[] = {
1768 {"help", no_argument, 0, 'h'},
1769 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1770 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
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);
b8fb60da 1775 if (c == -1) {
ea2384d3 1776 break;
b8fb60da 1777 }
ea2384d3 1778 switch(c) {
ef87394c 1779 case '?':
ea2384d3
FB
1780 case 'h':
1781 help();
1782 break;
1783 case 'f':
1784 fmt = optarg;
1785 break;
1786 case 'O':
1787 out_fmt = optarg;
1788 break;
f58c7b35
TS
1789 case 'B':
1790 out_baseimg = optarg;
1791 break;
ea2384d3 1792 case 'c':
eec77d9e 1793 compress = 1;
ea2384d3
FB
1794 break;
1795 case 'e':
9d42e15d 1796 error_report("option -e is deprecated, please use \'-o "
eec77d9e 1797 "encryption\' instead!");
2dc8328b 1798 ret = -1;
64bb01aa 1799 goto fail_getopt;
ec36ba14 1800 case '6':
9d42e15d 1801 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 1802 "compat6\' instead!");
2dc8328b 1803 ret = -1;
64bb01aa 1804 goto fail_getopt;
efa84d43 1805 case 'o':
2dc8328b
KW
1806 if (!is_valid_option_list(optarg)) {
1807 error_report("Invalid option list: %s", optarg);
1808 ret = -1;
64bb01aa 1809 goto fail_getopt;
2dc8328b
KW
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 }
efa84d43 1818 break;
51ef6727 1819 case 's':
1820 snapshot_name = optarg;
1821 break;
ef80654d
WX
1822 case 'l':
1823 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
1824 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1825 optarg, false);
ef80654d
WX
1826 if (!sn_opts) {
1827 error_report("Failed in parsing snapshot param '%s'",
1828 optarg);
2dc8328b 1829 ret = -1;
64bb01aa 1830 goto fail_getopt;
ef80654d
WX
1831 }
1832 } else {
1833 snapshot_name = optarg;
1834 }
1835 break;
a22f123c
KW
1836 case 'S':
1837 {
1838 int64_t sval;
e36b3695 1839 char *end;
4677bb40 1840 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 1841 if (sval < 0 || *end) {
a22f123c 1842 error_report("Invalid minimum zero buffer size for sparse output specified");
2dc8328b 1843 ret = -1;
64bb01aa 1844 goto fail_getopt;
a22f123c
KW
1845 }
1846
1847 min_sparse = sval / BDRV_SECTOR_SIZE;
1848 break;
1849 }
6b837bc4
JS
1850 case 'p':
1851 progress = 1;
1852 break;
661a0f71
FS
1853 case 't':
1854 cache = optarg;
1855 break;
40055951
HR
1856 case 'T':
1857 src_cache = optarg;
1858 break;
f382d43a
MR
1859 case 'q':
1860 quiet = true;
1861 break;
b2e10493
AD
1862 case 'n':
1863 skip_create = 1;
1864 break;
3babeb15
DB
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;
eb769f74
DB
1872 case OPTION_IMAGE_OPTS:
1873 image_opts = true;
1874 break;
ea2384d3
FB
1875 }
1876 }
3b46e624 1877
3babeb15
DB
1878 if (qemu_opts_foreach(&qemu_object_opts,
1879 user_creatable_add_opts_foreach,
51b9b478 1880 NULL, NULL)) {
3babeb15
DB
1881 goto fail_getopt;
1882 }
1883
64bb01aa 1884 /* Initialize before goto out */
f382d43a
MR
1885 if (quiet) {
1886 progress = 0;
1887 }
64bb01aa
KW
1888 qemu_progress_init(progress, 1.0);
1889
926c2d23 1890 bs_n = argc - optind - 1;
a283cb6e 1891 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
f58c7b35 1892
2dc8328b 1893 if (options && has_help_option(options)) {
4ac8aacd
JS
1894 ret = print_block_option_help(out_filename, out_fmt);
1895 goto out;
1896 }
1897
a283cb6e 1898 if (bs_n < 1) {
ac1307ab 1899 error_exit("Must specify image file name");
a283cb6e
KW
1900 }
1901
1902
c2abccec 1903 if (bs_n > 1 && out_baseimg) {
15654a6d
JS
1904 error_report("-B makes no sense when concatenating multiple input "
1905 "images");
31ca34b8
JS
1906 ret = -1;
1907 goto out;
c2abccec 1908 }
f8111c24 1909
ce099547
KW
1910 src_flags = 0;
1911 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
1912 if (ret < 0) {
1913 error_report("Invalid source cache option: %s", src_cache);
1914 goto out;
1915 }
1916
6b837bc4
JS
1917 qemu_progress_print(0, 100);
1918
26f54e9a 1919 blk = g_new0(BlockBackend *, bs_n);
d739f1c4 1920 bs = g_new0(BlockDriverState *, bs_n);
52bf1e72 1921 bs_sectors = g_new(int64_t, bs_n);
926c2d23
AZ
1922
1923 total_sectors = 0;
1924 for (bs_i = 0; bs_i < bs_n; bs_i++) {
efaa7c4e 1925 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
ce099547 1926 fmt, src_flags, src_writethrough, quiet);
7e7d56d9 1927 if (!blk[bs_i]) {
c2abccec
MK
1928 ret = -1;
1929 goto out;
1930 }
7e7d56d9 1931 bs[bs_i] = blk_bs(blk[bs_i]);
f1d3cd79 1932 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
52bf1e72
MA
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 }
d739f1c4 1939 total_sectors += bs_sectors[bs_i];
926c2d23 1940 }
ea2384d3 1941
ef80654d
WX
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) {
51ef6727 1948 if (bs_n > 1) {
6daf194d 1949 error_report("No support for concatenating multiple snapshot");
51ef6727 1950 ret = -1;
1951 goto out;
1952 }
7b4c4781
WX
1953
1954 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
ef80654d 1955 }
84d18f06 1956 if (local_err) {
c29b77f9 1957 error_reportf_err(local_err, "Failed to load snapshot: ");
ef80654d
WX
1958 ret = -1;
1959 goto out;
51ef6727 1960 }
1961
efa84d43 1962 /* Find driver and parse its options */
ea2384d3 1963 drv = bdrv_find_format(out_fmt);
c2abccec 1964 if (!drv) {
15654a6d 1965 error_report("Unknown file format '%s'", out_fmt);
c2abccec
MK
1966 ret = -1;
1967 goto out;
1968 }
efa84d43 1969
b65a5e12 1970 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
c2abccec 1971 if (!proto_drv) {
2867ce4a 1972 error_report_err(local_err);
c2abccec
MK
1973 ret = -1;
1974 goto out;
1975 }
b50cbabc 1976
2e024cde
HR
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 }
f75613cf 1984
2e024cde
HR
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 }
f75613cf 1991
2e024cde
HR
1992 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1993 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 1994
2e024cde 1995 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
1996 if (options) {
1997 qemu_opts_do_parse(opts, options, NULL, &local_err);
1998 if (local_err) {
97a2ca7a 1999 error_report_err(local_err);
dc523cd3
MA
2000 ret = -1;
2001 goto out;
2002 }
2e024cde 2003 }
efa84d43 2004
39101f25
MA
2005 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2006 &error_abort);
2e024cde
HR
2007 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2008 if (ret < 0) {
2009 goto out;
2010 }
c2abccec 2011 }
efa84d43 2012
a18953fb 2013 /* Get backing file name if -o backing_file was used */
83d0521a 2014 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 2015 if (out_baseimg_param) {
83d0521a 2016 out_baseimg = out_baseimg_param;
a18953fb
KW
2017 }
2018
efa84d43 2019 /* Check if compression is supported */
eec77d9e 2020 if (compress) {
83d0521a
CL
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);
efa84d43
KW
2025
2026 if (!drv->bdrv_write_compressed) {
15654a6d 2027 error_report("Compression not supported for this file format");
c2abccec
MK
2028 ret = -1;
2029 goto out;
efa84d43
KW
2030 }
2031
83d0521a 2032 if (encryption) {
15654a6d
JS
2033 error_report("Compression and encryption not supported at "
2034 "the same time");
c2abccec
MK
2035 ret = -1;
2036 goto out;
efa84d43 2037 }
41521fa4 2038
83d0521a
CL
2039 if (preallocation
2040 && strcmp(preallocation, "off"))
41521fa4
KW
2041 {
2042 error_report("Compression and preallocation not supported at "
2043 "the same time");
2044 ret = -1;
2045 goto out;
2046 }
efa84d43
KW
2047 }
2048
b2e10493
AD
2049 if (!skip_create) {
2050 /* Create the new image */
c282e1fd 2051 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 2052 if (ret < 0) {
c29b77f9
MA
2053 error_reportf_err(local_err, "%s: error while converting %s: ",
2054 out_filename, out_fmt);
b2e10493 2055 goto out;
ea2384d3
FB
2056 }
2057 }
3b46e624 2058
5a37b60a 2059 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
ce099547 2060 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2061 if (ret < 0) {
2062 error_report("Invalid cache option: %s", cache);
bb9cd2ee 2063 goto out;
661a0f71
FS
2064 }
2065
eb769f74
DB
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 */
ce099547 2071 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
7e7d56d9 2072 if (!out_blk) {
c2abccec
MK
2073 ret = -1;
2074 goto out;
2075 }
7e7d56d9 2076 out_bs = blk_bs(out_blk);
ea2384d3 2077
f2521c90
PL
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
b2e10493 2086 if (skip_create) {
f1d3cd79 2087 int64_t output_sectors = blk_nb_sectors(out_blk);
43716fa8 2088 if (output_sectors < 0) {
eec5eb42 2089 error_report("unable to get output image length: %s",
43716fa8 2090 strerror(-output_sectors));
b2e10493
AD
2091 ret = -1;
2092 goto out;
43716fa8 2093 } else if (output_sectors < total_sectors) {
b2e10493
AD
2094 error_report("output file is smaller than input file");
2095 ret = -1;
2096 goto out;
2097 }
2098 }
2099
24f833cd
PL
2100 cluster_sectors = 0;
2101 ret = bdrv_get_info(out_bs, &bdi);
2102 if (ret < 0) {
2103 if (compress) {
15654a6d 2104 error_report("could not get block driver info");
c2abccec
MK
2105 goto out;
2106 }
24f833cd 2107 } else {
85f49cad 2108 compress = compress || bdi.needs_compressed_writes;
24f833cd
PL
2109 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2110 }
2111
690c7301
KW
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);
802c3d4c 2125
c2abccec 2126out:
13c28af8
PL
2127 if (!ret) {
2128 qemu_progress_print(100, 0);
2129 }
6b837bc4 2130 qemu_progress_end();
83d0521a
CL
2131 qemu_opts_del(opts);
2132 qemu_opts_free(create_opts);
fbf28a43 2133 qemu_opts_del(sn_opts);
26f54e9a 2134 blk_unref(out_blk);
9ba10c95 2135 g_free(bs);
26f54e9a
MA
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 }
d739f1c4 2142 g_free(bs_sectors);
64bb01aa
KW
2143fail_getopt:
2144 g_free(options);
2145
c2abccec
MK
2146 if (ret) {
2147 return 1;
2148 }
ea2384d3
FB
2149 return 0;
2150}
2151
57d1a2b6 2152
faea38e7
FB
2153static void dump_snapshots(BlockDriverState *bs)
2154{
2155 QEMUSnapshotInfo *sn_tab, *sn;
2156 int nb_sns, i;
faea38e7
FB
2157
2158 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2159 if (nb_sns <= 0)
2160 return;
2161 printf("Snapshot list:\n");
5b917044
WX
2162 bdrv_snapshot_dump(fprintf, stdout, NULL);
2163 printf("\n");
faea38e7
FB
2164 for(i = 0; i < nb_sns; i++) {
2165 sn = &sn_tab[i];
5b917044
WX
2166 bdrv_snapshot_dump(fprintf, stdout, sn);
2167 printf("\n");
faea38e7 2168 }
7267c094 2169 g_free(sn_tab);
faea38e7
FB
2170}
2171
9699bf0d
SH
2172static void dump_json_image_info_list(ImageInfoList *list)
2173{
4399c438 2174 Error *local_err = NULL;
9699bf0d
SH
2175 QString *str;
2176 QmpOutputVisitor *ov = qmp_output_visitor_new();
2177 QObject *obj;
51e72bc1
EB
2178 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2179 &local_err);
9699bf0d
SH
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
c054b3fd
BC
2189static void dump_json_image_info(ImageInfo *info)
2190{
4399c438 2191 Error *local_err = NULL;
c054b3fd
BC
2192 QString *str;
2193 QmpOutputVisitor *ov = qmp_output_visitor_new();
2194 QObject *obj;
51e72bc1 2195 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
c054b3fd
BC
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
9699bf0d
SH
2205static 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
5b917044 2216 bdrv_image_info_dump(fprintf, stdout, elem->value);
9699bf0d
SH
2217 }
2218}
2219
2220static 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 */
eb769f74
DB
2237static ImageInfoList *collect_image_info_list(bool image_opts,
2238 const char *filename,
9699bf0d
SH
2239 const char *fmt,
2240 bool chain)
2241{
2242 ImageInfoList *head = NULL;
2243 ImageInfoList **last = &head;
2244 GHashTable *filenames;
43526ec8 2245 Error *err = NULL;
9699bf0d
SH
2246
2247 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2248
2249 while (filename) {
26f54e9a 2250 BlockBackend *blk;
9699bf0d
SH
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
efaa7c4e 2262 blk = img_open(image_opts, filename, fmt,
ce099547 2263 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
7e7d56d9 2264 if (!blk) {
9699bf0d
SH
2265 goto err;
2266 }
7e7d56d9 2267 bs = blk_bs(blk);
9699bf0d 2268
43526ec8 2269 bdrv_query_image_info(bs, &info, &err);
84d18f06 2270 if (err) {
565f65d2 2271 error_report_err(err);
26f54e9a 2272 blk_unref(blk);
43526ec8 2273 goto err;
fb0ed453 2274 }
9699bf0d
SH
2275
2276 elem = g_new0(ImageInfoList, 1);
2277 elem->value = info;
2278 *last = elem;
2279 last = &elem->next;
2280
26f54e9a 2281 blk_unref(blk);
9699bf0d
SH
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) {
92d617ab
JS
2288 error_report("Could not determine absolute backing filename,"
2289 " but backing filename '%s' present",
2290 info->backing_filename);
2291 goto err;
9699bf0d
SH
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
2301err:
2302 qapi_free_ImageInfoList(head);
2303 g_hash_table_destroy(filenames);
2304 return NULL;
2305}
2306
c054b3fd
BC
2307static int img_info(int argc, char **argv)
2308{
2309 int c;
2310 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 2311 bool chain = false;
c054b3fd 2312 const char *filename, *fmt, *output;
9699bf0d 2313 ImageInfoList *list;
eb769f74 2314 bool image_opts = false;
c054b3fd 2315
ea2384d3 2316 fmt = NULL;
c054b3fd 2317 output = NULL;
ea2384d3 2318 for(;;) {
c054b3fd
BC
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},
9699bf0d 2324 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3babeb15 2325 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2326 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
c054b3fd
BC
2327 {0, 0, 0, 0}
2328 };
2329 c = getopt_long(argc, argv, "f:h",
2330 long_options, &option_index);
b8fb60da 2331 if (c == -1) {
ea2384d3 2332 break;
b8fb60da 2333 }
ea2384d3 2334 switch(c) {
ef87394c 2335 case '?':
ea2384d3
FB
2336 case 'h':
2337 help();
2338 break;
2339 case 'f':
2340 fmt = optarg;
2341 break;
c054b3fd
BC
2342 case OPTION_OUTPUT:
2343 output = optarg;
2344 break;
9699bf0d
SH
2345 case OPTION_BACKING_CHAIN:
2346 chain = true;
2347 break;
3babeb15
DB
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;
eb769f74
DB
2356 case OPTION_IMAGE_OPTS:
2357 image_opts = true;
2358 break;
ea2384d3
FB
2359 }
2360 }
fc11eb26 2361 if (optind != argc - 1) {
ac1307ab 2362 error_exit("Expecting one image file name");
b8fb60da 2363 }
ea2384d3
FB
2364 filename = argv[optind++];
2365
c054b3fd
BC
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.");
c2abccec
MK
2372 return 1;
2373 }
c054b3fd 2374
3babeb15
DB
2375 if (qemu_opts_foreach(&qemu_object_opts,
2376 user_creatable_add_opts_foreach,
51b9b478 2377 NULL, NULL)) {
3babeb15
DB
2378 return 1;
2379 }
2380
eb769f74 2381 list = collect_image_info_list(image_opts, filename, fmt, chain);
9699bf0d 2382 if (!list) {
c2abccec 2383 return 1;
faea38e7 2384 }
c054b3fd 2385
c054b3fd
BC
2386 switch (output_format) {
2387 case OFORMAT_HUMAN:
9699bf0d 2388 dump_human_image_info_list(list);
c054b3fd
BC
2389 break;
2390 case OFORMAT_JSON:
9699bf0d
SH
2391 if (chain) {
2392 dump_json_image_info_list(list);
2393 } else {
2394 dump_json_image_info(list->value);
2395 }
c054b3fd 2396 break;
faea38e7 2397 }
c054b3fd 2398
9699bf0d 2399 qapi_free_ImageInfoList(list);
ea2384d3
FB
2400 return 0;
2401}
2402
4c93a13b
PB
2403static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2404 MapEntry *next)
2405{
2406 switch (output_format) {
2407 case OFORMAT_HUMAN:
16b0d555 2408 if (e->data && !e->has_offset) {
4c93a13b
PB
2409 error_report("File contains external, encrypted or compressed clusters.");
2410 exit(1);
2411 }
16b0d555 2412 if (e->data && !e->zero) {
4c93a13b 2413 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
16b0d555
FZ
2414 e->start, e->length,
2415 e->has_offset ? e->offset : 0,
2416 e->has_filename ? e->filename : "");
4c93a13b
PB
2417 }
2418 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2419 * Modify the flags here to allow more coalescing.
2420 */
16b0d555
FZ
2421 if (next && (!next->data || next->zero)) {
2422 next->data = false;
2423 next->zero = true;
4c93a13b
PB
2424 }
2425 break;
2426 case OFORMAT_JSON:
16b0d555
FZ
2427 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2428 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
4c93a13b
PB
2429 (e->start == 0 ? "[" : ",\n"),
2430 e->start, e->length, e->depth,
16b0d555
FZ
2431 e->zero ? "true" : "false",
2432 e->data ? "true" : "false");
2433 if (e->has_offset) {
c745bfb4 2434 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2435 }
2436 putchar('}');
2437
2438 if (!next) {
2439 printf("]\n");
2440 }
2441 break;
2442 }
2443}
2444
2445static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2446 int nb_sectors, MapEntry *e)
2447{
2448 int64_t ret;
2449 int depth;
67a0fd2a 2450 BlockDriverState *file;
2875645b 2451 bool has_offset;
4c93a13b
PB
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 (;;) {
67a0fd2a
FZ
2460 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2461 &file);
4c93a13b
PB
2462 if (ret < 0) {
2463 return ret;
2464 }
2465 assert(nb_sectors);
2466 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2467 break;
2468 }
760e0063 2469 bs = backing_bs(bs);
4c93a13b
PB
2470 if (bs == NULL) {
2471 ret = 0;
2472 break;
2473 }
2474
2475 depth++;
2476 }
2477
2875645b
JS
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
4c93a13b
PB
2492 return 0;
2493}
2494
16b0d555
FZ
2495static 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
4c93a13b
PB
2516static int img_map(int argc, char **argv)
2517{
2518 int c;
2519 OutputFormat output_format = OFORMAT_HUMAN;
26f54e9a 2520 BlockBackend *blk;
4c93a13b
PB
2521 BlockDriverState *bs;
2522 const char *filename, *fmt, *output;
2523 int64_t length;
2524 MapEntry curr = { .length = 0 }, next;
2525 int ret = 0;
eb769f74 2526 bool image_opts = false;
4c93a13b
PB
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},
3babeb15 2536 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2537 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4c93a13b
PB
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;
3babeb15
DB
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;
eb769f74
DB
2564 case OPTION_IMAGE_OPTS:
2565 image_opts = true;
2566 break;
4c93a13b
PB
2567 }
2568 }
ac1307ab
FZ
2569 if (optind != argc - 1) {
2570 error_exit("Expecting one image file name");
4c93a13b 2571 }
ac1307ab 2572 filename = argv[optind];
4c93a13b
PB
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
3babeb15
DB
2583 if (qemu_opts_foreach(&qemu_object_opts,
2584 user_creatable_add_opts_foreach,
51b9b478 2585 NULL, NULL)) {
3babeb15
DB
2586 return 1;
2587 }
2588
ce099547 2589 blk = img_open(image_opts, filename, fmt, 0, false, false);
7e7d56d9
MA
2590 if (!blk) {
2591 return 1;
4c93a13b 2592 }
7e7d56d9 2593 bs = blk_bs(blk);
4c93a13b
PB
2594
2595 if (output_format == OFORMAT_HUMAN) {
2596 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2597 }
2598
f1d3cd79 2599 length = blk_getlength(blk);
4c93a13b
PB
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
16b0d555 2617 if (entry_mergeable(&curr, &next)) {
4c93a13b
PB
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
2630out:
26f54e9a 2631 blk_unref(blk);
4c93a13b
PB
2632 return ret < 0;
2633}
2634
f7b4a940
AL
2635#define SNAPSHOT_LIST 1
2636#define SNAPSHOT_CREATE 2
2637#define SNAPSHOT_APPLY 3
2638#define SNAPSHOT_DELETE 4
2639
153859be 2640static int img_snapshot(int argc, char **argv)
f7b4a940 2641{
26f54e9a 2642 BlockBackend *blk;
f7b4a940
AL
2643 BlockDriverState *bs;
2644 QEMUSnapshotInfo sn;
2645 char *filename, *snapshot_name = NULL;
c2abccec 2646 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
2647 int action = 0;
2648 qemu_timeval tv;
f382d43a 2649 bool quiet = false;
a89d89d3 2650 Error *err = NULL;
eb769f74 2651 bool image_opts = false;
f7b4a940 2652
ce099547 2653 bdrv_oflags = BDRV_O_RDWR;
f7b4a940
AL
2654 /* Parse commandline parameters */
2655 for(;;) {
3babeb15
DB
2656 static const struct option long_options[] = {
2657 {"help", no_argument, 0, 'h'},
2658 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2659 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2660 {0, 0, 0, 0}
2661 };
2662 c = getopt_long(argc, argv, "la:c:d:hq",
2663 long_options, NULL);
b8fb60da 2664 if (c == -1) {
f7b4a940 2665 break;
b8fb60da 2666 }
f7b4a940 2667 switch(c) {
ef87394c 2668 case '?':
f7b4a940
AL
2669 case 'h':
2670 help();
153859be 2671 return 0;
f7b4a940
AL
2672 case 'l':
2673 if (action) {
ac1307ab 2674 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2675 return 0;
f7b4a940
AL
2676 }
2677 action = SNAPSHOT_LIST;
f5edb014 2678 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
2679 break;
2680 case 'a':
2681 if (action) {
ac1307ab 2682 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2683 return 0;
f7b4a940
AL
2684 }
2685 action = SNAPSHOT_APPLY;
2686 snapshot_name = optarg;
2687 break;
2688 case 'c':
2689 if (action) {
ac1307ab 2690 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2691 return 0;
f7b4a940
AL
2692 }
2693 action = SNAPSHOT_CREATE;
2694 snapshot_name = optarg;
2695 break;
2696 case 'd':
2697 if (action) {
ac1307ab 2698 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2699 return 0;
f7b4a940
AL
2700 }
2701 action = SNAPSHOT_DELETE;
2702 snapshot_name = optarg;
2703 break;
f382d43a
MR
2704 case 'q':
2705 quiet = true;
2706 break;
3babeb15
DB
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;
eb769f74
DB
2715 case OPTION_IMAGE_OPTS:
2716 image_opts = true;
2717 break;
f7b4a940
AL
2718 }
2719 }
2720
fc11eb26 2721 if (optind != argc - 1) {
ac1307ab 2722 error_exit("Expecting one image file name");
b8fb60da 2723 }
f7b4a940
AL
2724 filename = argv[optind++];
2725
3babeb15
DB
2726 if (qemu_opts_foreach(&qemu_object_opts,
2727 user_creatable_add_opts_foreach,
51b9b478 2728 NULL, NULL)) {
3babeb15
DB
2729 return 1;
2730 }
2731
f7b4a940 2732 /* Open the image */
ce099547 2733 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
7e7d56d9
MA
2734 if (!blk) {
2735 return 1;
c2abccec 2736 }
7e7d56d9 2737 bs = blk_bs(blk);
f7b4a940
AL
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);
b8fb60da 2754 if (ret) {
15654a6d 2755 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 2756 snapshot_name, ret, strerror(-ret));
b8fb60da 2757 }
f7b4a940
AL
2758 break;
2759
2760 case SNAPSHOT_APPLY:
2761 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 2762 if (ret) {
15654a6d 2763 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 2764 snapshot_name, ret, strerror(-ret));
b8fb60da 2765 }
f7b4a940
AL
2766 break;
2767
2768 case SNAPSHOT_DELETE:
a89d89d3 2769 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
84d18f06 2770 if (err) {
c29b77f9
MA
2771 error_reportf_err(err, "Could not delete snapshot '%s': ",
2772 snapshot_name);
a89d89d3 2773 ret = 1;
b8fb60da 2774 }
f7b4a940
AL
2775 break;
2776 }
2777
2778 /* Cleanup */
26f54e9a 2779 blk_unref(blk);
c2abccec
MK
2780 if (ret) {
2781 return 1;
2782 }
153859be 2783 return 0;
f7b4a940
AL
2784}
2785
3e85c6fd
KW
2786static int img_rebase(int argc, char **argv)
2787{
26f54e9a 2788 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
396374ca
PB
2789 uint8_t *buf_old = NULL;
2790 uint8_t *buf_new = NULL;
f1d3cd79 2791 BlockDriverState *bs = NULL;
3e85c6fd 2792 char *filename;
40055951
HR
2793 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2794 int c, flags, src_flags, ret;
ce099547 2795 bool writethrough, src_writethrough;
3e85c6fd 2796 int unsafe = 0;
6b837bc4 2797 int progress = 0;
f382d43a 2798 bool quiet = false;
34b5d2c6 2799 Error *local_err = NULL;
eb769f74 2800 bool image_opts = false;
3e85c6fd
KW
2801
2802 /* Parse commandline parameters */
e53dbee0 2803 fmt = NULL;
661a0f71 2804 cache = BDRV_DEFAULT_CACHE;
40055951 2805 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
2806 out_baseimg = NULL;
2807 out_basefmt = NULL;
3e85c6fd 2808 for(;;) {
3babeb15
DB
2809 static const struct option long_options[] = {
2810 {"help", no_argument, 0, 'h'},
2811 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2813 {0, 0, 0, 0}
2814 };
2815 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2816 long_options, NULL);
b8fb60da 2817 if (c == -1) {
3e85c6fd 2818 break;
b8fb60da 2819 }
3e85c6fd 2820 switch(c) {
ef87394c 2821 case '?':
3e85c6fd
KW
2822 case 'h':
2823 help();
2824 return 0;
e53dbee0
KW
2825 case 'f':
2826 fmt = optarg;
2827 break;
3e85c6fd
KW
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;
6b837bc4
JS
2837 case 'p':
2838 progress = 1;
2839 break;
661a0f71
FS
2840 case 't':
2841 cache = optarg;
2842 break;
40055951
HR
2843 case 'T':
2844 src_cache = optarg;
2845 break;
f382d43a
MR
2846 case 'q':
2847 quiet = true;
2848 break;
3babeb15
DB
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;
eb769f74
DB
2857 case OPTION_IMAGE_OPTS:
2858 image_opts = true;
2859 break;
3e85c6fd
KW
2860 }
2861 }
2862
f382d43a
MR
2863 if (quiet) {
2864 progress = 0;
2865 }
2866
ac1307ab
FZ
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)");
b8fb60da 2872 }
3e85c6fd
KW
2873 filename = argv[optind++];
2874
3babeb15
DB
2875 if (qemu_opts_foreach(&qemu_object_opts,
2876 user_creatable_add_opts_foreach,
51b9b478 2877 NULL, NULL)) {
3babeb15
DB
2878 return 1;
2879 }
2880
6b837bc4
JS
2881 qemu_progress_init(progress, 2.0);
2882 qemu_progress_print(0, 100);
2883
661a0f71 2884 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
ce099547 2885 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2886 if (ret < 0) {
2887 error_report("Invalid cache option: %s", cache);
40ed35a3 2888 goto out;
661a0f71
FS
2889 }
2890
ce099547
KW
2891 src_flags = 0;
2892 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
2893 if (ret < 0) {
2894 error_report("Invalid source cache option: %s", src_cache);
40ed35a3 2895 goto out;
40055951
HR
2896 }
2897
ce099547
KW
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
3e85c6fd
KW
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 */
ce099547 2908 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 2909 if (!blk) {
40ed35a3
SH
2910 ret = -1;
2911 goto out;
c2abccec 2912 }
7e7d56d9 2913 bs = blk_bs(blk);
3e85c6fd 2914
3e85c6fd 2915 if (out_basefmt != NULL) {
644483d9 2916 if (bdrv_find_format(out_basefmt) == NULL) {
15654a6d 2917 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
2918 ret = -1;
2919 goto out;
3e85c6fd
KW
2920 }
2921 }
2922
2923 /* For safe rebasing we need to compare old and new backing file */
40ed35a3 2924 if (!unsafe) {
9a29e18f 2925 char backing_name[PATH_MAX];
644483d9
HR
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 }
3e85c6fd 2932
3e85c6fd 2933 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
efaa7c4e 2934 blk_old_backing = blk_new_open(backing_name, NULL,
644483d9
HR
2935 options, src_flags, &local_err);
2936 if (!blk_old_backing) {
c29b77f9
MA
2937 error_reportf_err(local_err,
2938 "Could not open old backing file '%s': ",
2939 backing_name);
c2abccec 2940 goto out;
3e85c6fd 2941 }
644483d9 2942
a616673d 2943 if (out_baseimg[0]) {
644483d9
HR
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
efaa7c4e 2951 blk_new_backing = blk_new_open(out_baseimg, NULL,
644483d9
HR
2952 options, src_flags, &local_err);
2953 if (!blk_new_backing) {
c29b77f9
MA
2954 error_reportf_err(local_err,
2955 "Could not open new backing file '%s': ",
2956 out_baseimg);
a616673d
AB
2957 goto out;
2958 }
3e85c6fd
KW
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) {
52bf1e72
MA
2972 int64_t num_sectors;
2973 int64_t old_backing_num_sectors;
2974 int64_t new_backing_num_sectors = 0;
3e85c6fd 2975 uint64_t sector;
cc60e327 2976 int n;
1f710495 2977 float local_progress = 0;
d6771bfa 2978
f1d3cd79
HR
2979 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2980 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3e85c6fd 2981
f1d3cd79 2982 num_sectors = blk_nb_sectors(blk);
52bf1e72
MA
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 }
f1d3cd79 2989 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
52bf1e72 2990 if (old_backing_num_sectors < 0) {
9a29e18f 2991 char backing_name[PATH_MAX];
52bf1e72
MA
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 }
f1d3cd79
HR
2999 if (blk_new_backing) {
3000 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
52bf1e72
MA
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 }
a616673d 3007 }
3e85c6fd 3008
1f710495
KW
3009 if (num_sectors != 0) {
3010 local_progress = (float)100 /
3011 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3012 }
3013
3e85c6fd
KW
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 */
cc60e327 3024 ret = bdrv_is_allocated(bs, sector, n, &n);
d663640c
PB
3025 if (ret < 0) {
3026 error_report("error while reading image metadata: %s",
3027 strerror(-ret));
3028 goto out;
3029 }
cc60e327 3030 if (ret) {
3e85c6fd
KW
3031 continue;
3032 }
3033
87a1b3e3
KW
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
9166920a
EB
3045 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3046 buf_old, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3047 if (ret < 0) {
3048 error_report("error while reading from old backing file");
3049 goto out;
3050 }
3e85c6fd 3051 }
87a1b3e3 3052
f1d3cd79 3053 if (sector >= new_backing_num_sectors || !blk_new_backing) {
87a1b3e3
KW
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
9166920a
EB
3060 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3061 buf_new, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3062 if (ret < 0) {
3063 error_report("error while reading from new backing file");
3064 goto out;
3065 }
3e85c6fd
KW
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,
60b1bd4f 3075 buf_new + written * 512, n - written, &pnum))
3e85c6fd 3076 {
9166920a
EB
3077 ret = blk_pwrite(blk,
3078 (sector + written) << BDRV_SECTOR_BITS,
3079 buf_old + written * 512,
3080 pnum << BDRV_SECTOR_BITS, 0);
3e85c6fd 3081 if (ret < 0) {
15654a6d 3082 error_report("Error while writing to COW image: %s",
3e85c6fd 3083 strerror(-ret));
c2abccec 3084 goto out;
3e85c6fd
KW
3085 }
3086 }
3087
3088 written += pnum;
3089 }
6b837bc4 3090 qemu_progress_print(local_progress, 100);
3e85c6fd
KW
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 */
a616673d
AB
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
3e85c6fd 3105 if (ret == -ENOSPC) {
15654a6d
JS
3106 error_report("Could not change the backing file to '%s': No "
3107 "space left in the file header", out_baseimg);
3e85c6fd 3108 } else if (ret < 0) {
15654a6d 3109 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
3110 out_baseimg, strerror(-ret));
3111 }
3112
6b837bc4 3113 qemu_progress_print(100, 0);
3e85c6fd
KW
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 */
c2abccec 3120out:
6b837bc4 3121 qemu_progress_end();
3e85c6fd
KW
3122 /* Cleanup */
3123 if (!unsafe) {
26f54e9a 3124 blk_unref(blk_old_backing);
26f54e9a 3125 blk_unref(blk_new_backing);
3e85c6fd 3126 }
396374ca
PB
3127 qemu_vfree(buf_old);
3128 qemu_vfree(buf_new);
3e85c6fd 3129
26f54e9a 3130 blk_unref(blk);
c2abccec
MK
3131 if (ret) {
3132 return 1;
3133 }
3e85c6fd
KW
3134 return 0;
3135}
3136
ae6b0ed6
SH
3137static int img_resize(int argc, char **argv)
3138{
6750e795 3139 Error *err = NULL;
ae6b0ed6
SH
3140 int c, ret, relative;
3141 const char *filename, *fmt, *size;
3142 int64_t n, total_size;
f382d43a 3143 bool quiet = false;
26f54e9a 3144 BlockBackend *blk = NULL;
20caf0f7 3145 QemuOpts *param;
3babeb15 3146
20caf0f7
DXW
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 }
ae6b0ed6 3158 },
ae6b0ed6 3159 };
eb769f74 3160 bool image_opts = false;
ae6b0ed6 3161
e80fec7f
KW
3162 /* Remove size from argv manually so that negative numbers are not treated
3163 * as options by getopt. */
3164 if (argc < 3) {
ac1307ab 3165 error_exit("Not enough arguments");
e80fec7f
KW
3166 return 1;
3167 }
3168
3169 size = argv[--argc];
3170
3171 /* Parse getopt arguments */
ae6b0ed6
SH
3172 fmt = NULL;
3173 for(;;) {
3babeb15
DB
3174 static const struct option long_options[] = {
3175 {"help", no_argument, 0, 'h'},
3176 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3177 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3178 {0, 0, 0, 0}
3179 };
3180 c = getopt_long(argc, argv, "f:hq",
3181 long_options, NULL);
ae6b0ed6
SH
3182 if (c == -1) {
3183 break;
3184 }
3185 switch(c) {
ef87394c 3186 case '?':
ae6b0ed6
SH
3187 case 'h':
3188 help();
3189 break;
3190 case 'f':
3191 fmt = optarg;
3192 break;
f382d43a
MR
3193 case 'q':
3194 quiet = true;
3195 break;
3babeb15
DB
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;
eb769f74
DB
3204 case OPTION_IMAGE_OPTS:
3205 image_opts = true;
3206 break;
ae6b0ed6
SH
3207 }
3208 }
fc11eb26 3209 if (optind != argc - 1) {
ac1307ab 3210 error_exit("Expecting one image file name");
ae6b0ed6
SH
3211 }
3212 filename = argv[optind++];
ae6b0ed6 3213
3babeb15
DB
3214 if (qemu_opts_foreach(&qemu_object_opts,
3215 user_creatable_add_opts_foreach,
51b9b478 3216 NULL, NULL)) {
3babeb15
DB
3217 return 1;
3218 }
3219
ae6b0ed6
SH
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 */
87ea75d5 3236 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
f43e47db 3237 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
6750e795
MA
3238 if (err) {
3239 error_report_err(err);
2a81998a 3240 ret = -1;
20caf0f7 3241 qemu_opts_del(param);
2a81998a 3242 goto out;
ae6b0ed6 3243 }
20caf0f7
DXW
3244 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3245 qemu_opts_del(param);
ae6b0ed6 3246
efaa7c4e 3247 blk = img_open(image_opts, filename, fmt,
ce099547 3248 BDRV_O_RDWR, false, quiet);
7e7d56d9 3249 if (!blk) {
2a81998a
JS
3250 ret = -1;
3251 goto out;
c2abccec 3252 }
ae6b0ed6
SH
3253
3254 if (relative) {
f1d3cd79 3255 total_size = blk_getlength(blk) + n * relative;
ae6b0ed6
SH
3256 } else {
3257 total_size = n;
3258 }
3259 if (total_size <= 0) {
15654a6d 3260 error_report("New image size must be positive");
c2abccec
MK
3261 ret = -1;
3262 goto out;
ae6b0ed6
SH
3263 }
3264
f1d3cd79 3265 ret = blk_truncate(blk, total_size);
ae6b0ed6
SH
3266 switch (ret) {
3267 case 0:
f382d43a 3268 qprintf(quiet, "Image resized.\n");
ae6b0ed6
SH
3269 break;
3270 case -ENOTSUP:
259b2173 3271 error_report("This image does not support resize");
ae6b0ed6
SH
3272 break;
3273 case -EACCES:
15654a6d 3274 error_report("Image is read-only");
ae6b0ed6
SH
3275 break;
3276 default:
15654a6d 3277 error_report("Error resizing image (%d)", -ret);
ae6b0ed6
SH
3278 break;
3279 }
c2abccec 3280out:
26f54e9a 3281 blk_unref(blk);
c2abccec
MK
3282 if (ret) {
3283 return 1;
3284 }
ae6b0ed6
SH
3285 return 0;
3286}
3287
76a3a34d 3288static void amend_status_cb(BlockDriverState *bs,
8b13976d
HR
3289 int64_t offset, int64_t total_work_size,
3290 void *opaque)
76a3a34d
HR
3291{
3292 qemu_progress_print(100.f * offset / total_work_size, 0);
3293}
3294
6f176b48
HR
3295static int img_amend(int argc, char **argv)
3296{
dc523cd3 3297 Error *err = NULL;
6f176b48
HR
3298 int c, ret = 0;
3299 char *options = NULL;
83d0521a
CL
3300 QemuOptsList *create_opts = NULL;
3301 QemuOpts *opts = NULL;
bd39e6ed
HR
3302 const char *fmt = NULL, *filename, *cache;
3303 int flags;
ce099547 3304 bool writethrough;
76a3a34d 3305 bool quiet = false, progress = false;
26f54e9a 3306 BlockBackend *blk = NULL;
6f176b48 3307 BlockDriverState *bs = NULL;
eb769f74 3308 bool image_opts = false;
6f176b48 3309
bd39e6ed 3310 cache = BDRV_DEFAULT_CACHE;
6f176b48 3311 for (;;) {
3babeb15
DB
3312 static const struct option long_options[] = {
3313 {"help", no_argument, 0, 'h'},
3314 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3315 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3316 {0, 0, 0, 0}
3317 };
3318 c = getopt_long(argc, argv, "ho:f:t:pq",
3319 long_options, NULL);
6f176b48
HR
3320 if (c == -1) {
3321 break;
3322 }
3323
3324 switch (c) {
3325 case 'h':
3326 case '?':
3327 help();
3328 break;
3329 case 'o':
626f84f3
KW
3330 if (!is_valid_option_list(optarg)) {
3331 error_report("Invalid option list: %s", optarg);
3332 ret = -1;
e814dffc 3333 goto out_no_progress;
626f84f3
KW
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 }
6f176b48
HR
3342 break;
3343 case 'f':
3344 fmt = optarg;
3345 break;
bd39e6ed
HR
3346 case 't':
3347 cache = optarg;
3348 break;
76a3a34d
HR
3349 case 'p':
3350 progress = true;
3351 break;
6f176b48
HR
3352 case 'q':
3353 quiet = true;
3354 break;
3babeb15
DB
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;
eb769f74
DB
3363 case OPTION_IMAGE_OPTS:
3364 image_opts = true;
3365 break;
6f176b48
HR
3366 }
3367 }
3368
a283cb6e 3369 if (!options) {
ac1307ab 3370 error_exit("Must specify options (-o)");
6f176b48
HR
3371 }
3372
3babeb15
DB
3373 if (qemu_opts_foreach(&qemu_object_opts,
3374 user_creatable_add_opts_foreach,
51b9b478 3375 NULL, NULL)) {
3babeb15
DB
3376 ret = -1;
3377 goto out_no_progress;
3378 }
3379
76a3a34d
HR
3380 if (quiet) {
3381 progress = false;
3382 }
3383 qemu_progress_init(progress, 1.0);
3384
a283cb6e
KW
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;
6f176b48
HR
3391 }
3392
a283cb6e 3393 if (optind != argc - 1) {
b2f27e44
HR
3394 error_report("Expecting one image file name");
3395 ret = -1;
3396 goto out;
a283cb6e 3397 }
6f176b48 3398
ce099547
KW
3399 flags = BDRV_O_RDWR;
3400 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
bd39e6ed
HR
3401 if (ret < 0) {
3402 error_report("Invalid cache option: %s", cache);
3403 goto out;
3404 }
3405
ce099547 3406 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 3407 if (!blk) {
6f176b48
HR
3408 ret = -1;
3409 goto out;
3410 }
7e7d56d9 3411 bs = blk_bs(blk);
6f176b48
HR
3412
3413 fmt = bs->drv->format_name;
3414
626f84f3 3415 if (has_help_option(options)) {
a283cb6e 3416 /* If the format was auto-detected, print option help here */
6f176b48
HR
3417 ret = print_block_option_help(filename, fmt);
3418 goto out;
3419 }
3420
b2439d26
HR
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
c282e1fd 3428 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a 3429 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
3430 if (options) {
3431 qemu_opts_do_parse(opts, options, NULL, &err);
3432 if (err) {
97a2ca7a 3433 error_report_err(err);
dc523cd3
MA
3434 ret = -1;
3435 goto out;
3436 }
6f176b48
HR
3437 }
3438
76a3a34d
HR
3439 /* In case the driver does not call amend_status_cb() */
3440 qemu_progress_print(0.f, 0);
8b13976d 3441 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
76a3a34d 3442 qemu_progress_print(100.f, 0);
6f176b48
HR
3443 if (ret < 0) {
3444 error_report("Error while amending options: %s", strerror(-ret));
3445 goto out;
3446 }
3447
3448out:
76a3a34d
HR
3449 qemu_progress_end();
3450
e814dffc 3451out_no_progress:
26f54e9a 3452 blk_unref(blk);
83d0521a
CL
3453 qemu_opts_del(opts);
3454 qemu_opts_free(create_opts);
626f84f3
KW
3455 g_free(options);
3456
6f176b48
HR
3457 if (ret) {
3458 return 1;
3459 }
3460 return 0;
3461}
3462
c227f099 3463static const img_cmd_t img_cmds[] = {
153859be
SB
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
ea2384d3
FB
3472int main(int argc, char **argv)
3473{
c227f099 3474 const img_cmd_t *cmd;
153859be 3475 const char *cmdname;
2f78e491 3476 Error *local_error = NULL;
7db1689c 3477 int c;
7db1689c
JC
3478 static const struct option long_options[] = {
3479 {"help", no_argument, 0, 'h'},
5f6979cb 3480 {"version", no_argument, 0, 'v'},
7db1689c
JC
3481 {0, 0, 0, 0}
3482 };
ea2384d3 3483
526eda14
MK
3484#ifdef CONFIG_POSIX
3485 signal(SIGPIPE, SIG_IGN);
3486#endif
3487
53f76e58 3488 error_set_progname(argv[0]);
10f5bff6 3489 qemu_init_exec_dir(argv[0]);
53f76e58 3490
2f78e491 3491 if (qemu_init_main_loop(&local_error)) {
565f65d2 3492 error_report_err(local_error);
2f78e491
CN
3493 exit(EXIT_FAILURE);
3494 }
3495
e8f2d272 3496 qcrypto_init(&error_fatal);
c2297088 3497
064097d9 3498 module_call_init(MODULE_INIT_QOM);
ea2384d3 3499 bdrv_init();
ac1307ab
FZ
3500 if (argc < 2) {
3501 error_exit("Not enough arguments");
3502 }
153859be 3503 cmdname = argv[1];
153859be 3504
3babeb15 3505 qemu_add_opts(&qemu_object_opts);
eb769f74 3506 qemu_add_opts(&qemu_source_opts);
3babeb15 3507
153859be 3508 /* find the command */
5f6979cb 3509 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
153859be 3510 if (!strcmp(cmdname, cmd->name)) {
7db1689c 3511 return cmd->handler(argc - 1, argv + 1);
153859be 3512 }
ea2384d3 3513 }
153859be 3514
5f6979cb 3515 c = getopt_long(argc, argv, "h", long_options, NULL);
7db1689c
JC
3516
3517 if (c == 'h') {
3518 help();
3519 }
5f6979cb
JC
3520 if (c == 'v') {
3521 printf(QEMU_IMG_VERSION);
3522 return 0;
3523 }
7db1689c 3524
153859be 3525 /* not found */
ac1307ab 3526 error_exit("Command not found: %s", cmdname);
ea2384d3 3527}