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