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