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