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