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