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