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