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