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