]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-img.c
blockdev: Overlays are not snapshots
[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;
690c7301 1584 int min_sparse;
8dcd3c9b 1585 int alignment;
690c7301
KW
1586 size_t cluster_sectors;
1587 size_t buf_sectors;
9fd77f99 1588 long num_coroutines;
2d9187bc
PL
1589 int running_coroutines;
1590 Coroutine *co[MAX_COROUTINES];
1591 int64_t wait_sector_num[MAX_COROUTINES];
1592 CoMutex lock;
1593 int ret;
690c7301
KW
1594} ImgConvertState;
1595
2d9187bc
PL
1596static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1597 int *src_cur, int64_t *src_cur_offset)
690c7301 1598{
2d9187bc
PL
1599 *src_cur = 0;
1600 *src_cur_offset = 0;
1601 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1602 *src_cur_offset += s->src_sectors[*src_cur];
1603 (*src_cur)++;
1604 assert(*src_cur < s->src_num);
690c7301
KW
1605 }
1606}
1607
1608static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1609{
31826642
EB
1610 int64_t src_cur_offset;
1611 int ret, n, src_cur;
351c8eff 1612 bool post_backing_zero = false;
690c7301 1613
2d9187bc 1614 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
690c7301
KW
1615
1616 assert(s->total_sectors > sector_num);
1617 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1618
351c8eff
HR
1619 if (s->target_backing_sectors >= 0) {
1620 if (sector_num >= s->target_backing_sectors) {
1621 post_backing_zero = s->unallocated_blocks_are_zero;
1622 } else if (sector_num + n > s->target_backing_sectors) {
1623 /* Split requests around target_backing_sectors (because
1624 * starting from there, zeros are handled differently) */
1625 n = s->target_backing_sectors - sector_num;
1626 }
1627 }
1628
690c7301 1629 if (s->sector_next_status <= sector_num) {
31826642
EB
1630 int64_t count = n * BDRV_SECTOR_SIZE;
1631
9f1b92ad 1632 if (s->target_has_backing) {
237d78f8
EB
1633
1634 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1635 (sector_num - src_cur_offset) *
1636 BDRV_SECTOR_SIZE,
1637 count, &count, NULL, NULL);
9f1b92ad 1638 } else {
31826642
EB
1639 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1640 (sector_num - src_cur_offset) *
1641 BDRV_SECTOR_SIZE,
1642 count, &count, NULL, NULL);
9f1b92ad 1643 }
690c7301 1644 if (ret < 0) {
2058c2ad
EB
1645 error_report("error while reading block status of sector %" PRId64
1646 ": %s", sector_num, strerror(-ret));
690c7301
KW
1647 return ret;
1648 }
31826642 1649 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
690c7301
KW
1650
1651 if (ret & BDRV_BLOCK_ZERO) {
351c8eff 1652 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
690c7301
KW
1653 } else if (ret & BDRV_BLOCK_DATA) {
1654 s->status = BLK_DATA;
690c7301 1655 } else {
9f1b92ad 1656 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
690c7301
KW
1657 }
1658
1659 s->sector_next_status = sector_num + n;
1660 }
1661
1662 n = MIN(n, s->sector_next_status - sector_num);
1663 if (s->status == BLK_DATA) {
1664 n = MIN(n, s->buf_sectors);
1665 }
1666
1667 /* We need to write complete clusters for compressed images, so if an
1668 * unallocated area is shorter than that, we must consider the whole
1669 * cluster allocated. */
1670 if (s->compressed) {
1671 if (n < s->cluster_sectors) {
1672 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1673 s->status = BLK_DATA;
1674 } else {
1675 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1676 }
1677 }
1678
1679 return n;
1680}
1681
2d9187bc
PL
1682static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1683 int nb_sectors, uint8_t *buf)
690c7301 1684{
2d9187bc 1685 int n, ret;
690c7301 1686
690c7301
KW
1687 assert(nb_sectors <= s->buf_sectors);
1688 while (nb_sectors > 0) {
1689 BlockBackend *blk;
2d9187bc
PL
1690 int src_cur;
1691 int64_t bs_sectors, src_cur_offset;
690c7301
KW
1692
1693 /* In the case of compression with multiple source files, we can get a
1694 * nb_sectors that spreads into the next part. So we must be able to
1695 * read across multiple BDSes for one convert_read() call. */
2d9187bc
PL
1696 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1697 blk = s->src[src_cur];
1698 bs_sectors = s->src_sectors[src_cur];
1699
1700 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
2d9187bc 1701
265a7e54 1702 ret = blk_co_pread(
2d9187bc 1703 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
265a7e54 1704 n << BDRV_SECTOR_BITS, buf, 0);
690c7301
KW
1705 if (ret < 0) {
1706 return ret;
1707 }
1708
1709 sector_num += n;
1710 nb_sectors -= n;
1711 buf += n * BDRV_SECTOR_SIZE;
1712 }
1713
1714 return 0;
1715}
1716
2d9187bc
PL
1717
1718static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1719 int nb_sectors, uint8_t *buf,
1720 enum ImgConvertBlockStatus status)
690c7301
KW
1721{
1722 int ret;
1723
1724 while (nb_sectors > 0) {
1725 int n = nb_sectors;
db933fbe
LC
1726 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1727
2d9187bc 1728 switch (status) {
690c7301
KW
1729 case BLK_BACKING_FILE:
1730 /* If we have a backing file, leave clusters unallocated that are
1731 * unallocated in the source image, so that the backing file is
1732 * visible at the respective offset. */
1733 assert(s->target_has_backing);
1734 break;
1735
1736 case BLK_DATA:
db933fbe
LC
1737 /* If we're told to keep the target fully allocated (-S 0) or there
1738 * is real non-zero data, we must write it. Otherwise we can treat
1739 * it as zero sectors.
1740 * Compressed clusters need to be written as a whole, so in that
1741 * case we can only save the write if the buffer is completely
1742 * zeroed. */
690c7301 1743 if (!s->min_sparse ||
db933fbe 1744 (!s->compressed &&
8dcd3c9b
PL
1745 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1746 sector_num, s->alignment)) ||
db933fbe
LC
1747 (s->compressed &&
1748 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
690c7301 1749 {
265a7e54
VSO
1750 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1751 n << BDRV_SECTOR_BITS, buf, flags);
690c7301
KW
1752 if (ret < 0) {
1753 return ret;
1754 }
1755 break;
1756 }
1757 /* fall-through */
1758
1759 case BLK_ZERO:
1760 if (s->has_zero_init) {
db933fbe 1761 assert(!s->target_has_backing);
690c7301
KW
1762 break;
1763 }
2d9187bc
PL
1764 ret = blk_co_pwrite_zeroes(s->target,
1765 sector_num << BDRV_SECTOR_BITS,
a3d6ae22
NS
1766 n << BDRV_SECTOR_BITS,
1767 BDRV_REQ_MAY_UNMAP);
690c7301
KW
1768 if (ret < 0) {
1769 return ret;
1770 }
1771 break;
1772 }
1773
1774 sector_num += n;
1775 nb_sectors -= n;
1776 buf += n * BDRV_SECTOR_SIZE;
1777 }
1778
1779 return 0;
1780}
1781
ee5306d0
FZ
1782static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1783 int nb_sectors)
1784{
1785 int n, ret;
1786
1787 while (nb_sectors > 0) {
1788 BlockBackend *blk;
1789 int src_cur;
1790 int64_t bs_sectors, src_cur_offset;
1791 int64_t offset;
1792
1793 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1794 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1795 blk = s->src[src_cur];
1796 bs_sectors = s->src_sectors[src_cur];
1797
1798 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1799
1800 ret = blk_co_copy_range(blk, offset, s->target,
1801 sector_num << BDRV_SECTOR_BITS,
67b51fb9 1802 n << BDRV_SECTOR_BITS, 0, 0);
ee5306d0
FZ
1803 if (ret < 0) {
1804 return ret;
1805 }
1806
1807 sector_num += n;
1808 nb_sectors -= n;
1809 }
1810 return 0;
1811}
1812
2d9187bc 1813static void coroutine_fn convert_co_do_copy(void *opaque)
690c7301 1814{
2d9187bc 1815 ImgConvertState *s = opaque;
690c7301 1816 uint8_t *buf = NULL;
2d9187bc
PL
1817 int ret, i;
1818 int index = -1;
1819
1820 for (i = 0; i < s->num_coroutines; i++) {
1821 if (s->co[i] == qemu_coroutine_self()) {
1822 index = i;
1823 break;
1824 }
1825 }
1826 assert(index >= 0);
1827
1828 s->running_coroutines++;
1829 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1830
1831 while (1) {
1832 int n;
1833 int64_t sector_num;
1834 enum ImgConvertBlockStatus status;
ee5306d0 1835 bool copy_range;
2d9187bc
PL
1836
1837 qemu_co_mutex_lock(&s->lock);
1838 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1839 qemu_co_mutex_unlock(&s->lock);
b91127ed 1840 break;
2d9187bc
PL
1841 }
1842 n = convert_iteration_sectors(s, s->sector_num);
1843 if (n < 0) {
1844 qemu_co_mutex_unlock(&s->lock);
1845 s->ret = n;
b91127ed 1846 break;
2d9187bc
PL
1847 }
1848 /* save current sector and allocation status to local variables */
1849 sector_num = s->sector_num;
1850 status = s->status;
1851 if (!s->min_sparse && s->status == BLK_ZERO) {
1852 n = MIN(n, s->buf_sectors);
1853 }
1854 /* increment global sector counter so that other coroutines can
1855 * already continue reading beyond this request */
1856 s->sector_num += n;
1857 qemu_co_mutex_unlock(&s->lock);
1858
1859 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1860 s->allocated_done += n;
1861 qemu_progress_print(100.0 * s->allocated_done /
1862 s->allocated_sectors, 0);
1863 }
1864
ee5306d0
FZ
1865retry:
1866 copy_range = s->copy_range && s->status == BLK_DATA;
1867 if (status == BLK_DATA && !copy_range) {
2d9187bc
PL
1868 ret = convert_co_read(s, sector_num, n, buf);
1869 if (ret < 0) {
1870 error_report("error while reading sector %" PRId64
1871 ": %s", sector_num, strerror(-ret));
1872 s->ret = ret;
2d9187bc
PL
1873 }
1874 } else if (!s->min_sparse && status == BLK_ZERO) {
1875 status = BLK_DATA;
1876 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1877 }
1878
1879 if (s->wr_in_order) {
1880 /* keep writes in order */
b91127ed 1881 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
2d9187bc
PL
1882 s->wait_sector_num[index] = sector_num;
1883 qemu_coroutine_yield();
1884 }
1885 s->wait_sector_num[index] = -1;
1886 }
1887
b91127ed 1888 if (s->ret == -EINPROGRESS) {
ee5306d0
FZ
1889 if (copy_range) {
1890 ret = convert_co_copy_range(s, sector_num, n);
1891 if (ret) {
1892 s->copy_range = false;
1893 goto retry;
1894 }
1895 } else {
1896 ret = convert_co_write(s, sector_num, n, buf, status);
1897 }
b91127ed
AN
1898 if (ret < 0) {
1899 error_report("error while writing sector %" PRId64
1900 ": %s", sector_num, strerror(-ret));
1901 s->ret = ret;
1902 }
2d9187bc
PL
1903 }
1904
1905 if (s->wr_in_order) {
1906 /* reenter the coroutine that might have waited
1907 * for this write to complete */
1908 s->wr_offs = sector_num + n;
1909 for (i = 0; i < s->num_coroutines; i++) {
1910 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1911 /*
1912 * A -> B -> A cannot occur because A has
1913 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1914 * B will never enter A during this time window.
1915 */
1916 qemu_coroutine_enter(s->co[i]);
1917 break;
1918 }
1919 }
1920 }
1921 }
1922
2d9187bc
PL
1923 qemu_vfree(buf);
1924 s->co[index] = NULL;
1925 s->running_coroutines--;
1926 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1927 /* the convert job finished successfully */
1928 s->ret = 0;
1929 }
1930}
1931
1932static int convert_do_copy(ImgConvertState *s)
1933{
1934 int ret, i, n;
1935 int64_t sector_num = 0;
690c7301
KW
1936
1937 /* Check whether we have zero initialisation or can get it efficiently */
1938 s->has_zero_init = s->min_sparse && !s->target_has_backing
1939 ? bdrv_has_zero_init(blk_bs(s->target))
1940 : false;
1941
1942 if (!s->has_zero_init && !s->target_has_backing &&
1943 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1944 {
c9fdcf20 1945 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
690c7301
KW
1946 if (ret == 0) {
1947 s->has_zero_init = true;
1948 }
1949 }
1950
1951 /* Allocate buffer for copied data. For compressed images, only one cluster
1952 * can be copied at a time. */
1953 if (s->compressed) {
1954 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1955 error_report("invalid cluster size");
2d9187bc 1956 return -EINVAL;
690c7301
KW
1957 }
1958 s->buf_sectors = s->cluster_sectors;
1959 }
690c7301 1960
690c7301
KW
1961 while (sector_num < s->total_sectors) {
1962 n = convert_iteration_sectors(s, sector_num);
1963 if (n < 0) {
2d9187bc 1964 return n;
690c7301 1965 }
aad15de4
HR
1966 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1967 {
690c7301
KW
1968 s->allocated_sectors += n;
1969 }
1970 sector_num += n;
1971 }
1972
1973 /* Do the copy */
690c7301 1974 s->sector_next_status = 0;
2d9187bc 1975 s->ret = -EINPROGRESS;
690c7301 1976
2d9187bc
PL
1977 qemu_co_mutex_init(&s->lock);
1978 for (i = 0; i < s->num_coroutines; i++) {
1979 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1980 s->wait_sector_num[i] = -1;
1981 qemu_coroutine_enter(s->co[i]);
1982 }
690c7301 1983
b91127ed 1984 while (s->running_coroutines) {
2d9187bc 1985 main_loop_wait(false);
690c7301
KW
1986 }
1987
2d9187bc 1988 if (s->compressed && !s->ret) {
690c7301 1989 /* signal EOF to align */
fe5c1355 1990 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
690c7301 1991 if (ret < 0) {
2d9187bc 1992 return ret;
690c7301
KW
1993 }
1994 }
1995
2d9187bc 1996 return s->ret;
690c7301
KW
1997}
1998
6360ab27
PL
1999#define MAX_BUF_SECTORS 32768
2000
ea2384d3
FB
2001static int img_convert(int argc, char **argv)
2002{
9fd77f99 2003 int c, bs_i, flags, src_flags = 0;
305b4c60 2004 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
9fd77f99
PL
2005 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2006 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
305b4c60 2007 BlockDriver *drv = NULL, *proto_drv = NULL;
faea38e7 2008 BlockDriverInfo bdi;
9fd77f99
PL
2009 BlockDriverState *out_bs;
2010 QemuOpts *opts = NULL, *sn_opts = NULL;
83d0521a 2011 QemuOptsList *create_opts = NULL;
8d65a3cc 2012 QDict *open_opts = NULL;
efa84d43 2013 char *options = NULL;
cc84d90f 2014 Error *local_err = NULL;
9fd77f99 2015 bool writethrough, src_writethrough, quiet = false, image_opts = false,
305b4c60 2016 skip_create = false, progress = false, tgt_image_opts = false;
9fd77f99 2017 int64_t ret = -EINVAL;
335e9937 2018 bool force_share = false;
e11ce12f 2019 bool explict_min_sparse = false;
9fd77f99
PL
2020
2021 ImgConvertState s = (ImgConvertState) {
2022 /* Need at least 4k of zeros for sparse detection */
2023 .min_sparse = 8,
e11ce12f 2024 .copy_range = false,
9fd77f99
PL
2025 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2026 .wr_in_order = true,
2027 .num_coroutines = 8,
2028 };
ea2384d3 2029
ea2384d3 2030 for(;;) {
3babeb15
DB
2031 static const struct option long_options[] = {
2032 {"help", no_argument, 0, 'h'},
2033 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2034 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2035 {"force-share", no_argument, 0, 'U'},
305b4c60 2036 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
3babeb15
DB
2037 {0, 0, 0, 0}
2038 };
e11ce12f 2039 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
3babeb15 2040 long_options, NULL);
b8fb60da 2041 if (c == -1) {
ea2384d3 2042 break;
b8fb60da 2043 }
ea2384d3 2044 switch(c) {
c9192973
SH
2045 case ':':
2046 missing_argument(argv[optind - 1]);
2047 break;
ef87394c 2048 case '?':
c9192973
SH
2049 unrecognized_option(argv[optind - 1]);
2050 break;
ea2384d3
FB
2051 case 'h':
2052 help();
2053 break;
2054 case 'f':
2055 fmt = optarg;
2056 break;
2057 case 'O':
2058 out_fmt = optarg;
2059 break;
f58c7b35
TS
2060 case 'B':
2061 out_baseimg = optarg;
2062 break;
e11ce12f
FZ
2063 case 'C':
2064 s.copy_range = true;
2065 break;
ea2384d3 2066 case 'c':
9fd77f99 2067 s.compressed = true;
ea2384d3 2068 break;
efa84d43 2069 case 'o':
2dc8328b
KW
2070 if (!is_valid_option_list(optarg)) {
2071 error_report("Invalid option list: %s", optarg);
64bb01aa 2072 goto fail_getopt;
2dc8328b
KW
2073 }
2074 if (!options) {
2075 options = g_strdup(optarg);
2076 } else {
2077 char *old_options = options;
2078 options = g_strdup_printf("%s,%s", options, optarg);
2079 g_free(old_options);
2080 }
efa84d43 2081 break;
ef80654d
WX
2082 case 'l':
2083 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
2084 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2085 optarg, false);
ef80654d
WX
2086 if (!sn_opts) {
2087 error_report("Failed in parsing snapshot param '%s'",
2088 optarg);
64bb01aa 2089 goto fail_getopt;
ef80654d
WX
2090 }
2091 } else {
2092 snapshot_name = optarg;
2093 }
2094 break;
a22f123c
KW
2095 case 'S':
2096 {
2097 int64_t sval;
606caa0a
MA
2098
2099 sval = cvtnum(optarg);
6360ab27
PL
2100 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2101 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2102 error_report("Invalid buffer size for sparse output specified. "
2103 "Valid sizes are multiples of %llu up to %llu. Select "
2104 "0 to disable sparse detection (fully allocates output).",
2105 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
64bb01aa 2106 goto fail_getopt;
a22f123c
KW
2107 }
2108
9fd77f99 2109 s.min_sparse = sval / BDRV_SECTOR_SIZE;
e11ce12f 2110 explict_min_sparse = true;
a22f123c
KW
2111 break;
2112 }
6b837bc4 2113 case 'p':
9fd77f99 2114 progress = true;
6b837bc4 2115 break;
661a0f71
FS
2116 case 't':
2117 cache = optarg;
2118 break;
40055951
HR
2119 case 'T':
2120 src_cache = optarg;
2121 break;
f382d43a
MR
2122 case 'q':
2123 quiet = true;
2124 break;
b2e10493 2125 case 'n':
9fd77f99 2126 skip_create = true;
b2e10493 2127 break;
2d9187bc 2128 case 'm':
9fd77f99
PL
2129 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2130 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
2d9187bc
PL
2131 error_report("Invalid number of coroutines. Allowed number of"
2132 " coroutines is between 1 and %d", MAX_COROUTINES);
2d9187bc
PL
2133 goto fail_getopt;
2134 }
2135 break;
2136 case 'W':
9fd77f99 2137 s.wr_in_order = false;
2d9187bc 2138 break;
335e9937
FZ
2139 case 'U':
2140 force_share = true;
2141 break;
3258b911
HR
2142 case OPTION_OBJECT: {
2143 QemuOpts *object_opts;
2144 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2145 optarg, true);
2146 if (!object_opts) {
3babeb15
DB
2147 goto fail_getopt;
2148 }
2149 break;
3258b911 2150 }
eb769f74
DB
2151 case OPTION_IMAGE_OPTS:
2152 image_opts = true;
2153 break;
305b4c60
DB
2154 case OPTION_TARGET_IMAGE_OPTS:
2155 tgt_image_opts = true;
2156 break;
ea2384d3
FB
2157 }
2158 }
3b46e624 2159
305b4c60
DB
2160 if (!out_fmt && !tgt_image_opts) {
2161 out_fmt = "raw";
2162 }
2163
3babeb15
DB
2164 if (qemu_opts_foreach(&qemu_object_opts,
2165 user_creatable_add_opts_foreach,
334c43e2 2166 NULL, &error_fatal)) {
3babeb15
DB
2167 goto fail_getopt;
2168 }
2169
e11ce12f
FZ
2170 if (s.compressed && s.copy_range) {
2171 error_report("Cannot enable copy offloading when -c is used");
2172 goto fail_getopt;
2173 }
2174
2175 if (explict_min_sparse && s.copy_range) {
2176 error_report("Cannot enable copy offloading when -S is used");
2177 goto fail_getopt;
2178 }
2179
305b4c60
DB
2180 if (tgt_image_opts && !skip_create) {
2181 error_report("--target-image-opts requires use of -n flag");
2182 goto fail_getopt;
2183 }
2184
9fd77f99
PL
2185 s.src_num = argc - optind - 1;
2186 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
f58c7b35 2187
2dc8328b 2188 if (options && has_help_option(options)) {
305b4c60
DB
2189 if (out_fmt) {
2190 ret = print_block_option_help(out_filename, out_fmt);
2191 goto fail_getopt;
2192 } else {
2193 error_report("Option help requires a format be specified");
2194 goto fail_getopt;
2195 }
4ac8aacd
JS
2196 }
2197
9fd77f99
PL
2198 if (s.src_num < 1) {
2199 error_report("Must specify image file name");
2200 goto fail_getopt;
a283cb6e
KW
2201 }
2202
2203
9fd77f99 2204 /* ret is still -EINVAL until here */
ce099547 2205 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
2206 if (ret < 0) {
2207 error_report("Invalid source cache option: %s", src_cache);
9fd77f99 2208 goto fail_getopt;
40055951
HR
2209 }
2210
9fd77f99
PL
2211 /* Initialize before goto out */
2212 if (quiet) {
2213 progress = false;
2214 }
2215 qemu_progress_init(progress, 1.0);
6b837bc4
JS
2216 qemu_progress_print(0, 100);
2217
9fd77f99
PL
2218 s.src = g_new0(BlockBackend *, s.src_num);
2219 s.src_sectors = g_new(int64_t, s.src_num);
926c2d23 2220
9fd77f99
PL
2221 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2222 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
335e9937
FZ
2223 fmt, src_flags, src_writethrough, quiet,
2224 force_share);
9fd77f99 2225 if (!s.src[bs_i]) {
c2abccec
MK
2226 ret = -1;
2227 goto out;
2228 }
9fd77f99
PL
2229 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2230 if (s.src_sectors[bs_i] < 0) {
52bf1e72 2231 error_report("Could not get size of %s: %s",
9fd77f99 2232 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
52bf1e72
MA
2233 ret = -1;
2234 goto out;
2235 }
9fd77f99 2236 s.total_sectors += s.src_sectors[bs_i];
926c2d23 2237 }
ea2384d3 2238
ef80654d 2239 if (sn_opts) {
9fd77f99 2240 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
10d6eda1
PM
2241 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2242 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2243 &local_err);
ef80654d 2244 } else if (snapshot_name != NULL) {
9fd77f99 2245 if (s.src_num > 1) {
6daf194d 2246 error_report("No support for concatenating multiple snapshot");
51ef6727 2247 ret = -1;
2248 goto out;
2249 }
7b4c4781 2250
9fd77f99
PL
2251 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2252 &local_err);
ef80654d 2253 }
84d18f06 2254 if (local_err) {
c29b77f9 2255 error_reportf_err(local_err, "Failed to load snapshot: ");
ef80654d
WX
2256 ret = -1;
2257 goto out;
51ef6727 2258 }
2259
305b4c60
DB
2260 if (!skip_create) {
2261 /* Find driver and parse its options */
2262 drv = bdrv_find_format(out_fmt);
2263 if (!drv) {
2264 error_report("Unknown file format '%s'", out_fmt);
2265 ret = -1;
2266 goto out;
2267 }
efa84d43 2268
305b4c60
DB
2269 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2270 if (!proto_drv) {
2271 error_report_err(local_err);
2272 ret = -1;
2273 goto out;
2274 }
b50cbabc 2275
2e024cde
HR
2276 if (!drv->create_opts) {
2277 error_report("Format driver '%s' does not support image creation",
2278 drv->format_name);
2279 ret = -1;
2280 goto out;
2281 }
f75613cf 2282
2e024cde
HR
2283 if (!proto_drv->create_opts) {
2284 error_report("Protocol driver '%s' does not support image creation",
2285 proto_drv->format_name);
2286 ret = -1;
2287 goto out;
2288 }
f75613cf 2289
2e024cde
HR
2290 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2291 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 2292
2e024cde 2293 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
2294 if (options) {
2295 qemu_opts_do_parse(opts, options, NULL, &local_err);
2296 if (local_err) {
97a2ca7a 2297 error_report_err(local_err);
dc523cd3
MA
2298 ret = -1;
2299 goto out;
2300 }
2e024cde 2301 }
efa84d43 2302
9fd77f99 2303 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
39101f25 2304 &error_abort);
2e024cde
HR
2305 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2306 if (ret < 0) {
2307 goto out;
2308 }
c2abccec 2309 }
efa84d43 2310
a18953fb 2311 /* Get backing file name if -o backing_file was used */
83d0521a 2312 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 2313 if (out_baseimg_param) {
83d0521a 2314 out_baseimg = out_baseimg_param;
a18953fb 2315 }
9fd77f99 2316 s.target_has_backing = (bool) out_baseimg;
a18953fb 2317
48758a84
HR
2318 if (s.src_num > 1 && out_baseimg) {
2319 error_report("Having a backing file for the target makes no sense when "
2320 "concatenating multiple input images");
2321 ret = -1;
2322 goto out;
2323 }
2324
efa84d43 2325 /* Check if compression is supported */
9fd77f99 2326 if (s.compressed) {
83d0521a
CL
2327 bool encryption =
2328 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
0cb8d47b
DB
2329 const char *encryptfmt =
2330 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
83d0521a
CL
2331 const char *preallocation =
2332 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
efa84d43 2333
305b4c60 2334 if (drv && !drv->bdrv_co_pwritev_compressed) {
15654a6d 2335 error_report("Compression not supported for this file format");
c2abccec
MK
2336 ret = -1;
2337 goto out;
efa84d43
KW
2338 }
2339
0cb8d47b 2340 if (encryption || encryptfmt) {
15654a6d
JS
2341 error_report("Compression and encryption not supported at "
2342 "the same time");
c2abccec
MK
2343 ret = -1;
2344 goto out;
efa84d43 2345 }
41521fa4 2346
83d0521a
CL
2347 if (preallocation
2348 && strcmp(preallocation, "off"))
41521fa4
KW
2349 {
2350 error_report("Compression and preallocation not supported at "
2351 "the same time");
2352 ret = -1;
2353 goto out;
2354 }
efa84d43
KW
2355 }
2356
8d65a3cc
DB
2357 /*
2358 * The later open call will need any decryption secrets, and
2359 * bdrv_create() will purge "opts", so extract them now before
2360 * they are lost.
2361 */
2362 if (!skip_create) {
2363 open_opts = qdict_new();
2364 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2365 }
2366
b2e10493
AD
2367 if (!skip_create) {
2368 /* Create the new image */
c282e1fd 2369 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 2370 if (ret < 0) {
c29b77f9
MA
2371 error_reportf_err(local_err, "%s: error while converting %s: ",
2372 out_filename, out_fmt);
b2e10493 2373 goto out;
ea2384d3
FB
2374 }
2375 }
3b46e624 2376
9fd77f99 2377 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
ce099547 2378 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2379 if (ret < 0) {
2380 error_report("Invalid cache option: %s", cache);
bb9cd2ee 2381 goto out;
661a0f71
FS
2382 }
2383
305b4c60
DB
2384 if (skip_create) {
2385 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2386 flags, writethrough, quiet, false);
2387 } else {
2388 /* TODO ultimately we should allow --target-image-opts
2389 * to be used even when -n is not given.
2390 * That has to wait for bdrv_create to be improved
2391 * to allow filenames in option syntax
2392 */
8d65a3cc
DB
2393 s.target = img_open_file(out_filename, open_opts, out_fmt,
2394 flags, writethrough, quiet, false);
2395 open_opts = NULL; /* blk_new_open will have freed it */
305b4c60 2396 }
9fd77f99 2397 if (!s.target) {
c2abccec
MK
2398 ret = -1;
2399 goto out;
2400 }
9fd77f99 2401 out_bs = blk_bs(s.target);
ea2384d3 2402
305b4c60
DB
2403 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2404 error_report("Compression not supported for this file format");
2405 ret = -1;
2406 goto out;
2407 }
2408
5def6b80 2409 /* increase bufsectors from the default 4096 (2M) if opt_transfer
6360ab27
PL
2410 * or discard_alignment of the out_bs is greater. Limit to
2411 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2412 s.buf_sectors = MIN(MAX_BUF_SECTORS,
9fd77f99
PL
2413 MAX(s.buf_sectors,
2414 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2415 out_bs->bl.pdiscard_alignment >>
2416 BDRV_SECTOR_BITS)));
f2521c90 2417
8dcd3c9b
PL
2418 /* try to align the write requests to the destination to avoid unnecessary
2419 * RMW cycles. */
2420 s.alignment = MAX(pow2floor(s.min_sparse),
2421 DIV_ROUND_UP(out_bs->bl.request_alignment,
2422 BDRV_SECTOR_SIZE));
2423 assert(is_power_of_2(s.alignment));
2424
b2e10493 2425 if (skip_create) {
9fd77f99 2426 int64_t output_sectors = blk_nb_sectors(s.target);
43716fa8 2427 if (output_sectors < 0) {
eec5eb42 2428 error_report("unable to get output image length: %s",
43716fa8 2429 strerror(-output_sectors));
b2e10493
AD
2430 ret = -1;
2431 goto out;
9fd77f99 2432 } else if (output_sectors < s.total_sectors) {
b2e10493
AD
2433 error_report("output file is smaller than input file");
2434 ret = -1;
2435 goto out;
2436 }
2437 }
2438
351c8eff
HR
2439 if (s.target_has_backing) {
2440 /* Errors are treated as "backing length unknown" (which means
2441 * s.target_backing_sectors has to be negative, which it will
2442 * be automatically). The backing file length is used only
2443 * for optimizations, so such a case is not fatal. */
2444 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2445 } else {
2446 s.target_backing_sectors = -1;
2447 }
2448
24f833cd
PL
2449 ret = bdrv_get_info(out_bs, &bdi);
2450 if (ret < 0) {
9fd77f99 2451 if (s.compressed) {
15654a6d 2452 error_report("could not get block driver info");
c2abccec
MK
2453 goto out;
2454 }
24f833cd 2455 } else {
9fd77f99
PL
2456 s.compressed = s.compressed || bdi.needs_compressed_writes;
2457 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
351c8eff 2458 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
9fd77f99 2459 }
802c3d4c 2460
9fd77f99 2461 ret = convert_do_copy(&s);
c2abccec 2462out:
13c28af8
PL
2463 if (!ret) {
2464 qemu_progress_print(100, 0);
2465 }
6b837bc4 2466 qemu_progress_end();
83d0521a
CL
2467 qemu_opts_del(opts);
2468 qemu_opts_free(create_opts);
fbf28a43 2469 qemu_opts_del(sn_opts);
8d65a3cc 2470 qobject_unref(open_opts);
9fd77f99
PL
2471 blk_unref(s.target);
2472 if (s.src) {
2473 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2474 blk_unref(s.src[bs_i]);
26f54e9a 2475 }
9fd77f99 2476 g_free(s.src);
26f54e9a 2477 }
9fd77f99 2478 g_free(s.src_sectors);
64bb01aa
KW
2479fail_getopt:
2480 g_free(options);
2481
9fd77f99 2482 return !!ret;
ea2384d3
FB
2483}
2484
57d1a2b6 2485
faea38e7
FB
2486static void dump_snapshots(BlockDriverState *bs)
2487{
2488 QEMUSnapshotInfo *sn_tab, *sn;
2489 int nb_sns, i;
faea38e7
FB
2490
2491 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2492 if (nb_sns <= 0)
2493 return;
2494 printf("Snapshot list:\n");
e1ce7d74 2495 bdrv_snapshot_dump(NULL);
5b917044 2496 printf("\n");
faea38e7
FB
2497 for(i = 0; i < nb_sns; i++) {
2498 sn = &sn_tab[i];
e1ce7d74 2499 bdrv_snapshot_dump(sn);
5b917044 2500 printf("\n");
faea38e7 2501 }
7267c094 2502 g_free(sn_tab);
faea38e7
FB
2503}
2504
9699bf0d
SH
2505static void dump_json_image_info_list(ImageInfoList *list)
2506{
9699bf0d 2507 QString *str;
9699bf0d 2508 QObject *obj;
7d5e199a 2509 Visitor *v = qobject_output_visitor_new(&obj);
3b098d56
EB
2510
2511 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2512 visit_complete(v, &obj);
9699bf0d
SH
2513 str = qobject_to_json_pretty(obj);
2514 assert(str != NULL);
2515 printf("%s\n", qstring_get_str(str));
cb3e7f08 2516 qobject_unref(obj);
3b098d56 2517 visit_free(v);
cb3e7f08 2518 qobject_unref(str);
9699bf0d
SH
2519}
2520
c054b3fd
BC
2521static void dump_json_image_info(ImageInfo *info)
2522{
c054b3fd 2523 QString *str;
c054b3fd 2524 QObject *obj;
7d5e199a 2525 Visitor *v = qobject_output_visitor_new(&obj);
3b098d56
EB
2526
2527 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2528 visit_complete(v, &obj);
c054b3fd
BC
2529 str = qobject_to_json_pretty(obj);
2530 assert(str != NULL);
2531 printf("%s\n", qstring_get_str(str));
cb3e7f08 2532 qobject_unref(obj);
3b098d56 2533 visit_free(v);
cb3e7f08 2534 qobject_unref(str);
c054b3fd
BC
2535}
2536
9699bf0d
SH
2537static void dump_human_image_info_list(ImageInfoList *list)
2538{
2539 ImageInfoList *elem;
2540 bool delim = false;
2541
2542 for (elem = list; elem; elem = elem->next) {
2543 if (delim) {
2544 printf("\n");
2545 }
2546 delim = true;
2547
e1ce7d74 2548 bdrv_image_info_dump(elem->value);
9699bf0d
SH
2549 }
2550}
2551
2552static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2553{
2554 return strcmp(a, b) == 0;
2555}
2556
2557/**
2558 * Open an image file chain and return an ImageInfoList
2559 *
2560 * @filename: topmost image filename
2561 * @fmt: topmost image format (may be NULL to autodetect)
2562 * @chain: true - enumerate entire backing file chain
2563 * false - only topmost image file
2564 *
2565 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2566 * image file. If there was an error a message will have been printed to
2567 * stderr.
2568 */
eb769f74
DB
2569static ImageInfoList *collect_image_info_list(bool image_opts,
2570 const char *filename,
9699bf0d 2571 const char *fmt,
335e9937 2572 bool chain, bool force_share)
9699bf0d
SH
2573{
2574 ImageInfoList *head = NULL;
2575 ImageInfoList **last = &head;
2576 GHashTable *filenames;
43526ec8 2577 Error *err = NULL;
9699bf0d
SH
2578
2579 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2580
2581 while (filename) {
26f54e9a 2582 BlockBackend *blk;
9699bf0d
SH
2583 BlockDriverState *bs;
2584 ImageInfo *info;
2585 ImageInfoList *elem;
2586
2587 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2588 error_report("Backing file '%s' creates an infinite loop.",
2589 filename);
2590 goto err;
2591 }
2592 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2593
efaa7c4e 2594 blk = img_open(image_opts, filename, fmt,
335e9937
FZ
2595 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2596 force_share);
7e7d56d9 2597 if (!blk) {
9699bf0d
SH
2598 goto err;
2599 }
7e7d56d9 2600 bs = blk_bs(blk);
9699bf0d 2601
43526ec8 2602 bdrv_query_image_info(bs, &info, &err);
84d18f06 2603 if (err) {
565f65d2 2604 error_report_err(err);
26f54e9a 2605 blk_unref(blk);
43526ec8 2606 goto err;
fb0ed453 2607 }
9699bf0d
SH
2608
2609 elem = g_new0(ImageInfoList, 1);
2610 elem->value = info;
2611 *last = elem;
2612 last = &elem->next;
2613
26f54e9a 2614 blk_unref(blk);
9699bf0d
SH
2615
2616 filename = fmt = NULL;
2617 if (chain) {
2618 if (info->has_full_backing_filename) {
2619 filename = info->full_backing_filename;
2620 } else if (info->has_backing_filename) {
92d617ab
JS
2621 error_report("Could not determine absolute backing filename,"
2622 " but backing filename '%s' present",
2623 info->backing_filename);
2624 goto err;
9699bf0d
SH
2625 }
2626 if (info->has_backing_filename_format) {
2627 fmt = info->backing_filename_format;
2628 }
2629 }
2630 }
2631 g_hash_table_destroy(filenames);
2632 return head;
2633
2634err:
2635 qapi_free_ImageInfoList(head);
2636 g_hash_table_destroy(filenames);
2637 return NULL;
2638}
2639
c054b3fd
BC
2640static int img_info(int argc, char **argv)
2641{
2642 int c;
2643 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 2644 bool chain = false;
c054b3fd 2645 const char *filename, *fmt, *output;
9699bf0d 2646 ImageInfoList *list;
eb769f74 2647 bool image_opts = false;
335e9937 2648 bool force_share = false;
c054b3fd 2649
ea2384d3 2650 fmt = NULL;
c054b3fd 2651 output = NULL;
ea2384d3 2652 for(;;) {
c054b3fd
BC
2653 int option_index = 0;
2654 static const struct option long_options[] = {
2655 {"help", no_argument, 0, 'h'},
2656 {"format", required_argument, 0, 'f'},
2657 {"output", required_argument, 0, OPTION_OUTPUT},
9699bf0d 2658 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3babeb15 2659 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2660 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2661 {"force-share", no_argument, 0, 'U'},
c054b3fd
BC
2662 {0, 0, 0, 0}
2663 };
335e9937 2664 c = getopt_long(argc, argv, ":f:hU",
c054b3fd 2665 long_options, &option_index);
b8fb60da 2666 if (c == -1) {
ea2384d3 2667 break;
b8fb60da 2668 }
ea2384d3 2669 switch(c) {
c9192973
SH
2670 case ':':
2671 missing_argument(argv[optind - 1]);
2672 break;
ef87394c 2673 case '?':
c9192973
SH
2674 unrecognized_option(argv[optind - 1]);
2675 break;
ea2384d3
FB
2676 case 'h':
2677 help();
2678 break;
2679 case 'f':
2680 fmt = optarg;
2681 break;
335e9937
FZ
2682 case 'U':
2683 force_share = true;
2684 break;
c054b3fd
BC
2685 case OPTION_OUTPUT:
2686 output = optarg;
2687 break;
9699bf0d
SH
2688 case OPTION_BACKING_CHAIN:
2689 chain = true;
2690 break;
3babeb15
DB
2691 case OPTION_OBJECT: {
2692 QemuOpts *opts;
2693 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2694 optarg, true);
2695 if (!opts) {
2696 return 1;
2697 }
2698 } break;
eb769f74
DB
2699 case OPTION_IMAGE_OPTS:
2700 image_opts = true;
2701 break;
ea2384d3
FB
2702 }
2703 }
fc11eb26 2704 if (optind != argc - 1) {
ac1307ab 2705 error_exit("Expecting one image file name");
b8fb60da 2706 }
ea2384d3
FB
2707 filename = argv[optind++];
2708
c054b3fd
BC
2709 if (output && !strcmp(output, "json")) {
2710 output_format = OFORMAT_JSON;
2711 } else if (output && !strcmp(output, "human")) {
2712 output_format = OFORMAT_HUMAN;
2713 } else if (output) {
2714 error_report("--output must be used with human or json as argument.");
c2abccec
MK
2715 return 1;
2716 }
c054b3fd 2717
3babeb15
DB
2718 if (qemu_opts_foreach(&qemu_object_opts,
2719 user_creatable_add_opts_foreach,
334c43e2 2720 NULL, &error_fatal)) {
3babeb15
DB
2721 return 1;
2722 }
2723
335e9937
FZ
2724 list = collect_image_info_list(image_opts, filename, fmt, chain,
2725 force_share);
9699bf0d 2726 if (!list) {
c2abccec 2727 return 1;
faea38e7 2728 }
c054b3fd 2729
c054b3fd
BC
2730 switch (output_format) {
2731 case OFORMAT_HUMAN:
9699bf0d 2732 dump_human_image_info_list(list);
c054b3fd
BC
2733 break;
2734 case OFORMAT_JSON:
9699bf0d
SH
2735 if (chain) {
2736 dump_json_image_info_list(list);
2737 } else {
2738 dump_json_image_info(list->value);
2739 }
c054b3fd 2740 break;
faea38e7 2741 }
c054b3fd 2742
9699bf0d 2743 qapi_free_ImageInfoList(list);
ea2384d3
FB
2744 return 0;
2745}
2746
30065d14
EB
2747static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2748 MapEntry *next)
4c93a13b
PB
2749{
2750 switch (output_format) {
2751 case OFORMAT_HUMAN:
16b0d555 2752 if (e->data && !e->has_offset) {
4c93a13b 2753 error_report("File contains external, encrypted or compressed clusters.");
30065d14 2754 return -1;
4c93a13b 2755 }
16b0d555 2756 if (e->data && !e->zero) {
4c93a13b 2757 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
16b0d555
FZ
2758 e->start, e->length,
2759 e->has_offset ? e->offset : 0,
2760 e->has_filename ? e->filename : "");
4c93a13b
PB
2761 }
2762 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2763 * Modify the flags here to allow more coalescing.
2764 */
16b0d555
FZ
2765 if (next && (!next->data || next->zero)) {
2766 next->data = false;
2767 next->zero = true;
4c93a13b
PB
2768 }
2769 break;
2770 case OFORMAT_JSON:
16b0d555
FZ
2771 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2772 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
4c93a13b
PB
2773 (e->start == 0 ? "[" : ",\n"),
2774 e->start, e->length, e->depth,
16b0d555
FZ
2775 e->zero ? "true" : "false",
2776 e->data ? "true" : "false");
2777 if (e->has_offset) {
c745bfb4 2778 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2779 }
2780 putchar('}');
2781
2782 if (!next) {
2783 printf("]\n");
2784 }
2785 break;
2786 }
30065d14 2787 return 0;
4c93a13b
PB
2788}
2789
5e344dd8
EB
2790static int get_block_status(BlockDriverState *bs, int64_t offset,
2791 int64_t bytes, MapEntry *e)
4c93a13b 2792{
237d78f8 2793 int ret;
4c93a13b 2794 int depth;
67a0fd2a 2795 BlockDriverState *file;
2875645b 2796 bool has_offset;
237d78f8 2797 int64_t map;
f30c66ba 2798 char *filename = NULL;
4c93a13b
PB
2799
2800 /* As an optimization, we could cache the current range of unallocated
2801 * clusters in each file of the chain, and avoid querying the same
2802 * range repeatedly.
2803 */
2804
2805 depth = 0;
2806 for (;;) {
237d78f8 2807 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
4c93a13b
PB
2808 if (ret < 0) {
2809 return ret;
2810 }
237d78f8 2811 assert(bytes);
4c93a13b
PB
2812 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2813 break;
2814 }
760e0063 2815 bs = backing_bs(bs);
4c93a13b
PB
2816 if (bs == NULL) {
2817 ret = 0;
2818 break;
2819 }
2820
2821 depth++;
2822 }
2823
2875645b
JS
2824 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2825
f30c66ba
HR
2826 if (file && has_offset) {
2827 bdrv_refresh_filename(file);
2828 filename = file->filename;
2829 }
2830
2875645b 2831 *e = (MapEntry) {
5e344dd8 2832 .start = offset,
237d78f8 2833 .length = bytes,
2875645b
JS
2834 .data = !!(ret & BDRV_BLOCK_DATA),
2835 .zero = !!(ret & BDRV_BLOCK_ZERO),
237d78f8 2836 .offset = map,
2875645b
JS
2837 .has_offset = has_offset,
2838 .depth = depth,
f30c66ba
HR
2839 .has_filename = filename,
2840 .filename = filename,
2875645b
JS
2841 };
2842
4c93a13b
PB
2843 return 0;
2844}
2845
16b0d555
FZ
2846static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2847{
2848 if (curr->length == 0) {
2849 return false;
2850 }
2851 if (curr->zero != next->zero ||
2852 curr->data != next->data ||
2853 curr->depth != next->depth ||
2854 curr->has_filename != next->has_filename ||
2855 curr->has_offset != next->has_offset) {
2856 return false;
2857 }
2858 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2859 return false;
2860 }
2861 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2862 return false;
2863 }
2864 return true;
2865}
2866
4c93a13b
PB
2867static int img_map(int argc, char **argv)
2868{
2869 int c;
2870 OutputFormat output_format = OFORMAT_HUMAN;
26f54e9a 2871 BlockBackend *blk;
4c93a13b
PB
2872 BlockDriverState *bs;
2873 const char *filename, *fmt, *output;
2874 int64_t length;
2875 MapEntry curr = { .length = 0 }, next;
2876 int ret = 0;
eb769f74 2877 bool image_opts = false;
335e9937 2878 bool force_share = false;
4c93a13b
PB
2879
2880 fmt = NULL;
2881 output = NULL;
2882 for (;;) {
2883 int option_index = 0;
2884 static const struct option long_options[] = {
2885 {"help", no_argument, 0, 'h'},
2886 {"format", required_argument, 0, 'f'},
2887 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 2888 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2889 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 2890 {"force-share", no_argument, 0, 'U'},
4c93a13b
PB
2891 {0, 0, 0, 0}
2892 };
335e9937 2893 c = getopt_long(argc, argv, ":f:hU",
4c93a13b
PB
2894 long_options, &option_index);
2895 if (c == -1) {
2896 break;
2897 }
2898 switch (c) {
c9192973
SH
2899 case ':':
2900 missing_argument(argv[optind - 1]);
2901 break;
4c93a13b 2902 case '?':
c9192973
SH
2903 unrecognized_option(argv[optind - 1]);
2904 break;
4c93a13b
PB
2905 case 'h':
2906 help();
2907 break;
2908 case 'f':
2909 fmt = optarg;
2910 break;
335e9937
FZ
2911 case 'U':
2912 force_share = true;
2913 break;
4c93a13b
PB
2914 case OPTION_OUTPUT:
2915 output = optarg;
2916 break;
3babeb15
DB
2917 case OPTION_OBJECT: {
2918 QemuOpts *opts;
2919 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2920 optarg, true);
2921 if (!opts) {
2922 return 1;
2923 }
2924 } break;
eb769f74
DB
2925 case OPTION_IMAGE_OPTS:
2926 image_opts = true;
2927 break;
4c93a13b
PB
2928 }
2929 }
ac1307ab
FZ
2930 if (optind != argc - 1) {
2931 error_exit("Expecting one image file name");
4c93a13b 2932 }
ac1307ab 2933 filename = argv[optind];
4c93a13b
PB
2934
2935 if (output && !strcmp(output, "json")) {
2936 output_format = OFORMAT_JSON;
2937 } else if (output && !strcmp(output, "human")) {
2938 output_format = OFORMAT_HUMAN;
2939 } else if (output) {
2940 error_report("--output must be used with human or json as argument.");
2941 return 1;
2942 }
2943
3babeb15
DB
2944 if (qemu_opts_foreach(&qemu_object_opts,
2945 user_creatable_add_opts_foreach,
334c43e2 2946 NULL, &error_fatal)) {
3babeb15
DB
2947 return 1;
2948 }
2949
335e9937 2950 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
7e7d56d9
MA
2951 if (!blk) {
2952 return 1;
4c93a13b 2953 }
7e7d56d9 2954 bs = blk_bs(blk);
4c93a13b
PB
2955
2956 if (output_format == OFORMAT_HUMAN) {
2957 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2958 }
2959
f1d3cd79 2960 length = blk_getlength(blk);
4c93a13b 2961 while (curr.start + curr.length < length) {
5e344dd8
EB
2962 int64_t offset = curr.start + curr.length;
2963 int64_t n;
4c93a13b
PB
2964
2965 /* Probe up to 1 GiB at a time. */
97ede57a 2966 n = MIN(1 * GiB, length - offset);
5e344dd8 2967 ret = get_block_status(bs, offset, n, &next);
4c93a13b
PB
2968
2969 if (ret < 0) {
2970 error_report("Could not read file metadata: %s", strerror(-ret));
2971 goto out;
2972 }
2973
16b0d555 2974 if (entry_mergeable(&curr, &next)) {
4c93a13b
PB
2975 curr.length += next.length;
2976 continue;
2977 }
2978
2979 if (curr.length > 0) {
30065d14
EB
2980 ret = dump_map_entry(output_format, &curr, &next);
2981 if (ret < 0) {
2982 goto out;
2983 }
4c93a13b
PB
2984 }
2985 curr = next;
2986 }
2987
30065d14 2988 ret = dump_map_entry(output_format, &curr, NULL);
4c93a13b
PB
2989
2990out:
26f54e9a 2991 blk_unref(blk);
4c93a13b
PB
2992 return ret < 0;
2993}
2994
f7b4a940
AL
2995#define SNAPSHOT_LIST 1
2996#define SNAPSHOT_CREATE 2
2997#define SNAPSHOT_APPLY 3
2998#define SNAPSHOT_DELETE 4
2999
153859be 3000static int img_snapshot(int argc, char **argv)
f7b4a940 3001{
26f54e9a 3002 BlockBackend *blk;
f7b4a940
AL
3003 BlockDriverState *bs;
3004 QEMUSnapshotInfo sn;
3005 char *filename, *snapshot_name = NULL;
c2abccec 3006 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
3007 int action = 0;
3008 qemu_timeval tv;
f382d43a 3009 bool quiet = false;
a89d89d3 3010 Error *err = NULL;
eb769f74 3011 bool image_opts = false;
335e9937 3012 bool force_share = false;
f7b4a940 3013
ce099547 3014 bdrv_oflags = BDRV_O_RDWR;
f7b4a940
AL
3015 /* Parse commandline parameters */
3016 for(;;) {
3babeb15
DB
3017 static const struct option long_options[] = {
3018 {"help", no_argument, 0, 'h'},
3019 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3020 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 3021 {"force-share", no_argument, 0, 'U'},
3babeb15
DB
3022 {0, 0, 0, 0}
3023 };
335e9937 3024 c = getopt_long(argc, argv, ":la:c:d:hqU",
3babeb15 3025 long_options, NULL);
b8fb60da 3026 if (c == -1) {
f7b4a940 3027 break;
b8fb60da 3028 }
f7b4a940 3029 switch(c) {
c9192973
SH
3030 case ':':
3031 missing_argument(argv[optind - 1]);
3032 break;
ef87394c 3033 case '?':
c9192973
SH
3034 unrecognized_option(argv[optind - 1]);
3035 break;
f7b4a940
AL
3036 case 'h':
3037 help();
153859be 3038 return 0;
f7b4a940
AL
3039 case 'l':
3040 if (action) {
ac1307ab 3041 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 3042 return 0;
f7b4a940
AL
3043 }
3044 action = SNAPSHOT_LIST;
f5edb014 3045 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
3046 break;
3047 case 'a':
3048 if (action) {
ac1307ab 3049 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 3050 return 0;
f7b4a940
AL
3051 }
3052 action = SNAPSHOT_APPLY;
3053 snapshot_name = optarg;
3054 break;
3055 case 'c':
3056 if (action) {
ac1307ab 3057 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 3058 return 0;
f7b4a940
AL
3059 }
3060 action = SNAPSHOT_CREATE;
3061 snapshot_name = optarg;
3062 break;
3063 case 'd':
3064 if (action) {
ac1307ab 3065 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 3066 return 0;
f7b4a940
AL
3067 }
3068 action = SNAPSHOT_DELETE;
3069 snapshot_name = optarg;
3070 break;
f382d43a
MR
3071 case 'q':
3072 quiet = true;
3073 break;
335e9937
FZ
3074 case 'U':
3075 force_share = true;
3076 break;
3babeb15
DB
3077 case OPTION_OBJECT: {
3078 QemuOpts *opts;
3079 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3080 optarg, true);
3081 if (!opts) {
3082 return 1;
3083 }
3084 } break;
eb769f74
DB
3085 case OPTION_IMAGE_OPTS:
3086 image_opts = true;
3087 break;
f7b4a940
AL
3088 }
3089 }
3090
fc11eb26 3091 if (optind != argc - 1) {
ac1307ab 3092 error_exit("Expecting one image file name");
b8fb60da 3093 }
f7b4a940
AL
3094 filename = argv[optind++];
3095
3babeb15
DB
3096 if (qemu_opts_foreach(&qemu_object_opts,
3097 user_creatable_add_opts_foreach,
334c43e2 3098 NULL, &error_fatal)) {
3babeb15
DB
3099 return 1;
3100 }
3101
f7b4a940 3102 /* Open the image */
335e9937
FZ
3103 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3104 force_share);
7e7d56d9
MA
3105 if (!blk) {
3106 return 1;
c2abccec 3107 }
7e7d56d9 3108 bs = blk_bs(blk);
f7b4a940
AL
3109
3110 /* Perform the requested action */
3111 switch(action) {
3112 case SNAPSHOT_LIST:
3113 dump_snapshots(bs);
3114 break;
3115
3116 case SNAPSHOT_CREATE:
3117 memset(&sn, 0, sizeof(sn));
3118 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3119
3120 qemu_gettimeofday(&tv);
3121 sn.date_sec = tv.tv_sec;
3122 sn.date_nsec = tv.tv_usec * 1000;
3123
3124 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 3125 if (ret) {
15654a6d 3126 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 3127 snapshot_name, ret, strerror(-ret));
b8fb60da 3128 }
f7b4a940
AL
3129 break;
3130
3131 case SNAPSHOT_APPLY:
0b62bcbc 3132 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
b8fb60da 3133 if (ret) {
0b62bcbc
KW
3134 error_reportf_err(err, "Could not apply snapshot '%s': ",
3135 snapshot_name);
b8fb60da 3136 }
f7b4a940
AL
3137 break;
3138
3139 case SNAPSHOT_DELETE:
8c04093c
DHB
3140 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3141 if (ret < 0) {
3142 error_report("Could not delete snapshot '%s': snapshot not "
3143 "found", snapshot_name);
a89d89d3 3144 ret = 1;
8c04093c
DHB
3145 } else {
3146 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3147 if (ret < 0) {
3148 error_reportf_err(err, "Could not delete snapshot '%s': ",
3149 snapshot_name);
3150 ret = 1;
3151 }
b8fb60da 3152 }
f7b4a940
AL
3153 break;
3154 }
3155
3156 /* Cleanup */
26f54e9a 3157 blk_unref(blk);
c2abccec
MK
3158 if (ret) {
3159 return 1;
3160 }
153859be 3161 return 0;
f7b4a940
AL
3162}
3163
3e85c6fd
KW
3164static int img_rebase(int argc, char **argv)
3165{
26f54e9a 3166 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
396374ca
PB
3167 uint8_t *buf_old = NULL;
3168 uint8_t *buf_new = NULL;
863cc78f 3169 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
3e85c6fd 3170 char *filename;
40055951
HR
3171 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3172 int c, flags, src_flags, ret;
ce099547 3173 bool writethrough, src_writethrough;
3e85c6fd 3174 int unsafe = 0;
335e9937 3175 bool force_share = false;
6b837bc4 3176 int progress = 0;
f382d43a 3177 bool quiet = false;
34b5d2c6 3178 Error *local_err = NULL;
eb769f74 3179 bool image_opts = false;
3e85c6fd
KW
3180
3181 /* Parse commandline parameters */
e53dbee0 3182 fmt = NULL;
661a0f71 3183 cache = BDRV_DEFAULT_CACHE;
40055951 3184 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
3185 out_baseimg = NULL;
3186 out_basefmt = NULL;
3e85c6fd 3187 for(;;) {
3babeb15
DB
3188 static const struct option long_options[] = {
3189 {"help", no_argument, 0, 'h'},
3190 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3191 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 3192 {"force-share", no_argument, 0, 'U'},
3babeb15
DB
3193 {0, 0, 0, 0}
3194 };
335e9937 3195 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
3babeb15 3196 long_options, NULL);
b8fb60da 3197 if (c == -1) {
3e85c6fd 3198 break;
b8fb60da 3199 }
3e85c6fd 3200 switch(c) {
c9192973
SH
3201 case ':':
3202 missing_argument(argv[optind - 1]);
3203 break;
ef87394c 3204 case '?':
c9192973
SH
3205 unrecognized_option(argv[optind - 1]);
3206 break;
3e85c6fd
KW
3207 case 'h':
3208 help();
3209 return 0;
e53dbee0
KW
3210 case 'f':
3211 fmt = optarg;
3212 break;
3e85c6fd
KW
3213 case 'F':
3214 out_basefmt = optarg;
3215 break;
3216 case 'b':
3217 out_baseimg = optarg;
3218 break;
3219 case 'u':
3220 unsafe = 1;
3221 break;
6b837bc4
JS
3222 case 'p':
3223 progress = 1;
3224 break;
661a0f71
FS
3225 case 't':
3226 cache = optarg;
3227 break;
40055951
HR
3228 case 'T':
3229 src_cache = optarg;
3230 break;
f382d43a
MR
3231 case 'q':
3232 quiet = true;
3233 break;
3babeb15
DB
3234 case OPTION_OBJECT: {
3235 QemuOpts *opts;
3236 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3237 optarg, true);
3238 if (!opts) {
3239 return 1;
3240 }
3241 } break;
eb769f74
DB
3242 case OPTION_IMAGE_OPTS:
3243 image_opts = true;
3244 break;
335e9937
FZ
3245 case 'U':
3246 force_share = true;
3247 break;
3e85c6fd
KW
3248 }
3249 }
3250
f382d43a
MR
3251 if (quiet) {
3252 progress = 0;
3253 }
3254
ac1307ab
FZ
3255 if (optind != argc - 1) {
3256 error_exit("Expecting one image file name");
3257 }
3258 if (!unsafe && !out_baseimg) {
3259 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
b8fb60da 3260 }
3e85c6fd
KW
3261 filename = argv[optind++];
3262
3babeb15
DB
3263 if (qemu_opts_foreach(&qemu_object_opts,
3264 user_creatable_add_opts_foreach,
334c43e2 3265 NULL, &error_fatal)) {
3babeb15
DB
3266 return 1;
3267 }
3268
6b837bc4
JS
3269 qemu_progress_init(progress, 2.0);
3270 qemu_progress_print(0, 100);
3271
661a0f71 3272 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
ce099547 3273 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
3274 if (ret < 0) {
3275 error_report("Invalid cache option: %s", cache);
40ed35a3 3276 goto out;
661a0f71
FS
3277 }
3278
ce099547
KW
3279 src_flags = 0;
3280 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
3281 if (ret < 0) {
3282 error_report("Invalid source cache option: %s", src_cache);
40ed35a3 3283 goto out;
40055951
HR
3284 }
3285
ce099547
KW
3286 /* The source files are opened read-only, don't care about WCE */
3287 assert((src_flags & BDRV_O_RDWR) == 0);
3288 (void) src_writethrough;
3289
3e85c6fd
KW
3290 /*
3291 * Open the images.
3292 *
3293 * Ignore the old backing file for unsafe rebase in case we want to correct
3294 * the reference to a renamed or moved backing file.
3295 */
335e9937
FZ
3296 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3297 false);
7e7d56d9 3298 if (!blk) {
40ed35a3
SH
3299 ret = -1;
3300 goto out;
c2abccec 3301 }
7e7d56d9 3302 bs = blk_bs(blk);
3e85c6fd 3303
3e85c6fd 3304 if (out_basefmt != NULL) {
644483d9 3305 if (bdrv_find_format(out_basefmt) == NULL) {
15654a6d 3306 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
3307 ret = -1;
3308 goto out;
3e85c6fd
KW
3309 }
3310 }
3311
3312 /* For safe rebasing we need to compare old and new backing file */
40ed35a3 3313 if (!unsafe) {
644483d9 3314 QDict *options = NULL;
4ebe0617 3315 BlockDriverState *base_bs = backing_bs(bs);
644483d9 3316
4ebe0617 3317 if (base_bs) {
d861ab3a
KW
3318 blk_old_backing = blk_new(qemu_get_aio_context(),
3319 BLK_PERM_CONSISTENT_READ,
4ebe0617
SE
3320 BLK_PERM_ALL);
3321 ret = blk_insert_bs(blk_old_backing, base_bs,
3322 &local_err);
3323 if (ret < 0) {
35ddd930 3324 error_reportf_err(local_err,
4ebe0617
SE
3325 "Could not reuse old backing file '%s': ",
3326 base_bs->filename);
35ddd930
HR
3327 goto out;
3328 }
3329 } else {
3330 blk_old_backing = NULL;
3e85c6fd 3331 }
644483d9 3332
a616673d 3333 if (out_baseimg[0]) {
d16699b6
HR
3334 const char *overlay_filename;
3335 char *out_real_path;
3336
335e9937 3337 options = qdict_new();
644483d9 3338 if (out_basefmt) {
46f5ac20 3339 qdict_put_str(options, "driver", out_basefmt);
335e9937
FZ
3340 }
3341 if (force_share) {
3342 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
644483d9
HR
3343 }
3344
f30c66ba 3345 bdrv_refresh_filename(bs);
d16699b6
HR
3346 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3347 : bs->filename;
645ae7d8
HR
3348 out_real_path =
3349 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3350 out_baseimg,
3351 &local_err);
d16699b6 3352 if (local_err) {
f22356d9 3353 qobject_unref(options);
d16699b6
HR
3354 error_reportf_err(local_err,
3355 "Could not resolve backing filename: ");
3356 ret = -1;
d16699b6
HR
3357 goto out;
3358 }
3359
863cc78f
SE
3360 /*
3361 * Find out whether we rebase an image on top of a previous image
3362 * in its chain.
3363 */
3364 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
330c7295 3365 if (prefix_chain_bs) {
f22356d9 3366 qobject_unref(options);
330c7295 3367 g_free(out_real_path);
f22356d9 3368
d861ab3a
KW
3369 blk_new_backing = blk_new(qemu_get_aio_context(),
3370 BLK_PERM_CONSISTENT_READ,
330c7295
SE
3371 BLK_PERM_ALL);
3372 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3373 &local_err);
3374 if (ret < 0) {
3375 error_reportf_err(local_err,
3376 "Could not reuse backing file '%s': ",
3377 out_baseimg);
3378 goto out;
3379 }
3380 } else {
3381 blk_new_backing = blk_new_open(out_real_path, NULL,
3382 options, src_flags, &local_err);
3383 g_free(out_real_path);
3384 if (!blk_new_backing) {
3385 error_reportf_err(local_err,
3386 "Could not open new backing file '%s': ",
3387 out_baseimg);
3388 ret = -1;
3389 goto out;
3390 }
a616673d 3391 }
3e85c6fd
KW
3392 }
3393 }
3394
3395 /*
3396 * Check each unallocated cluster in the COW file. If it is unallocated,
3397 * accesses go to the backing file. We must therefore compare this cluster
3398 * in the old and new backing file, and if they differ we need to copy it
3399 * from the old backing file into the COW file.
3400 *
3401 * If qemu-img crashes during this step, no harm is done. The content of
3402 * the image is the same as the original one at any time.
3403 */
3404 if (!unsafe) {
41536287 3405 int64_t size;
35ddd930 3406 int64_t old_backing_size = 0;
41536287
EB
3407 int64_t new_backing_size = 0;
3408 uint64_t offset;
3409 int64_t n;
1f710495 3410 float local_progress = 0;
d6771bfa 3411
f1d3cd79
HR
3412 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3413 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3e85c6fd 3414
41536287
EB
3415 size = blk_getlength(blk);
3416 if (size < 0) {
52bf1e72 3417 error_report("Could not get size of '%s': %s",
41536287 3418 filename, strerror(-size));
52bf1e72
MA
3419 ret = -1;
3420 goto out;
3421 }
35ddd930
HR
3422 if (blk_old_backing) {
3423 old_backing_size = blk_getlength(blk_old_backing);
3424 if (old_backing_size < 0) {
3425 char backing_name[PATH_MAX];
52bf1e72 3426
35ddd930
HR
3427 bdrv_get_backing_filename(bs, backing_name,
3428 sizeof(backing_name));
3429 error_report("Could not get size of '%s': %s",
3430 backing_name, strerror(-old_backing_size));
3431 ret = -1;
3432 goto out;
3433 }
52bf1e72 3434 }
f1d3cd79 3435 if (blk_new_backing) {
41536287
EB
3436 new_backing_size = blk_getlength(blk_new_backing);
3437 if (new_backing_size < 0) {
52bf1e72 3438 error_report("Could not get size of '%s': %s",
41536287 3439 out_baseimg, strerror(-new_backing_size));
52bf1e72
MA
3440 ret = -1;
3441 goto out;
3442 }
a616673d 3443 }
3e85c6fd 3444
41536287
EB
3445 if (size != 0) {
3446 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
1f710495
KW
3447 }
3448
41536287 3449 for (offset = 0; offset < size; offset += n) {
1c6e8779
HR
3450 bool buf_old_is_zero = false;
3451
41536287
EB
3452 /* How many bytes can we handle with the next read? */
3453 n = MIN(IO_BUF_SIZE, size - offset);
3e85c6fd
KW
3454
3455 /* If the cluster is allocated, we don't need to take action */
41536287 3456 ret = bdrv_is_allocated(bs, offset, n, &n);
d663640c
PB
3457 if (ret < 0) {
3458 error_report("error while reading image metadata: %s",
3459 strerror(-ret));
3460 goto out;
3461 }
cc60e327 3462 if (ret) {
3e85c6fd
KW
3463 continue;
3464 }
3465
863cc78f
SE
3466 if (prefix_chain_bs) {
3467 /*
3468 * If cluster wasn't changed since prefix_chain, we don't need
3469 * to take action
3470 */
3471 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
3472 offset, n, &n);
3473 if (ret < 0) {
3474 error_report("error while reading image metadata: %s",
3475 strerror(-ret));
3476 goto out;
3477 }
3478 if (!ret) {
3479 continue;
3480 }
3481 }
3482
87a1b3e3
KW
3483 /*
3484 * Read old and new backing file and take into consideration that
3485 * backing files may be smaller than the COW image.
3486 */
41536287
EB
3487 if (offset >= old_backing_size) {
3488 memset(buf_old, 0, n);
1c6e8779 3489 buf_old_is_zero = true;
87a1b3e3 3490 } else {
41536287
EB
3491 if (offset + n > old_backing_size) {
3492 n = old_backing_size - offset;
87a1b3e3
KW
3493 }
3494
41536287 3495 ret = blk_pread(blk_old_backing, offset, buf_old, n);
87a1b3e3
KW
3496 if (ret < 0) {
3497 error_report("error while reading from old backing file");
3498 goto out;
3499 }
3e85c6fd 3500 }
87a1b3e3 3501
41536287
EB
3502 if (offset >= new_backing_size || !blk_new_backing) {
3503 memset(buf_new, 0, n);
87a1b3e3 3504 } else {
41536287
EB
3505 if (offset + n > new_backing_size) {
3506 n = new_backing_size - offset;
87a1b3e3
KW
3507 }
3508
41536287 3509 ret = blk_pread(blk_new_backing, offset, buf_new, n);
87a1b3e3
KW
3510 if (ret < 0) {
3511 error_report("error while reading from new backing file");
3512 goto out;
3513 }
3e85c6fd
KW
3514 }
3515
3516 /* If they differ, we need to write to the COW file */
3517 uint64_t written = 0;
3518
41536287 3519 while (written < n) {
dc61cd3b 3520 int64_t pnum;
3e85c6fd 3521
41536287
EB
3522 if (compare_buffers(buf_old + written, buf_new + written,
3523 n - written, &pnum))
3e85c6fd 3524 {
1c6e8779
HR
3525 if (buf_old_is_zero) {
3526 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3527 } else {
3528 ret = blk_pwrite(blk, offset + written,
3529 buf_old + written, pnum, 0);
3530 }
3e85c6fd 3531 if (ret < 0) {
15654a6d 3532 error_report("Error while writing to COW image: %s",
3e85c6fd 3533 strerror(-ret));
c2abccec 3534 goto out;
3e85c6fd
KW
3535 }
3536 }
3537
3538 written += pnum;
3539 }
6b837bc4 3540 qemu_progress_print(local_progress, 100);
3e85c6fd
KW
3541 }
3542 }
3543
3544 /*
3545 * Change the backing file. All clusters that are different from the old
3546 * backing file are overwritten in the COW file now, so the visible content
3547 * doesn't change when we switch the backing file.
3548 */
a616673d
AB
3549 if (out_baseimg && *out_baseimg) {
3550 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3551 } else {
3552 ret = bdrv_change_backing_file(bs, NULL, NULL);
3553 }
3554
3e85c6fd 3555 if (ret == -ENOSPC) {
15654a6d
JS
3556 error_report("Could not change the backing file to '%s': No "
3557 "space left in the file header", out_baseimg);
3e85c6fd 3558 } else if (ret < 0) {
15654a6d 3559 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
3560 out_baseimg, strerror(-ret));
3561 }
3562
6b837bc4 3563 qemu_progress_print(100, 0);
3e85c6fd
KW
3564 /*
3565 * TODO At this point it is possible to check if any clusters that are
3566 * allocated in the COW file are the same in the backing file. If so, they
3567 * could be dropped from the COW file. Don't do this before switching the
3568 * backing file, in case of a crash this would lead to corruption.
3569 */
c2abccec 3570out:
6b837bc4 3571 qemu_progress_end();
3e85c6fd
KW
3572 /* Cleanup */
3573 if (!unsafe) {
26f54e9a 3574 blk_unref(blk_old_backing);
26f54e9a 3575 blk_unref(blk_new_backing);
3e85c6fd 3576 }
396374ca
PB
3577 qemu_vfree(buf_old);
3578 qemu_vfree(buf_new);
3e85c6fd 3579
26f54e9a 3580 blk_unref(blk);
c2abccec
MK
3581 if (ret) {
3582 return 1;
3583 }
3e85c6fd
KW
3584 return 0;
3585}
3586
ae6b0ed6
SH
3587static int img_resize(int argc, char **argv)
3588{
6750e795 3589 Error *err = NULL;
ae6b0ed6
SH
3590 int c, ret, relative;
3591 const char *filename, *fmt, *size;
5279b303 3592 int64_t n, total_size, current_size, new_size;
f382d43a 3593 bool quiet = false;
26f54e9a 3594 BlockBackend *blk = NULL;
dc5f690b 3595 PreallocMode prealloc = PREALLOC_MODE_OFF;
20caf0f7 3596 QemuOpts *param;
3babeb15 3597
20caf0f7
DXW
3598 static QemuOptsList resize_options = {
3599 .name = "resize_options",
3600 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3601 .desc = {
3602 {
3603 .name = BLOCK_OPT_SIZE,
3604 .type = QEMU_OPT_SIZE,
3605 .help = "Virtual disk size"
3606 }, {
3607 /* end of list */
3608 }
ae6b0ed6 3609 },
ae6b0ed6 3610 };
eb769f74 3611 bool image_opts = false;
4ffca890 3612 bool shrink = false;
ae6b0ed6 3613
e80fec7f
KW
3614 /* Remove size from argv manually so that negative numbers are not treated
3615 * as options by getopt. */
3616 if (argc < 3) {
ac1307ab 3617 error_exit("Not enough arguments");
e80fec7f
KW
3618 return 1;
3619 }
3620
3621 size = argv[--argc];
3622
3623 /* Parse getopt arguments */
ae6b0ed6
SH
3624 fmt = NULL;
3625 for(;;) {
3babeb15
DB
3626 static const struct option long_options[] = {
3627 {"help", no_argument, 0, 'h'},
3628 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3629 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
dc5f690b 3630 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
4ffca890 3631 {"shrink", no_argument, 0, OPTION_SHRINK},
3babeb15
DB
3632 {0, 0, 0, 0}
3633 };
c9192973 3634 c = getopt_long(argc, argv, ":f:hq",
3babeb15 3635 long_options, NULL);
ae6b0ed6
SH
3636 if (c == -1) {
3637 break;
3638 }
3639 switch(c) {
c9192973
SH
3640 case ':':
3641 missing_argument(argv[optind - 1]);
3642 break;
ef87394c 3643 case '?':
c9192973
SH
3644 unrecognized_option(argv[optind - 1]);
3645 break;
ae6b0ed6
SH
3646 case 'h':
3647 help();
3648 break;
3649 case 'f':
3650 fmt = optarg;
3651 break;
f382d43a
MR
3652 case 'q':
3653 quiet = true;
3654 break;
3babeb15
DB
3655 case OPTION_OBJECT: {
3656 QemuOpts *opts;
3657 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3658 optarg, true);
3659 if (!opts) {
3660 return 1;
3661 }
3662 } break;
eb769f74
DB
3663 case OPTION_IMAGE_OPTS:
3664 image_opts = true;
3665 break;
dc5f690b 3666 case OPTION_PREALLOCATION:
f7abe0ec 3667 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
06c60b6c 3668 PREALLOC_MODE__MAX, NULL);
dc5f690b
HR
3669 if (prealloc == PREALLOC_MODE__MAX) {
3670 error_report("Invalid preallocation mode '%s'", optarg);
3671 return 1;
3672 }
3673 break;
4ffca890
PB
3674 case OPTION_SHRINK:
3675 shrink = true;
3676 break;
ae6b0ed6
SH
3677 }
3678 }
fc11eb26 3679 if (optind != argc - 1) {
be8fbd47 3680 error_exit("Expecting image file name and size");
ae6b0ed6
SH
3681 }
3682 filename = argv[optind++];
ae6b0ed6 3683
3babeb15
DB
3684 if (qemu_opts_foreach(&qemu_object_opts,
3685 user_creatable_add_opts_foreach,
334c43e2 3686 NULL, &error_fatal)) {
3babeb15
DB
3687 return 1;
3688 }
3689
ae6b0ed6
SH
3690 /* Choose grow, shrink, or absolute resize mode */
3691 switch (size[0]) {
3692 case '+':
3693 relative = 1;
3694 size++;
3695 break;
3696 case '-':
3697 relative = -1;
3698 size++;
3699 break;
3700 default:
3701 relative = 0;
3702 break;
3703 }
3704
3705 /* Parse size */
87ea75d5 3706 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
f43e47db 3707 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
6750e795
MA
3708 if (err) {
3709 error_report_err(err);
2a81998a 3710 ret = -1;
20caf0f7 3711 qemu_opts_del(param);
2a81998a 3712 goto out;
ae6b0ed6 3713 }
20caf0f7
DXW
3714 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3715 qemu_opts_del(param);
ae6b0ed6 3716
efaa7c4e 3717 blk = img_open(image_opts, filename, fmt,
335e9937
FZ
3718 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3719 false);
7e7d56d9 3720 if (!blk) {
2a81998a
JS
3721 ret = -1;
3722 goto out;
c2abccec 3723 }
ae6b0ed6 3724
dc5f690b
HR
3725 current_size = blk_getlength(blk);
3726 if (current_size < 0) {
3727 error_report("Failed to inquire current image length: %s",
3728 strerror(-current_size));
3729 ret = -1;
3730 goto out;
3731 }
3732
ae6b0ed6 3733 if (relative) {
dc5f690b 3734 total_size = current_size + n * relative;
ae6b0ed6
SH
3735 } else {
3736 total_size = n;
3737 }
3738 if (total_size <= 0) {
15654a6d 3739 error_report("New image size must be positive");
c2abccec
MK
3740 ret = -1;
3741 goto out;
ae6b0ed6
SH
3742 }
3743
dc5f690b
HR
3744 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3745 error_report("Preallocation can only be used for growing images");
3746 ret = -1;
3747 goto out;
3748 }
3749
4ffca890
PB
3750 if (total_size < current_size && !shrink) {
3751 warn_report("Shrinking an image will delete all data beyond the "
3752 "shrunken image's end. Before performing such an "
3753 "operation, make sure there is no important data there.");
3754
3755 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3756 error_report(
3757 "Use the --shrink option to perform a shrink operation.");
3758 ret = -1;
3759 goto out;
3760 } else {
3761 warn_report("Using the --shrink option will suppress this message. "
3762 "Note that future versions of qemu-img may refuse to "
3763 "shrink images without this option.");
3764 }
3765 }
3766
dc5f690b 3767 ret = blk_truncate(blk, total_size, prealloc, &err);
5279b303 3768 if (ret < 0) {
ed3d2ec9 3769 error_report_err(err);
5279b303
HR
3770 goto out;
3771 }
3772
3773 new_size = blk_getlength(blk);
3774 if (new_size < 0) {
3775 error_report("Failed to verify truncated image length: %s",
3776 strerror(-new_size));
3777 ret = -1;
3778 goto out;
ae6b0ed6 3779 }
5279b303
HR
3780
3781 /* Some block drivers implement a truncation method, but only so
3782 * the user can cause qemu to refresh the image's size from disk.
3783 * The idea is that the user resizes the image outside of qemu and
3784 * then invokes block_resize to inform qemu about it.
3785 * (This includes iscsi and file-posix for device files.)
3786 * Of course, that is not the behavior someone invoking
3787 * qemu-img resize would find useful, so we catch that behavior
3788 * here and tell the user. */
3789 if (new_size != total_size && new_size == current_size) {
3790 error_report("Image was not resized; resizing may not be supported "
3791 "for this image");
3792 ret = -1;
3793 goto out;
3794 }
3795
3796 if (new_size != total_size) {
3797 warn_report("Image should have been resized to %" PRIi64
3798 " bytes, but was resized to %" PRIi64 " bytes",
3799 total_size, new_size);
3800 }
3801
3802 qprintf(quiet, "Image resized.\n");
3803
c2abccec 3804out:
26f54e9a 3805 blk_unref(blk);
c2abccec
MK
3806 if (ret) {
3807 return 1;
3808 }
ae6b0ed6
SH
3809 return 0;
3810}
3811
76a3a34d 3812static void amend_status_cb(BlockDriverState *bs,
8b13976d
HR
3813 int64_t offset, int64_t total_work_size,
3814 void *opaque)
76a3a34d
HR
3815{
3816 qemu_progress_print(100.f * offset / total_work_size, 0);
3817}
3818
51641351
HR
3819static int print_amend_option_help(const char *format)
3820{
3821 BlockDriver *drv;
3822
3823 /* Find driver and parse its options */
3824 drv = bdrv_find_format(format);
3825 if (!drv) {
3826 error_report("Unknown file format '%s'", format);
3827 return 1;
3828 }
3829
3830 if (!drv->bdrv_amend_options) {
3831 error_report("Format driver '%s' does not support option amendment",
3832 format);
3833 return 1;
3834 }
3835
3836 /* Every driver supporting amendment must have create_opts */
3837 assert(drv->create_opts);
3838
3839 printf("Creation options for '%s':\n", format);
63898712 3840 qemu_opts_print_help(drv->create_opts, false);
51641351
HR
3841 printf("\nNote that not all of these options may be amendable.\n");
3842 return 0;
3843}
3844
6f176b48
HR
3845static int img_amend(int argc, char **argv)
3846{
dc523cd3 3847 Error *err = NULL;
6f176b48
HR
3848 int c, ret = 0;
3849 char *options = NULL;
83d0521a
CL
3850 QemuOptsList *create_opts = NULL;
3851 QemuOpts *opts = NULL;
bd39e6ed
HR
3852 const char *fmt = NULL, *filename, *cache;
3853 int flags;
ce099547 3854 bool writethrough;
76a3a34d 3855 bool quiet = false, progress = false;
26f54e9a 3856 BlockBackend *blk = NULL;
6f176b48 3857 BlockDriverState *bs = NULL;
eb769f74 3858 bool image_opts = false;
6f176b48 3859
bd39e6ed 3860 cache = BDRV_DEFAULT_CACHE;
6f176b48 3861 for (;;) {
3babeb15
DB
3862 static const struct option long_options[] = {
3863 {"help", no_argument, 0, 'h'},
3864 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3865 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3866 {0, 0, 0, 0}
3867 };
c9192973 3868 c = getopt_long(argc, argv, ":ho:f:t:pq",
3babeb15 3869 long_options, NULL);
6f176b48
HR
3870 if (c == -1) {
3871 break;
3872 }
3873
3874 switch (c) {
c9192973
SH
3875 case ':':
3876 missing_argument(argv[optind - 1]);
3877 break;
f7077624 3878 case '?':
c9192973
SH
3879 unrecognized_option(argv[optind - 1]);
3880 break;
3881 case 'h':
f7077624
SH
3882 help();
3883 break;
3884 case 'o':
3885 if (!is_valid_option_list(optarg)) {
3886 error_report("Invalid option list: %s", optarg);
3887 ret = -1;
3888 goto out_no_progress;
3889 }
3890 if (!options) {
3891 options = g_strdup(optarg);
3892 } else {
3893 char *old_options = options;
3894 options = g_strdup_printf("%s,%s", options, optarg);
3895 g_free(old_options);
3896 }
3897 break;
3898 case 'f':
3899 fmt = optarg;
3900 break;
3901 case 't':
3902 cache = optarg;
3903 break;
3904 case 'p':
3905 progress = true;
3906 break;
3907 case 'q':
3908 quiet = true;
3909 break;
3910 case OPTION_OBJECT:
3911 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3912 optarg, true);
3913 if (!opts) {
3914 ret = -1;
3915 goto out_no_progress;
3916 }
3917 break;
3918 case OPTION_IMAGE_OPTS:
3919 image_opts = true;
3920 break;
6f176b48
HR
3921 }
3922 }
3923
a283cb6e 3924 if (!options) {
ac1307ab 3925 error_exit("Must specify options (-o)");
6f176b48
HR
3926 }
3927
3babeb15
DB
3928 if (qemu_opts_foreach(&qemu_object_opts,
3929 user_creatable_add_opts_foreach,
334c43e2 3930 NULL, &error_fatal)) {
3babeb15
DB
3931 ret = -1;
3932 goto out_no_progress;
3933 }
3934
76a3a34d
HR
3935 if (quiet) {
3936 progress = false;
3937 }
3938 qemu_progress_init(progress, 1.0);
3939
a283cb6e
KW
3940 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3941 if (fmt && has_help_option(options)) {
3942 /* If a format is explicitly specified (and possibly no filename is
3943 * given), print option help here */
51641351 3944 ret = print_amend_option_help(fmt);
a283cb6e 3945 goto out;
6f176b48
HR
3946 }
3947
a283cb6e 3948 if (optind != argc - 1) {
b2f27e44
HR
3949 error_report("Expecting one image file name");
3950 ret = -1;
3951 goto out;
a283cb6e 3952 }
6f176b48 3953
ce099547
KW
3954 flags = BDRV_O_RDWR;
3955 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
bd39e6ed
HR
3956 if (ret < 0) {
3957 error_report("Invalid cache option: %s", cache);
3958 goto out;
3959 }
3960
335e9937
FZ
3961 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3962 false);
7e7d56d9 3963 if (!blk) {
6f176b48
HR
3964 ret = -1;
3965 goto out;
3966 }
7e7d56d9 3967 bs = blk_bs(blk);
6f176b48
HR
3968
3969 fmt = bs->drv->format_name;
3970
626f84f3 3971 if (has_help_option(options)) {
a283cb6e 3972 /* If the format was auto-detected, print option help here */
51641351 3973 ret = print_amend_option_help(fmt);
6f176b48
HR
3974 goto out;
3975 }
3976
1f996683
HR
3977 if (!bs->drv->bdrv_amend_options) {
3978 error_report("Format driver '%s' does not support option amendment",
b2439d26
HR
3979 fmt);
3980 ret = -1;
3981 goto out;
3982 }
3983
1f996683
HR
3984 /* Every driver supporting amendment must have create_opts */
3985 assert(bs->drv->create_opts);
3986
c282e1fd 3987 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a 3988 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
ece9086e
PB
3989 qemu_opts_do_parse(opts, options, NULL, &err);
3990 if (err) {
3991 error_report_err(err);
3992 ret = -1;
3993 goto out;
6f176b48
HR
3994 }
3995
76a3a34d
HR
3996 /* In case the driver does not call amend_status_cb() */
3997 qemu_progress_print(0.f, 0);
d1402b50 3998 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
76a3a34d 3999 qemu_progress_print(100.f, 0);
6f176b48 4000 if (ret < 0) {
d1402b50 4001 error_report_err(err);
6f176b48
HR
4002 goto out;
4003 }
4004
4005out:
76a3a34d
HR
4006 qemu_progress_end();
4007
e814dffc 4008out_no_progress:
26f54e9a 4009 blk_unref(blk);
83d0521a
CL
4010 qemu_opts_del(opts);
4011 qemu_opts_free(create_opts);
626f84f3
KW
4012 g_free(options);
4013
6f176b48
HR
4014 if (ret) {
4015 return 1;
4016 }
4017 return 0;
4018}
4019
b6133b8c
KW
4020typedef struct BenchData {
4021 BlockBackend *blk;
4022 uint64_t image_size;
b6495fa8 4023 bool write;
b6133b8c 4024 int bufsize;
83de9be0 4025 int step;
b6133b8c
KW
4026 int nrreq;
4027 int n;
55d539c8
KW
4028 int flush_interval;
4029 bool drain_on_flush;
b6133b8c
KW
4030 uint8_t *buf;
4031 QEMUIOVector *qiov;
4032
4033 int in_flight;
55d539c8 4034 bool in_flush;
b6133b8c
KW
4035 uint64_t offset;
4036} BenchData;
4037
55d539c8
KW
4038static void bench_undrained_flush_cb(void *opaque, int ret)
4039{
4040 if (ret < 0) {
df3c286c 4041 error_report("Failed flush request: %s", strerror(-ret));
55d539c8
KW
4042 exit(EXIT_FAILURE);
4043 }
4044}
4045
b6133b8c
KW
4046static void bench_cb(void *opaque, int ret)
4047{
4048 BenchData *b = opaque;
4049 BlockAIOCB *acb;
4050
4051 if (ret < 0) {
df3c286c 4052 error_report("Failed request: %s", strerror(-ret));
b6133b8c
KW
4053 exit(EXIT_FAILURE);
4054 }
55d539c8
KW
4055
4056 if (b->in_flush) {
4057 /* Just finished a flush with drained queue: Start next requests */
4058 assert(b->in_flight == 0);
4059 b->in_flush = false;
4060 } else if (b->in_flight > 0) {
4061 int remaining = b->n - b->in_flight;
4062
b6133b8c
KW
4063 b->n--;
4064 b->in_flight--;
55d539c8
KW
4065
4066 /* Time for flush? Drain queue if requested, then flush */
4067 if (b->flush_interval && remaining % b->flush_interval == 0) {
4068 if (!b->in_flight || !b->drain_on_flush) {
4069 BlockCompletionFunc *cb;
4070
4071 if (b->drain_on_flush) {
4072 b->in_flush = true;
4073 cb = bench_cb;
4074 } else {
4075 cb = bench_undrained_flush_cb;
4076 }
4077
4078 acb = blk_aio_flush(b->blk, cb, b);
4079 if (!acb) {
4080 error_report("Failed to issue flush request");
4081 exit(EXIT_FAILURE);
4082 }
4083 }
4084 if (b->drain_on_flush) {
4085 return;
4086 }
4087 }
b6133b8c
KW
4088 }
4089
4090 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
4baaa8c3
PB
4091 int64_t offset = b->offset;
4092 /* blk_aio_* might look for completed I/Os and kick bench_cb
4093 * again, so make sure this operation is counted by in_flight
4094 * and b->offset is ready for the next submission.
4095 */
4096 b->in_flight++;
4097 b->offset += b->step;
4098 b->offset %= b->image_size;
b6495fa8 4099 if (b->write) {
4baaa8c3 4100 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
b6495fa8 4101 } else {
4baaa8c3 4102 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
b6495fa8 4103 }
b6133b8c
KW
4104 if (!acb) {
4105 error_report("Failed to issue request");
4106 exit(EXIT_FAILURE);
4107 }
b6133b8c
KW
4108 }
4109}
4110
4111static int img_bench(int argc, char **argv)
4112{
4113 int c, ret = 0;
4114 const char *fmt = NULL, *filename;
4115 bool quiet = false;
4116 bool image_opts = false;
b6495fa8 4117 bool is_write = false;
b6133b8c
KW
4118 int count = 75000;
4119 int depth = 64;
d3199a31 4120 int64_t offset = 0;
b6133b8c 4121 size_t bufsize = 4096;
b6495fa8 4122 int pattern = 0;
83de9be0 4123 size_t step = 0;
55d539c8
KW
4124 int flush_interval = 0;
4125 bool drain_on_flush = true;
b6133b8c
KW
4126 int64_t image_size;
4127 BlockBackend *blk = NULL;
4128 BenchData data = {};
4129 int flags = 0;
604e8613 4130 bool writethrough = false;
b6133b8c
KW
4131 struct timeval t1, t2;
4132 int i;
335e9937 4133 bool force_share = false;
79d46583 4134 size_t buf_size;
b6133b8c
KW
4135
4136 for (;;) {
4137 static const struct option long_options[] = {
4138 {"help", no_argument, 0, 'h'},
55d539c8 4139 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
b6133b8c 4140 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
b6495fa8 4141 {"pattern", required_argument, 0, OPTION_PATTERN},
55d539c8 4142 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
335e9937 4143 {"force-share", no_argument, 0, 'U'},
b6133b8c
KW
4144 {0, 0, 0, 0}
4145 };
335e9937 4146 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
b6133b8c
KW
4147 if (c == -1) {
4148 break;
4149 }
4150
4151 switch (c) {
c9192973
SH
4152 case ':':
4153 missing_argument(argv[optind - 1]);
4154 break;
b6133b8c 4155 case '?':
c9192973
SH
4156 unrecognized_option(argv[optind - 1]);
4157 break;
4158 case 'h':
b6133b8c
KW
4159 help();
4160 break;
4161 case 'c':
4162 {
8b3c6792
PM
4163 unsigned long res;
4164
4165 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
b6133b8c
KW
4166 error_report("Invalid request count specified");
4167 return 1;
4168 }
8b3c6792 4169 count = res;
b6133b8c
KW
4170 break;
4171 }
4172 case 'd':
4173 {
8b3c6792
PM
4174 unsigned long res;
4175
4176 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
b6133b8c
KW
4177 error_report("Invalid queue depth specified");
4178 return 1;
4179 }
8b3c6792 4180 depth = res;
b6133b8c
KW
4181 break;
4182 }
4183 case 'f':
4184 fmt = optarg;
4185 break;
4186 case 'n':
4187 flags |= BDRV_O_NATIVE_AIO;
4188 break;
d3199a31
KW
4189 case 'o':
4190 {
606caa0a
MA
4191 offset = cvtnum(optarg);
4192 if (offset < 0) {
d3199a31
KW
4193 error_report("Invalid offset specified");
4194 return 1;
4195 }
4196 break;
4197 }
4198 break;
b6133b8c
KW
4199 case 'q':
4200 quiet = true;
4201 break;
4202 case 's':
4203 {
4204 int64_t sval;
b6133b8c 4205
606caa0a
MA
4206 sval = cvtnum(optarg);
4207 if (sval < 0 || sval > INT_MAX) {
b6133b8c
KW
4208 error_report("Invalid buffer size specified");
4209 return 1;
4210 }
4211
4212 bufsize = sval;
4213 break;
4214 }
83de9be0
KW
4215 case 'S':
4216 {
4217 int64_t sval;
83de9be0 4218
606caa0a
MA
4219 sval = cvtnum(optarg);
4220 if (sval < 0 || sval > INT_MAX) {
83de9be0
KW
4221 error_report("Invalid step size specified");
4222 return 1;
4223 }
4224
4225 step = sval;
4226 break;
4227 }
b6133b8c
KW
4228 case 't':
4229 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4230 if (ret < 0) {
4231 error_report("Invalid cache mode");
4232 ret = -1;
4233 goto out;
4234 }
4235 break;
b6495fa8
KW
4236 case 'w':
4237 flags |= BDRV_O_RDWR;
4238 is_write = true;
4239 break;
335e9937
FZ
4240 case 'U':
4241 force_share = true;
4242 break;
b6495fa8
KW
4243 case OPTION_PATTERN:
4244 {
8b3c6792
PM
4245 unsigned long res;
4246
4247 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
b6495fa8
KW
4248 error_report("Invalid pattern byte specified");
4249 return 1;
4250 }
8b3c6792 4251 pattern = res;
b6495fa8
KW
4252 break;
4253 }
55d539c8
KW
4254 case OPTION_FLUSH_INTERVAL:
4255 {
8b3c6792
PM
4256 unsigned long res;
4257
4258 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
55d539c8
KW
4259 error_report("Invalid flush interval specified");
4260 return 1;
4261 }
8b3c6792 4262 flush_interval = res;
55d539c8
KW
4263 break;
4264 }
4265 case OPTION_NO_DRAIN:
4266 drain_on_flush = false;
4267 break;
b6133b8c
KW
4268 case OPTION_IMAGE_OPTS:
4269 image_opts = true;
4270 break;
4271 }
4272 }
4273
4274 if (optind != argc - 1) {
4275 error_exit("Expecting one image file name");
4276 }
4277 filename = argv[argc - 1];
4278
55d539c8
KW
4279 if (!is_write && flush_interval) {
4280 error_report("--flush-interval is only available in write tests");
4281 ret = -1;
4282 goto out;
4283 }
4284 if (flush_interval && flush_interval < depth) {
4285 error_report("Flush interval can't be smaller than depth");
4286 ret = -1;
4287 goto out;
4288 }
4289
335e9937
FZ
4290 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4291 force_share);
b6133b8c
KW
4292 if (!blk) {
4293 ret = -1;
4294 goto out;
4295 }
4296
4297 image_size = blk_getlength(blk);
4298 if (image_size < 0) {
4299 ret = image_size;
4300 goto out;
4301 }
4302
4303 data = (BenchData) {
55d539c8
KW
4304 .blk = blk,
4305 .image_size = image_size,
4306 .bufsize = bufsize,
4307 .step = step ?: bufsize,
4308 .nrreq = depth,
4309 .n = count,
4310 .offset = offset,
4311 .write = is_write,
4312 .flush_interval = flush_interval,
4313 .drain_on_flush = drain_on_flush,
b6133b8c 4314 };
d3199a31 4315 printf("Sending %d %s requests, %d bytes each, %d in parallel "
83de9be0 4316 "(starting at offset %" PRId64 ", step size %d)\n",
d3199a31 4317 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
83de9be0 4318 data.offset, data.step);
55d539c8
KW
4319 if (flush_interval) {
4320 printf("Sending flush every %d requests\n", flush_interval);
4321 }
b6133b8c 4322
79d46583
FZ
4323 buf_size = data.nrreq * data.bufsize;
4324 data.buf = blk_blockalign(blk, buf_size);
b6495fa8
KW
4325 memset(data.buf, pattern, data.nrreq * data.bufsize);
4326
79d46583
FZ
4327 blk_register_buf(blk, data.buf, buf_size);
4328
b6133b8c
KW
4329 data.qiov = g_new(QEMUIOVector, data.nrreq);
4330 for (i = 0; i < data.nrreq; i++) {
4331 qemu_iovec_init(&data.qiov[i], 1);
4332 qemu_iovec_add(&data.qiov[i],
4333 data.buf + i * data.bufsize, data.bufsize);
4334 }
4335
4336 gettimeofday(&t1, NULL);
4337 bench_cb(&data, 0);
4338
4339 while (data.n > 0) {
4340 main_loop_wait(false);
4341 }
4342 gettimeofday(&t2, NULL);
4343
4344 printf("Run completed in %3.3f seconds.\n",
4345 (t2.tv_sec - t1.tv_sec)
4346 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4347
4348out:
79d46583
FZ
4349 if (data.buf) {
4350 blk_unregister_buf(blk, data.buf);
4351 }
b6133b8c
KW
4352 qemu_vfree(data.buf);
4353 blk_unref(blk);
4354
4355 if (ret) {
86ce1f6e
RS
4356 return 1;
4357 }
4358 return 0;
4359}
4360
4361#define C_BS 01
4362#define C_COUNT 02
4363#define C_IF 04
4364#define C_OF 010
f7c15533 4365#define C_SKIP 020
86ce1f6e
RS
4366
4367struct DdInfo {
4368 unsigned int flags;
4369 int64_t count;
4370};
4371
4372struct DdIo {
4373 int bsz; /* Block size */
4374 char *filename;
4375 uint8_t *buf;
f7c15533 4376 int64_t offset;
86ce1f6e
RS
4377};
4378
4379struct DdOpts {
4380 const char *name;
4381 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4382 unsigned int flag;
4383};
4384
4385static int img_dd_bs(const char *arg,
4386 struct DdIo *in, struct DdIo *out,
4387 struct DdInfo *dd)
4388{
86ce1f6e
RS
4389 int64_t res;
4390
606caa0a 4391 res = cvtnum(arg);
86ce1f6e 4392
606caa0a 4393 if (res <= 0 || res > INT_MAX) {
86ce1f6e
RS
4394 error_report("invalid number: '%s'", arg);
4395 return 1;
4396 }
4397 in->bsz = out->bsz = res;
4398
4399 return 0;
4400}
4401
4402static int img_dd_count(const char *arg,
4403 struct DdIo *in, struct DdIo *out,
4404 struct DdInfo *dd)
4405{
606caa0a 4406 dd->count = cvtnum(arg);
86ce1f6e 4407
606caa0a 4408 if (dd->count < 0) {
86ce1f6e
RS
4409 error_report("invalid number: '%s'", arg);
4410 return 1;
4411 }
4412
4413 return 0;
4414}
4415
4416static int img_dd_if(const char *arg,
4417 struct DdIo *in, struct DdIo *out,
4418 struct DdInfo *dd)
4419{
4420 in->filename = g_strdup(arg);
4421
4422 return 0;
4423}
4424
4425static int img_dd_of(const char *arg,
4426 struct DdIo *in, struct DdIo *out,
4427 struct DdInfo *dd)
4428{
4429 out->filename = g_strdup(arg);
4430
4431 return 0;
4432}
4433
f7c15533
RS
4434static int img_dd_skip(const char *arg,
4435 struct DdIo *in, struct DdIo *out,
4436 struct DdInfo *dd)
4437{
606caa0a 4438 in->offset = cvtnum(arg);
f7c15533 4439
606caa0a 4440 if (in->offset < 0) {
f7c15533
RS
4441 error_report("invalid number: '%s'", arg);
4442 return 1;
4443 }
4444
4445 return 0;
4446}
4447
86ce1f6e
RS
4448static int img_dd(int argc, char **argv)
4449{
4450 int ret = 0;
4451 char *arg = NULL;
4452 char *tmp;
4453 BlockDriver *drv = NULL, *proto_drv = NULL;
4454 BlockBackend *blk1 = NULL, *blk2 = NULL;
4455 QemuOpts *opts = NULL;
4456 QemuOptsList *create_opts = NULL;
4457 Error *local_err = NULL;
4458 bool image_opts = false;
4459 int c, i;
4460 const char *out_fmt = "raw";
4461 const char *fmt = NULL;
4462 int64_t size = 0;
4463 int64_t block_count = 0, out_pos, in_pos;
335e9937 4464 bool force_share = false;
86ce1f6e
RS
4465 struct DdInfo dd = {
4466 .flags = 0,
4467 .count = 0,
4468 };
4469 struct DdIo in = {
4470 .bsz = 512, /* Block size is by default 512 bytes */
4471 .filename = NULL,
f7c15533
RS
4472 .buf = NULL,
4473 .offset = 0
86ce1f6e
RS
4474 };
4475 struct DdIo out = {
4476 .bsz = 512,
4477 .filename = NULL,
f7c15533
RS
4478 .buf = NULL,
4479 .offset = 0
86ce1f6e
RS
4480 };
4481
4482 const struct DdOpts options[] = {
4483 { "bs", img_dd_bs, C_BS },
4484 { "count", img_dd_count, C_COUNT },
4485 { "if", img_dd_if, C_IF },
4486 { "of", img_dd_of, C_OF },
f7c15533 4487 { "skip", img_dd_skip, C_SKIP },
86ce1f6e
RS
4488 { NULL, NULL, 0 }
4489 };
4490 const struct option long_options[] = {
4491 { "help", no_argument, 0, 'h'},
83d4bf94 4492 { "object", required_argument, 0, OPTION_OBJECT},
86ce1f6e 4493 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
335e9937 4494 { "force-share", no_argument, 0, 'U'},
86ce1f6e
RS
4495 { 0, 0, 0, 0 }
4496 };
4497
335e9937 4498 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
86ce1f6e
RS
4499 if (c == EOF) {
4500 break;
4501 }
4502 switch (c) {
4503 case 'O':
4504 out_fmt = optarg;
4505 break;
4506 case 'f':
4507 fmt = optarg;
4508 break;
c9192973
SH
4509 case ':':
4510 missing_argument(argv[optind - 1]);
4511 break;
86ce1f6e 4512 case '?':
c9192973
SH
4513 unrecognized_option(argv[optind - 1]);
4514 break;
86ce1f6e
RS
4515 case 'h':
4516 help();
4517 break;
335e9937
FZ
4518 case 'U':
4519 force_share = true;
4520 break;
2a245709
SH
4521 case OPTION_OBJECT:
4522 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
83d4bf94
DB
4523 ret = -1;
4524 goto out;
4525 }
2a245709 4526 break;
86ce1f6e
RS
4527 case OPTION_IMAGE_OPTS:
4528 image_opts = true;
4529 break;
4530 }
4531 }
4532
4533 for (i = optind; i < argc; i++) {
4534 int j;
4535 arg = g_strdup(argv[i]);
4536
4537 tmp = strchr(arg, '=');
4538 if (tmp == NULL) {
4539 error_report("unrecognized operand %s", arg);
4540 ret = -1;
4541 goto out;
4542 }
4543
4544 *tmp++ = '\0';
4545
4546 for (j = 0; options[j].name != NULL; j++) {
4547 if (!strcmp(arg, options[j].name)) {
4548 break;
4549 }
4550 }
4551 if (options[j].name == NULL) {
4552 error_report("unrecognized operand %s", arg);
4553 ret = -1;
4554 goto out;
4555 }
4556
4557 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4558 ret = -1;
4559 goto out;
4560 }
4561 dd.flags |= options[j].flag;
4562 g_free(arg);
4563 arg = NULL;
4564 }
4565
4566 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4567 error_report("Must specify both input and output files");
4568 ret = -1;
4569 goto out;
4570 }
83d4bf94
DB
4571
4572 if (qemu_opts_foreach(&qemu_object_opts,
4573 user_creatable_add_opts_foreach,
334c43e2 4574 NULL, &error_fatal)) {
83d4bf94
DB
4575 ret = -1;
4576 goto out;
4577 }
4578
335e9937
FZ
4579 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4580 force_share);
86ce1f6e
RS
4581
4582 if (!blk1) {
4583 ret = -1;
4584 goto out;
4585 }
4586
4587 drv = bdrv_find_format(out_fmt);
4588 if (!drv) {
4589 error_report("Unknown file format");
4590 ret = -1;
4591 goto out;
4592 }
4593 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4594
4595 if (!proto_drv) {
4596 error_report_err(local_err);
4597 ret = -1;
4598 goto out;
4599 }
4600 if (!drv->create_opts) {
4601 error_report("Format driver '%s' does not support image creation",
4602 drv->format_name);
4603 ret = -1;
4604 goto out;
4605 }
4606 if (!proto_drv->create_opts) {
4607 error_report("Protocol driver '%s' does not support image creation",
4608 proto_drv->format_name);
4609 ret = -1;
4610 goto out;
4611 }
4612 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4613 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4614
4615 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4616
4617 size = blk_getlength(blk1);
4618 if (size < 0) {
4619 error_report("Failed to get size for '%s'", in.filename);
4620 ret = -1;
4621 goto out;
4622 }
4623
4624 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4625 dd.count * in.bsz < size) {
4626 size = dd.count * in.bsz;
4627 }
4628
f7c15533
RS
4629 /* Overflow means the specified offset is beyond input image's size */
4630 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4631 size < in.bsz * in.offset)) {
4632 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4633 } else {
4634 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4635 size - in.bsz * in.offset, &error_abort);
4636 }
86ce1f6e
RS
4637
4638 ret = bdrv_create(drv, out.filename, opts, &local_err);
4639 if (ret < 0) {
4640 error_reportf_err(local_err,
4641 "%s: error while creating output image: ",
4642 out.filename);
4643 ret = -1;
4644 goto out;
4645 }
4646
ea204dda
DB
4647 /* TODO, we can't honour --image-opts for the target,
4648 * since it needs to be given in a format compatible
4649 * with the bdrv_create() call above which does not
4650 * support image-opts style.
4651 */
29cf9336 4652 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
ea204dda 4653 false, false, false);
86ce1f6e
RS
4654
4655 if (!blk2) {
4656 ret = -1;
4657 goto out;
4658 }
4659
f7c15533
RS
4660 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4661 size < in.offset * in.bsz)) {
4662 /* We give a warning if the skip option is bigger than the input
4663 * size and create an empty output disk image (i.e. like dd(1)).
4664 */
4665 error_report("%s: cannot skip to specified offset", in.filename);
4666 in_pos = size;
4667 } else {
4668 in_pos = in.offset * in.bsz;
4669 }
4670
86ce1f6e
RS
4671 in.buf = g_new(uint8_t, in.bsz);
4672
f7c15533 4673 for (out_pos = 0; in_pos < size; block_count++) {
86ce1f6e
RS
4674 int in_ret, out_ret;
4675
4676 if (in_pos + in.bsz > size) {
4677 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4678 } else {
4679 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4680 }
4681 if (in_ret < 0) {
4682 error_report("error while reading from input image file: %s",
4683 strerror(-in_ret));
4684 ret = -1;
4685 goto out;
4686 }
4687 in_pos += in_ret;
4688
4689 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4690
4691 if (out_ret < 0) {
4692 error_report("error while writing to output image file: %s",
4693 strerror(-out_ret));
4694 ret = -1;
4695 goto out;
4696 }
4697 out_pos += out_ret;
4698 }
4699
4700out:
4701 g_free(arg);
4702 qemu_opts_del(opts);
4703 qemu_opts_free(create_opts);
4704 blk_unref(blk1);
4705 blk_unref(blk2);
4706 g_free(in.filename);
4707 g_free(out.filename);
4708 g_free(in.buf);
4709 g_free(out.buf);
4710
4711 if (ret) {
b6133b8c
KW
4712 return 1;
4713 }
4714 return 0;
4715}
4716
fd03c2b8
SH
4717static void dump_json_block_measure_info(BlockMeasureInfo *info)
4718{
4719 QString *str;
4720 QObject *obj;
4721 Visitor *v = qobject_output_visitor_new(&obj);
4722
4723 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4724 visit_complete(v, &obj);
4725 str = qobject_to_json_pretty(obj);
4726 assert(str != NULL);
4727 printf("%s\n", qstring_get_str(str));
cb3e7f08 4728 qobject_unref(obj);
fd03c2b8 4729 visit_free(v);
cb3e7f08 4730 qobject_unref(str);
fd03c2b8
SH
4731}
4732
4733static int img_measure(int argc, char **argv)
4734{
4735 static const struct option long_options[] = {
4736 {"help", no_argument, 0, 'h'},
4737 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4738 {"object", required_argument, 0, OPTION_OBJECT},
4739 {"output", required_argument, 0, OPTION_OUTPUT},
4740 {"size", required_argument, 0, OPTION_SIZE},
4741 {"force-share", no_argument, 0, 'U'},
4742 {0, 0, 0, 0}
4743 };
4744 OutputFormat output_format = OFORMAT_HUMAN;
4745 BlockBackend *in_blk = NULL;
4746 BlockDriver *drv;
4747 const char *filename = NULL;
4748 const char *fmt = NULL;
4749 const char *out_fmt = "raw";
4750 char *options = NULL;
4751 char *snapshot_name = NULL;
4752 bool force_share = false;
4753 QemuOpts *opts = NULL;
4754 QemuOpts *object_opts = NULL;
4755 QemuOpts *sn_opts = NULL;
4756 QemuOptsList *create_opts = NULL;
4757 bool image_opts = false;
4758 uint64_t img_size = UINT64_MAX;
4759 BlockMeasureInfo *info = NULL;
4760 Error *local_err = NULL;
4761 int ret = 1;
4762 int c;
4763
4764 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4765 long_options, NULL)) != -1) {
4766 switch (c) {
4767 case '?':
4768 case 'h':
4769 help();
4770 break;
4771 case 'f':
4772 fmt = optarg;
4773 break;
4774 case 'O':
4775 out_fmt = optarg;
4776 break;
4777 case 'o':
4778 if (!is_valid_option_list(optarg)) {
4779 error_report("Invalid option list: %s", optarg);
4780 goto out;
4781 }
4782 if (!options) {
4783 options = g_strdup(optarg);
4784 } else {
4785 char *old_options = options;
4786 options = g_strdup_printf("%s,%s", options, optarg);
4787 g_free(old_options);
4788 }
4789 break;
4790 case 'l':
4791 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4792 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4793 optarg, false);
4794 if (!sn_opts) {
4795 error_report("Failed in parsing snapshot param '%s'",
4796 optarg);
4797 goto out;
4798 }
4799 } else {
4800 snapshot_name = optarg;
4801 }
4802 break;
4803 case 'U':
4804 force_share = true;
4805 break;
4806 case OPTION_OBJECT:
4807 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4808 optarg, true);
4809 if (!object_opts) {
4810 goto out;
4811 }
4812 break;
4813 case OPTION_IMAGE_OPTS:
4814 image_opts = true;
4815 break;
4816 case OPTION_OUTPUT:
4817 if (!strcmp(optarg, "json")) {
4818 output_format = OFORMAT_JSON;
4819 } else if (!strcmp(optarg, "human")) {
4820 output_format = OFORMAT_HUMAN;
4821 } else {
4822 error_report("--output must be used with human or json "
4823 "as argument.");
4824 goto out;
4825 }
4826 break;
4827 case OPTION_SIZE:
4828 {
4829 int64_t sval;
4830
4831 sval = cvtnum(optarg);
4832 if (sval < 0) {
4833 if (sval == -ERANGE) {
4834 error_report("Image size must be less than 8 EiB!");
4835 } else {
4836 error_report("Invalid image size specified! You may use "
4837 "k, M, G, T, P or E suffixes for ");
4838 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4839 "petabytes and exabytes.");
4840 }
4841 goto out;
4842 }
4843 img_size = (uint64_t)sval;
4844 }
4845 break;
4846 }
4847 }
4848
4849 if (qemu_opts_foreach(&qemu_object_opts,
4850 user_creatable_add_opts_foreach,
334c43e2 4851 NULL, &error_fatal)) {
fd03c2b8
SH
4852 goto out;
4853 }
4854
4855 if (argc - optind > 1) {
4856 error_report("At most one filename argument is allowed.");
4857 goto out;
4858 } else if (argc - optind == 1) {
4859 filename = argv[optind];
4860 }
4861
4862 if (!filename &&
4863 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4864 error_report("--object, --image-opts, -f, and -l "
4865 "require a filename argument.");
4866 goto out;
4867 }
4868 if (filename && img_size != UINT64_MAX) {
4869 error_report("--size N cannot be used together with a filename.");
4870 goto out;
4871 }
4872 if (!filename && img_size == UINT64_MAX) {
4873 error_report("Either --size N or one filename must be specified.");
4874 goto out;
4875 }
4876
4877 if (filename) {
4878 in_blk = img_open(image_opts, filename, fmt, 0,
4879 false, false, force_share);
4880 if (!in_blk) {
4881 goto out;
4882 }
4883
4884 if (sn_opts) {
4885 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4886 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4887 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4888 &local_err);
4889 } else if (snapshot_name != NULL) {
4890 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4891 snapshot_name, &local_err);
4892 }
4893 if (local_err) {
4894 error_reportf_err(local_err, "Failed to load snapshot: ");
4895 goto out;
4896 }
4897 }
4898
4899 drv = bdrv_find_format(out_fmt);
4900 if (!drv) {
4901 error_report("Unknown file format '%s'", out_fmt);
4902 goto out;
4903 }
4904 if (!drv->create_opts) {
4905 error_report("Format driver '%s' does not support image creation",
4906 drv->format_name);
4907 goto out;
4908 }
4909
4910 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4911 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4912 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4913 if (options) {
4914 qemu_opts_do_parse(opts, options, NULL, &local_err);
4915 if (local_err) {
4916 error_report_err(local_err);
4917 error_report("Invalid options for file format '%s'", out_fmt);
4918 goto out;
4919 }
4920 }
4921 if (img_size != UINT64_MAX) {
4922 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4923 }
4924
4925 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4926 if (local_err) {
4927 error_report_err(local_err);
4928 goto out;
4929 }
4930
4931 if (output_format == OFORMAT_HUMAN) {
4932 printf("required size: %" PRIu64 "\n", info->required);
4933 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4934 } else {
4935 dump_json_block_measure_info(info);
4936 }
4937
4938 ret = 0;
4939
4940out:
4941 qapi_free_BlockMeasureInfo(info);
4942 qemu_opts_del(object_opts);
4943 qemu_opts_del(opts);
4944 qemu_opts_del(sn_opts);
4945 qemu_opts_free(create_opts);
4946 g_free(options);
4947 blk_unref(in_blk);
4948 return ret;
4949}
b6133b8c 4950
c227f099 4951static const img_cmd_t img_cmds[] = {
153859be
SB
4952#define DEF(option, callback, arg_string) \
4953 { option, callback },
4954#include "qemu-img-cmds.h"
4955#undef DEF
153859be
SB
4956 { NULL, NULL, },
4957};
4958
ea2384d3
FB
4959int main(int argc, char **argv)
4960{
c227f099 4961 const img_cmd_t *cmd;
153859be 4962 const char *cmdname;
2f78e491 4963 Error *local_error = NULL;
06a1e0c1 4964 char *trace_file = NULL;
7db1689c 4965 int c;
7db1689c
JC
4966 static const struct option long_options[] = {
4967 {"help", no_argument, 0, 'h'},
10985131 4968 {"version", no_argument, 0, 'V'},
06a1e0c1 4969 {"trace", required_argument, NULL, 'T'},
7db1689c
JC
4970 {0, 0, 0, 0}
4971 };
ea2384d3 4972
526eda14
MK
4973#ifdef CONFIG_POSIX
4974 signal(SIGPIPE, SIG_IGN);
4975#endif
4976
f5852efa 4977 error_init(argv[0]);
fe4db84d 4978 module_call_init(MODULE_INIT_TRACE);
10f5bff6 4979 qemu_init_exec_dir(argv[0]);
53f76e58 4980
2f78e491 4981 if (qemu_init_main_loop(&local_error)) {
565f65d2 4982 error_report_err(local_error);
2f78e491
CN
4983 exit(EXIT_FAILURE);
4984 }
4985
e8f2d272 4986 qcrypto_init(&error_fatal);
c2297088 4987
064097d9 4988 module_call_init(MODULE_INIT_QOM);
ea2384d3 4989 bdrv_init();
ac1307ab
FZ
4990 if (argc < 2) {
4991 error_exit("Not enough arguments");
4992 }
153859be 4993
3babeb15 4994 qemu_add_opts(&qemu_object_opts);
eb769f74 4995 qemu_add_opts(&qemu_source_opts);
06a1e0c1 4996 qemu_add_opts(&qemu_trace_opts);
3babeb15 4997
c9192973 4998 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
10985131 4999 switch (c) {
c9192973
SH
5000 case ':':
5001 missing_argument(argv[optind - 1]);
5002 return 0;
4581c16f 5003 case '?':
c9192973
SH
5004 unrecognized_option(argv[optind - 1]);
5005 return 0;
5006 case 'h':
10985131
DL
5007 help();
5008 return 0;
5009 case 'V':
5010 printf(QEMU_IMG_VERSION);
5011 return 0;
06a1e0c1
DL
5012 case 'T':
5013 g_free(trace_file);
5014 trace_file = trace_opt_parse(optarg);
5015 break;
153859be 5016 }
ea2384d3 5017 }
153859be 5018
10985131 5019 cmdname = argv[optind];
7db1689c 5020
10985131
DL
5021 /* reset getopt_long scanning */
5022 argc -= optind;
5023 if (argc < 1) {
5f6979cb
JC
5024 return 0;
5025 }
10985131 5026 argv += optind;
d339d766 5027 qemu_reset_optind();
10985131 5028
06a1e0c1
DL
5029 if (!trace_init_backends()) {
5030 exit(1);
5031 }
5032 trace_init_file(trace_file);
5033 qemu_set_log(LOG_TRACE);
5034
10985131
DL
5035 /* find the command */
5036 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5037 if (!strcmp(cmdname, cmd->name)) {
5038 return cmd->handler(argc, argv);
5039 }
5040 }
7db1689c 5041
153859be 5042 /* not found */
ac1307ab 5043 error_exit("Command not found: %s", cmdname);
ea2384d3 5044}