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