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