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