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