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