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