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