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