]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-img.c
block: Switch bdrv_make_zero() to byte-based
[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
1175static int64_t sectors_to_process(int64_t total, int64_t from)
1176{
1177 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1178}
1179
1180/*
1181 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1182 *
1183 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1184 * data and negative value on error.
1185 *
f1d3cd79 1186 * @param blk: BlockBackend for the image
d14ed18c
MR
1187 * @param sect_num: Number of first sector to check
1188 * @param sect_count: Number of sectors to check
1189 * @param filename: Name of disk file we are checking (logging purpose)
1190 * @param buffer: Allocated buffer for storing read data
1191 * @param quiet: Flag for quiet mode
1192 */
f1d3cd79 1193static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
d14ed18c
MR
1194 int sect_count, const char *filename,
1195 uint8_t *buffer, bool quiet)
1196{
1197 int pnum, ret = 0;
9166920a
EB
1198 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1199 sect_count << BDRV_SECTOR_BITS);
d14ed18c
MR
1200 if (ret < 0) {
1201 error_report("Error while reading offset %" PRId64 " of %s: %s",
1202 sectors_to_bytes(sect_num), filename, strerror(-ret));
1203 return ret;
1204 }
1205 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1206 if (ret || pnum != sect_count) {
1207 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1208 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1209 return 1;
1210 }
1211
1212 return 0;
1213}
1214
1215/*
1216 * Compares two images. Exit codes:
1217 *
1218 * 0 - Images are identical
1219 * 1 - Images differ
1220 * >1 - Error occurred
1221 */
1222static int img_compare(int argc, char **argv)
1223{
40055951 1224 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
26f54e9a 1225 BlockBackend *blk1, *blk2;
d14ed18c
MR
1226 BlockDriverState *bs1, *bs2;
1227 int64_t total_sectors1, total_sectors2;
1228 uint8_t *buf1 = NULL, *buf2 = NULL;
1229 int pnum1, pnum2;
1230 int allocated1, allocated2;
1231 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1232 bool progress = false, quiet = false, strict = false;
40055951 1233 int flags;
ce099547 1234 bool writethrough;
d14ed18c
MR
1235 int64_t total_sectors;
1236 int64_t sector_num = 0;
1237 int64_t nb_sectors;
1238 int c, pnum;
d14ed18c 1239 uint64_t progress_base;
eb769f74 1240 bool image_opts = false;
335e9937 1241 bool force_share = false;
d14ed18c 1242
40055951 1243 cache = BDRV_DEFAULT_CACHE;
d14ed18c 1244 for (;;) {
3babeb15
DB
1245 static const struct option long_options[] = {
1246 {"help", no_argument, 0, 'h'},
1247 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1248 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 1249 {"force-share", no_argument, 0, 'U'},
3babeb15
DB
1250 {0, 0, 0, 0}
1251 };
335e9937 1252 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
3babeb15 1253 long_options, NULL);
d14ed18c
MR
1254 if (c == -1) {
1255 break;
1256 }
1257 switch (c) {
c9192973
SH
1258 case ':':
1259 missing_argument(argv[optind - 1]);
1260 break;
d14ed18c 1261 case '?':
c9192973
SH
1262 unrecognized_option(argv[optind - 1]);
1263 break;
d14ed18c
MR
1264 case 'h':
1265 help();
1266 break;
1267 case 'f':
1268 fmt1 = optarg;
1269 break;
1270 case 'F':
1271 fmt2 = optarg;
1272 break;
40055951
HR
1273 case 'T':
1274 cache = optarg;
1275 break;
d14ed18c
MR
1276 case 'p':
1277 progress = true;
1278 break;
1279 case 'q':
1280 quiet = true;
1281 break;
1282 case 's':
1283 strict = true;
1284 break;
335e9937
FZ
1285 case 'U':
1286 force_share = true;
1287 break;
3babeb15
DB
1288 case OPTION_OBJECT: {
1289 QemuOpts *opts;
1290 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1291 optarg, true);
1292 if (!opts) {
1293 ret = 2;
1294 goto out4;
1295 }
1296 } break;
eb769f74
DB
1297 case OPTION_IMAGE_OPTS:
1298 image_opts = true;
1299 break;
d14ed18c
MR
1300 }
1301 }
1302
1303 /* Progress is not shown in Quiet mode */
1304 if (quiet) {
1305 progress = false;
1306 }
1307
1308
fc11eb26 1309 if (optind != argc - 2) {
ac1307ab 1310 error_exit("Expecting two image file names");
d14ed18c
MR
1311 }
1312 filename1 = argv[optind++];
1313 filename2 = argv[optind++];
1314
3babeb15
DB
1315 if (qemu_opts_foreach(&qemu_object_opts,
1316 user_creatable_add_opts_foreach,
51b9b478 1317 NULL, NULL)) {
3babeb15
DB
1318 ret = 2;
1319 goto out4;
1320 }
1321
cbda016d
SH
1322 /* Initialize before goto out */
1323 qemu_progress_init(progress, 2.0);
1324
ce099547
KW
1325 flags = 0;
1326 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
1327 if (ret < 0) {
1328 error_report("Invalid source cache option: %s", cache);
1329 ret = 2;
1330 goto out3;
1331 }
1332
335e9937
FZ
1333 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1334 force_share);
7e7d56d9 1335 if (!blk1) {
d14ed18c 1336 ret = 2;
7e7d56d9 1337 goto out3;
d14ed18c
MR
1338 }
1339
335e9937
FZ
1340 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1341 force_share);
7e7d56d9 1342 if (!blk2) {
d14ed18c 1343 ret = 2;
7e7d56d9 1344 goto out2;
d14ed18c 1345 }
eb769f74 1346 bs1 = blk_bs(blk1);
7e7d56d9 1347 bs2 = blk_bs(blk2);
d14ed18c 1348
f1d3cd79
HR
1349 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1350 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1351 total_sectors1 = blk_nb_sectors(blk1);
52bf1e72
MA
1352 if (total_sectors1 < 0) {
1353 error_report("Can't get size of %s: %s",
1354 filename1, strerror(-total_sectors1));
1355 ret = 4;
1356 goto out;
1357 }
f1d3cd79 1358 total_sectors2 = blk_nb_sectors(blk2);
52bf1e72
MA
1359 if (total_sectors2 < 0) {
1360 error_report("Can't get size of %s: %s",
1361 filename2, strerror(-total_sectors2));
1362 ret = 4;
1363 goto out;
1364 }
d14ed18c
MR
1365 total_sectors = MIN(total_sectors1, total_sectors2);
1366 progress_base = MAX(total_sectors1, total_sectors2);
1367
1368 qemu_progress_print(0, 100);
1369
1370 if (strict && total_sectors1 != total_sectors2) {
1371 ret = 1;
1372 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1373 goto out;
1374 }
1375
1376 for (;;) {
25ad8e6e 1377 int64_t status1, status2;
67a0fd2a 1378
d14ed18c
MR
1379 nb_sectors = sectors_to_process(total_sectors, sector_num);
1380 if (nb_sectors <= 0) {
1381 break;
1382 }
25ad8e6e
FZ
1383 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1384 total_sectors1 - sector_num,
298a1665 1385 &pnum1, NULL);
25ad8e6e 1386 if (status1 < 0) {
d14ed18c
MR
1387 ret = 3;
1388 error_report("Sector allocation test failed for %s", filename1);
1389 goto out;
1390 }
25ad8e6e 1391 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
d14ed18c 1392
25ad8e6e
FZ
1393 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1394 total_sectors2 - sector_num,
298a1665 1395 &pnum2, NULL);
25ad8e6e 1396 if (status2 < 0) {
d14ed18c
MR
1397 ret = 3;
1398 error_report("Sector allocation test failed for %s", filename2);
1399 goto out;
1400 }
25ad8e6e
FZ
1401 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1402 if (pnum1) {
1403 nb_sectors = MIN(nb_sectors, pnum1);
1404 }
1405 if (pnum2) {
1406 nb_sectors = MIN(nb_sectors, pnum2);
1407 }
d14ed18c 1408
25ad8e6e
FZ
1409 if (strict) {
1410 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1411 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1412 ret = 1;
1413 qprintf(quiet, "Strict mode: Offset %" PRId64
1414 " block status mismatch!\n",
1415 sectors_to_bytes(sector_num));
1416 goto out;
1417 }
1418 }
1419 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1420 nb_sectors = MIN(pnum1, pnum2);
1421 } else if (allocated1 == allocated2) {
d14ed18c 1422 if (allocated1) {
9166920a
EB
1423 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1424 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
1425 if (ret < 0) {
1426 error_report("Error while reading offset %" PRId64 " of %s:"
1427 " %s", sectors_to_bytes(sector_num), filename1,
1428 strerror(-ret));
1429 ret = 4;
1430 goto out;
1431 }
9166920a
EB
1432 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1433 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
1434 if (ret < 0) {
1435 error_report("Error while reading offset %" PRId64
1436 " of %s: %s", sectors_to_bytes(sector_num),
1437 filename2, strerror(-ret));
1438 ret = 4;
1439 goto out;
1440 }
1441 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1442 if (ret || pnum != nb_sectors) {
d14ed18c
MR
1443 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1444 sectors_to_bytes(
1445 ret ? sector_num : sector_num + pnum));
36452f12 1446 ret = 1;
d14ed18c
MR
1447 goto out;
1448 }
1449 }
1450 } else {
d14ed18c
MR
1451
1452 if (allocated1) {
f1d3cd79 1453 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
d14ed18c
MR
1454 filename1, buf1, quiet);
1455 } else {
f1d3cd79 1456 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
d14ed18c
MR
1457 filename2, buf1, quiet);
1458 }
1459 if (ret) {
1460 if (ret < 0) {
d14ed18c
MR
1461 error_report("Error while reading offset %" PRId64 ": %s",
1462 sectors_to_bytes(sector_num), strerror(-ret));
36452f12 1463 ret = 4;
d14ed18c
MR
1464 }
1465 goto out;
1466 }
1467 }
1468 sector_num += nb_sectors;
1469 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1470 }
1471
1472 if (total_sectors1 != total_sectors2) {
f1d3cd79 1473 BlockBackend *blk_over;
d14ed18c
MR
1474 int64_t total_sectors_over;
1475 const char *filename_over;
1476
1477 qprintf(quiet, "Warning: Image size mismatch!\n");
1478 if (total_sectors1 > total_sectors2) {
1479 total_sectors_over = total_sectors1;
f1d3cd79 1480 blk_over = blk1;
d14ed18c
MR
1481 filename_over = filename1;
1482 } else {
1483 total_sectors_over = total_sectors2;
f1d3cd79 1484 blk_over = blk2;
d14ed18c
MR
1485 filename_over = filename2;
1486 }
1487
1488 for (;;) {
51b0a488
EB
1489 int64_t count;
1490
d14ed18c
MR
1491 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1492 if (nb_sectors <= 0) {
1493 break;
1494 }
51b0a488
EB
1495 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL,
1496 sector_num * BDRV_SECTOR_SIZE,
1497 nb_sectors * BDRV_SECTOR_SIZE,
1498 &count);
d14ed18c
MR
1499 if (ret < 0) {
1500 ret = 3;
1501 error_report("Sector allocation test failed for %s",
1502 filename_over);
1503 goto out;
1504
1505 }
51b0a488
EB
1506 /* TODO relax this once bdrv_is_allocated_above does not enforce
1507 * sector alignment */
1508 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1509 nb_sectors = count >> BDRV_SECTOR_BITS;
d14ed18c 1510 if (ret) {
f1d3cd79 1511 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
d14ed18c
MR
1512 filename_over, buf1, quiet);
1513 if (ret) {
1514 if (ret < 0) {
d14ed18c
MR
1515 error_report("Error while reading offset %" PRId64
1516 " of %s: %s", sectors_to_bytes(sector_num),
1517 filename_over, strerror(-ret));
36452f12 1518 ret = 4;
d14ed18c
MR
1519 }
1520 goto out;
1521 }
1522 }
1523 sector_num += nb_sectors;
1524 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1525 }
1526 }
1527
1528 qprintf(quiet, "Images are identical.\n");
1529 ret = 0;
1530
1531out:
d14ed18c
MR
1532 qemu_vfree(buf1);
1533 qemu_vfree(buf2);
26f54e9a 1534 blk_unref(blk2);
d14ed18c 1535out2:
26f54e9a 1536 blk_unref(blk1);
d14ed18c
MR
1537out3:
1538 qemu_progress_end();
3babeb15 1539out4:
d14ed18c
MR
1540 return ret;
1541}
1542
690c7301
KW
1543enum ImgConvertBlockStatus {
1544 BLK_DATA,
1545 BLK_ZERO,
1546 BLK_BACKING_FILE,
1547};
1548
2d9187bc
PL
1549#define MAX_COROUTINES 16
1550
690c7301
KW
1551typedef struct ImgConvertState {
1552 BlockBackend **src;
1553 int64_t *src_sectors;
2d9187bc 1554 int src_num;
690c7301
KW
1555 int64_t total_sectors;
1556 int64_t allocated_sectors;
2d9187bc
PL
1557 int64_t allocated_done;
1558 int64_t sector_num;
1559 int64_t wr_offs;
690c7301
KW
1560 enum ImgConvertBlockStatus status;
1561 int64_t sector_next_status;
1562 BlockBackend *target;
1563 bool has_zero_init;
1564 bool compressed;
1565 bool target_has_backing;
2d9187bc 1566 bool wr_in_order;
690c7301
KW
1567 int min_sparse;
1568 size_t cluster_sectors;
1569 size_t buf_sectors;
9fd77f99 1570 long num_coroutines;
2d9187bc
PL
1571 int running_coroutines;
1572 Coroutine *co[MAX_COROUTINES];
1573 int64_t wait_sector_num[MAX_COROUTINES];
1574 CoMutex lock;
1575 int ret;
690c7301
KW
1576} ImgConvertState;
1577
2d9187bc
PL
1578static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1579 int *src_cur, int64_t *src_cur_offset)
690c7301 1580{
2d9187bc
PL
1581 *src_cur = 0;
1582 *src_cur_offset = 0;
1583 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1584 *src_cur_offset += s->src_sectors[*src_cur];
1585 (*src_cur)++;
1586 assert(*src_cur < s->src_num);
690c7301
KW
1587 }
1588}
1589
1590static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1591{
2d9187bc
PL
1592 int64_t ret, src_cur_offset;
1593 int n, src_cur;
690c7301 1594
2d9187bc 1595 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
690c7301
KW
1596
1597 assert(s->total_sectors > sector_num);
1598 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1599
1600 if (s->sector_next_status <= sector_num) {
9f1b92ad
VSO
1601 if (s->target_has_backing) {
1602 ret = bdrv_get_block_status(blk_bs(s->src[src_cur]),
1603 sector_num - src_cur_offset,
298a1665 1604 n, &n, NULL);
9f1b92ad
VSO
1605 } else {
1606 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1607 sector_num - src_cur_offset,
298a1665 1608 n, &n, NULL);
9f1b92ad 1609 }
690c7301
KW
1610 if (ret < 0) {
1611 return ret;
1612 }
1613
1614 if (ret & BDRV_BLOCK_ZERO) {
1615 s->status = BLK_ZERO;
1616 } else if (ret & BDRV_BLOCK_DATA) {
1617 s->status = BLK_DATA;
690c7301 1618 } else {
9f1b92ad 1619 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
690c7301
KW
1620 }
1621
1622 s->sector_next_status = sector_num + n;
1623 }
1624
1625 n = MIN(n, s->sector_next_status - sector_num);
1626 if (s->status == BLK_DATA) {
1627 n = MIN(n, s->buf_sectors);
1628 }
1629
1630 /* We need to write complete clusters for compressed images, so if an
1631 * unallocated area is shorter than that, we must consider the whole
1632 * cluster allocated. */
1633 if (s->compressed) {
1634 if (n < s->cluster_sectors) {
1635 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1636 s->status = BLK_DATA;
1637 } else {
1638 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1639 }
1640 }
1641
1642 return n;
1643}
1644
2d9187bc
PL
1645static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1646 int nb_sectors, uint8_t *buf)
690c7301 1647{
2d9187bc
PL
1648 int n, ret;
1649 QEMUIOVector qiov;
1650 struct iovec iov;
690c7301 1651
690c7301
KW
1652 assert(nb_sectors <= s->buf_sectors);
1653 while (nb_sectors > 0) {
1654 BlockBackend *blk;
2d9187bc
PL
1655 int src_cur;
1656 int64_t bs_sectors, src_cur_offset;
690c7301
KW
1657
1658 /* In the case of compression with multiple source files, we can get a
1659 * nb_sectors that spreads into the next part. So we must be able to
1660 * read across multiple BDSes for one convert_read() call. */
2d9187bc
PL
1661 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1662 blk = s->src[src_cur];
1663 bs_sectors = s->src_sectors[src_cur];
1664
1665 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1666 iov.iov_base = buf;
1667 iov.iov_len = n << BDRV_SECTOR_BITS;
1668 qemu_iovec_init_external(&qiov, &iov, 1);
1669
1670 ret = blk_co_preadv(
1671 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1672 n << BDRV_SECTOR_BITS, &qiov, 0);
690c7301
KW
1673 if (ret < 0) {
1674 return ret;
1675 }
1676
1677 sector_num += n;
1678 nb_sectors -= n;
1679 buf += n * BDRV_SECTOR_SIZE;
1680 }
1681
1682 return 0;
1683}
1684
2d9187bc
PL
1685
1686static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1687 int nb_sectors, uint8_t *buf,
1688 enum ImgConvertBlockStatus status)
690c7301
KW
1689{
1690 int ret;
2d9187bc
PL
1691 QEMUIOVector qiov;
1692 struct iovec iov;
690c7301
KW
1693
1694 while (nb_sectors > 0) {
1695 int n = nb_sectors;
db933fbe
LC
1696 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1697
2d9187bc 1698 switch (status) {
690c7301
KW
1699 case BLK_BACKING_FILE:
1700 /* If we have a backing file, leave clusters unallocated that are
1701 * unallocated in the source image, so that the backing file is
1702 * visible at the respective offset. */
1703 assert(s->target_has_backing);
1704 break;
1705
1706 case BLK_DATA:
db933fbe
LC
1707 /* If we're told to keep the target fully allocated (-S 0) or there
1708 * is real non-zero data, we must write it. Otherwise we can treat
1709 * it as zero sectors.
1710 * Compressed clusters need to be written as a whole, so in that
1711 * case we can only save the write if the buffer is completely
1712 * zeroed. */
690c7301 1713 if (!s->min_sparse ||
db933fbe
LC
1714 (!s->compressed &&
1715 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1716 (s->compressed &&
1717 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
690c7301 1718 {
2d9187bc
PL
1719 iov.iov_base = buf;
1720 iov.iov_len = n << BDRV_SECTOR_BITS;
1721 qemu_iovec_init_external(&qiov, &iov, 1);
1722
1723 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
db933fbe 1724 n << BDRV_SECTOR_BITS, &qiov, flags);
690c7301
KW
1725 if (ret < 0) {
1726 return ret;
1727 }
1728 break;
1729 }
1730 /* fall-through */
1731
1732 case BLK_ZERO:
1733 if (s->has_zero_init) {
db933fbe 1734 assert(!s->target_has_backing);
690c7301
KW
1735 break;
1736 }
2d9187bc
PL
1737 ret = blk_co_pwrite_zeroes(s->target,
1738 sector_num << BDRV_SECTOR_BITS,
1739 n << BDRV_SECTOR_BITS, 0);
690c7301
KW
1740 if (ret < 0) {
1741 return ret;
1742 }
1743 break;
1744 }
1745
1746 sector_num += n;
1747 nb_sectors -= n;
1748 buf += n * BDRV_SECTOR_SIZE;
1749 }
1750
1751 return 0;
1752}
1753
2d9187bc 1754static void coroutine_fn convert_co_do_copy(void *opaque)
690c7301 1755{
2d9187bc 1756 ImgConvertState *s = opaque;
690c7301 1757 uint8_t *buf = NULL;
2d9187bc
PL
1758 int ret, i;
1759 int index = -1;
1760
1761 for (i = 0; i < s->num_coroutines; i++) {
1762 if (s->co[i] == qemu_coroutine_self()) {
1763 index = i;
1764 break;
1765 }
1766 }
1767 assert(index >= 0);
1768
1769 s->running_coroutines++;
1770 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1771
1772 while (1) {
1773 int n;
1774 int64_t sector_num;
1775 enum ImgConvertBlockStatus status;
1776
1777 qemu_co_mutex_lock(&s->lock);
1778 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1779 qemu_co_mutex_unlock(&s->lock);
b91127ed 1780 break;
2d9187bc
PL
1781 }
1782 n = convert_iteration_sectors(s, s->sector_num);
1783 if (n < 0) {
1784 qemu_co_mutex_unlock(&s->lock);
1785 s->ret = n;
b91127ed 1786 break;
2d9187bc
PL
1787 }
1788 /* save current sector and allocation status to local variables */
1789 sector_num = s->sector_num;
1790 status = s->status;
1791 if (!s->min_sparse && s->status == BLK_ZERO) {
1792 n = MIN(n, s->buf_sectors);
1793 }
1794 /* increment global sector counter so that other coroutines can
1795 * already continue reading beyond this request */
1796 s->sector_num += n;
1797 qemu_co_mutex_unlock(&s->lock);
1798
1799 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1800 s->allocated_done += n;
1801 qemu_progress_print(100.0 * s->allocated_done /
1802 s->allocated_sectors, 0);
1803 }
1804
1805 if (status == BLK_DATA) {
1806 ret = convert_co_read(s, sector_num, n, buf);
1807 if (ret < 0) {
1808 error_report("error while reading sector %" PRId64
1809 ": %s", sector_num, strerror(-ret));
1810 s->ret = ret;
2d9187bc
PL
1811 }
1812 } else if (!s->min_sparse && status == BLK_ZERO) {
1813 status = BLK_DATA;
1814 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1815 }
1816
1817 if (s->wr_in_order) {
1818 /* keep writes in order */
b91127ed 1819 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2d9187bc
PL
1820 s->wait_sector_num[index] = sector_num;
1821 qemu_coroutine_yield();
1822 }
1823 s->wait_sector_num[index] = -1;
1824 }
1825
b91127ed
AN
1826 if (s->ret == -EINPROGRESS) {
1827 ret = convert_co_write(s, sector_num, n, buf, status);
1828 if (ret < 0) {
1829 error_report("error while writing sector %" PRId64
1830 ": %s", sector_num, strerror(-ret));
1831 s->ret = ret;
1832 }
2d9187bc
PL
1833 }
1834
1835 if (s->wr_in_order) {
1836 /* reenter the coroutine that might have waited
1837 * for this write to complete */
1838 s->wr_offs = sector_num + n;
1839 for (i = 0; i < s->num_coroutines; i++) {
1840 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1841 /*
1842 * A -> B -> A cannot occur because A has
1843 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1844 * B will never enter A during this time window.
1845 */
1846 qemu_coroutine_enter(s->co[i]);
1847 break;
1848 }
1849 }
1850 }
1851 }
1852
2d9187bc
PL
1853 qemu_vfree(buf);
1854 s->co[index] = NULL;
1855 s->running_coroutines--;
1856 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1857 /* the convert job finished successfully */
1858 s->ret = 0;
1859 }
1860}
1861
1862static int convert_do_copy(ImgConvertState *s)
1863{
1864 int ret, i, n;
1865 int64_t sector_num = 0;
690c7301
KW
1866
1867 /* Check whether we have zero initialisation or can get it efficiently */
1868 s->has_zero_init = s->min_sparse && !s->target_has_backing
1869 ? bdrv_has_zero_init(blk_bs(s->target))
1870 : false;
1871
1872 if (!s->has_zero_init && !s->target_has_backing &&
1873 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1874 {
720ff280 1875 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
690c7301
KW
1876 if (ret == 0) {
1877 s->has_zero_init = true;
1878 }
1879 }
1880
1881 /* Allocate buffer for copied data. For compressed images, only one cluster
1882 * can be copied at a time. */
1883 if (s->compressed) {
1884 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1885 error_report("invalid cluster size");
2d9187bc 1886 return -EINVAL;
690c7301
KW
1887 }
1888 s->buf_sectors = s->cluster_sectors;
1889 }
690c7301 1890
690c7301
KW
1891 while (sector_num < s->total_sectors) {
1892 n = convert_iteration_sectors(s, sector_num);
1893 if (n < 0) {
2d9187bc 1894 return n;
690c7301 1895 }
aad15de4
HR
1896 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1897 {
690c7301
KW
1898 s->allocated_sectors += n;
1899 }
1900 sector_num += n;
1901 }
1902
1903 /* Do the copy */
690c7301 1904 s->sector_next_status = 0;
2d9187bc 1905 s->ret = -EINPROGRESS;
690c7301 1906
2d9187bc
PL
1907 qemu_co_mutex_init(&s->lock);
1908 for (i = 0; i < s->num_coroutines; i++) {
1909 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1910 s->wait_sector_num[i] = -1;
1911 qemu_coroutine_enter(s->co[i]);
1912 }
690c7301 1913
b91127ed 1914 while (s->running_coroutines) {
2d9187bc 1915 main_loop_wait(false);
690c7301
KW
1916 }
1917
2d9187bc 1918 if (s->compressed && !s->ret) {
690c7301 1919 /* signal EOF to align */
fe5c1355 1920 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
690c7301 1921 if (ret < 0) {
2d9187bc 1922 return ret;
690c7301
KW
1923 }
1924 }
1925
2d9187bc 1926 return s->ret;
690c7301
KW
1927}
1928
ea2384d3
FB
1929static int img_convert(int argc, char **argv)
1930{
9fd77f99 1931 int c, bs_i, flags, src_flags = 0;
305b4c60 1932 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
9fd77f99
PL
1933 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1934 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
305b4c60 1935 BlockDriver *drv = NULL, *proto_drv = NULL;
faea38e7 1936 BlockDriverInfo bdi;
9fd77f99
PL
1937 BlockDriverState *out_bs;
1938 QemuOpts *opts = NULL, *sn_opts = NULL;
83d0521a 1939 QemuOptsList *create_opts = NULL;
efa84d43 1940 char *options = NULL;
cc84d90f 1941 Error *local_err = NULL;
9fd77f99 1942 bool writethrough, src_writethrough, quiet = false, image_opts = false,
305b4c60 1943 skip_create = false, progress = false, tgt_image_opts = false;
9fd77f99 1944 int64_t ret = -EINVAL;
335e9937 1945 bool force_share = false;
9fd77f99
PL
1946
1947 ImgConvertState s = (ImgConvertState) {
1948 /* Need at least 4k of zeros for sparse detection */
1949 .min_sparse = 8,
1950 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1951 .wr_in_order = true,
1952 .num_coroutines = 8,
1953 };
ea2384d3 1954
ea2384d3 1955 for(;;) {
3babeb15
DB
1956 static const struct option long_options[] = {
1957 {"help", no_argument, 0, 'h'},
1958 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1959 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 1960 {"force-share", no_argument, 0, 'U'},
305b4c60 1961 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
3babeb15
DB
1962 {0, 0, 0, 0}
1963 };
6b4df548 1964 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
3babeb15 1965 long_options, NULL);
b8fb60da 1966 if (c == -1) {
ea2384d3 1967 break;
b8fb60da 1968 }
ea2384d3 1969 switch(c) {
c9192973
SH
1970 case ':':
1971 missing_argument(argv[optind - 1]);
1972 break;
ef87394c 1973 case '?':
c9192973
SH
1974 unrecognized_option(argv[optind - 1]);
1975 break;
ea2384d3
FB
1976 case 'h':
1977 help();
1978 break;
1979 case 'f':
1980 fmt = optarg;
1981 break;
1982 case 'O':
1983 out_fmt = optarg;
1984 break;
f58c7b35
TS
1985 case 'B':
1986 out_baseimg = optarg;
1987 break;
ea2384d3 1988 case 'c':
9fd77f99 1989 s.compressed = true;
ea2384d3 1990 break;
efa84d43 1991 case 'o':
2dc8328b
KW
1992 if (!is_valid_option_list(optarg)) {
1993 error_report("Invalid option list: %s", optarg);
64bb01aa 1994 goto fail_getopt;
2dc8328b
KW
1995 }
1996 if (!options) {
1997 options = g_strdup(optarg);
1998 } else {
1999 char *old_options = options;
2000 options = g_strdup_printf("%s,%s", options, optarg);
2001 g_free(old_options);
2002 }
efa84d43 2003 break;
51ef6727 2004 case 's':
2005 snapshot_name = optarg;
2006 break;
ef80654d
WX
2007 case 'l':
2008 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
2009 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2010 optarg, false);
ef80654d
WX
2011 if (!sn_opts) {
2012 error_report("Failed in parsing snapshot param '%s'",
2013 optarg);
64bb01aa 2014 goto fail_getopt;
ef80654d
WX
2015 }
2016 } else {
2017 snapshot_name = optarg;
2018 }
2019 break;
a22f123c
KW
2020 case 'S':
2021 {
2022 int64_t sval;
606caa0a
MA
2023
2024 sval = cvtnum(optarg);
2025 if (sval < 0) {
a22f123c 2026 error_report("Invalid minimum zero buffer size for sparse output specified");
64bb01aa 2027 goto fail_getopt;
a22f123c
KW
2028 }
2029
9fd77f99 2030 s.min_sparse = sval / BDRV_SECTOR_SIZE;
a22f123c
KW
2031 break;
2032 }
6b837bc4 2033 case 'p':
9fd77f99 2034 progress = true;
6b837bc4 2035 break;
661a0f71
FS
2036 case 't':
2037 cache = optarg;
2038 break;
40055951
HR
2039 case 'T':
2040 src_cache = optarg;
2041 break;
f382d43a
MR
2042 case 'q':
2043 quiet = true;
2044 break;
b2e10493 2045 case 'n':
9fd77f99 2046 skip_create = true;
b2e10493 2047 break;
2d9187bc 2048 case 'm':
9fd77f99
PL
2049 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2050 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2d9187bc
PL
2051 error_report("Invalid number of coroutines. Allowed number of"
2052 " coroutines is between 1 and %d", MAX_COROUTINES);
2d9187bc
PL
2053 goto fail_getopt;
2054 }
2055 break;
2056 case 'W':
9fd77f99 2057 s.wr_in_order = false;
2d9187bc 2058 break;
335e9937
FZ
2059 case 'U':
2060 force_share = true;
2061 break;
3258b911
HR
2062 case OPTION_OBJECT: {
2063 QemuOpts *object_opts;
2064 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2065 optarg, true);
2066 if (!object_opts) {
3babeb15
DB
2067 goto fail_getopt;
2068 }
2069 break;
3258b911 2070 }
eb769f74
DB
2071 case OPTION_IMAGE_OPTS:
2072 image_opts = true;
2073 break;
305b4c60
DB
2074 case OPTION_TARGET_IMAGE_OPTS:
2075 tgt_image_opts = true;
2076 break;
ea2384d3
FB
2077 }
2078 }
3b46e624 2079
305b4c60
DB
2080 if (!out_fmt && !tgt_image_opts) {
2081 out_fmt = "raw";
2082 }
2083
3babeb15
DB
2084 if (qemu_opts_foreach(&qemu_object_opts,
2085 user_creatable_add_opts_foreach,
51b9b478 2086 NULL, NULL)) {
3babeb15
DB
2087 goto fail_getopt;
2088 }
2089
9fd77f99 2090 if (!s.wr_in_order && s.compressed) {
2d9187bc 2091 error_report("Out of order write and compress are mutually exclusive");
2d9187bc
PL
2092 goto fail_getopt;
2093 }
2094
305b4c60
DB
2095 if (tgt_image_opts && !skip_create) {
2096 error_report("--target-image-opts requires use of -n flag");
2097 goto fail_getopt;
2098 }
2099
9fd77f99
PL
2100 s.src_num = argc - optind - 1;
2101 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
f58c7b35 2102
2dc8328b 2103 if (options && has_help_option(options)) {
305b4c60
DB
2104 if (out_fmt) {
2105 ret = print_block_option_help(out_filename, out_fmt);
2106 goto fail_getopt;
2107 } else {
2108 error_report("Option help requires a format be specified");
2109 goto fail_getopt;
2110 }
4ac8aacd
JS
2111 }
2112
9fd77f99
PL
2113 if (s.src_num < 1) {
2114 error_report("Must specify image file name");
2115 goto fail_getopt;
a283cb6e
KW
2116 }
2117
2118
9fd77f99 2119 /* ret is still -EINVAL until here */
ce099547 2120 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
2121 if (ret < 0) {
2122 error_report("Invalid source cache option: %s", src_cache);
9fd77f99 2123 goto fail_getopt;
40055951
HR
2124 }
2125
9fd77f99
PL
2126 /* Initialize before goto out */
2127 if (quiet) {
2128 progress = false;
2129 }
2130 qemu_progress_init(progress, 1.0);
6b837bc4
JS
2131 qemu_progress_print(0, 100);
2132
9fd77f99
PL
2133 s.src = g_new0(BlockBackend *, s.src_num);
2134 s.src_sectors = g_new(int64_t, s.src_num);
926c2d23 2135
9fd77f99
PL
2136 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2137 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
335e9937
FZ
2138 fmt, src_flags, src_writethrough, quiet,
2139 force_share);
9fd77f99 2140 if (!s.src[bs_i]) {
c2abccec
MK
2141 ret = -1;
2142 goto out;
2143 }
9fd77f99
PL
2144 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2145 if (s.src_sectors[bs_i] < 0) {
52bf1e72 2146 error_report("Could not get size of %s: %s",
9fd77f99 2147 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
52bf1e72
MA
2148 ret = -1;
2149 goto out;
2150 }
9fd77f99 2151 s.total_sectors += s.src_sectors[bs_i];
926c2d23 2152 }
ea2384d3 2153
ef80654d 2154 if (sn_opts) {
9fd77f99 2155 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
10d6eda1
PM
2156 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2157 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2158 &local_err);
ef80654d 2159 } else if (snapshot_name != NULL) {
9fd77f99 2160 if (s.src_num > 1) {
6daf194d 2161 error_report("No support for concatenating multiple snapshot");
51ef6727 2162 ret = -1;
2163 goto out;
2164 }
7b4c4781 2165
9fd77f99
PL
2166 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2167 &local_err);
ef80654d 2168 }
84d18f06 2169 if (local_err) {
c29b77f9 2170 error_reportf_err(local_err, "Failed to load snapshot: ");
ef80654d
WX
2171 ret = -1;
2172 goto out;
51ef6727 2173 }
2174
305b4c60
DB
2175 if (!skip_create) {
2176 /* Find driver and parse its options */
2177 drv = bdrv_find_format(out_fmt);
2178 if (!drv) {
2179 error_report("Unknown file format '%s'", out_fmt);
2180 ret = -1;
2181 goto out;
2182 }
efa84d43 2183
305b4c60
DB
2184 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2185 if (!proto_drv) {
2186 error_report_err(local_err);
2187 ret = -1;
2188 goto out;
2189 }
b50cbabc 2190
2e024cde
HR
2191 if (!drv->create_opts) {
2192 error_report("Format driver '%s' does not support image creation",
2193 drv->format_name);
2194 ret = -1;
2195 goto out;
2196 }
f75613cf 2197
2e024cde
HR
2198 if (!proto_drv->create_opts) {
2199 error_report("Protocol driver '%s' does not support image creation",
2200 proto_drv->format_name);
2201 ret = -1;
2202 goto out;
2203 }
f75613cf 2204
2e024cde
HR
2205 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2206 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 2207
2e024cde 2208 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
2209 if (options) {
2210 qemu_opts_do_parse(opts, options, NULL, &local_err);
2211 if (local_err) {
97a2ca7a 2212 error_report_err(local_err);
dc523cd3
MA
2213 ret = -1;
2214 goto out;
2215 }
2e024cde 2216 }
efa84d43 2217
9fd77f99 2218 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
39101f25 2219 &error_abort);
2e024cde
HR
2220 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2221 if (ret < 0) {
2222 goto out;
2223 }
c2abccec 2224 }
efa84d43 2225
a18953fb 2226 /* Get backing file name if -o backing_file was used */
83d0521a 2227 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 2228 if (out_baseimg_param) {
83d0521a 2229 out_baseimg = out_baseimg_param;
a18953fb 2230 }
9fd77f99 2231 s.target_has_backing = (bool) out_baseimg;
a18953fb 2232
48758a84
HR
2233 if (s.src_num > 1 && out_baseimg) {
2234 error_report("Having a backing file for the target makes no sense when "
2235 "concatenating multiple input images");
2236 ret = -1;
2237 goto out;
2238 }
2239
efa84d43 2240 /* Check if compression is supported */
9fd77f99 2241 if (s.compressed) {
83d0521a
CL
2242 bool encryption =
2243 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
0cb8d47b
DB
2244 const char *encryptfmt =
2245 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
83d0521a
CL
2246 const char *preallocation =
2247 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
efa84d43 2248
305b4c60 2249 if (drv && !drv->bdrv_co_pwritev_compressed) {
15654a6d 2250 error_report("Compression not supported for this file format");
c2abccec
MK
2251 ret = -1;
2252 goto out;
efa84d43
KW
2253 }
2254
0cb8d47b 2255 if (encryption || encryptfmt) {
15654a6d
JS
2256 error_report("Compression and encryption not supported at "
2257 "the same time");
c2abccec
MK
2258 ret = -1;
2259 goto out;
efa84d43 2260 }
41521fa4 2261
83d0521a
CL
2262 if (preallocation
2263 && strcmp(preallocation, "off"))
41521fa4
KW
2264 {
2265 error_report("Compression and preallocation not supported at "
2266 "the same time");
2267 ret = -1;
2268 goto out;
2269 }
efa84d43
KW
2270 }
2271
b2e10493
AD
2272 if (!skip_create) {
2273 /* Create the new image */
c282e1fd 2274 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 2275 if (ret < 0) {
c29b77f9
MA
2276 error_reportf_err(local_err, "%s: error while converting %s: ",
2277 out_filename, out_fmt);
b2e10493 2278 goto out;
ea2384d3
FB
2279 }
2280 }
3b46e624 2281
9fd77f99 2282 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
ce099547 2283 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2284 if (ret < 0) {
2285 error_report("Invalid cache option: %s", cache);
bb9cd2ee 2286 goto out;
661a0f71
FS
2287 }
2288
305b4c60
DB
2289 if (skip_create) {
2290 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2291 flags, writethrough, quiet, false);
2292 } else {
2293 /* TODO ultimately we should allow --target-image-opts
2294 * to be used even when -n is not given.
2295 * That has to wait for bdrv_create to be improved
2296 * to allow filenames in option syntax
2297 */
29cf9336
DB
2298 s.target = img_open_new_file(out_filename, opts, out_fmt,
2299 flags, writethrough, quiet, false);
305b4c60 2300 }
9fd77f99 2301 if (!s.target) {
c2abccec
MK
2302 ret = -1;
2303 goto out;
2304 }
9fd77f99 2305 out_bs = blk_bs(s.target);
ea2384d3 2306
305b4c60
DB
2307 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2308 error_report("Compression not supported for this file format");
2309 ret = -1;
2310 goto out;
2311 }
2312
5def6b80 2313 /* increase bufsectors from the default 4096 (2M) if opt_transfer
f2521c90
PL
2314 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2315 * as maximum. */
9fd77f99
PL
2316 s.buf_sectors = MIN(32768,
2317 MAX(s.buf_sectors,
2318 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2319 out_bs->bl.pdiscard_alignment >>
2320 BDRV_SECTOR_BITS)));
f2521c90 2321
b2e10493 2322 if (skip_create) {
9fd77f99 2323 int64_t output_sectors = blk_nb_sectors(s.target);
43716fa8 2324 if (output_sectors < 0) {
eec5eb42 2325 error_report("unable to get output image length: %s",
43716fa8 2326 strerror(-output_sectors));
b2e10493
AD
2327 ret = -1;
2328 goto out;
9fd77f99 2329 } else if (output_sectors < s.total_sectors) {
b2e10493
AD
2330 error_report("output file is smaller than input file");
2331 ret = -1;
2332 goto out;
2333 }
2334 }
2335
24f833cd
PL
2336 ret = bdrv_get_info(out_bs, &bdi);
2337 if (ret < 0) {
9fd77f99 2338 if (s.compressed) {
15654a6d 2339 error_report("could not get block driver info");
c2abccec
MK
2340 goto out;
2341 }
24f833cd 2342 } else {
9fd77f99
PL
2343 s.compressed = s.compressed || bdi.needs_compressed_writes;
2344 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2345 }
802c3d4c 2346
9fd77f99 2347 ret = convert_do_copy(&s);
c2abccec 2348out:
13c28af8
PL
2349 if (!ret) {
2350 qemu_progress_print(100, 0);
2351 }
6b837bc4 2352 qemu_progress_end();
83d0521a
CL
2353 qemu_opts_del(opts);
2354 qemu_opts_free(create_opts);
fbf28a43 2355 qemu_opts_del(sn_opts);
9fd77f99
PL
2356 blk_unref(s.target);
2357 if (s.src) {
2358 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2359 blk_unref(s.src[bs_i]);
26f54e9a 2360 }
9fd77f99 2361 g_free(s.src);
26f54e9a 2362 }
9fd77f99 2363 g_free(s.src_sectors);
64bb01aa
KW
2364fail_getopt:
2365 g_free(options);
2366
9fd77f99 2367 return !!ret;
ea2384d3
FB
2368}
2369
57d1a2b6 2370
faea38e7
FB
2371static void dump_snapshots(BlockDriverState *bs)
2372{
2373 QEMUSnapshotInfo *sn_tab, *sn;
2374 int nb_sns, i;
faea38e7
FB
2375
2376 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2377 if (nb_sns <= 0)
2378 return;
2379 printf("Snapshot list:\n");
5b917044
WX
2380 bdrv_snapshot_dump(fprintf, stdout, NULL);
2381 printf("\n");
faea38e7
FB
2382 for(i = 0; i < nb_sns; i++) {
2383 sn = &sn_tab[i];
5b917044
WX
2384 bdrv_snapshot_dump(fprintf, stdout, sn);
2385 printf("\n");
faea38e7 2386 }
7267c094 2387 g_free(sn_tab);
faea38e7
FB
2388}
2389
9699bf0d
SH
2390static void dump_json_image_info_list(ImageInfoList *list)
2391{
9699bf0d 2392 QString *str;
9699bf0d 2393 QObject *obj;
7d5e199a 2394 Visitor *v = qobject_output_visitor_new(&obj);
3b098d56
EB
2395
2396 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2397 visit_complete(v, &obj);
9699bf0d
SH
2398 str = qobject_to_json_pretty(obj);
2399 assert(str != NULL);
2400 printf("%s\n", qstring_get_str(str));
2401 qobject_decref(obj);
3b098d56 2402 visit_free(v);
9699bf0d
SH
2403 QDECREF(str);
2404}
2405
c054b3fd
BC
2406static void dump_json_image_info(ImageInfo *info)
2407{
c054b3fd 2408 QString *str;
c054b3fd 2409 QObject *obj;
7d5e199a 2410 Visitor *v = qobject_output_visitor_new(&obj);
3b098d56
EB
2411
2412 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2413 visit_complete(v, &obj);
c054b3fd
BC
2414 str = qobject_to_json_pretty(obj);
2415 assert(str != NULL);
2416 printf("%s\n", qstring_get_str(str));
2417 qobject_decref(obj);
3b098d56 2418 visit_free(v);
c054b3fd
BC
2419 QDECREF(str);
2420}
2421
9699bf0d
SH
2422static void dump_human_image_info_list(ImageInfoList *list)
2423{
2424 ImageInfoList *elem;
2425 bool delim = false;
2426
2427 for (elem = list; elem; elem = elem->next) {
2428 if (delim) {
2429 printf("\n");
2430 }
2431 delim = true;
2432
5b917044 2433 bdrv_image_info_dump(fprintf, stdout, elem->value);
9699bf0d
SH
2434 }
2435}
2436
2437static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2438{
2439 return strcmp(a, b) == 0;
2440}
2441
2442/**
2443 * Open an image file chain and return an ImageInfoList
2444 *
2445 * @filename: topmost image filename
2446 * @fmt: topmost image format (may be NULL to autodetect)
2447 * @chain: true - enumerate entire backing file chain
2448 * false - only topmost image file
2449 *
2450 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2451 * image file. If there was an error a message will have been printed to
2452 * stderr.
2453 */
eb769f74
DB
2454static ImageInfoList *collect_image_info_list(bool image_opts,
2455 const char *filename,
9699bf0d 2456 const char *fmt,
335e9937 2457 bool chain, bool force_share)
9699bf0d
SH
2458{
2459 ImageInfoList *head = NULL;
2460 ImageInfoList **last = &head;
2461 GHashTable *filenames;
43526ec8 2462 Error *err = NULL;
9699bf0d
SH
2463
2464 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2465
2466 while (filename) {
26f54e9a 2467 BlockBackend *blk;
9699bf0d
SH
2468 BlockDriverState *bs;
2469 ImageInfo *info;
2470 ImageInfoList *elem;
2471
2472 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2473 error_report("Backing file '%s' creates an infinite loop.",
2474 filename);
2475 goto err;
2476 }
2477 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2478
efaa7c4e 2479 blk = img_open(image_opts, filename, fmt,
335e9937
FZ
2480 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2481 force_share);
7e7d56d9 2482 if (!blk) {
9699bf0d
SH
2483 goto err;
2484 }
7e7d56d9 2485 bs = blk_bs(blk);
9699bf0d 2486
43526ec8 2487 bdrv_query_image_info(bs, &info, &err);
84d18f06 2488 if (err) {
565f65d2 2489 error_report_err(err);
26f54e9a 2490 blk_unref(blk);
43526ec8 2491 goto err;
fb0ed453 2492 }
9699bf0d
SH
2493
2494 elem = g_new0(ImageInfoList, 1);
2495 elem->value = info;
2496 *last = elem;
2497 last = &elem->next;
2498
26f54e9a 2499 blk_unref(blk);
9699bf0d
SH
2500
2501 filename = fmt = NULL;
2502 if (chain) {
2503 if (info->has_full_backing_filename) {
2504 filename = info->full_backing_filename;
2505 } else if (info->has_backing_filename) {
92d617ab
JS
2506 error_report("Could not determine absolute backing filename,"
2507 " but backing filename '%s' present",
2508 info->backing_filename);
2509 goto err;
9699bf0d
SH
2510 }
2511 if (info->has_backing_filename_format) {
2512 fmt = info->backing_filename_format;
2513 }
2514 }
2515 }
2516 g_hash_table_destroy(filenames);
2517 return head;
2518
2519err:
2520 qapi_free_ImageInfoList(head);
2521 g_hash_table_destroy(filenames);
2522 return NULL;
2523}
2524
c054b3fd
BC
2525static int img_info(int argc, char **argv)
2526{
2527 int c;
2528 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 2529 bool chain = false;
c054b3fd 2530 const char *filename, *fmt, *output;
9699bf0d 2531 ImageInfoList *list;
eb769f74 2532 bool image_opts = false;
335e9937 2533 bool force_share = false;
c054b3fd 2534
ea2384d3 2535 fmt = NULL;
c054b3fd 2536 output = NULL;
ea2384d3 2537 for(;;) {
c054b3fd
BC
2538 int option_index = 0;
2539 static const struct option long_options[] = {
2540 {"help", no_argument, 0, 'h'},
2541 {"format", required_argument, 0, 'f'},
2542 {"output", required_argument, 0, OPTION_OUTPUT},
9699bf0d 2543 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3babeb15 2544 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2545 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2546 {"force-share", no_argument, 0, 'U'},
c054b3fd
BC
2547 {0, 0, 0, 0}
2548 };
335e9937 2549 c = getopt_long(argc, argv, ":f:hU",
c054b3fd 2550 long_options, &option_index);
b8fb60da 2551 if (c == -1) {
ea2384d3 2552 break;
b8fb60da 2553 }
ea2384d3 2554 switch(c) {
c9192973
SH
2555 case ':':
2556 missing_argument(argv[optind - 1]);
2557 break;
ef87394c 2558 case '?':
c9192973
SH
2559 unrecognized_option(argv[optind - 1]);
2560 break;
ea2384d3
FB
2561 case 'h':
2562 help();
2563 break;
2564 case 'f':
2565 fmt = optarg;
2566 break;
335e9937
FZ
2567 case 'U':
2568 force_share = true;
2569 break;
c054b3fd
BC
2570 case OPTION_OUTPUT:
2571 output = optarg;
2572 break;
9699bf0d
SH
2573 case OPTION_BACKING_CHAIN:
2574 chain = true;
2575 break;
3babeb15
DB
2576 case OPTION_OBJECT: {
2577 QemuOpts *opts;
2578 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2579 optarg, true);
2580 if (!opts) {
2581 return 1;
2582 }
2583 } break;
eb769f74
DB
2584 case OPTION_IMAGE_OPTS:
2585 image_opts = true;
2586 break;
ea2384d3
FB
2587 }
2588 }
fc11eb26 2589 if (optind != argc - 1) {
ac1307ab 2590 error_exit("Expecting one image file name");
b8fb60da 2591 }
ea2384d3
FB
2592 filename = argv[optind++];
2593
c054b3fd
BC
2594 if (output && !strcmp(output, "json")) {
2595 output_format = OFORMAT_JSON;
2596 } else if (output && !strcmp(output, "human")) {
2597 output_format = OFORMAT_HUMAN;
2598 } else if (output) {
2599 error_report("--output must be used with human or json as argument.");
c2abccec
MK
2600 return 1;
2601 }
c054b3fd 2602
3babeb15
DB
2603 if (qemu_opts_foreach(&qemu_object_opts,
2604 user_creatable_add_opts_foreach,
51b9b478 2605 NULL, NULL)) {
3babeb15
DB
2606 return 1;
2607 }
2608
335e9937
FZ
2609 list = collect_image_info_list(image_opts, filename, fmt, chain,
2610 force_share);
9699bf0d 2611 if (!list) {
c2abccec 2612 return 1;
faea38e7 2613 }
c054b3fd 2614
c054b3fd
BC
2615 switch (output_format) {
2616 case OFORMAT_HUMAN:
9699bf0d 2617 dump_human_image_info_list(list);
c054b3fd
BC
2618 break;
2619 case OFORMAT_JSON:
9699bf0d
SH
2620 if (chain) {
2621 dump_json_image_info_list(list);
2622 } else {
2623 dump_json_image_info(list->value);
2624 }
c054b3fd 2625 break;
faea38e7 2626 }
c054b3fd 2627
9699bf0d 2628 qapi_free_ImageInfoList(list);
ea2384d3
FB
2629 return 0;
2630}
2631
4c93a13b
PB
2632static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2633 MapEntry *next)
2634{
2635 switch (output_format) {
2636 case OFORMAT_HUMAN:
16b0d555 2637 if (e->data && !e->has_offset) {
4c93a13b
PB
2638 error_report("File contains external, encrypted or compressed clusters.");
2639 exit(1);
2640 }
16b0d555 2641 if (e->data && !e->zero) {
4c93a13b 2642 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
16b0d555
FZ
2643 e->start, e->length,
2644 e->has_offset ? e->offset : 0,
2645 e->has_filename ? e->filename : "");
4c93a13b
PB
2646 }
2647 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2648 * Modify the flags here to allow more coalescing.
2649 */
16b0d555
FZ
2650 if (next && (!next->data || next->zero)) {
2651 next->data = false;
2652 next->zero = true;
4c93a13b
PB
2653 }
2654 break;
2655 case OFORMAT_JSON:
16b0d555
FZ
2656 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2657 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
4c93a13b
PB
2658 (e->start == 0 ? "[" : ",\n"),
2659 e->start, e->length, e->depth,
16b0d555
FZ
2660 e->zero ? "true" : "false",
2661 e->data ? "true" : "false");
2662 if (e->has_offset) {
c745bfb4 2663 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2664 }
2665 putchar('}');
2666
2667 if (!next) {
2668 printf("]\n");
2669 }
2670 break;
2671 }
2672}
2673
2674static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2675 int nb_sectors, MapEntry *e)
2676{
2677 int64_t ret;
2678 int depth;
67a0fd2a 2679 BlockDriverState *file;
2875645b 2680 bool has_offset;
4c93a13b
PB
2681
2682 /* As an optimization, we could cache the current range of unallocated
2683 * clusters in each file of the chain, and avoid querying the same
2684 * range repeatedly.
2685 */
2686
2687 depth = 0;
2688 for (;;) {
67a0fd2a
FZ
2689 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2690 &file);
4c93a13b
PB
2691 if (ret < 0) {
2692 return ret;
2693 }
2694 assert(nb_sectors);
2695 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2696 break;
2697 }
760e0063 2698 bs = backing_bs(bs);
4c93a13b
PB
2699 if (bs == NULL) {
2700 ret = 0;
2701 break;
2702 }
2703
2704 depth++;
2705 }
2706
2875645b
JS
2707 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2708
2709 *e = (MapEntry) {
2710 .start = sector_num * BDRV_SECTOR_SIZE,
2711 .length = nb_sectors * BDRV_SECTOR_SIZE,
2712 .data = !!(ret & BDRV_BLOCK_DATA),
2713 .zero = !!(ret & BDRV_BLOCK_ZERO),
2714 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2715 .has_offset = has_offset,
2716 .depth = depth,
2717 .has_filename = file && has_offset,
2718 .filename = file && has_offset ? file->filename : NULL,
2719 };
2720
4c93a13b
PB
2721 return 0;
2722}
2723
16b0d555
FZ
2724static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2725{
2726 if (curr->length == 0) {
2727 return false;
2728 }
2729 if (curr->zero != next->zero ||
2730 curr->data != next->data ||
2731 curr->depth != next->depth ||
2732 curr->has_filename != next->has_filename ||
2733 curr->has_offset != next->has_offset) {
2734 return false;
2735 }
2736 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2737 return false;
2738 }
2739 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2740 return false;
2741 }
2742 return true;
2743}
2744
4c93a13b
PB
2745static int img_map(int argc, char **argv)
2746{
2747 int c;
2748 OutputFormat output_format = OFORMAT_HUMAN;
26f54e9a 2749 BlockBackend *blk;
4c93a13b
PB
2750 BlockDriverState *bs;
2751 const char *filename, *fmt, *output;
2752 int64_t length;
2753 MapEntry curr = { .length = 0 }, next;
2754 int ret = 0;
eb769f74 2755 bool image_opts = false;
335e9937 2756 bool force_share = false;
4c93a13b
PB
2757
2758 fmt = NULL;
2759 output = NULL;
2760 for (;;) {
2761 int option_index = 0;
2762 static const struct option long_options[] = {
2763 {"help", no_argument, 0, 'h'},
2764 {"format", required_argument, 0, 'f'},
2765 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 2766 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2767 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2768 {"force-share", no_argument, 0, 'U'},
4c93a13b
PB
2769 {0, 0, 0, 0}
2770 };
335e9937 2771 c = getopt_long(argc, argv, ":f:hU",
4c93a13b
PB
2772 long_options, &option_index);
2773 if (c == -1) {
2774 break;
2775 }
2776 switch (c) {
c9192973
SH
2777 case ':':
2778 missing_argument(argv[optind - 1]);
2779 break;
4c93a13b 2780 case '?':
c9192973
SH
2781 unrecognized_option(argv[optind - 1]);
2782 break;
4c93a13b
PB
2783 case 'h':
2784 help();
2785 break;
2786 case 'f':
2787 fmt = optarg;
2788 break;
335e9937
FZ
2789 case 'U':
2790 force_share = true;
2791 break;
4c93a13b
PB
2792 case OPTION_OUTPUT:
2793 output = optarg;
2794 break;
3babeb15
DB
2795 case OPTION_OBJECT: {
2796 QemuOpts *opts;
2797 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2798 optarg, true);
2799 if (!opts) {
2800 return 1;
2801 }
2802 } break;
eb769f74
DB
2803 case OPTION_IMAGE_OPTS:
2804 image_opts = true;
2805 break;
4c93a13b
PB
2806 }
2807 }
ac1307ab
FZ
2808 if (optind != argc - 1) {
2809 error_exit("Expecting one image file name");
4c93a13b 2810 }
ac1307ab 2811 filename = argv[optind];
4c93a13b
PB
2812
2813 if (output && !strcmp(output, "json")) {
2814 output_format = OFORMAT_JSON;
2815 } else if (output && !strcmp(output, "human")) {
2816 output_format = OFORMAT_HUMAN;
2817 } else if (output) {
2818 error_report("--output must be used with human or json as argument.");
2819 return 1;
2820 }
2821
3babeb15
DB
2822 if (qemu_opts_foreach(&qemu_object_opts,
2823 user_creatable_add_opts_foreach,
51b9b478 2824 NULL, NULL)) {
3babeb15
DB
2825 return 1;
2826 }
2827
335e9937 2828 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
7e7d56d9
MA
2829 if (!blk) {
2830 return 1;
4c93a13b 2831 }
7e7d56d9 2832 bs = blk_bs(blk);
4c93a13b
PB
2833
2834 if (output_format == OFORMAT_HUMAN) {
2835 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2836 }
2837
f1d3cd79 2838 length = blk_getlength(blk);
4c93a13b
PB
2839 while (curr.start + curr.length < length) {
2840 int64_t nsectors_left;
2841 int64_t sector_num;
2842 int n;
2843
2844 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2845
2846 /* Probe up to 1 GiB at a time. */
2847 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2848 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2849 ret = get_block_status(bs, sector_num, n, &next);
2850
2851 if (ret < 0) {
2852 error_report("Could not read file metadata: %s", strerror(-ret));
2853 goto out;
2854 }
2855
16b0d555 2856 if (entry_mergeable(&curr, &next)) {
4c93a13b
PB
2857 curr.length += next.length;
2858 continue;
2859 }
2860
2861 if (curr.length > 0) {
2862 dump_map_entry(output_format, &curr, &next);
2863 }
2864 curr = next;
2865 }
2866
2867 dump_map_entry(output_format, &curr, NULL);
2868
2869out:
26f54e9a 2870 blk_unref(blk);
4c93a13b
PB
2871 return ret < 0;
2872}
2873
f7b4a940
AL
2874#define SNAPSHOT_LIST 1
2875#define SNAPSHOT_CREATE 2
2876#define SNAPSHOT_APPLY 3
2877#define SNAPSHOT_DELETE 4
2878
153859be 2879static int img_snapshot(int argc, char **argv)
f7b4a940 2880{
26f54e9a 2881 BlockBackend *blk;
f7b4a940
AL
2882 BlockDriverState *bs;
2883 QEMUSnapshotInfo sn;
2884 char *filename, *snapshot_name = NULL;
c2abccec 2885 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
2886 int action = 0;
2887 qemu_timeval tv;
f382d43a 2888 bool quiet = false;
a89d89d3 2889 Error *err = NULL;
eb769f74 2890 bool image_opts = false;
335e9937 2891 bool force_share = false;
f7b4a940 2892
ce099547 2893 bdrv_oflags = BDRV_O_RDWR;
f7b4a940
AL
2894 /* Parse commandline parameters */
2895 for(;;) {
3babeb15
DB
2896 static const struct option long_options[] = {
2897 {"help", no_argument, 0, 'h'},
2898 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2899 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2900 {"force-share", no_argument, 0, 'U'},
3babeb15
DB
2901 {0, 0, 0, 0}
2902 };
335e9937 2903 c = getopt_long(argc, argv, ":la:c:d:hqU",
3babeb15 2904 long_options, NULL);
b8fb60da 2905 if (c == -1) {
f7b4a940 2906 break;
b8fb60da 2907 }
f7b4a940 2908 switch(c) {
c9192973
SH
2909 case ':':
2910 missing_argument(argv[optind - 1]);
2911 break;
ef87394c 2912 case '?':
c9192973
SH
2913 unrecognized_option(argv[optind - 1]);
2914 break;
f7b4a940
AL
2915 case 'h':
2916 help();
153859be 2917 return 0;
f7b4a940
AL
2918 case 'l':
2919 if (action) {
ac1307ab 2920 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2921 return 0;
f7b4a940
AL
2922 }
2923 action = SNAPSHOT_LIST;
f5edb014 2924 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
2925 break;
2926 case 'a':
2927 if (action) {
ac1307ab 2928 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2929 return 0;
f7b4a940
AL
2930 }
2931 action = SNAPSHOT_APPLY;
2932 snapshot_name = optarg;
2933 break;
2934 case 'c':
2935 if (action) {
ac1307ab 2936 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2937 return 0;
f7b4a940
AL
2938 }
2939 action = SNAPSHOT_CREATE;
2940 snapshot_name = optarg;
2941 break;
2942 case 'd':
2943 if (action) {
ac1307ab 2944 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2945 return 0;
f7b4a940
AL
2946 }
2947 action = SNAPSHOT_DELETE;
2948 snapshot_name = optarg;
2949 break;
f382d43a
MR
2950 case 'q':
2951 quiet = true;
2952 break;
335e9937
FZ
2953 case 'U':
2954 force_share = true;
2955 break;
3babeb15
DB
2956 case OPTION_OBJECT: {
2957 QemuOpts *opts;
2958 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2959 optarg, true);
2960 if (!opts) {
2961 return 1;
2962 }
2963 } break;
eb769f74
DB
2964 case OPTION_IMAGE_OPTS:
2965 image_opts = true;
2966 break;
f7b4a940
AL
2967 }
2968 }
2969
fc11eb26 2970 if (optind != argc - 1) {
ac1307ab 2971 error_exit("Expecting one image file name");
b8fb60da 2972 }
f7b4a940
AL
2973 filename = argv[optind++];
2974
3babeb15
DB
2975 if (qemu_opts_foreach(&qemu_object_opts,
2976 user_creatable_add_opts_foreach,
51b9b478 2977 NULL, NULL)) {
3babeb15
DB
2978 return 1;
2979 }
2980
f7b4a940 2981 /* Open the image */
335e9937
FZ
2982 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2983 force_share);
7e7d56d9
MA
2984 if (!blk) {
2985 return 1;
c2abccec 2986 }
7e7d56d9 2987 bs = blk_bs(blk);
f7b4a940
AL
2988
2989 /* Perform the requested action */
2990 switch(action) {
2991 case SNAPSHOT_LIST:
2992 dump_snapshots(bs);
2993 break;
2994
2995 case SNAPSHOT_CREATE:
2996 memset(&sn, 0, sizeof(sn));
2997 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2998
2999 qemu_gettimeofday(&tv);
3000 sn.date_sec = tv.tv_sec;
3001 sn.date_nsec = tv.tv_usec * 1000;
3002
3003 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 3004 if (ret) {
15654a6d 3005 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 3006 snapshot_name, ret, strerror(-ret));
b8fb60da 3007 }
f7b4a940
AL
3008 break;
3009
3010 case SNAPSHOT_APPLY:
3011 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 3012 if (ret) {
15654a6d 3013 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 3014 snapshot_name, ret, strerror(-ret));
b8fb60da 3015 }
f7b4a940
AL
3016 break;
3017
3018 case SNAPSHOT_DELETE:
a89d89d3 3019 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
84d18f06 3020 if (err) {
c29b77f9
MA
3021 error_reportf_err(err, "Could not delete snapshot '%s': ",
3022 snapshot_name);
a89d89d3 3023 ret = 1;
b8fb60da 3024 }
f7b4a940
AL
3025 break;
3026 }
3027
3028 /* Cleanup */
26f54e9a 3029 blk_unref(blk);
c2abccec
MK
3030 if (ret) {
3031 return 1;
3032 }
153859be 3033 return 0;
f7b4a940
AL
3034}
3035
3e85c6fd
KW
3036static int img_rebase(int argc, char **argv)
3037{
26f54e9a 3038 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
396374ca
PB
3039 uint8_t *buf_old = NULL;
3040 uint8_t *buf_new = NULL;
f1d3cd79 3041 BlockDriverState *bs = NULL;
3e85c6fd 3042 char *filename;
40055951
HR
3043 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3044 int c, flags, src_flags, ret;
ce099547 3045 bool writethrough, src_writethrough;
3e85c6fd 3046 int unsafe = 0;
335e9937 3047 bool force_share = false;
6b837bc4 3048 int progress = 0;
f382d43a 3049 bool quiet = false;
34b5d2c6 3050 Error *local_err = NULL;
eb769f74 3051 bool image_opts = false;
3e85c6fd
KW
3052
3053 /* Parse commandline parameters */
e53dbee0 3054 fmt = NULL;
661a0f71 3055 cache = BDRV_DEFAULT_CACHE;
40055951 3056 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
3057 out_baseimg = NULL;
3058 out_basefmt = NULL;
3e85c6fd 3059 for(;;) {
3babeb15
DB
3060 static const struct option long_options[] = {
3061 {"help", no_argument, 0, 'h'},
3062 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3063 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 3064 {"force-share", no_argument, 0, 'U'},
3babeb15
DB
3065 {0, 0, 0, 0}
3066 };
335e9937 3067 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3babeb15 3068 long_options, NULL);
b8fb60da 3069 if (c == -1) {
3e85c6fd 3070 break;
b8fb60da 3071 }
3e85c6fd 3072 switch(c) {
c9192973
SH
3073 case ':':
3074 missing_argument(argv[optind - 1]);
3075 break;
ef87394c 3076 case '?':
c9192973
SH
3077 unrecognized_option(argv[optind - 1]);
3078 break;
3e85c6fd
KW
3079 case 'h':
3080 help();
3081 return 0;
e53dbee0
KW
3082 case 'f':
3083 fmt = optarg;
3084 break;
3e85c6fd
KW
3085 case 'F':
3086 out_basefmt = optarg;
3087 break;
3088 case 'b':
3089 out_baseimg = optarg;
3090 break;
3091 case 'u':
3092 unsafe = 1;
3093 break;
6b837bc4
JS
3094 case 'p':
3095 progress = 1;
3096 break;
661a0f71
FS
3097 case 't':
3098 cache = optarg;
3099 break;
40055951
HR
3100 case 'T':
3101 src_cache = optarg;
3102 break;
f382d43a
MR
3103 case 'q':
3104 quiet = true;
3105 break;
3babeb15
DB
3106 case OPTION_OBJECT: {
3107 QemuOpts *opts;
3108 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3109 optarg, true);
3110 if (!opts) {
3111 return 1;
3112 }
3113 } break;
eb769f74
DB
3114 case OPTION_IMAGE_OPTS:
3115 image_opts = true;
3116 break;
335e9937
FZ
3117 case 'U':
3118 force_share = true;
3119 break;
3e85c6fd
KW
3120 }
3121 }
3122
f382d43a
MR
3123 if (quiet) {
3124 progress = 0;
3125 }
3126
ac1307ab
FZ
3127 if (optind != argc - 1) {
3128 error_exit("Expecting one image file name");
3129 }
3130 if (!unsafe && !out_baseimg) {
3131 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
b8fb60da 3132 }
3e85c6fd
KW
3133 filename = argv[optind++];
3134
3babeb15
DB
3135 if (qemu_opts_foreach(&qemu_object_opts,
3136 user_creatable_add_opts_foreach,
51b9b478 3137 NULL, NULL)) {
3babeb15
DB
3138 return 1;
3139 }
3140
6b837bc4
JS
3141 qemu_progress_init(progress, 2.0);
3142 qemu_progress_print(0, 100);
3143
661a0f71 3144 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
ce099547 3145 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
3146 if (ret < 0) {
3147 error_report("Invalid cache option: %s", cache);
40ed35a3 3148 goto out;
661a0f71
FS
3149 }
3150
ce099547
KW
3151 src_flags = 0;
3152 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
3153 if (ret < 0) {
3154 error_report("Invalid source cache option: %s", src_cache);
40ed35a3 3155 goto out;
40055951
HR
3156 }
3157
ce099547
KW
3158 /* The source files are opened read-only, don't care about WCE */
3159 assert((src_flags & BDRV_O_RDWR) == 0);
3160 (void) src_writethrough;
3161
3e85c6fd
KW
3162 /*
3163 * Open the images.
3164 *
3165 * Ignore the old backing file for unsafe rebase in case we want to correct
3166 * the reference to a renamed or moved backing file.
3167 */
335e9937
FZ
3168 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3169 false);
7e7d56d9 3170 if (!blk) {
40ed35a3
SH
3171 ret = -1;
3172 goto out;
c2abccec 3173 }
7e7d56d9 3174 bs = blk_bs(blk);
3e85c6fd 3175
3e85c6fd 3176 if (out_basefmt != NULL) {
644483d9 3177 if (bdrv_find_format(out_basefmt) == NULL) {
15654a6d 3178 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
3179 ret = -1;
3180 goto out;
3e85c6fd
KW
3181 }
3182 }
3183
3184 /* For safe rebasing we need to compare old and new backing file */
40ed35a3 3185 if (!unsafe) {
9a29e18f 3186 char backing_name[PATH_MAX];
644483d9
HR
3187 QDict *options = NULL;
3188
3189 if (bs->backing_format[0] != '\0') {
3190 options = qdict_new();
46f5ac20 3191 qdict_put_str(options, "driver", bs->backing_format);
644483d9 3192 }
3e85c6fd 3193
335e9937
FZ
3194 if (force_share) {
3195 if (!options) {
3196 options = qdict_new();
3197 }
579cf1d1 3198 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
335e9937 3199 }
3e85c6fd 3200 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
efaa7c4e 3201 blk_old_backing = blk_new_open(backing_name, NULL,
644483d9
HR
3202 options, src_flags, &local_err);
3203 if (!blk_old_backing) {
c29b77f9
MA
3204 error_reportf_err(local_err,
3205 "Could not open old backing file '%s': ",
3206 backing_name);
e84a0dd5 3207 ret = -1;
c2abccec 3208 goto out;
3e85c6fd 3209 }
644483d9 3210
a616673d 3211 if (out_baseimg[0]) {
335e9937 3212 options = qdict_new();
644483d9 3213 if (out_basefmt) {
46f5ac20 3214 qdict_put_str(options, "driver", out_basefmt);
335e9937
FZ
3215 }
3216 if (force_share) {
3217 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
644483d9
HR
3218 }
3219
efaa7c4e 3220 blk_new_backing = blk_new_open(out_baseimg, NULL,
644483d9
HR
3221 options, src_flags, &local_err);
3222 if (!blk_new_backing) {
c29b77f9
MA
3223 error_reportf_err(local_err,
3224 "Could not open new backing file '%s': ",
3225 out_baseimg);
e84a0dd5 3226 ret = -1;
a616673d
AB
3227 goto out;
3228 }
3e85c6fd
KW
3229 }
3230 }
3231
3232 /*
3233 * Check each unallocated cluster in the COW file. If it is unallocated,
3234 * accesses go to the backing file. We must therefore compare this cluster
3235 * in the old and new backing file, and if they differ we need to copy it
3236 * from the old backing file into the COW file.
3237 *
3238 * If qemu-img crashes during this step, no harm is done. The content of
3239 * the image is the same as the original one at any time.
3240 */
3241 if (!unsafe) {
52bf1e72
MA
3242 int64_t num_sectors;
3243 int64_t old_backing_num_sectors;
3244 int64_t new_backing_num_sectors = 0;
3e85c6fd 3245 uint64_t sector;
cc60e327 3246 int n;
d6a644bb 3247 int64_t count;
1f710495 3248 float local_progress = 0;
d6771bfa 3249
f1d3cd79
HR
3250 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3251 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3e85c6fd 3252
f1d3cd79 3253 num_sectors = blk_nb_sectors(blk);
52bf1e72
MA
3254 if (num_sectors < 0) {
3255 error_report("Could not get size of '%s': %s",
3256 filename, strerror(-num_sectors));
3257 ret = -1;
3258 goto out;
3259 }
f1d3cd79 3260 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
52bf1e72 3261 if (old_backing_num_sectors < 0) {
9a29e18f 3262 char backing_name[PATH_MAX];
52bf1e72
MA
3263
3264 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3265 error_report("Could not get size of '%s': %s",
3266 backing_name, strerror(-old_backing_num_sectors));
3267 ret = -1;
3268 goto out;
3269 }
f1d3cd79
HR
3270 if (blk_new_backing) {
3271 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
52bf1e72
MA
3272 if (new_backing_num_sectors < 0) {
3273 error_report("Could not get size of '%s': %s",
3274 out_baseimg, strerror(-new_backing_num_sectors));
3275 ret = -1;
3276 goto out;
3277 }
a616673d 3278 }
3e85c6fd 3279
1f710495
KW
3280 if (num_sectors != 0) {
3281 local_progress = (float)100 /
3282 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3283 }
3284
3e85c6fd
KW
3285 for (sector = 0; sector < num_sectors; sector += n) {
3286
3287 /* How many sectors can we handle with the next read? */
3288 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3289 n = (IO_BUF_SIZE / 512);
3290 } else {
3291 n = num_sectors - sector;
3292 }
3293
3294 /* If the cluster is allocated, we don't need to take action */
d6a644bb
EB
3295 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3296 n << BDRV_SECTOR_BITS, &count);
d663640c
PB
3297 if (ret < 0) {
3298 error_report("error while reading image metadata: %s",
3299 strerror(-ret));
3300 goto out;
3301 }
d6a644bb
EB
3302 /* TODO relax this once bdrv_is_allocated does not enforce
3303 * sector alignment */
3304 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3305 n = count >> BDRV_SECTOR_BITS;
cc60e327 3306 if (ret) {
3e85c6fd
KW
3307 continue;
3308 }
3309
87a1b3e3
KW
3310 /*
3311 * Read old and new backing file and take into consideration that
3312 * backing files may be smaller than the COW image.
3313 */
3314 if (sector >= old_backing_num_sectors) {
3315 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3316 } else {
3317 if (sector + n > old_backing_num_sectors) {
3318 n = old_backing_num_sectors - sector;
3319 }
3320
9166920a
EB
3321 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3322 buf_old, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3323 if (ret < 0) {
3324 error_report("error while reading from old backing file");
3325 goto out;
3326 }
3e85c6fd 3327 }
87a1b3e3 3328
f1d3cd79 3329 if (sector >= new_backing_num_sectors || !blk_new_backing) {
87a1b3e3
KW
3330 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3331 } else {
3332 if (sector + n > new_backing_num_sectors) {
3333 n = new_backing_num_sectors - sector;
3334 }
3335
9166920a
EB
3336 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3337 buf_new, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3338 if (ret < 0) {
3339 error_report("error while reading from new backing file");
3340 goto out;
3341 }
3e85c6fd
KW
3342 }
3343
3344 /* If they differ, we need to write to the COW file */
3345 uint64_t written = 0;
3346
3347 while (written < n) {
3348 int pnum;
3349
3350 if (compare_sectors(buf_old + written * 512,
60b1bd4f 3351 buf_new + written * 512, n - written, &pnum))
3e85c6fd 3352 {
9166920a
EB
3353 ret = blk_pwrite(blk,
3354 (sector + written) << BDRV_SECTOR_BITS,
3355 buf_old + written * 512,
3356 pnum << BDRV_SECTOR_BITS, 0);
3e85c6fd 3357 if (ret < 0) {
15654a6d 3358 error_report("Error while writing to COW image: %s",
3e85c6fd 3359 strerror(-ret));
c2abccec 3360 goto out;
3e85c6fd
KW
3361 }
3362 }
3363
3364 written += pnum;
3365 }
6b837bc4 3366 qemu_progress_print(local_progress, 100);
3e85c6fd
KW
3367 }
3368 }
3369
3370 /*
3371 * Change the backing file. All clusters that are different from the old
3372 * backing file are overwritten in the COW file now, so the visible content
3373 * doesn't change when we switch the backing file.
3374 */
a616673d
AB
3375 if (out_baseimg && *out_baseimg) {
3376 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3377 } else {
3378 ret = bdrv_change_backing_file(bs, NULL, NULL);
3379 }
3380
3e85c6fd 3381 if (ret == -ENOSPC) {
15654a6d
JS
3382 error_report("Could not change the backing file to '%s': No "
3383 "space left in the file header", out_baseimg);
3e85c6fd 3384 } else if (ret < 0) {
15654a6d 3385 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
3386 out_baseimg, strerror(-ret));
3387 }
3388
6b837bc4 3389 qemu_progress_print(100, 0);
3e85c6fd
KW
3390 /*
3391 * TODO At this point it is possible to check if any clusters that are
3392 * allocated in the COW file are the same in the backing file. If so, they
3393 * could be dropped from the COW file. Don't do this before switching the
3394 * backing file, in case of a crash this would lead to corruption.
3395 */
c2abccec 3396out:
6b837bc4 3397 qemu_progress_end();
3e85c6fd
KW
3398 /* Cleanup */
3399 if (!unsafe) {
26f54e9a 3400 blk_unref(blk_old_backing);
26f54e9a 3401 blk_unref(blk_new_backing);
3e85c6fd 3402 }
396374ca
PB
3403 qemu_vfree(buf_old);
3404 qemu_vfree(buf_new);
3e85c6fd 3405
26f54e9a 3406 blk_unref(blk);
c2abccec
MK
3407 if (ret) {
3408 return 1;
3409 }
3e85c6fd
KW
3410 return 0;
3411}
3412
ae6b0ed6
SH
3413static int img_resize(int argc, char **argv)
3414{
6750e795 3415 Error *err = NULL;
ae6b0ed6
SH
3416 int c, ret, relative;
3417 const char *filename, *fmt, *size;
dc5f690b 3418 int64_t n, total_size, current_size;
f382d43a 3419 bool quiet = false;
26f54e9a 3420 BlockBackend *blk = NULL;
dc5f690b 3421 PreallocMode prealloc = PREALLOC_MODE_OFF;
20caf0f7 3422 QemuOpts *param;
3babeb15 3423
20caf0f7
DXW
3424 static QemuOptsList resize_options = {
3425 .name = "resize_options",
3426 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3427 .desc = {
3428 {
3429 .name = BLOCK_OPT_SIZE,
3430 .type = QEMU_OPT_SIZE,
3431 .help = "Virtual disk size"
3432 }, {
3433 /* end of list */
3434 }
ae6b0ed6 3435 },
ae6b0ed6 3436 };
eb769f74 3437 bool image_opts = false;
4ffca890 3438 bool shrink = false;
ae6b0ed6 3439
e80fec7f
KW
3440 /* Remove size from argv manually so that negative numbers are not treated
3441 * as options by getopt. */
3442 if (argc < 3) {
ac1307ab 3443 error_exit("Not enough arguments");
e80fec7f
KW
3444 return 1;
3445 }
3446
3447 size = argv[--argc];
3448
3449 /* Parse getopt arguments */
ae6b0ed6
SH
3450 fmt = NULL;
3451 for(;;) {
3babeb15
DB
3452 static const struct option long_options[] = {
3453 {"help", no_argument, 0, 'h'},
3454 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3455 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
dc5f690b 3456 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
4ffca890 3457 {"shrink", no_argument, 0, OPTION_SHRINK},
3babeb15
DB
3458 {0, 0, 0, 0}
3459 };
c9192973 3460 c = getopt_long(argc, argv, ":f:hq",
3babeb15 3461 long_options, NULL);
ae6b0ed6
SH
3462 if (c == -1) {
3463 break;
3464 }
3465 switch(c) {
c9192973
SH
3466 case ':':
3467 missing_argument(argv[optind - 1]);
3468 break;
ef87394c 3469 case '?':
c9192973
SH
3470 unrecognized_option(argv[optind - 1]);
3471 break;
ae6b0ed6
SH
3472 case 'h':
3473 help();
3474 break;
3475 case 'f':
3476 fmt = optarg;
3477 break;
f382d43a
MR
3478 case 'q':
3479 quiet = true;
3480 break;
3babeb15
DB
3481 case OPTION_OBJECT: {
3482 QemuOpts *opts;
3483 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3484 optarg, true);
3485 if (!opts) {
3486 return 1;
3487 }
3488 } break;
eb769f74
DB
3489 case OPTION_IMAGE_OPTS:
3490 image_opts = true;
3491 break;
dc5f690b 3492 case OPTION_PREALLOCATION:
f7abe0ec 3493 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
06c60b6c 3494 PREALLOC_MODE__MAX, NULL);
dc5f690b
HR
3495 if (prealloc == PREALLOC_MODE__MAX) {
3496 error_report("Invalid preallocation mode '%s'", optarg);
3497 return 1;
3498 }
3499 break;
4ffca890
PB
3500 case OPTION_SHRINK:
3501 shrink = true;
3502 break;
ae6b0ed6
SH
3503 }
3504 }
fc11eb26 3505 if (optind != argc - 1) {
ac1307ab 3506 error_exit("Expecting one image file name");
ae6b0ed6
SH
3507 }
3508 filename = argv[optind++];
ae6b0ed6 3509
3babeb15
DB
3510 if (qemu_opts_foreach(&qemu_object_opts,
3511 user_creatable_add_opts_foreach,
51b9b478 3512 NULL, NULL)) {
3babeb15
DB
3513 return 1;
3514 }
3515
ae6b0ed6
SH
3516 /* Choose grow, shrink, or absolute resize mode */
3517 switch (size[0]) {
3518 case '+':
3519 relative = 1;
3520 size++;
3521 break;
3522 case '-':
3523 relative = -1;
3524 size++;
3525 break;
3526 default:
3527 relative = 0;
3528 break;
3529 }
3530
3531 /* Parse size */
87ea75d5 3532 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
f43e47db 3533 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
6750e795
MA
3534 if (err) {
3535 error_report_err(err);
2a81998a 3536 ret = -1;
20caf0f7 3537 qemu_opts_del(param);
2a81998a 3538 goto out;
ae6b0ed6 3539 }
20caf0f7
DXW
3540 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3541 qemu_opts_del(param);
ae6b0ed6 3542
efaa7c4e 3543 blk = img_open(image_opts, filename, fmt,
335e9937
FZ
3544 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3545 false);
7e7d56d9 3546 if (!blk) {
2a81998a
JS
3547 ret = -1;
3548 goto out;
c2abccec 3549 }
ae6b0ed6 3550
dc5f690b
HR
3551 current_size = blk_getlength(blk);
3552 if (current_size < 0) {
3553 error_report("Failed to inquire current image length: %s",
3554 strerror(-current_size));
3555 ret = -1;
3556 goto out;
3557 }
3558
ae6b0ed6 3559 if (relative) {
dc5f690b 3560 total_size = current_size + n * relative;
ae6b0ed6
SH
3561 } else {
3562 total_size = n;
3563 }
3564 if (total_size <= 0) {
15654a6d 3565 error_report("New image size must be positive");
c2abccec
MK
3566 ret = -1;
3567 goto out;
ae6b0ed6
SH
3568 }
3569
dc5f690b
HR
3570 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3571 error_report("Preallocation can only be used for growing images");
3572 ret = -1;
3573 goto out;
3574 }
3575
4ffca890
PB
3576 if (total_size < current_size && !shrink) {
3577 warn_report("Shrinking an image will delete all data beyond the "
3578 "shrunken image's end. Before performing such an "
3579 "operation, make sure there is no important data there.");
3580
3581 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3582 error_report(
3583 "Use the --shrink option to perform a shrink operation.");
3584 ret = -1;
3585 goto out;
3586 } else {
3587 warn_report("Using the --shrink option will suppress this message. "
3588 "Note that future versions of qemu-img may refuse to "
3589 "shrink images without this option.");
3590 }
3591 }
3592
dc5f690b 3593 ret = blk_truncate(blk, total_size, prealloc, &err);
ed3d2ec9 3594 if (!ret) {
f382d43a 3595 qprintf(quiet, "Image resized.\n");
ed3d2ec9
HR
3596 } else {
3597 error_report_err(err);
ae6b0ed6 3598 }
c2abccec 3599out:
26f54e9a 3600 blk_unref(blk);
c2abccec
MK
3601 if (ret) {
3602 return 1;
3603 }
ae6b0ed6
SH
3604 return 0;
3605}
3606
76a3a34d 3607static void amend_status_cb(BlockDriverState *bs,
8b13976d
HR
3608 int64_t offset, int64_t total_work_size,
3609 void *opaque)
76a3a34d
HR
3610{
3611 qemu_progress_print(100.f * offset / total_work_size, 0);
3612}
3613
6f176b48
HR
3614static int img_amend(int argc, char **argv)
3615{
dc523cd3 3616 Error *err = NULL;
6f176b48
HR
3617 int c, ret = 0;
3618 char *options = NULL;
83d0521a
CL
3619 QemuOptsList *create_opts = NULL;
3620 QemuOpts *opts = NULL;
bd39e6ed
HR
3621 const char *fmt = NULL, *filename, *cache;
3622 int flags;
ce099547 3623 bool writethrough;
76a3a34d 3624 bool quiet = false, progress = false;
26f54e9a 3625 BlockBackend *blk = NULL;
6f176b48 3626 BlockDriverState *bs = NULL;
eb769f74 3627 bool image_opts = false;
6f176b48 3628
bd39e6ed 3629 cache = BDRV_DEFAULT_CACHE;
6f176b48 3630 for (;;) {
3babeb15
DB
3631 static const struct option long_options[] = {
3632 {"help", no_argument, 0, 'h'},
3633 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3634 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3635 {0, 0, 0, 0}
3636 };
c9192973 3637 c = getopt_long(argc, argv, ":ho:f:t:pq",
3babeb15 3638 long_options, NULL);
6f176b48
HR
3639 if (c == -1) {
3640 break;
3641 }
3642
3643 switch (c) {
c9192973
SH
3644 case ':':
3645 missing_argument(argv[optind - 1]);
3646 break;
f7077624 3647 case '?':
c9192973
SH
3648 unrecognized_option(argv[optind - 1]);
3649 break;
3650 case 'h':
f7077624
SH
3651 help();
3652 break;
3653 case 'o':
3654 if (!is_valid_option_list(optarg)) {
3655 error_report("Invalid option list: %s", optarg);
3656 ret = -1;
3657 goto out_no_progress;
3658 }
3659 if (!options) {
3660 options = g_strdup(optarg);
3661 } else {
3662 char *old_options = options;
3663 options = g_strdup_printf("%s,%s", options, optarg);
3664 g_free(old_options);
3665 }
3666 break;
3667 case 'f':
3668 fmt = optarg;
3669 break;
3670 case 't':
3671 cache = optarg;
3672 break;
3673 case 'p':
3674 progress = true;
3675 break;
3676 case 'q':
3677 quiet = true;
3678 break;
3679 case OPTION_OBJECT:
3680 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3681 optarg, true);
3682 if (!opts) {
3683 ret = -1;
3684 goto out_no_progress;
3685 }
3686 break;
3687 case OPTION_IMAGE_OPTS:
3688 image_opts = true;
3689 break;
6f176b48
HR
3690 }
3691 }
3692
a283cb6e 3693 if (!options) {
ac1307ab 3694 error_exit("Must specify options (-o)");
6f176b48
HR
3695 }
3696
3babeb15
DB
3697 if (qemu_opts_foreach(&qemu_object_opts,
3698 user_creatable_add_opts_foreach,
51b9b478 3699 NULL, NULL)) {
3babeb15
DB
3700 ret = -1;
3701 goto out_no_progress;
3702 }
3703
76a3a34d
HR
3704 if (quiet) {
3705 progress = false;
3706 }
3707 qemu_progress_init(progress, 1.0);
3708
a283cb6e
KW
3709 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3710 if (fmt && has_help_option(options)) {
3711 /* If a format is explicitly specified (and possibly no filename is
3712 * given), print option help here */
3713 ret = print_block_option_help(filename, fmt);
3714 goto out;
6f176b48
HR
3715 }
3716
a283cb6e 3717 if (optind != argc - 1) {
b2f27e44
HR
3718 error_report("Expecting one image file name");
3719 ret = -1;
3720 goto out;
a283cb6e 3721 }
6f176b48 3722
ce099547
KW
3723 flags = BDRV_O_RDWR;
3724 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
bd39e6ed
HR
3725 if (ret < 0) {
3726 error_report("Invalid cache option: %s", cache);
3727 goto out;
3728 }
3729
335e9937
FZ
3730 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3731 false);
7e7d56d9 3732 if (!blk) {
6f176b48
HR
3733 ret = -1;
3734 goto out;
3735 }
7e7d56d9 3736 bs = blk_bs(blk);
6f176b48
HR
3737
3738 fmt = bs->drv->format_name;
3739
626f84f3 3740 if (has_help_option(options)) {
a283cb6e 3741 /* If the format was auto-detected, print option help here */
6f176b48
HR
3742 ret = print_block_option_help(filename, fmt);
3743 goto out;
3744 }
3745
b2439d26
HR
3746 if (!bs->drv->create_opts) {
3747 error_report("Format driver '%s' does not support any options to amend",
3748 fmt);
3749 ret = -1;
3750 goto out;
3751 }
3752
c282e1fd 3753 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a 3754 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
ece9086e
PB
3755 qemu_opts_do_parse(opts, options, NULL, &err);
3756 if (err) {
3757 error_report_err(err);
3758 ret = -1;
3759 goto out;
6f176b48
HR
3760 }
3761
76a3a34d
HR
3762 /* In case the driver does not call amend_status_cb() */
3763 qemu_progress_print(0.f, 0);
8b13976d 3764 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
76a3a34d 3765 qemu_progress_print(100.f, 0);
6f176b48
HR
3766 if (ret < 0) {
3767 error_report("Error while amending options: %s", strerror(-ret));
3768 goto out;
3769 }
3770
3771out:
76a3a34d
HR
3772 qemu_progress_end();
3773
e814dffc 3774out_no_progress:
26f54e9a 3775 blk_unref(blk);
83d0521a
CL
3776 qemu_opts_del(opts);
3777 qemu_opts_free(create_opts);
626f84f3
KW
3778 g_free(options);
3779
6f176b48
HR
3780 if (ret) {
3781 return 1;
3782 }
3783 return 0;
3784}
3785
b6133b8c
KW
3786typedef struct BenchData {
3787 BlockBackend *blk;
3788 uint64_t image_size;
b6495fa8 3789 bool write;
b6133b8c 3790 int bufsize;
83de9be0 3791 int step;
b6133b8c
KW
3792 int nrreq;
3793 int n;
55d539c8
KW
3794 int flush_interval;
3795 bool drain_on_flush;
b6133b8c
KW
3796 uint8_t *buf;
3797 QEMUIOVector *qiov;
3798
3799 int in_flight;
55d539c8 3800 bool in_flush;
b6133b8c
KW
3801 uint64_t offset;
3802} BenchData;
3803
55d539c8
KW
3804static void bench_undrained_flush_cb(void *opaque, int ret)
3805{
3806 if (ret < 0) {
df3c286c 3807 error_report("Failed flush request: %s", strerror(-ret));
55d539c8
KW
3808 exit(EXIT_FAILURE);
3809 }
3810}
3811
b6133b8c
KW
3812static void bench_cb(void *opaque, int ret)
3813{
3814 BenchData *b = opaque;
3815 BlockAIOCB *acb;
3816
3817 if (ret < 0) {
df3c286c 3818 error_report("Failed request: %s", strerror(-ret));
b6133b8c
KW
3819 exit(EXIT_FAILURE);
3820 }
55d539c8
KW
3821
3822 if (b->in_flush) {
3823 /* Just finished a flush with drained queue: Start next requests */
3824 assert(b->in_flight == 0);
3825 b->in_flush = false;
3826 } else if (b->in_flight > 0) {
3827 int remaining = b->n - b->in_flight;
3828
b6133b8c
KW
3829 b->n--;
3830 b->in_flight--;
55d539c8
KW
3831
3832 /* Time for flush? Drain queue if requested, then flush */
3833 if (b->flush_interval && remaining % b->flush_interval == 0) {
3834 if (!b->in_flight || !b->drain_on_flush) {
3835 BlockCompletionFunc *cb;
3836
3837 if (b->drain_on_flush) {
3838 b->in_flush = true;
3839 cb = bench_cb;
3840 } else {
3841 cb = bench_undrained_flush_cb;
3842 }
3843
3844 acb = blk_aio_flush(b->blk, cb, b);
3845 if (!acb) {
3846 error_report("Failed to issue flush request");
3847 exit(EXIT_FAILURE);
3848 }
3849 }
3850 if (b->drain_on_flush) {
3851 return;
3852 }
3853 }
b6133b8c
KW
3854 }
3855
3856 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4baaa8c3
PB
3857 int64_t offset = b->offset;
3858 /* blk_aio_* might look for completed I/Os and kick bench_cb
3859 * again, so make sure this operation is counted by in_flight
3860 * and b->offset is ready for the next submission.
3861 */
3862 b->in_flight++;
3863 b->offset += b->step;
3864 b->offset %= b->image_size;
b6495fa8 3865 if (b->write) {
4baaa8c3 3866 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
b6495fa8 3867 } else {
4baaa8c3 3868 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
b6495fa8 3869 }
b6133b8c
KW
3870 if (!acb) {
3871 error_report("Failed to issue request");
3872 exit(EXIT_FAILURE);
3873 }
b6133b8c
KW
3874 }
3875}
3876
3877static int img_bench(int argc, char **argv)
3878{
3879 int c, ret = 0;
3880 const char *fmt = NULL, *filename;
3881 bool quiet = false;
3882 bool image_opts = false;
b6495fa8 3883 bool is_write = false;
b6133b8c
KW
3884 int count = 75000;
3885 int depth = 64;
d3199a31 3886 int64_t offset = 0;
b6133b8c 3887 size_t bufsize = 4096;
b6495fa8 3888 int pattern = 0;
83de9be0 3889 size_t step = 0;
55d539c8
KW
3890 int flush_interval = 0;
3891 bool drain_on_flush = true;
b6133b8c
KW
3892 int64_t image_size;
3893 BlockBackend *blk = NULL;
3894 BenchData data = {};
3895 int flags = 0;
604e8613 3896 bool writethrough = false;
b6133b8c
KW
3897 struct timeval t1, t2;
3898 int i;
335e9937 3899 bool force_share = false;
b6133b8c
KW
3900
3901 for (;;) {
3902 static const struct option long_options[] = {
3903 {"help", no_argument, 0, 'h'},
55d539c8 3904 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
b6133b8c 3905 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
b6495fa8 3906 {"pattern", required_argument, 0, OPTION_PATTERN},
55d539c8 3907 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
335e9937 3908 {"force-share", no_argument, 0, 'U'},
b6133b8c
KW
3909 {0, 0, 0, 0}
3910 };
335e9937 3911 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
b6133b8c
KW
3912 if (c == -1) {
3913 break;
3914 }
3915
3916 switch (c) {
c9192973
SH
3917 case ':':
3918 missing_argument(argv[optind - 1]);
3919 break;
b6133b8c 3920 case '?':
c9192973
SH
3921 unrecognized_option(argv[optind - 1]);
3922 break;
3923 case 'h':
b6133b8c
KW
3924 help();
3925 break;
3926 case 'c':
3927 {
8b3c6792
PM
3928 unsigned long res;
3929
3930 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
b6133b8c
KW
3931 error_report("Invalid request count specified");
3932 return 1;
3933 }
8b3c6792 3934 count = res;
b6133b8c
KW
3935 break;
3936 }
3937 case 'd':
3938 {
8b3c6792
PM
3939 unsigned long res;
3940
3941 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
b6133b8c
KW
3942 error_report("Invalid queue depth specified");
3943 return 1;
3944 }
8b3c6792 3945 depth = res;
b6133b8c
KW
3946 break;
3947 }
3948 case 'f':
3949 fmt = optarg;
3950 break;
3951 case 'n':
3952 flags |= BDRV_O_NATIVE_AIO;
3953 break;
d3199a31
KW
3954 case 'o':
3955 {
606caa0a
MA
3956 offset = cvtnum(optarg);
3957 if (offset < 0) {
d3199a31
KW
3958 error_report("Invalid offset specified");
3959 return 1;
3960 }
3961 break;
3962 }
3963 break;
b6133b8c
KW
3964 case 'q':
3965 quiet = true;
3966 break;
3967 case 's':
3968 {
3969 int64_t sval;
b6133b8c 3970
606caa0a
MA
3971 sval = cvtnum(optarg);
3972 if (sval < 0 || sval > INT_MAX) {
b6133b8c
KW
3973 error_report("Invalid buffer size specified");
3974 return 1;
3975 }
3976
3977 bufsize = sval;
3978 break;
3979 }
83de9be0
KW
3980 case 'S':
3981 {
3982 int64_t sval;
83de9be0 3983
606caa0a
MA
3984 sval = cvtnum(optarg);
3985 if (sval < 0 || sval > INT_MAX) {
83de9be0
KW
3986 error_report("Invalid step size specified");
3987 return 1;
3988 }
3989
3990 step = sval;
3991 break;
3992 }
b6133b8c
KW
3993 case 't':
3994 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3995 if (ret < 0) {
3996 error_report("Invalid cache mode");
3997 ret = -1;
3998 goto out;
3999 }
4000 break;
b6495fa8
KW
4001 case 'w':
4002 flags |= BDRV_O_RDWR;
4003 is_write = true;
4004 break;
335e9937
FZ
4005 case 'U':
4006 force_share = true;
4007 break;
b6495fa8
KW
4008 case OPTION_PATTERN:
4009 {
8b3c6792
PM
4010 unsigned long res;
4011
4012 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
b6495fa8
KW
4013 error_report("Invalid pattern byte specified");
4014 return 1;
4015 }
8b3c6792 4016 pattern = res;
b6495fa8
KW
4017 break;
4018 }
55d539c8
KW
4019 case OPTION_FLUSH_INTERVAL:
4020 {
8b3c6792
PM
4021 unsigned long res;
4022
4023 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
55d539c8
KW
4024 error_report("Invalid flush interval specified");
4025 return 1;
4026 }
8b3c6792 4027 flush_interval = res;
55d539c8
KW
4028 break;
4029 }
4030 case OPTION_NO_DRAIN:
4031 drain_on_flush = false;
4032 break;
b6133b8c
KW
4033 case OPTION_IMAGE_OPTS:
4034 image_opts = true;
4035 break;
4036 }
4037 }
4038
4039 if (optind != argc - 1) {
4040 error_exit("Expecting one image file name");
4041 }
4042 filename = argv[argc - 1];
4043
55d539c8
KW
4044 if (!is_write && flush_interval) {
4045 error_report("--flush-interval is only available in write tests");
4046 ret = -1;
4047 goto out;
4048 }
4049 if (flush_interval && flush_interval < depth) {
4050 error_report("Flush interval can't be smaller than depth");
4051 ret = -1;
4052 goto out;
4053 }
4054
335e9937
FZ
4055 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4056 force_share);
b6133b8c
KW
4057 if (!blk) {
4058 ret = -1;
4059 goto out;
4060 }
4061
4062 image_size = blk_getlength(blk);
4063 if (image_size < 0) {
4064 ret = image_size;
4065 goto out;
4066 }
4067
4068 data = (BenchData) {
55d539c8
KW
4069 .blk = blk,
4070 .image_size = image_size,
4071 .bufsize = bufsize,
4072 .step = step ?: bufsize,
4073 .nrreq = depth,
4074 .n = count,
4075 .offset = offset,
4076 .write = is_write,
4077 .flush_interval = flush_interval,
4078 .drain_on_flush = drain_on_flush,
b6133b8c 4079 };
d3199a31 4080 printf("Sending %d %s requests, %d bytes each, %d in parallel "
83de9be0 4081 "(starting at offset %" PRId64 ", step size %d)\n",
d3199a31 4082 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
83de9be0 4083 data.offset, data.step);
55d539c8
KW
4084 if (flush_interval) {
4085 printf("Sending flush every %d requests\n", flush_interval);
4086 }
b6133b8c
KW
4087
4088 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
b6495fa8
KW
4089 memset(data.buf, pattern, data.nrreq * data.bufsize);
4090
b6133b8c
KW
4091 data.qiov = g_new(QEMUIOVector, data.nrreq);
4092 for (i = 0; i < data.nrreq; i++) {
4093 qemu_iovec_init(&data.qiov[i], 1);
4094 qemu_iovec_add(&data.qiov[i],
4095 data.buf + i * data.bufsize, data.bufsize);
4096 }
4097
4098 gettimeofday(&t1, NULL);
4099 bench_cb(&data, 0);
4100
4101 while (data.n > 0) {
4102 main_loop_wait(false);
4103 }
4104 gettimeofday(&t2, NULL);
4105
4106 printf("Run completed in %3.3f seconds.\n",
4107 (t2.tv_sec - t1.tv_sec)
4108 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4109
4110out:
4111 qemu_vfree(data.buf);
4112 blk_unref(blk);
4113
4114 if (ret) {
86ce1f6e
RS
4115 return 1;
4116 }
4117 return 0;
4118}
4119
4120#define C_BS 01
4121#define C_COUNT 02
4122#define C_IF 04
4123#define C_OF 010
f7c15533 4124#define C_SKIP 020
86ce1f6e
RS
4125
4126struct DdInfo {
4127 unsigned int flags;
4128 int64_t count;
4129};
4130
4131struct DdIo {
4132 int bsz; /* Block size */
4133 char *filename;
4134 uint8_t *buf;
f7c15533 4135 int64_t offset;
86ce1f6e
RS
4136};
4137
4138struct DdOpts {
4139 const char *name;
4140 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4141 unsigned int flag;
4142};
4143
4144static int img_dd_bs(const char *arg,
4145 struct DdIo *in, struct DdIo *out,
4146 struct DdInfo *dd)
4147{
86ce1f6e
RS
4148 int64_t res;
4149
606caa0a 4150 res = cvtnum(arg);
86ce1f6e 4151
606caa0a 4152 if (res <= 0 || res > INT_MAX) {
86ce1f6e
RS
4153 error_report("invalid number: '%s'", arg);
4154 return 1;
4155 }
4156 in->bsz = out->bsz = res;
4157
4158 return 0;
4159}
4160
4161static int img_dd_count(const char *arg,
4162 struct DdIo *in, struct DdIo *out,
4163 struct DdInfo *dd)
4164{
606caa0a 4165 dd->count = cvtnum(arg);
86ce1f6e 4166
606caa0a 4167 if (dd->count < 0) {
86ce1f6e
RS
4168 error_report("invalid number: '%s'", arg);
4169 return 1;
4170 }
4171
4172 return 0;
4173}
4174
4175static int img_dd_if(const char *arg,
4176 struct DdIo *in, struct DdIo *out,
4177 struct DdInfo *dd)
4178{
4179 in->filename = g_strdup(arg);
4180
4181 return 0;
4182}
4183
4184static int img_dd_of(const char *arg,
4185 struct DdIo *in, struct DdIo *out,
4186 struct DdInfo *dd)
4187{
4188 out->filename = g_strdup(arg);
4189
4190 return 0;
4191}
4192
f7c15533
RS
4193static int img_dd_skip(const char *arg,
4194 struct DdIo *in, struct DdIo *out,
4195 struct DdInfo *dd)
4196{
606caa0a 4197 in->offset = cvtnum(arg);
f7c15533 4198
606caa0a 4199 if (in->offset < 0) {
f7c15533
RS
4200 error_report("invalid number: '%s'", arg);
4201 return 1;
4202 }
4203
4204 return 0;
4205}
4206
86ce1f6e
RS
4207static int img_dd(int argc, char **argv)
4208{
4209 int ret = 0;
4210 char *arg = NULL;
4211 char *tmp;
4212 BlockDriver *drv = NULL, *proto_drv = NULL;
4213 BlockBackend *blk1 = NULL, *blk2 = NULL;
4214 QemuOpts *opts = NULL;
4215 QemuOptsList *create_opts = NULL;
4216 Error *local_err = NULL;
4217 bool image_opts = false;
4218 int c, i;
4219 const char *out_fmt = "raw";
4220 const char *fmt = NULL;
4221 int64_t size = 0;
4222 int64_t block_count = 0, out_pos, in_pos;
335e9937 4223 bool force_share = false;
86ce1f6e
RS
4224 struct DdInfo dd = {
4225 .flags = 0,
4226 .count = 0,
4227 };
4228 struct DdIo in = {
4229 .bsz = 512, /* Block size is by default 512 bytes */
4230 .filename = NULL,
f7c15533
RS
4231 .buf = NULL,
4232 .offset = 0
86ce1f6e
RS
4233 };
4234 struct DdIo out = {
4235 .bsz = 512,
4236 .filename = NULL,
f7c15533
RS
4237 .buf = NULL,
4238 .offset = 0
86ce1f6e
RS
4239 };
4240
4241 const struct DdOpts options[] = {
4242 { "bs", img_dd_bs, C_BS },
4243 { "count", img_dd_count, C_COUNT },
4244 { "if", img_dd_if, C_IF },
4245 { "of", img_dd_of, C_OF },
f7c15533 4246 { "skip", img_dd_skip, C_SKIP },
86ce1f6e
RS
4247 { NULL, NULL, 0 }
4248 };
4249 const struct option long_options[] = {
4250 { "help", no_argument, 0, 'h'},
83d4bf94 4251 { "object", required_argument, 0, OPTION_OBJECT},
86ce1f6e 4252 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 4253 { "force-share", no_argument, 0, 'U'},
86ce1f6e
RS
4254 { 0, 0, 0, 0 }
4255 };
4256
335e9937 4257 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
86ce1f6e
RS
4258 if (c == EOF) {
4259 break;
4260 }
4261 switch (c) {
4262 case 'O':
4263 out_fmt = optarg;
4264 break;
4265 case 'f':
4266 fmt = optarg;
4267 break;
c9192973
SH
4268 case ':':
4269 missing_argument(argv[optind - 1]);
4270 break;
86ce1f6e 4271 case '?':
c9192973
SH
4272 unrecognized_option(argv[optind - 1]);
4273 break;
86ce1f6e
RS
4274 case 'h':
4275 help();
4276 break;
335e9937
FZ
4277 case 'U':
4278 force_share = true;
4279 break;
2a245709
SH
4280 case OPTION_OBJECT:
4281 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
83d4bf94
DB
4282 ret = -1;
4283 goto out;
4284 }
2a245709 4285 break;
86ce1f6e
RS
4286 case OPTION_IMAGE_OPTS:
4287 image_opts = true;
4288 break;
4289 }
4290 }
4291
4292 for (i = optind; i < argc; i++) {
4293 int j;
4294 arg = g_strdup(argv[i]);
4295
4296 tmp = strchr(arg, '=');
4297 if (tmp == NULL) {
4298 error_report("unrecognized operand %s", arg);
4299 ret = -1;
4300 goto out;
4301 }
4302
4303 *tmp++ = '\0';
4304
4305 for (j = 0; options[j].name != NULL; j++) {
4306 if (!strcmp(arg, options[j].name)) {
4307 break;
4308 }
4309 }
4310 if (options[j].name == NULL) {
4311 error_report("unrecognized operand %s", arg);
4312 ret = -1;
4313 goto out;
4314 }
4315
4316 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4317 ret = -1;
4318 goto out;
4319 }
4320 dd.flags |= options[j].flag;
4321 g_free(arg);
4322 arg = NULL;
4323 }
4324
4325 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4326 error_report("Must specify both input and output files");
4327 ret = -1;
4328 goto out;
4329 }
83d4bf94
DB
4330
4331 if (qemu_opts_foreach(&qemu_object_opts,
4332 user_creatable_add_opts_foreach,
4333 NULL, NULL)) {
4334 ret = -1;
4335 goto out;
4336 }
4337
335e9937
FZ
4338 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4339 force_share);
86ce1f6e
RS
4340
4341 if (!blk1) {
4342 ret = -1;
4343 goto out;
4344 }
4345
4346 drv = bdrv_find_format(out_fmt);
4347 if (!drv) {
4348 error_report("Unknown file format");
4349 ret = -1;
4350 goto out;
4351 }
4352 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4353
4354 if (!proto_drv) {
4355 error_report_err(local_err);
4356 ret = -1;
4357 goto out;
4358 }
4359 if (!drv->create_opts) {
4360 error_report("Format driver '%s' does not support image creation",
4361 drv->format_name);
4362 ret = -1;
4363 goto out;
4364 }
4365 if (!proto_drv->create_opts) {
4366 error_report("Protocol driver '%s' does not support image creation",
4367 proto_drv->format_name);
4368 ret = -1;
4369 goto out;
4370 }
4371 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4372 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4373
4374 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4375
4376 size = blk_getlength(blk1);
4377 if (size < 0) {
4378 error_report("Failed to get size for '%s'", in.filename);
4379 ret = -1;
4380 goto out;
4381 }
4382
4383 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4384 dd.count * in.bsz < size) {
4385 size = dd.count * in.bsz;
4386 }
4387
f7c15533
RS
4388 /* Overflow means the specified offset is beyond input image's size */
4389 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4390 size < in.bsz * in.offset)) {
4391 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4392 } else {
4393 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4394 size - in.bsz * in.offset, &error_abort);
4395 }
86ce1f6e
RS
4396
4397 ret = bdrv_create(drv, out.filename, opts, &local_err);
4398 if (ret < 0) {
4399 error_reportf_err(local_err,
4400 "%s: error while creating output image: ",
4401 out.filename);
4402 ret = -1;
4403 goto out;
4404 }
4405
ea204dda
DB
4406 /* TODO, we can't honour --image-opts for the target,
4407 * since it needs to be given in a format compatible
4408 * with the bdrv_create() call above which does not
4409 * support image-opts style.
4410 */
29cf9336 4411 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
ea204dda 4412 false, false, false);
86ce1f6e
RS
4413
4414 if (!blk2) {
4415 ret = -1;
4416 goto out;
4417 }
4418
f7c15533
RS
4419 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4420 size < in.offset * in.bsz)) {
4421 /* We give a warning if the skip option is bigger than the input
4422 * size and create an empty output disk image (i.e. like dd(1)).
4423 */
4424 error_report("%s: cannot skip to specified offset", in.filename);
4425 in_pos = size;
4426 } else {
4427 in_pos = in.offset * in.bsz;
4428 }
4429
86ce1f6e
RS
4430 in.buf = g_new(uint8_t, in.bsz);
4431
f7c15533 4432 for (out_pos = 0; in_pos < size; block_count++) {
86ce1f6e
RS
4433 int in_ret, out_ret;
4434
4435 if (in_pos + in.bsz > size) {
4436 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4437 } else {
4438 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4439 }
4440 if (in_ret < 0) {
4441 error_report("error while reading from input image file: %s",
4442 strerror(-in_ret));
4443 ret = -1;
4444 goto out;
4445 }
4446 in_pos += in_ret;
4447
4448 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4449
4450 if (out_ret < 0) {
4451 error_report("error while writing to output image file: %s",
4452 strerror(-out_ret));
4453 ret = -1;
4454 goto out;
4455 }
4456 out_pos += out_ret;
4457 }
4458
4459out:
4460 g_free(arg);
4461 qemu_opts_del(opts);
4462 qemu_opts_free(create_opts);
4463 blk_unref(blk1);
4464 blk_unref(blk2);
4465 g_free(in.filename);
4466 g_free(out.filename);
4467 g_free(in.buf);
4468 g_free(out.buf);
4469
4470 if (ret) {
b6133b8c
KW
4471 return 1;
4472 }
4473 return 0;
4474}
4475
fd03c2b8
SH
4476static void dump_json_block_measure_info(BlockMeasureInfo *info)
4477{
4478 QString *str;
4479 QObject *obj;
4480 Visitor *v = qobject_output_visitor_new(&obj);
4481
4482 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4483 visit_complete(v, &obj);
4484 str = qobject_to_json_pretty(obj);
4485 assert(str != NULL);
4486 printf("%s\n", qstring_get_str(str));
4487 qobject_decref(obj);
4488 visit_free(v);
4489 QDECREF(str);
4490}
4491
4492static int img_measure(int argc, char **argv)
4493{
4494 static const struct option long_options[] = {
4495 {"help", no_argument, 0, 'h'},
4496 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4497 {"object", required_argument, 0, OPTION_OBJECT},
4498 {"output", required_argument, 0, OPTION_OUTPUT},
4499 {"size", required_argument, 0, OPTION_SIZE},
4500 {"force-share", no_argument, 0, 'U'},
4501 {0, 0, 0, 0}
4502 };
4503 OutputFormat output_format = OFORMAT_HUMAN;
4504 BlockBackend *in_blk = NULL;
4505 BlockDriver *drv;
4506 const char *filename = NULL;
4507 const char *fmt = NULL;
4508 const char *out_fmt = "raw";
4509 char *options = NULL;
4510 char *snapshot_name = NULL;
4511 bool force_share = false;
4512 QemuOpts *opts = NULL;
4513 QemuOpts *object_opts = NULL;
4514 QemuOpts *sn_opts = NULL;
4515 QemuOptsList *create_opts = NULL;
4516 bool image_opts = false;
4517 uint64_t img_size = UINT64_MAX;
4518 BlockMeasureInfo *info = NULL;
4519 Error *local_err = NULL;
4520 int ret = 1;
4521 int c;
4522
4523 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4524 long_options, NULL)) != -1) {
4525 switch (c) {
4526 case '?':
4527 case 'h':
4528 help();
4529 break;
4530 case 'f':
4531 fmt = optarg;
4532 break;
4533 case 'O':
4534 out_fmt = optarg;
4535 break;
4536 case 'o':
4537 if (!is_valid_option_list(optarg)) {
4538 error_report("Invalid option list: %s", optarg);
4539 goto out;
4540 }
4541 if (!options) {
4542 options = g_strdup(optarg);
4543 } else {
4544 char *old_options = options;
4545 options = g_strdup_printf("%s,%s", options, optarg);
4546 g_free(old_options);
4547 }
4548 break;
4549 case 'l':
4550 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4551 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4552 optarg, false);
4553 if (!sn_opts) {
4554 error_report("Failed in parsing snapshot param '%s'",
4555 optarg);
4556 goto out;
4557 }
4558 } else {
4559 snapshot_name = optarg;
4560 }
4561 break;
4562 case 'U':
4563 force_share = true;
4564 break;
4565 case OPTION_OBJECT:
4566 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4567 optarg, true);
4568 if (!object_opts) {
4569 goto out;
4570 }
4571 break;
4572 case OPTION_IMAGE_OPTS:
4573 image_opts = true;
4574 break;
4575 case OPTION_OUTPUT:
4576 if (!strcmp(optarg, "json")) {
4577 output_format = OFORMAT_JSON;
4578 } else if (!strcmp(optarg, "human")) {
4579 output_format = OFORMAT_HUMAN;
4580 } else {
4581 error_report("--output must be used with human or json "
4582 "as argument.");
4583 goto out;
4584 }
4585 break;
4586 case OPTION_SIZE:
4587 {
4588 int64_t sval;
4589
4590 sval = cvtnum(optarg);
4591 if (sval < 0) {
4592 if (sval == -ERANGE) {
4593 error_report("Image size must be less than 8 EiB!");
4594 } else {
4595 error_report("Invalid image size specified! You may use "
4596 "k, M, G, T, P or E suffixes for ");
4597 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4598 "petabytes and exabytes.");
4599 }
4600 goto out;
4601 }
4602 img_size = (uint64_t)sval;
4603 }
4604 break;
4605 }
4606 }
4607
4608 if (qemu_opts_foreach(&qemu_object_opts,
4609 user_creatable_add_opts_foreach,
4610 NULL, NULL)) {
4611 goto out;
4612 }
4613
4614 if (argc - optind > 1) {
4615 error_report("At most one filename argument is allowed.");
4616 goto out;
4617 } else if (argc - optind == 1) {
4618 filename = argv[optind];
4619 }
4620
4621 if (!filename &&
4622 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4623 error_report("--object, --image-opts, -f, and -l "
4624 "require a filename argument.");
4625 goto out;
4626 }
4627 if (filename && img_size != UINT64_MAX) {
4628 error_report("--size N cannot be used together with a filename.");
4629 goto out;
4630 }
4631 if (!filename && img_size == UINT64_MAX) {
4632 error_report("Either --size N or one filename must be specified.");
4633 goto out;
4634 }
4635
4636 if (filename) {
4637 in_blk = img_open(image_opts, filename, fmt, 0,
4638 false, false, force_share);
4639 if (!in_blk) {
4640 goto out;
4641 }
4642
4643 if (sn_opts) {
4644 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4645 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4646 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4647 &local_err);
4648 } else if (snapshot_name != NULL) {
4649 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4650 snapshot_name, &local_err);
4651 }
4652 if (local_err) {
4653 error_reportf_err(local_err, "Failed to load snapshot: ");
4654 goto out;
4655 }
4656 }
4657
4658 drv = bdrv_find_format(out_fmt);
4659 if (!drv) {
4660 error_report("Unknown file format '%s'", out_fmt);
4661 goto out;
4662 }
4663 if (!drv->create_opts) {
4664 error_report("Format driver '%s' does not support image creation",
4665 drv->format_name);
4666 goto out;
4667 }
4668
4669 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4670 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4671 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4672 if (options) {
4673 qemu_opts_do_parse(opts, options, NULL, &local_err);
4674 if (local_err) {
4675 error_report_err(local_err);
4676 error_report("Invalid options for file format '%s'", out_fmt);
4677 goto out;
4678 }
4679 }
4680 if (img_size != UINT64_MAX) {
4681 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4682 }
4683
4684 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4685 if (local_err) {
4686 error_report_err(local_err);
4687 goto out;
4688 }
4689
4690 if (output_format == OFORMAT_HUMAN) {
4691 printf("required size: %" PRIu64 "\n", info->required);
4692 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4693 } else {
4694 dump_json_block_measure_info(info);
4695 }
4696
4697 ret = 0;
4698
4699out:
4700 qapi_free_BlockMeasureInfo(info);
4701 qemu_opts_del(object_opts);
4702 qemu_opts_del(opts);
4703 qemu_opts_del(sn_opts);
4704 qemu_opts_free(create_opts);
4705 g_free(options);
4706 blk_unref(in_blk);
4707 return ret;
4708}
b6133b8c 4709
c227f099 4710static const img_cmd_t img_cmds[] = {
153859be
SB
4711#define DEF(option, callback, arg_string) \
4712 { option, callback },
4713#include "qemu-img-cmds.h"
4714#undef DEF
4715#undef GEN_DOCS
4716 { NULL, NULL, },
4717};
4718
ea2384d3
FB
4719int main(int argc, char **argv)
4720{
c227f099 4721 const img_cmd_t *cmd;
153859be 4722 const char *cmdname;
2f78e491 4723 Error *local_error = NULL;
06a1e0c1 4724 char *trace_file = NULL;
7db1689c 4725 int c;
7db1689c
JC
4726 static const struct option long_options[] = {
4727 {"help", no_argument, 0, 'h'},
10985131 4728 {"version", no_argument, 0, 'V'},
06a1e0c1 4729 {"trace", required_argument, NULL, 'T'},
7db1689c
JC
4730 {0, 0, 0, 0}
4731 };
ea2384d3 4732
526eda14
MK
4733#ifdef CONFIG_POSIX
4734 signal(SIGPIPE, SIG_IGN);
4735#endif
4736
fe4db84d 4737 module_call_init(MODULE_INIT_TRACE);
53f76e58 4738 error_set_progname(argv[0]);
10f5bff6 4739 qemu_init_exec_dir(argv[0]);
53f76e58 4740
2f78e491 4741 if (qemu_init_main_loop(&local_error)) {
565f65d2 4742 error_report_err(local_error);
2f78e491
CN
4743 exit(EXIT_FAILURE);
4744 }
4745
e8f2d272 4746 qcrypto_init(&error_fatal);
c2297088 4747
064097d9 4748 module_call_init(MODULE_INIT_QOM);
ea2384d3 4749 bdrv_init();
ac1307ab
FZ
4750 if (argc < 2) {
4751 error_exit("Not enough arguments");
4752 }
153859be 4753
3babeb15 4754 qemu_add_opts(&qemu_object_opts);
eb769f74 4755 qemu_add_opts(&qemu_source_opts);
06a1e0c1 4756 qemu_add_opts(&qemu_trace_opts);
3babeb15 4757
c9192973 4758 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
10985131 4759 switch (c) {
c9192973
SH
4760 case ':':
4761 missing_argument(argv[optind - 1]);
4762 return 0;
4581c16f 4763 case '?':
c9192973
SH
4764 unrecognized_option(argv[optind - 1]);
4765 return 0;
4766 case 'h':
10985131
DL
4767 help();
4768 return 0;
4769 case 'V':
4770 printf(QEMU_IMG_VERSION);
4771 return 0;
06a1e0c1
DL
4772 case 'T':
4773 g_free(trace_file);
4774 trace_file = trace_opt_parse(optarg);
4775 break;
153859be 4776 }
ea2384d3 4777 }
153859be 4778
10985131 4779 cmdname = argv[optind];
7db1689c 4780
10985131
DL
4781 /* reset getopt_long scanning */
4782 argc -= optind;
4783 if (argc < 1) {
5f6979cb
JC
4784 return 0;
4785 }
10985131 4786 argv += optind;
cfef6a45 4787 optind = 0;
10985131 4788
06a1e0c1
DL
4789 if (!trace_init_backends()) {
4790 exit(1);
4791 }
4792 trace_init_file(trace_file);
4793 qemu_set_log(LOG_TRACE);
4794
10985131
DL
4795 /* find the command */
4796 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4797 if (!strcmp(cmdname, cmd->name)) {
4798 return cmd->handler(argc, argv);
4799 }
4800 }
7db1689c 4801
153859be 4802 /* not found */
ac1307ab 4803 error_exit("Command not found: %s", cmdname);
ea2384d3 4804}