]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-img.c
replay: Fix dangling location bug in replay_configure()
[mirror_qemu.git] / qemu-img.c
CommitLineData
ea2384d3 1/*
fb43f4dd 2 * QEMU disk image utility
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
ea2384d3
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
80c71a24 24#include "qemu/osdep.h"
da34e65c 25#include "qapi/error.h"
c054b3fd
BC
26#include "qapi-visit.h"
27#include "qapi/qmp-output-visitor.h"
cc7a8ea7 28#include "qapi/qmp/qerror.h"
7b1b5d19 29#include "qapi/qmp/qjson.h"
f348b6d1 30#include "qemu/cutils.h"
3babeb15 31#include "qemu/config-file.h"
1de7afc9
PB
32#include "qemu/option.h"
33#include "qemu/error-report.h"
3babeb15 34#include "qom/object_interfaces.h"
9c17d615 35#include "sysemu/sysemu.h"
26f54e9a 36#include "sysemu/block-backend.h"
737e150e 37#include "block/block_int.h"
d4a3238a 38#include "block/blockjob.h"
f364ec65 39#include "block/qapi.h"
c2297088 40#include "crypto/init.h"
c054b3fd 41#include <getopt.h>
e8445331 42
61979a6a 43#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
5f6979cb
JC
44 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
45
c227f099 46typedef struct img_cmd_t {
153859be
SB
47 const char *name;
48 int (*handler)(int argc, char **argv);
c227f099 49} img_cmd_t;
153859be 50
8599ea4c
FS
51enum {
52 OPTION_OUTPUT = 256,
53 OPTION_BACKING_CHAIN = 257,
3babeb15 54 OPTION_OBJECT = 258,
eb769f74 55 OPTION_IMAGE_OPTS = 259,
8599ea4c
FS
56};
57
58typedef enum OutputFormat {
59 OFORMAT_JSON,
60 OFORMAT_HUMAN,
61} OutputFormat;
62
e6996143 63/* Default to cache=writeback as data integrity is not important for qemu-img */
661a0f71 64#define BDRV_DEFAULT_CACHE "writeback"
137519ce 65
00c6d403 66static void format_print(void *opaque, const char *name)
ea2384d3 67{
00c6d403 68 printf(" %s", name);
ea2384d3
FB
69}
70
ac1307ab
FZ
71static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
72{
73 va_list ap;
74
75 error_printf("qemu-img: ");
76
77 va_start(ap, fmt);
78 error_vprintf(fmt, ap);
79 va_end(ap);
80
81 error_printf("\nTry 'qemu-img --help' for more information\n");
82 exit(EXIT_FAILURE);
83}
84
d2c639d6 85/* Please keep in synch with qemu-img.texi */
ac1307ab 86static void QEMU_NORETURN help(void)
ea2384d3 87{
e00291c0 88 const char *help_msg =
5f6979cb 89 QEMU_IMG_VERSION
3f020d70 90 "usage: qemu-img command [command options]\n"
91 "QEMU disk image utility\n"
92 "\n"
93 "Command syntax:\n"
153859be
SB
94#define DEF(option, callback, arg_string) \
95 " " arg_string "\n"
96#include "qemu-img-cmds.h"
97#undef DEF
98#undef GEN_DOCS
3f020d70 99 "\n"
100 "Command parameters:\n"
101 " 'filename' is a disk image filename\n"
3babeb15
DB
102 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
103 " manual page for a description of the object properties. The most common\n"
104 " object type is a 'secret', which is used to supply passwords and/or\n"
105 " encryption keys.\n"
3f020d70 106 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
661a0f71 107 " 'cache' is the cache mode used to write the output disk image, the valid\n"
80ccf93b
LY
108 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
109 " 'directsync' and 'unsafe' (default for convert)\n"
bb87fdf8
SH
110 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
111 " options are the same as for the 'cache' option\n"
3f020d70 112 " 'size' is the disk image size in bytes. Optional suffixes\n"
5e00984a
KW
113 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
114 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
115 " supported. 'b' is ignored.\n"
3f020d70 116 " 'output_filename' is the destination disk image filename\n"
117 " 'output_fmt' is the destination format\n"
118 " 'options' is a comma separated list of format specific options in a\n"
119 " name=value format. Use -o ? for an overview of the options supported by the\n"
120 " used format\n"
ef80654d
WX
121 " 'snapshot_param' is param used for internal snapshot, format\n"
122 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
123 " '[ID_OR_NAME]'\n"
124 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
125 " instead\n"
3f020d70 126 " '-c' indicates that target image must be compressed (qcow format only)\n"
127 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
128 " match exactly. The image doesn't need a working backing file before\n"
129 " rebasing in this case (useful for renaming the backing file)\n"
130 " '-h' with or without a command shows this help and lists the supported formats\n"
6b837bc4 131 " '-p' show progress of command (only certain commands)\n"
f382d43a 132 " '-q' use Quiet mode - do not print any output (except errors)\n"
11b6699a
PL
133 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
134 " contain only zeros for qemu-img to create a sparse image during\n"
135 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
136 " unallocated or zero sectors, and the destination image will always be\n"
137 " fully allocated\n"
c054b3fd 138 " '--output' takes the format in which the output must be done (human or json)\n"
b2e10493
AD
139 " '-n' skips the target volume creation (useful if the volume is created\n"
140 " prior to running qemu-img)\n"
3f020d70 141 "\n"
4534ff54
KW
142 "Parameters to check subcommand:\n"
143 " '-r' tries to repair any inconsistencies that are found during the check.\n"
144 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
145 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
0546b8c2 146 " hiding corruption that has already occurred.\n"
4534ff54 147 "\n"
3f020d70 148 "Parameters to snapshot subcommand:\n"
149 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
150 " '-a' applies a snapshot (revert disk to saved state)\n"
151 " '-c' creates a snapshot\n"
152 " '-d' deletes a snapshot\n"
d14ed18c
MR
153 " '-l' lists all snapshots in the given image\n"
154 "\n"
155 "Parameters to compare subcommand:\n"
156 " '-f' first image format\n"
157 " '-F' second image format\n"
158 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
e00291c0
PB
159
160 printf("%s\nSupported formats:", help_msg);
00c6d403 161 bdrv_iterate_format(format_print, NULL);
ea2384d3 162 printf("\n");
ac1307ab 163 exit(EXIT_SUCCESS);
ea2384d3
FB
164}
165
3babeb15
DB
166static QemuOptsList qemu_object_opts = {
167 .name = "object",
168 .implied_opt_name = "qom-type",
169 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
170 .desc = {
171 { }
172 },
173};
174
eb769f74
DB
175static QemuOptsList qemu_source_opts = {
176 .name = "source",
177 .implied_opt_name = "file",
178 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
179 .desc = {
180 { }
181 },
182};
183
7c30f657 184static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
f382d43a
MR
185{
186 int ret = 0;
187 if (!quiet) {
188 va_list args;
189 va_start(args, fmt);
190 ret = vprintf(fmt, args);
191 va_end(args);
192 }
193 return ret;
194}
195
ea2384d3 196
4ac8aacd
JS
197static int print_block_option_help(const char *filename, const char *fmt)
198{
199 BlockDriver *drv, *proto_drv;
83d0521a 200 QemuOptsList *create_opts = NULL;
b65a5e12 201 Error *local_err = NULL;
4ac8aacd
JS
202
203 /* Find driver and parse its options */
204 drv = bdrv_find_format(fmt);
205 if (!drv) {
15654a6d 206 error_report("Unknown file format '%s'", fmt);
4ac8aacd
JS
207 return 1;
208 }
209
c282e1fd 210 create_opts = qemu_opts_append(create_opts, drv->create_opts);
a283cb6e 211 if (filename) {
b65a5e12 212 proto_drv = bdrv_find_protocol(filename, true, &local_err);
a283cb6e 213 if (!proto_drv) {
2867ce4a 214 error_report_err(local_err);
83d0521a 215 qemu_opts_free(create_opts);
a283cb6e
KW
216 return 1;
217 }
c282e1fd 218 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
a283cb6e
KW
219 }
220
83d0521a
CL
221 qemu_opts_print_help(create_opts);
222 qemu_opts_free(create_opts);
4ac8aacd
JS
223 return 0;
224}
225
eb769f74
DB
226
227static int img_open_password(BlockBackend *blk, const char *filename,
abb06c5a 228 int flags, bool quiet)
75c23805
FB
229{
230 BlockDriverState *bs;
75c23805 231 char password[256];
eb769f74
DB
232
233 bs = blk_bs(blk);
4ef130fc
DB
234 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
235 !(flags & BDRV_O_NO_IO)) {
eb769f74
DB
236 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
237 if (qemu_read_password(password, sizeof(password)) < 0) {
238 error_report("No password given");
239 return -1;
240 }
241 if (bdrv_set_key(bs, password) < 0) {
242 error_report("invalid password");
243 return -1;
244 }
245 }
246 return 0;
247}
248
249
efaa7c4e 250static BlockBackend *img_open_opts(const char *optstr,
ce099547 251 QemuOpts *opts, int flags, bool writethrough,
abb06c5a 252 bool quiet)
eb769f74
DB
253{
254 QDict *options;
255 Error *local_err = NULL;
256 BlockBackend *blk;
257 options = qemu_opts_to_qdict(opts, NULL);
efaa7c4e 258 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
eb769f74 259 if (!blk) {
143605a2 260 error_reportf_err(local_err, "Could not open '%s': ", optstr);
eb769f74
DB
261 return NULL;
262 }
ce099547 263 blk_set_enable_write_cache(blk, !writethrough);
eb769f74 264
abb06c5a 265 if (img_open_password(blk, optstr, flags, quiet) < 0) {
eb769f74
DB
266 blk_unref(blk);
267 return NULL;
268 }
269 return blk;
270}
271
efaa7c4e 272static BlockBackend *img_open_file(const char *filename,
eb769f74 273 const char *fmt, int flags,
ce099547 274 bool writethrough, bool quiet)
eb769f74
DB
275{
276 BlockBackend *blk;
34b5d2c6 277 Error *local_err = NULL;
5bd31326 278 QDict *options = NULL;
ad717139 279
75c23805 280 if (fmt) {
5bd31326
HR
281 options = qdict_new();
282 qdict_put(options, "driver", qstring_from_str(fmt));
75c23805 283 }
b9eaf9ec 284
efaa7c4e 285 blk = blk_new_open(filename, NULL, options, flags, &local_err);
5bd31326 286 if (!blk) {
c29b77f9 287 error_reportf_err(local_err, "Could not open '%s': ", filename);
eb769f74 288 return NULL;
75c23805 289 }
ce099547 290 blk_set_enable_write_cache(blk, !writethrough);
b9eaf9ec 291
abb06c5a 292 if (img_open_password(blk, filename, flags, quiet) < 0) {
eb769f74
DB
293 blk_unref(blk);
294 return NULL;
295 }
296 return blk;
297}
298
299
efaa7c4e 300static BlockBackend *img_open(bool image_opts,
eb769f74 301 const char *filename,
ce099547 302 const char *fmt, int flags, bool writethrough,
abb06c5a 303 bool quiet)
eb769f74
DB
304{
305 BlockBackend *blk;
306 if (image_opts) {
307 QemuOpts *opts;
308 if (fmt) {
309 error_report("--image-opts and --format are mutually exclusive");
310 return NULL;
311 }
312 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
313 filename, true);
314 if (!opts) {
315 return NULL;
316 }
ce099547 317 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
eb769f74 318 } else {
ce099547 319 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
75c23805 320 }
7e7d56d9 321 return blk;
75c23805
FB
322}
323
eb769f74 324
83d0521a 325static int add_old_style_options(const char *fmt, QemuOpts *opts,
eec77d9e
JS
326 const char *base_filename,
327 const char *base_fmt)
efa84d43 328{
6750e795
MA
329 Error *err = NULL;
330
efa84d43 331 if (base_filename) {
f43e47db 332 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
6750e795 333 if (err) {
15654a6d
JS
334 error_report("Backing file not supported for file format '%s'",
335 fmt);
6750e795 336 error_free(err);
c2abccec 337 return -1;
efa84d43
KW
338 }
339 }
340 if (base_fmt) {
f43e47db 341 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
6750e795 342 if (err) {
15654a6d
JS
343 error_report("Backing file format not supported for file "
344 "format '%s'", fmt);
6750e795 345 error_free(err);
c2abccec 346 return -1;
efa84d43
KW
347 }
348 }
c2abccec 349 return 0;
efa84d43
KW
350}
351
ea2384d3
FB
352static int img_create(int argc, char **argv)
353{
a9300911 354 int c;
1da7cfbd 355 uint64_t img_size = -1;
ea2384d3 356 const char *fmt = "raw";
9230eaf6 357 const char *base_fmt = NULL;
ea2384d3
FB
358 const char *filename;
359 const char *base_filename = NULL;
9ea2ea71 360 char *options = NULL;
9b37525a 361 Error *local_err = NULL;
f382d43a 362 bool quiet = false;
3b46e624 363
ea2384d3 364 for(;;) {
3babeb15
DB
365 static const struct option long_options[] = {
366 {"help", no_argument, 0, 'h'},
367 {"object", required_argument, 0, OPTION_OBJECT},
368 {0, 0, 0, 0}
369 };
370 c = getopt_long(argc, argv, "F:b:f:he6o:q",
371 long_options, NULL);
b8fb60da 372 if (c == -1) {
ea2384d3 373 break;
b8fb60da 374 }
ea2384d3 375 switch(c) {
ef87394c 376 case '?':
ea2384d3
FB
377 case 'h':
378 help();
379 break;
9230eaf6
AL
380 case 'F':
381 base_fmt = optarg;
382 break;
ea2384d3
FB
383 case 'b':
384 base_filename = optarg;
385 break;
386 case 'f':
387 fmt = optarg;
388 break;
389 case 'e':
9d42e15d 390 error_report("option -e is deprecated, please use \'-o "
eec77d9e 391 "encryption\' instead!");
77386bf6 392 goto fail;
d8871c5a 393 case '6':
9d42e15d 394 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 395 "compat6\' instead!");
77386bf6 396 goto fail;
9ea2ea71 397 case 'o':
77386bf6
KW
398 if (!is_valid_option_list(optarg)) {
399 error_report("Invalid option list: %s", optarg);
400 goto fail;
401 }
402 if (!options) {
403 options = g_strdup(optarg);
404 } else {
405 char *old_options = options;
406 options = g_strdup_printf("%s,%s", options, optarg);
407 g_free(old_options);
408 }
9ea2ea71 409 break;
f382d43a
MR
410 case 'q':
411 quiet = true;
412 break;
3babeb15
DB
413 case OPTION_OBJECT: {
414 QemuOpts *opts;
415 opts = qemu_opts_parse_noisily(&qemu_object_opts,
416 optarg, true);
417 if (!opts) {
418 goto fail;
419 }
420 } break;
ea2384d3
FB
421 }
422 }
9230eaf6 423
b50cbabc 424 /* Get the filename */
a283cb6e
KW
425 filename = (optind < argc) ? argv[optind] : NULL;
426 if (options && has_help_option(options)) {
427 g_free(options);
428 return print_block_option_help(filename, fmt);
429 }
430
b8fb60da 431 if (optind >= argc) {
ac1307ab 432 error_exit("Expecting image file name");
b8fb60da 433 }
a283cb6e 434 optind++;
b50cbabc 435
3babeb15
DB
436 if (qemu_opts_foreach(&qemu_object_opts,
437 user_creatable_add_opts_foreach,
438 NULL, &local_err)) {
439 error_report_err(local_err);
440 goto fail;
441 }
442
1da7cfbd
JS
443 /* Get image size, if specified */
444 if (optind < argc) {
70b4f4bb 445 int64_t sval;
e36b3695 446 char *end;
4677bb40
MAL
447 sval = qemu_strtosz_suffix(argv[optind++], &end,
448 QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 449 if (sval < 0 || *end) {
79443397
LG
450 if (sval == -ERANGE) {
451 error_report("Image size must be less than 8 EiB!");
452 } else {
453 error_report("Invalid image size specified! You may use k, M, "
5e00984a
KW
454 "G, T, P or E suffixes for ");
455 error_report("kilobytes, megabytes, gigabytes, terabytes, "
456 "petabytes and exabytes.");
79443397 457 }
77386bf6 458 goto fail;
1da7cfbd
JS
459 }
460 img_size = (uint64_t)sval;
461 }
fc11eb26 462 if (optind != argc) {
ac1307ab 463 error_exit("Unexpected argument: %s", argv[optind]);
fc11eb26 464 }
1da7cfbd 465
9b37525a 466 bdrv_img_create(filename, fmt, base_filename, base_fmt,
61de4c68 467 options, img_size, 0, &local_err, quiet);
84d18f06 468 if (local_err) {
c29b77f9 469 error_reportf_err(local_err, "%s: ", filename);
77386bf6 470 goto fail;
c2abccec 471 }
a9300911 472
77386bf6 473 g_free(options);
ea2384d3 474 return 0;
77386bf6
KW
475
476fail:
477 g_free(options);
478 return 1;
ea2384d3
FB
479}
480
f382d43a 481static void dump_json_image_check(ImageCheck *check, bool quiet)
8599ea4c 482{
4399c438 483 Error *local_err = NULL;
8599ea4c
FS
484 QString *str;
485 QmpOutputVisitor *ov = qmp_output_visitor_new();
486 QObject *obj;
51e72bc1
EB
487 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
488 &local_err);
8599ea4c
FS
489 obj = qmp_output_get_qobject(ov);
490 str = qobject_to_json_pretty(obj);
491 assert(str != NULL);
f382d43a 492 qprintf(quiet, "%s\n", qstring_get_str(str));
8599ea4c
FS
493 qobject_decref(obj);
494 qmp_output_visitor_cleanup(ov);
495 QDECREF(str);
496}
497
f382d43a 498static void dump_human_image_check(ImageCheck *check, bool quiet)
8599ea4c
FS
499{
500 if (!(check->corruptions || check->leaks || check->check_errors)) {
f382d43a 501 qprintf(quiet, "No errors were found on the image.\n");
8599ea4c
FS
502 } else {
503 if (check->corruptions) {
f382d43a
MR
504 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
505 "Data may be corrupted, or further writes to the image "
506 "may corrupt it.\n",
507 check->corruptions);
8599ea4c
FS
508 }
509
510 if (check->leaks) {
f382d43a
MR
511 qprintf(quiet,
512 "\n%" PRId64 " leaked clusters were found on the image.\n"
513 "This means waste of disk space, but no harm to data.\n",
514 check->leaks);
8599ea4c
FS
515 }
516
517 if (check->check_errors) {
f382d43a
MR
518 qprintf(quiet,
519 "\n%" PRId64
520 " internal errors have occurred during the check.\n",
521 check->check_errors);
8599ea4c
FS
522 }
523 }
524
525 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
f382d43a
MR
526 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
527 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
528 check->allocated_clusters, check->total_clusters,
529 check->allocated_clusters * 100.0 / check->total_clusters,
530 check->fragmented_clusters * 100.0 / check->allocated_clusters,
531 check->compressed_clusters * 100.0 /
532 check->allocated_clusters);
8599ea4c
FS
533 }
534
535 if (check->image_end_offset) {
f382d43a
MR
536 qprintf(quiet,
537 "Image end offset: %" PRId64 "\n", check->image_end_offset);
8599ea4c
FS
538 }
539}
540
541static int collect_image_check(BlockDriverState *bs,
542 ImageCheck *check,
543 const char *filename,
544 const char *fmt,
545 int fix)
546{
547 int ret;
548 BdrvCheckResult result;
549
550 ret = bdrv_check(bs, &result, fix);
551 if (ret < 0) {
552 return ret;
553 }
554
555 check->filename = g_strdup(filename);
556 check->format = g_strdup(bdrv_get_format_name(bs));
557 check->check_errors = result.check_errors;
558 check->corruptions = result.corruptions;
559 check->has_corruptions = result.corruptions != 0;
560 check->leaks = result.leaks;
561 check->has_leaks = result.leaks != 0;
562 check->corruptions_fixed = result.corruptions_fixed;
563 check->has_corruptions_fixed = result.corruptions != 0;
564 check->leaks_fixed = result.leaks_fixed;
565 check->has_leaks_fixed = result.leaks != 0;
566 check->image_end_offset = result.image_end_offset;
567 check->has_image_end_offset = result.image_end_offset != 0;
568 check->total_clusters = result.bfi.total_clusters;
569 check->has_total_clusters = result.bfi.total_clusters != 0;
570 check->allocated_clusters = result.bfi.allocated_clusters;
571 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
572 check->fragmented_clusters = result.bfi.fragmented_clusters;
573 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
e6439d78
SH
574 check->compressed_clusters = result.bfi.compressed_clusters;
575 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
8599ea4c
FS
576
577 return 0;
578}
579
e076f338
KW
580/*
581 * Checks an image for consistency. Exit codes:
582 *
d6635c4d
HR
583 * 0 - Check completed, image is good
584 * 1 - Check not completed because of internal errors
585 * 2 - Check completed, image is corrupted
586 * 3 - Check completed, image has leaked clusters, but is good otherwise
587 * 63 - Checks are not supported by the image format
e076f338 588 */
1585969c
AL
589static int img_check(int argc, char **argv)
590{
591 int c, ret;
8599ea4c 592 OutputFormat output_format = OFORMAT_HUMAN;
40055951 593 const char *filename, *fmt, *output, *cache;
26f54e9a 594 BlockBackend *blk;
1585969c 595 BlockDriverState *bs;
4534ff54 596 int fix = 0;
ce099547
KW
597 int flags = BDRV_O_CHECK;
598 bool writethrough;
7e7d56d9 599 ImageCheck *check;
f382d43a 600 bool quiet = false;
3babeb15 601 Error *local_err = NULL;
eb769f74 602 bool image_opts = false;
1585969c
AL
603
604 fmt = NULL;
8599ea4c 605 output = NULL;
40055951 606 cache = BDRV_DEFAULT_CACHE;
ce099547 607
1585969c 608 for(;;) {
8599ea4c
FS
609 int option_index = 0;
610 static const struct option long_options[] = {
611 {"help", no_argument, 0, 'h'},
612 {"format", required_argument, 0, 'f'},
4fd6a984 613 {"repair", required_argument, 0, 'r'},
8599ea4c 614 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 615 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 616 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
8599ea4c
FS
617 {0, 0, 0, 0}
618 };
40055951 619 c = getopt_long(argc, argv, "hf:r:T:q",
8599ea4c 620 long_options, &option_index);
b8fb60da 621 if (c == -1) {
1585969c 622 break;
b8fb60da 623 }
1585969c 624 switch(c) {
ef87394c 625 case '?':
1585969c
AL
626 case 'h':
627 help();
628 break;
629 case 'f':
630 fmt = optarg;
631 break;
4534ff54
KW
632 case 'r':
633 flags |= BDRV_O_RDWR;
634
635 if (!strcmp(optarg, "leaks")) {
636 fix = BDRV_FIX_LEAKS;
637 } else if (!strcmp(optarg, "all")) {
638 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
639 } else {
ac1307ab
FZ
640 error_exit("Unknown option value for -r "
641 "(expecting 'leaks' or 'all'): %s", optarg);
4534ff54
KW
642 }
643 break;
8599ea4c
FS
644 case OPTION_OUTPUT:
645 output = optarg;
646 break;
40055951
HR
647 case 'T':
648 cache = optarg;
649 break;
f382d43a
MR
650 case 'q':
651 quiet = true;
652 break;
3babeb15
DB
653 case OPTION_OBJECT: {
654 QemuOpts *opts;
655 opts = qemu_opts_parse_noisily(&qemu_object_opts,
656 optarg, true);
657 if (!opts) {
658 return 1;
659 }
660 } break;
eb769f74
DB
661 case OPTION_IMAGE_OPTS:
662 image_opts = true;
663 break;
1585969c
AL
664 }
665 }
fc11eb26 666 if (optind != argc - 1) {
ac1307ab 667 error_exit("Expecting one image file name");
b8fb60da 668 }
1585969c
AL
669 filename = argv[optind++];
670
8599ea4c
FS
671 if (output && !strcmp(output, "json")) {
672 output_format = OFORMAT_JSON;
673 } else if (output && !strcmp(output, "human")) {
674 output_format = OFORMAT_HUMAN;
675 } else if (output) {
676 error_report("--output must be used with human or json as argument.");
677 return 1;
678 }
679
3babeb15
DB
680 if (qemu_opts_foreach(&qemu_object_opts,
681 user_creatable_add_opts_foreach,
682 NULL, &local_err)) {
683 error_report_err(local_err);
684 return 1;
685 }
686
ce099547 687 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
688 if (ret < 0) {
689 error_report("Invalid source cache option: %s", cache);
690 return 1;
691 }
692
ce099547 693 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
694 if (!blk) {
695 return 1;
c2abccec 696 }
7e7d56d9 697 bs = blk_bs(blk);
8599ea4c
FS
698
699 check = g_new0(ImageCheck, 1);
700 ret = collect_image_check(bs, check, filename, fmt, fix);
e076f338
KW
701
702 if (ret == -ENOTSUP) {
55d492d7 703 error_report("This image format does not support checks");
fefddf95 704 ret = 63;
8599ea4c 705 goto fail;
e076f338
KW
706 }
707
8599ea4c
FS
708 if (check->corruptions_fixed || check->leaks_fixed) {
709 int corruptions_fixed, leaks_fixed;
ccf34716 710
8599ea4c
FS
711 leaks_fixed = check->leaks_fixed;
712 corruptions_fixed = check->corruptions_fixed;
e076f338 713
8599ea4c 714 if (output_format == OFORMAT_HUMAN) {
f382d43a
MR
715 qprintf(quiet,
716 "The following inconsistencies were found and repaired:\n\n"
717 " %" PRId64 " leaked clusters\n"
718 " %" PRId64 " corruptions\n\n"
719 "Double checking the fixed image now...\n",
720 check->leaks_fixed,
721 check->corruptions_fixed);
e076f338
KW
722 }
723
8599ea4c 724 ret = collect_image_check(bs, check, filename, fmt, 0);
1585969c 725
8599ea4c
FS
726 check->leaks_fixed = leaks_fixed;
727 check->corruptions_fixed = corruptions_fixed;
f8111c24
DXW
728 }
729
832390a5
HR
730 if (!ret) {
731 switch (output_format) {
732 case OFORMAT_HUMAN:
733 dump_human_image_check(check, quiet);
734 break;
735 case OFORMAT_JSON:
736 dump_json_image_check(check, quiet);
737 break;
738 }
c6bb9ad1
FS
739 }
740
8599ea4c 741 if (ret || check->check_errors) {
832390a5
HR
742 if (ret) {
743 error_report("Check failed: %s", strerror(-ret));
744 } else {
745 error_report("Check failed");
746 }
8599ea4c
FS
747 ret = 1;
748 goto fail;
c2abccec 749 }
e076f338 750
8599ea4c
FS
751 if (check->corruptions) {
752 ret = 2;
753 } else if (check->leaks) {
754 ret = 3;
e076f338 755 } else {
8599ea4c 756 ret = 0;
e076f338 757 }
8599ea4c
FS
758
759fail:
760 qapi_free_ImageCheck(check);
26f54e9a 761 blk_unref(blk);
8599ea4c 762 return ret;
1585969c
AL
763}
764
d4a3238a
HR
765typedef struct CommonBlockJobCBInfo {
766 BlockDriverState *bs;
767 Error **errp;
768} CommonBlockJobCBInfo;
769
770static void common_block_job_cb(void *opaque, int ret)
771{
772 CommonBlockJobCBInfo *cbi = opaque;
773
774 if (ret < 0) {
775 error_setg_errno(cbi->errp, -ret, "Block job failed");
776 }
d4a3238a
HR
777}
778
779static void run_block_job(BlockJob *job, Error **errp)
780{
781 AioContext *aio_context = bdrv_get_aio_context(job->bs);
782
783 do {
784 aio_poll(aio_context, true);
62547b8a
JS
785 qemu_progress_print(job->len ?
786 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
d4a3238a
HR
787 } while (!job->ready);
788
789 block_job_complete_sync(job, errp);
687fa1d8
HR
790
791 /* A block job may finish instantaneously without publishing any progress,
792 * so just signal completion here */
793 qemu_progress_print(100.f, 0);
d4a3238a
HR
794}
795
ea2384d3
FB
796static int img_commit(int argc, char **argv)
797{
661a0f71 798 int c, ret, flags;
1b22bffd 799 const char *filename, *fmt, *cache, *base;
26f54e9a 800 BlockBackend *blk;
d4a3238a 801 BlockDriverState *bs, *base_bs;
687fa1d8 802 bool progress = false, quiet = false, drop = false;
ce099547 803 bool writethrough;
d4a3238a
HR
804 Error *local_err = NULL;
805 CommonBlockJobCBInfo cbi;
eb769f74 806 bool image_opts = false;
ea2384d3
FB
807
808 fmt = NULL;
661a0f71 809 cache = BDRV_DEFAULT_CACHE;
1b22bffd 810 base = NULL;
ea2384d3 811 for(;;) {
3babeb15
DB
812 static const struct option long_options[] = {
813 {"help", no_argument, 0, 'h'},
814 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 815 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
816 {0, 0, 0, 0}
817 };
818 c = getopt_long(argc, argv, "f:ht:b:dpq",
819 long_options, NULL);
b8fb60da 820 if (c == -1) {
ea2384d3 821 break;
b8fb60da 822 }
ea2384d3 823 switch(c) {
ef87394c 824 case '?':
ea2384d3
FB
825 case 'h':
826 help();
827 break;
828 case 'f':
829 fmt = optarg;
830 break;
661a0f71
FS
831 case 't':
832 cache = optarg;
833 break;
1b22bffd
HR
834 case 'b':
835 base = optarg;
836 /* -b implies -d */
837 drop = true;
838 break;
9a86fe48
HR
839 case 'd':
840 drop = true;
841 break;
687fa1d8
HR
842 case 'p':
843 progress = true;
844 break;
f382d43a
MR
845 case 'q':
846 quiet = true;
847 break;
3babeb15
DB
848 case OPTION_OBJECT: {
849 QemuOpts *opts;
850 opts = qemu_opts_parse_noisily(&qemu_object_opts,
851 optarg, true);
852 if (!opts) {
853 return 1;
854 }
855 } break;
eb769f74
DB
856 case OPTION_IMAGE_OPTS:
857 image_opts = true;
858 break;
ea2384d3
FB
859 }
860 }
687fa1d8
HR
861
862 /* Progress is not shown in Quiet mode */
863 if (quiet) {
864 progress = false;
865 }
866
fc11eb26 867 if (optind != argc - 1) {
ac1307ab 868 error_exit("Expecting one image file name");
b8fb60da 869 }
ea2384d3
FB
870 filename = argv[optind++];
871
3babeb15
DB
872 if (qemu_opts_foreach(&qemu_object_opts,
873 user_creatable_add_opts_foreach,
874 NULL, &local_err)) {
875 error_report_err(local_err);
876 return 1;
877 }
878
9a86fe48 879 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
ce099547 880 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
881 if (ret < 0) {
882 error_report("Invalid cache option: %s", cache);
a3981eb9 883 return 1;
661a0f71
FS
884 }
885
ce099547 886 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
887 if (!blk) {
888 return 1;
c2abccec 889 }
7e7d56d9
MA
890 bs = blk_bs(blk);
891
687fa1d8
HR
892 qemu_progress_init(progress, 1.f);
893 qemu_progress_print(0.f, 100);
894
1b22bffd
HR
895 if (base) {
896 base_bs = bdrv_find_backing_image(bs, base);
897 if (!base_bs) {
c6bd8c70 898 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
1b22bffd
HR
899 goto done;
900 }
901 } else {
902 /* This is different from QMP, which by default uses the deepest file in
903 * the backing chain (i.e., the very base); however, the traditional
904 * behavior of qemu-img commit is using the immediate backing file. */
760e0063 905 base_bs = backing_bs(bs);
1b22bffd
HR
906 if (!base_bs) {
907 error_setg(&local_err, "Image does not have a backing file");
908 goto done;
909 }
d4a3238a
HR
910 }
911
912 cbi = (CommonBlockJobCBInfo){
913 .errp = &local_err,
914 .bs = bs,
915 };
916
917 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
918 common_block_job_cb, &cbi, &local_err);
919 if (local_err) {
920 goto done;
ea2384d3
FB
921 }
922
3f09bfbc
KW
923 /* When the block job completes, the BlockBackend reference will point to
924 * the old backing file. In order to avoid that the top image is already
925 * deleted, so we can still empty it afterwards, increment the reference
926 * counter here preemptively. */
9a86fe48 927 if (!drop) {
3f09bfbc 928 bdrv_ref(bs);
9a86fe48
HR
929 }
930
d4a3238a 931 run_block_job(bs->job, &local_err);
9a86fe48
HR
932 if (local_err) {
933 goto unref_backing;
934 }
935
3f09bfbc
KW
936 if (!drop && bs->drv->bdrv_make_empty) {
937 ret = bs->drv->bdrv_make_empty(bs);
9a86fe48
HR
938 if (ret) {
939 error_setg_errno(&local_err, -ret, "Could not empty %s",
940 filename);
941 goto unref_backing;
942 }
943 }
944
945unref_backing:
946 if (!drop) {
3f09bfbc 947 bdrv_unref(bs);
9a86fe48 948 }
d4a3238a
HR
949
950done:
687fa1d8
HR
951 qemu_progress_end();
952
26f54e9a 953 blk_unref(blk);
d4a3238a
HR
954
955 if (local_err) {
6936f299 956 error_report_err(local_err);
c2abccec
MK
957 return 1;
958 }
d4a3238a
HR
959
960 qprintf(quiet, "Image committed.\n");
ea2384d3
FB
961 return 0;
962}
963
f58c7b35
TS
964/*
965 * Returns true iff the first sector pointed to by 'buf' contains at least
966 * a non-NUL byte.
967 *
968 * 'pnum' is set to the number of sectors (including and immediately following
969 * the first one) that are known to be in the same allocated/unallocated state.
970 */
ea2384d3
FB
971static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
972{
1a6d39fd
SH
973 bool is_zero;
974 int i;
ea2384d3
FB
975
976 if (n <= 0) {
977 *pnum = 0;
978 return 0;
979 }
1a6d39fd 980 is_zero = buffer_is_zero(buf, 512);
ea2384d3
FB
981 for(i = 1; i < n; i++) {
982 buf += 512;
1a6d39fd 983 if (is_zero != buffer_is_zero(buf, 512)) {
ea2384d3 984 break;
1a6d39fd 985 }
ea2384d3
FB
986 }
987 *pnum = i;
1a6d39fd 988 return !is_zero;
ea2384d3
FB
989}
990
a22f123c
KW
991/*
992 * Like is_allocated_sectors, but if the buffer starts with a used sector,
993 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
994 * breaking up write requests for only small sparse areas.
995 */
996static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
997 int min)
998{
999 int ret;
1000 int num_checked, num_used;
1001
1002 if (n < min) {
1003 min = n;
1004 }
1005
1006 ret = is_allocated_sectors(buf, n, pnum);
1007 if (!ret) {
1008 return ret;
1009 }
1010
1011 num_used = *pnum;
1012 buf += BDRV_SECTOR_SIZE * *pnum;
1013 n -= *pnum;
1014 num_checked = num_used;
1015
1016 while (n > 0) {
1017 ret = is_allocated_sectors(buf, n, pnum);
1018
1019 buf += BDRV_SECTOR_SIZE * *pnum;
1020 n -= *pnum;
1021 num_checked += *pnum;
1022 if (ret) {
1023 num_used = num_checked;
1024 } else if (*pnum >= min) {
1025 break;
1026 }
1027 }
1028
1029 *pnum = num_used;
1030 return 1;
1031}
1032
3e85c6fd
KW
1033/*
1034 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1035 * buffers matches, non-zero otherwise.
1036 *
1037 * pnum is set to the number of sectors (including and immediately following
1038 * the first one) that are known to have the same comparison result
1039 */
1040static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1041 int *pnum)
1042{
8c1ac475
RK
1043 bool res;
1044 int i;
3e85c6fd
KW
1045
1046 if (n <= 0) {
1047 *pnum = 0;
1048 return 0;
1049 }
1050
1051 res = !!memcmp(buf1, buf2, 512);
1052 for(i = 1; i < n; i++) {
1053 buf1 += 512;
1054 buf2 += 512;
1055
1056 if (!!memcmp(buf1, buf2, 512) != res) {
1057 break;
1058 }
1059 }
1060
1061 *pnum = i;
1062 return res;
1063}
1064
80ee15a6 1065#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3 1066
d14ed18c
MR
1067static int64_t sectors_to_bytes(int64_t sectors)
1068{
1069 return sectors << BDRV_SECTOR_BITS;
1070}
1071
1072static int64_t sectors_to_process(int64_t total, int64_t from)
1073{
1074 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1075}
1076
1077/*
1078 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1079 *
1080 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1081 * data and negative value on error.
1082 *
f1d3cd79 1083 * @param blk: BlockBackend for the image
d14ed18c
MR
1084 * @param sect_num: Number of first sector to check
1085 * @param sect_count: Number of sectors to check
1086 * @param filename: Name of disk file we are checking (logging purpose)
1087 * @param buffer: Allocated buffer for storing read data
1088 * @param quiet: Flag for quiet mode
1089 */
f1d3cd79 1090static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
d14ed18c
MR
1091 int sect_count, const char *filename,
1092 uint8_t *buffer, bool quiet)
1093{
1094 int pnum, ret = 0;
f1d3cd79 1095 ret = blk_read(blk, sect_num, buffer, sect_count);
d14ed18c
MR
1096 if (ret < 0) {
1097 error_report("Error while reading offset %" PRId64 " of %s: %s",
1098 sectors_to_bytes(sect_num), filename, strerror(-ret));
1099 return ret;
1100 }
1101 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1102 if (ret || pnum != sect_count) {
1103 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1104 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1105 return 1;
1106 }
1107
1108 return 0;
1109}
1110
1111/*
1112 * Compares two images. Exit codes:
1113 *
1114 * 0 - Images are identical
1115 * 1 - Images differ
1116 * >1 - Error occurred
1117 */
1118static int img_compare(int argc, char **argv)
1119{
40055951 1120 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
26f54e9a 1121 BlockBackend *blk1, *blk2;
d14ed18c
MR
1122 BlockDriverState *bs1, *bs2;
1123 int64_t total_sectors1, total_sectors2;
1124 uint8_t *buf1 = NULL, *buf2 = NULL;
1125 int pnum1, pnum2;
1126 int allocated1, allocated2;
1127 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1128 bool progress = false, quiet = false, strict = false;
40055951 1129 int flags;
ce099547 1130 bool writethrough;
d14ed18c
MR
1131 int64_t total_sectors;
1132 int64_t sector_num = 0;
1133 int64_t nb_sectors;
1134 int c, pnum;
d14ed18c 1135 uint64_t progress_base;
3babeb15 1136 Error *local_err = NULL;
eb769f74 1137 bool image_opts = false;
d14ed18c 1138
40055951 1139 cache = BDRV_DEFAULT_CACHE;
d14ed18c 1140 for (;;) {
3babeb15
DB
1141 static const struct option long_options[] = {
1142 {"help", no_argument, 0, 'h'},
1143 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1144 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
1145 {0, 0, 0, 0}
1146 };
1147 c = getopt_long(argc, argv, "hf:F:T:pqs",
1148 long_options, NULL);
d14ed18c
MR
1149 if (c == -1) {
1150 break;
1151 }
1152 switch (c) {
1153 case '?':
1154 case 'h':
1155 help();
1156 break;
1157 case 'f':
1158 fmt1 = optarg;
1159 break;
1160 case 'F':
1161 fmt2 = optarg;
1162 break;
40055951
HR
1163 case 'T':
1164 cache = optarg;
1165 break;
d14ed18c
MR
1166 case 'p':
1167 progress = true;
1168 break;
1169 case 'q':
1170 quiet = true;
1171 break;
1172 case 's':
1173 strict = true;
1174 break;
3babeb15
DB
1175 case OPTION_OBJECT: {
1176 QemuOpts *opts;
1177 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1178 optarg, true);
1179 if (!opts) {
1180 ret = 2;
1181 goto out4;
1182 }
1183 } break;
eb769f74
DB
1184 case OPTION_IMAGE_OPTS:
1185 image_opts = true;
1186 break;
d14ed18c
MR
1187 }
1188 }
1189
1190 /* Progress is not shown in Quiet mode */
1191 if (quiet) {
1192 progress = false;
1193 }
1194
1195
fc11eb26 1196 if (optind != argc - 2) {
ac1307ab 1197 error_exit("Expecting two image file names");
d14ed18c
MR
1198 }
1199 filename1 = argv[optind++];
1200 filename2 = argv[optind++];
1201
3babeb15
DB
1202 if (qemu_opts_foreach(&qemu_object_opts,
1203 user_creatable_add_opts_foreach,
1204 NULL, &local_err)) {
1205 error_report_err(local_err);
1206 ret = 2;
1207 goto out4;
1208 }
1209
cbda016d
SH
1210 /* Initialize before goto out */
1211 qemu_progress_init(progress, 2.0);
1212
ce099547
KW
1213 flags = 0;
1214 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
1215 if (ret < 0) {
1216 error_report("Invalid source cache option: %s", cache);
1217 ret = 2;
1218 goto out3;
1219 }
1220
ce099547 1221 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
7e7d56d9 1222 if (!blk1) {
d14ed18c 1223 ret = 2;
7e7d56d9 1224 goto out3;
d14ed18c
MR
1225 }
1226
ce099547 1227 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
7e7d56d9 1228 if (!blk2) {
d14ed18c 1229 ret = 2;
7e7d56d9 1230 goto out2;
d14ed18c 1231 }
eb769f74 1232 bs1 = blk_bs(blk1);
7e7d56d9 1233 bs2 = blk_bs(blk2);
d14ed18c 1234
f1d3cd79
HR
1235 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1236 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1237 total_sectors1 = blk_nb_sectors(blk1);
52bf1e72
MA
1238 if (total_sectors1 < 0) {
1239 error_report("Can't get size of %s: %s",
1240 filename1, strerror(-total_sectors1));
1241 ret = 4;
1242 goto out;
1243 }
f1d3cd79 1244 total_sectors2 = blk_nb_sectors(blk2);
52bf1e72
MA
1245 if (total_sectors2 < 0) {
1246 error_report("Can't get size of %s: %s",
1247 filename2, strerror(-total_sectors2));
1248 ret = 4;
1249 goto out;
1250 }
d14ed18c
MR
1251 total_sectors = MIN(total_sectors1, total_sectors2);
1252 progress_base = MAX(total_sectors1, total_sectors2);
1253
1254 qemu_progress_print(0, 100);
1255
1256 if (strict && total_sectors1 != total_sectors2) {
1257 ret = 1;
1258 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1259 goto out;
1260 }
1261
1262 for (;;) {
25ad8e6e 1263 int64_t status1, status2;
67a0fd2a
FZ
1264 BlockDriverState *file;
1265
d14ed18c
MR
1266 nb_sectors = sectors_to_process(total_sectors, sector_num);
1267 if (nb_sectors <= 0) {
1268 break;
1269 }
25ad8e6e
FZ
1270 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1271 total_sectors1 - sector_num,
67a0fd2a 1272 &pnum1, &file);
25ad8e6e 1273 if (status1 < 0) {
d14ed18c
MR
1274 ret = 3;
1275 error_report("Sector allocation test failed for %s", filename1);
1276 goto out;
1277 }
25ad8e6e 1278 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
d14ed18c 1279
25ad8e6e
FZ
1280 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1281 total_sectors2 - sector_num,
67a0fd2a 1282 &pnum2, &file);
25ad8e6e 1283 if (status2 < 0) {
d14ed18c
MR
1284 ret = 3;
1285 error_report("Sector allocation test failed for %s", filename2);
1286 goto out;
1287 }
25ad8e6e
FZ
1288 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1289 if (pnum1) {
1290 nb_sectors = MIN(nb_sectors, pnum1);
1291 }
1292 if (pnum2) {
1293 nb_sectors = MIN(nb_sectors, pnum2);
1294 }
d14ed18c 1295
25ad8e6e
FZ
1296 if (strict) {
1297 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1298 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1299 ret = 1;
1300 qprintf(quiet, "Strict mode: Offset %" PRId64
1301 " block status mismatch!\n",
1302 sectors_to_bytes(sector_num));
1303 goto out;
1304 }
1305 }
1306 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1307 nb_sectors = MIN(pnum1, pnum2);
1308 } else if (allocated1 == allocated2) {
d14ed18c 1309 if (allocated1) {
f1d3cd79 1310 ret = blk_read(blk1, sector_num, buf1, nb_sectors);
d14ed18c
MR
1311 if (ret < 0) {
1312 error_report("Error while reading offset %" PRId64 " of %s:"
1313 " %s", sectors_to_bytes(sector_num), filename1,
1314 strerror(-ret));
1315 ret = 4;
1316 goto out;
1317 }
f1d3cd79 1318 ret = blk_read(blk2, sector_num, buf2, nb_sectors);
d14ed18c
MR
1319 if (ret < 0) {
1320 error_report("Error while reading offset %" PRId64
1321 " of %s: %s", sectors_to_bytes(sector_num),
1322 filename2, strerror(-ret));
1323 ret = 4;
1324 goto out;
1325 }
1326 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1327 if (ret || pnum != nb_sectors) {
d14ed18c
MR
1328 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1329 sectors_to_bytes(
1330 ret ? sector_num : sector_num + pnum));
36452f12 1331 ret = 1;
d14ed18c
MR
1332 goto out;
1333 }
1334 }
1335 } else {
d14ed18c
MR
1336
1337 if (allocated1) {
f1d3cd79 1338 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
d14ed18c
MR
1339 filename1, buf1, quiet);
1340 } else {
f1d3cd79 1341 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
d14ed18c
MR
1342 filename2, buf1, quiet);
1343 }
1344 if (ret) {
1345 if (ret < 0) {
d14ed18c
MR
1346 error_report("Error while reading offset %" PRId64 ": %s",
1347 sectors_to_bytes(sector_num), strerror(-ret));
36452f12 1348 ret = 4;
d14ed18c
MR
1349 }
1350 goto out;
1351 }
1352 }
1353 sector_num += nb_sectors;
1354 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1355 }
1356
1357 if (total_sectors1 != total_sectors2) {
f1d3cd79 1358 BlockBackend *blk_over;
d14ed18c
MR
1359 int64_t total_sectors_over;
1360 const char *filename_over;
1361
1362 qprintf(quiet, "Warning: Image size mismatch!\n");
1363 if (total_sectors1 > total_sectors2) {
1364 total_sectors_over = total_sectors1;
f1d3cd79 1365 blk_over = blk1;
d14ed18c
MR
1366 filename_over = filename1;
1367 } else {
1368 total_sectors_over = total_sectors2;
f1d3cd79 1369 blk_over = blk2;
d14ed18c
MR
1370 filename_over = filename2;
1371 }
1372
1373 for (;;) {
1374 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1375 if (nb_sectors <= 0) {
1376 break;
1377 }
f1d3cd79 1378 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
d14ed18c
MR
1379 nb_sectors, &pnum);
1380 if (ret < 0) {
1381 ret = 3;
1382 error_report("Sector allocation test failed for %s",
1383 filename_over);
1384 goto out;
1385
1386 }
1387 nb_sectors = pnum;
1388 if (ret) {
f1d3cd79 1389 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
d14ed18c
MR
1390 filename_over, buf1, quiet);
1391 if (ret) {
1392 if (ret < 0) {
d14ed18c
MR
1393 error_report("Error while reading offset %" PRId64
1394 " of %s: %s", sectors_to_bytes(sector_num),
1395 filename_over, strerror(-ret));
36452f12 1396 ret = 4;
d14ed18c
MR
1397 }
1398 goto out;
1399 }
1400 }
1401 sector_num += nb_sectors;
1402 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1403 }
1404 }
1405
1406 qprintf(quiet, "Images are identical.\n");
1407 ret = 0;
1408
1409out:
d14ed18c
MR
1410 qemu_vfree(buf1);
1411 qemu_vfree(buf2);
26f54e9a 1412 blk_unref(blk2);
d14ed18c 1413out2:
26f54e9a 1414 blk_unref(blk1);
d14ed18c
MR
1415out3:
1416 qemu_progress_end();
3babeb15 1417out4:
d14ed18c
MR
1418 return ret;
1419}
1420
690c7301
KW
1421enum ImgConvertBlockStatus {
1422 BLK_DATA,
1423 BLK_ZERO,
1424 BLK_BACKING_FILE,
1425};
1426
1427typedef struct ImgConvertState {
1428 BlockBackend **src;
1429 int64_t *src_sectors;
1430 int src_cur, src_num;
1431 int64_t src_cur_offset;
1432 int64_t total_sectors;
1433 int64_t allocated_sectors;
1434 enum ImgConvertBlockStatus status;
1435 int64_t sector_next_status;
1436 BlockBackend *target;
1437 bool has_zero_init;
1438 bool compressed;
1439 bool target_has_backing;
1440 int min_sparse;
1441 size_t cluster_sectors;
1442 size_t buf_sectors;
1443} ImgConvertState;
1444
1445static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1446{
1447 assert(sector_num >= s->src_cur_offset);
1448 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1449 s->src_cur_offset += s->src_sectors[s->src_cur];
1450 s->src_cur++;
1451 assert(s->src_cur < s->src_num);
1452 }
1453}
1454
1455static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1456{
1457 int64_t ret;
1458 int n;
1459
1460 convert_select_part(s, sector_num);
1461
1462 assert(s->total_sectors > sector_num);
1463 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1464
1465 if (s->sector_next_status <= sector_num) {
67a0fd2a 1466 BlockDriverState *file;
690c7301
KW
1467 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1468 sector_num - s->src_cur_offset,
67a0fd2a 1469 n, &n, &file);
690c7301
KW
1470 if (ret < 0) {
1471 return ret;
1472 }
1473
1474 if (ret & BDRV_BLOCK_ZERO) {
1475 s->status = BLK_ZERO;
1476 } else if (ret & BDRV_BLOCK_DATA) {
1477 s->status = BLK_DATA;
1478 } else if (!s->target_has_backing) {
1479 /* Without a target backing file we must copy over the contents of
1480 * the backing file as well. */
1481 /* TODO Check block status of the backing file chain to avoid
1482 * needlessly reading zeroes and limiting the iteration to the
1483 * buffer size */
1484 s->status = BLK_DATA;
1485 } else {
1486 s->status = BLK_BACKING_FILE;
1487 }
1488
1489 s->sector_next_status = sector_num + n;
1490 }
1491
1492 n = MIN(n, s->sector_next_status - sector_num);
1493 if (s->status == BLK_DATA) {
1494 n = MIN(n, s->buf_sectors);
1495 }
1496
1497 /* We need to write complete clusters for compressed images, so if an
1498 * unallocated area is shorter than that, we must consider the whole
1499 * cluster allocated. */
1500 if (s->compressed) {
1501 if (n < s->cluster_sectors) {
1502 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1503 s->status = BLK_DATA;
1504 } else {
1505 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1506 }
1507 }
1508
1509 return n;
1510}
1511
1512static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1513 uint8_t *buf)
1514{
1515 int n;
1516 int ret;
1517
690c7301
KW
1518 assert(nb_sectors <= s->buf_sectors);
1519 while (nb_sectors > 0) {
1520 BlockBackend *blk;
1521 int64_t bs_sectors;
1522
1523 /* In the case of compression with multiple source files, we can get a
1524 * nb_sectors that spreads into the next part. So we must be able to
1525 * read across multiple BDSes for one convert_read() call. */
1526 convert_select_part(s, sector_num);
1527 blk = s->src[s->src_cur];
1528 bs_sectors = s->src_sectors[s->src_cur];
1529
1530 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
1531 ret = blk_read(blk, sector_num - s->src_cur_offset, buf, n);
1532 if (ret < 0) {
1533 return ret;
1534 }
1535
1536 sector_num += n;
1537 nb_sectors -= n;
1538 buf += n * BDRV_SECTOR_SIZE;
1539 }
1540
1541 return 0;
1542}
1543
1544static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1545 const uint8_t *buf)
1546{
1547 int ret;
1548
1549 while (nb_sectors > 0) {
1550 int n = nb_sectors;
1551
1552 switch (s->status) {
1553 case BLK_BACKING_FILE:
1554 /* If we have a backing file, leave clusters unallocated that are
1555 * unallocated in the source image, so that the backing file is
1556 * visible at the respective offset. */
1557 assert(s->target_has_backing);
1558 break;
1559
1560 case BLK_DATA:
1561 /* We must always write compressed clusters as a whole, so don't
1562 * try to find zeroed parts in the buffer. We can only save the
1563 * write if the buffer is completely zeroed and we're allowed to
1564 * keep the target sparse. */
1565 if (s->compressed) {
1566 if (s->has_zero_init && s->min_sparse &&
1567 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1568 {
1569 assert(!s->target_has_backing);
1570 break;
1571 }
1572
1573 ret = blk_write_compressed(s->target, sector_num, buf, n);
1574 if (ret < 0) {
1575 return ret;
1576 }
1577 break;
1578 }
1579
1580 /* If there is real non-zero data or we're told to keep the target
1581 * fully allocated (-S 0), we must write it. Otherwise we can treat
1582 * it as zero sectors. */
1583 if (!s->min_sparse ||
1584 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1585 {
1586 ret = blk_write(s->target, sector_num, buf, n);
1587 if (ret < 0) {
1588 return ret;
1589 }
1590 break;
1591 }
1592 /* fall-through */
1593
1594 case BLK_ZERO:
1595 if (s->has_zero_init) {
1596 break;
1597 }
1598 ret = blk_write_zeroes(s->target, sector_num, n, 0);
1599 if (ret < 0) {
1600 return ret;
1601 }
1602 break;
1603 }
1604
1605 sector_num += n;
1606 nb_sectors -= n;
1607 buf += n * BDRV_SECTOR_SIZE;
1608 }
1609
1610 return 0;
1611}
1612
1613static int convert_do_copy(ImgConvertState *s)
1614{
1615 uint8_t *buf = NULL;
1616 int64_t sector_num, allocated_done;
1617 int ret;
1618 int n;
1619
1620 /* Check whether we have zero initialisation or can get it efficiently */
1621 s->has_zero_init = s->min_sparse && !s->target_has_backing
1622 ? bdrv_has_zero_init(blk_bs(s->target))
1623 : false;
1624
1625 if (!s->has_zero_init && !s->target_has_backing &&
1626 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1627 {
1628 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1629 if (ret == 0) {
1630 s->has_zero_init = true;
1631 }
1632 }
1633
1634 /* Allocate buffer for copied data. For compressed images, only one cluster
1635 * can be copied at a time. */
1636 if (s->compressed) {
1637 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1638 error_report("invalid cluster size");
1639 ret = -EINVAL;
1640 goto fail;
1641 }
1642 s->buf_sectors = s->cluster_sectors;
1643 }
1644 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1645
1646 /* Calculate allocated sectors for progress */
1647 s->allocated_sectors = 0;
1648 sector_num = 0;
1649 while (sector_num < s->total_sectors) {
1650 n = convert_iteration_sectors(s, sector_num);
1651 if (n < 0) {
1652 ret = n;
1653 goto fail;
1654 }
aad15de4
HR
1655 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1656 {
690c7301
KW
1657 s->allocated_sectors += n;
1658 }
1659 sector_num += n;
1660 }
1661
1662 /* Do the copy */
1663 s->src_cur = 0;
1664 s->src_cur_offset = 0;
1665 s->sector_next_status = 0;
1666
1667 sector_num = 0;
1668 allocated_done = 0;
1669
1670 while (sector_num < s->total_sectors) {
1671 n = convert_iteration_sectors(s, sector_num);
1672 if (n < 0) {
1673 ret = n;
1674 goto fail;
1675 }
aad15de4
HR
1676 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1677 {
690c7301
KW
1678 allocated_done += n;
1679 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1680 0);
1681 }
1682
aad15de4
HR
1683 if (s->status == BLK_DATA) {
1684 ret = convert_read(s, sector_num, n, buf);
1685 if (ret < 0) {
1686 error_report("error while reading sector %" PRId64
1687 ": %s", sector_num, strerror(-ret));
1688 goto fail;
1689 }
1690 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1691 n = MIN(n, s->buf_sectors);
1692 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1693 s->status = BLK_DATA;
690c7301
KW
1694 }
1695
1696 ret = convert_write(s, sector_num, n, buf);
1697 if (ret < 0) {
1698 error_report("error while writing sector %" PRId64
1699 ": %s", sector_num, strerror(-ret));
1700 goto fail;
1701 }
1702
1703 sector_num += n;
1704 }
1705
1706 if (s->compressed) {
1707 /* signal EOF to align */
1708 ret = blk_write_compressed(s->target, 0, NULL, 0);
1709 if (ret < 0) {
1710 goto fail;
1711 }
1712 }
1713
1714 ret = 0;
1715fail:
1716 qemu_vfree(buf);
1717 return ret;
1718}
1719
ea2384d3
FB
1720static int img_convert(int argc, char **argv)
1721{
690c7301 1722 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
13c28af8 1723 int64_t ret = 0;
40055951 1724 int progress = 0, flags, src_flags;
ce099547 1725 bool writethrough, src_writethrough;
40055951 1726 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
b50cbabc 1727 BlockDriver *drv, *proto_drv;
26f54e9a 1728 BlockBackend **blk = NULL, *out_blk = NULL;
c2abccec 1729 BlockDriverState **bs = NULL, *out_bs = NULL;
690c7301 1730 int64_t total_sectors;
52bf1e72 1731 int64_t *bs_sectors = NULL;
f2521c90 1732 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
faea38e7 1733 BlockDriverInfo bdi;
83d0521a
CL
1734 QemuOpts *opts = NULL;
1735 QemuOptsList *create_opts = NULL;
1736 const char *out_baseimg_param;
efa84d43 1737 char *options = NULL;
51ef6727 1738 const char *snapshot_name = NULL;
a22f123c 1739 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
f382d43a 1740 bool quiet = false;
cc84d90f 1741 Error *local_err = NULL;
ef80654d 1742 QemuOpts *sn_opts = NULL;
690c7301 1743 ImgConvertState state;
eb769f74 1744 bool image_opts = false;
ea2384d3
FB
1745
1746 fmt = NULL;
1747 out_fmt = "raw";
661a0f71 1748 cache = "unsafe";
40055951 1749 src_cache = BDRV_DEFAULT_CACHE;
f58c7b35 1750 out_baseimg = NULL;
eec77d9e 1751 compress = 0;
b2e10493 1752 skip_create = 0;
ea2384d3 1753 for(;;) {
3babeb15
DB
1754 static const struct option long_options[] = {
1755 {"help", no_argument, 0, 'h'},
1756 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1757 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
1758 {0, 0, 0, 0}
1759 };
1760 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1761 long_options, NULL);
b8fb60da 1762 if (c == -1) {
ea2384d3 1763 break;
b8fb60da 1764 }
ea2384d3 1765 switch(c) {
ef87394c 1766 case '?':
ea2384d3
FB
1767 case 'h':
1768 help();
1769 break;
1770 case 'f':
1771 fmt = optarg;
1772 break;
1773 case 'O':
1774 out_fmt = optarg;
1775 break;
f58c7b35
TS
1776 case 'B':
1777 out_baseimg = optarg;
1778 break;
ea2384d3 1779 case 'c':
eec77d9e 1780 compress = 1;
ea2384d3
FB
1781 break;
1782 case 'e':
9d42e15d 1783 error_report("option -e is deprecated, please use \'-o "
eec77d9e 1784 "encryption\' instead!");
2dc8328b 1785 ret = -1;
64bb01aa 1786 goto fail_getopt;
ec36ba14 1787 case '6':
9d42e15d 1788 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 1789 "compat6\' instead!");
2dc8328b 1790 ret = -1;
64bb01aa 1791 goto fail_getopt;
efa84d43 1792 case 'o':
2dc8328b
KW
1793 if (!is_valid_option_list(optarg)) {
1794 error_report("Invalid option list: %s", optarg);
1795 ret = -1;
64bb01aa 1796 goto fail_getopt;
2dc8328b
KW
1797 }
1798 if (!options) {
1799 options = g_strdup(optarg);
1800 } else {
1801 char *old_options = options;
1802 options = g_strdup_printf("%s,%s", options, optarg);
1803 g_free(old_options);
1804 }
efa84d43 1805 break;
51ef6727 1806 case 's':
1807 snapshot_name = optarg;
1808 break;
ef80654d
WX
1809 case 'l':
1810 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
1811 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1812 optarg, false);
ef80654d
WX
1813 if (!sn_opts) {
1814 error_report("Failed in parsing snapshot param '%s'",
1815 optarg);
2dc8328b 1816 ret = -1;
64bb01aa 1817 goto fail_getopt;
ef80654d
WX
1818 }
1819 } else {
1820 snapshot_name = optarg;
1821 }
1822 break;
a22f123c
KW
1823 case 'S':
1824 {
1825 int64_t sval;
e36b3695 1826 char *end;
4677bb40 1827 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 1828 if (sval < 0 || *end) {
a22f123c 1829 error_report("Invalid minimum zero buffer size for sparse output specified");
2dc8328b 1830 ret = -1;
64bb01aa 1831 goto fail_getopt;
a22f123c
KW
1832 }
1833
1834 min_sparse = sval / BDRV_SECTOR_SIZE;
1835 break;
1836 }
6b837bc4
JS
1837 case 'p':
1838 progress = 1;
1839 break;
661a0f71
FS
1840 case 't':
1841 cache = optarg;
1842 break;
40055951
HR
1843 case 'T':
1844 src_cache = optarg;
1845 break;
f382d43a
MR
1846 case 'q':
1847 quiet = true;
1848 break;
b2e10493
AD
1849 case 'n':
1850 skip_create = 1;
1851 break;
3babeb15
DB
1852 case OPTION_OBJECT:
1853 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1854 optarg, true);
1855 if (!opts) {
1856 goto fail_getopt;
1857 }
1858 break;
eb769f74
DB
1859 case OPTION_IMAGE_OPTS:
1860 image_opts = true;
1861 break;
ea2384d3
FB
1862 }
1863 }
3b46e624 1864
3babeb15
DB
1865 if (qemu_opts_foreach(&qemu_object_opts,
1866 user_creatable_add_opts_foreach,
1867 NULL, &local_err)) {
1868 error_report_err(local_err);
1869 goto fail_getopt;
1870 }
1871
64bb01aa 1872 /* Initialize before goto out */
f382d43a
MR
1873 if (quiet) {
1874 progress = 0;
1875 }
64bb01aa
KW
1876 qemu_progress_init(progress, 1.0);
1877
926c2d23 1878 bs_n = argc - optind - 1;
a283cb6e 1879 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
f58c7b35 1880
2dc8328b 1881 if (options && has_help_option(options)) {
4ac8aacd
JS
1882 ret = print_block_option_help(out_filename, out_fmt);
1883 goto out;
1884 }
1885
a283cb6e 1886 if (bs_n < 1) {
ac1307ab 1887 error_exit("Must specify image file name");
a283cb6e
KW
1888 }
1889
1890
c2abccec 1891 if (bs_n > 1 && out_baseimg) {
15654a6d
JS
1892 error_report("-B makes no sense when concatenating multiple input "
1893 "images");
31ca34b8
JS
1894 ret = -1;
1895 goto out;
c2abccec 1896 }
f8111c24 1897
ce099547
KW
1898 src_flags = 0;
1899 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
1900 if (ret < 0) {
1901 error_report("Invalid source cache option: %s", src_cache);
1902 goto out;
1903 }
1904
6b837bc4
JS
1905 qemu_progress_print(0, 100);
1906
26f54e9a 1907 blk = g_new0(BlockBackend *, bs_n);
d739f1c4 1908 bs = g_new0(BlockDriverState *, bs_n);
52bf1e72 1909 bs_sectors = g_new(int64_t, bs_n);
926c2d23
AZ
1910
1911 total_sectors = 0;
1912 for (bs_i = 0; bs_i < bs_n; bs_i++) {
efaa7c4e 1913 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
ce099547 1914 fmt, src_flags, src_writethrough, quiet);
7e7d56d9 1915 if (!blk[bs_i]) {
c2abccec
MK
1916 ret = -1;
1917 goto out;
1918 }
7e7d56d9 1919 bs[bs_i] = blk_bs(blk[bs_i]);
f1d3cd79 1920 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
52bf1e72
MA
1921 if (bs_sectors[bs_i] < 0) {
1922 error_report("Could not get size of %s: %s",
1923 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1924 ret = -1;
1925 goto out;
1926 }
d739f1c4 1927 total_sectors += bs_sectors[bs_i];
926c2d23 1928 }
ea2384d3 1929
ef80654d
WX
1930 if (sn_opts) {
1931 ret = bdrv_snapshot_load_tmp(bs[0],
1932 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1933 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1934 &local_err);
1935 } else if (snapshot_name != NULL) {
51ef6727 1936 if (bs_n > 1) {
6daf194d 1937 error_report("No support for concatenating multiple snapshot");
51ef6727 1938 ret = -1;
1939 goto out;
1940 }
7b4c4781
WX
1941
1942 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
ef80654d 1943 }
84d18f06 1944 if (local_err) {
c29b77f9 1945 error_reportf_err(local_err, "Failed to load snapshot: ");
ef80654d
WX
1946 ret = -1;
1947 goto out;
51ef6727 1948 }
1949
efa84d43 1950 /* Find driver and parse its options */
ea2384d3 1951 drv = bdrv_find_format(out_fmt);
c2abccec 1952 if (!drv) {
15654a6d 1953 error_report("Unknown file format '%s'", out_fmt);
c2abccec
MK
1954 ret = -1;
1955 goto out;
1956 }
efa84d43 1957
b65a5e12 1958 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
c2abccec 1959 if (!proto_drv) {
2867ce4a 1960 error_report_err(local_err);
c2abccec
MK
1961 ret = -1;
1962 goto out;
1963 }
b50cbabc 1964
2e024cde
HR
1965 if (!skip_create) {
1966 if (!drv->create_opts) {
1967 error_report("Format driver '%s' does not support image creation",
1968 drv->format_name);
1969 ret = -1;
1970 goto out;
1971 }
f75613cf 1972
2e024cde
HR
1973 if (!proto_drv->create_opts) {
1974 error_report("Protocol driver '%s' does not support image creation",
1975 proto_drv->format_name);
1976 ret = -1;
1977 goto out;
1978 }
f75613cf 1979
2e024cde
HR
1980 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1981 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 1982
2e024cde 1983 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
1984 if (options) {
1985 qemu_opts_do_parse(opts, options, NULL, &local_err);
1986 if (local_err) {
97a2ca7a 1987 error_report_err(local_err);
dc523cd3
MA
1988 ret = -1;
1989 goto out;
1990 }
2e024cde 1991 }
efa84d43 1992
39101f25
MA
1993 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
1994 &error_abort);
2e024cde
HR
1995 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
1996 if (ret < 0) {
1997 goto out;
1998 }
c2abccec 1999 }
efa84d43 2000
a18953fb 2001 /* Get backing file name if -o backing_file was used */
83d0521a 2002 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 2003 if (out_baseimg_param) {
83d0521a 2004 out_baseimg = out_baseimg_param;
a18953fb
KW
2005 }
2006
efa84d43 2007 /* Check if compression is supported */
eec77d9e 2008 if (compress) {
83d0521a
CL
2009 bool encryption =
2010 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2011 const char *preallocation =
2012 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
efa84d43
KW
2013
2014 if (!drv->bdrv_write_compressed) {
15654a6d 2015 error_report("Compression not supported for this file format");
c2abccec
MK
2016 ret = -1;
2017 goto out;
efa84d43
KW
2018 }
2019
83d0521a 2020 if (encryption) {
15654a6d
JS
2021 error_report("Compression and encryption not supported at "
2022 "the same time");
c2abccec
MK
2023 ret = -1;
2024 goto out;
efa84d43 2025 }
41521fa4 2026
83d0521a
CL
2027 if (preallocation
2028 && strcmp(preallocation, "off"))
41521fa4
KW
2029 {
2030 error_report("Compression and preallocation not supported at "
2031 "the same time");
2032 ret = -1;
2033 goto out;
2034 }
efa84d43
KW
2035 }
2036
b2e10493
AD
2037 if (!skip_create) {
2038 /* Create the new image */
c282e1fd 2039 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 2040 if (ret < 0) {
c29b77f9
MA
2041 error_reportf_err(local_err, "%s: error while converting %s: ",
2042 out_filename, out_fmt);
b2e10493 2043 goto out;
ea2384d3
FB
2044 }
2045 }
3b46e624 2046
5a37b60a 2047 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
ce099547 2048 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2049 if (ret < 0) {
2050 error_report("Invalid cache option: %s", cache);
bb9cd2ee 2051 goto out;
661a0f71
FS
2052 }
2053
eb769f74
DB
2054 /* XXX we should allow --image-opts to trigger use of
2055 * img_open() here, but then we have trouble with
2056 * the bdrv_create() call which takes different params.
2057 * Not critical right now, so fix can wait...
2058 */
ce099547 2059 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
7e7d56d9 2060 if (!out_blk) {
c2abccec
MK
2061 ret = -1;
2062 goto out;
2063 }
7e7d56d9 2064 out_bs = blk_bs(out_blk);
ea2384d3 2065
f2521c90
PL
2066 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2067 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2068 * as maximum. */
2069 bufsectors = MIN(32768,
2070 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2071 out_bs->bl.discard_alignment))
2072 );
2073
b2e10493 2074 if (skip_create) {
f1d3cd79 2075 int64_t output_sectors = blk_nb_sectors(out_blk);
43716fa8 2076 if (output_sectors < 0) {
eec5eb42 2077 error_report("unable to get output image length: %s",
43716fa8 2078 strerror(-output_sectors));
b2e10493
AD
2079 ret = -1;
2080 goto out;
43716fa8 2081 } else if (output_sectors < total_sectors) {
b2e10493
AD
2082 error_report("output file is smaller than input file");
2083 ret = -1;
2084 goto out;
2085 }
2086 }
2087
24f833cd
PL
2088 cluster_sectors = 0;
2089 ret = bdrv_get_info(out_bs, &bdi);
2090 if (ret < 0) {
2091 if (compress) {
15654a6d 2092 error_report("could not get block driver info");
c2abccec
MK
2093 goto out;
2094 }
24f833cd 2095 } else {
85f49cad 2096 compress = compress || bdi.needs_compressed_writes;
24f833cd
PL
2097 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2098 }
2099
690c7301
KW
2100 state = (ImgConvertState) {
2101 .src = blk,
2102 .src_sectors = bs_sectors,
2103 .src_num = bs_n,
2104 .total_sectors = total_sectors,
2105 .target = out_blk,
2106 .compressed = compress,
2107 .target_has_backing = (bool) out_baseimg,
2108 .min_sparse = min_sparse,
2109 .cluster_sectors = cluster_sectors,
2110 .buf_sectors = bufsectors,
2111 };
2112 ret = convert_do_copy(&state);
802c3d4c 2113
c2abccec 2114out:
13c28af8
PL
2115 if (!ret) {
2116 qemu_progress_print(100, 0);
2117 }
6b837bc4 2118 qemu_progress_end();
83d0521a
CL
2119 qemu_opts_del(opts);
2120 qemu_opts_free(create_opts);
fbf28a43 2121 qemu_opts_del(sn_opts);
26f54e9a 2122 blk_unref(out_blk);
9ba10c95 2123 g_free(bs);
26f54e9a
MA
2124 if (blk) {
2125 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2126 blk_unref(blk[bs_i]);
2127 }
2128 g_free(blk);
2129 }
d739f1c4 2130 g_free(bs_sectors);
64bb01aa
KW
2131fail_getopt:
2132 g_free(options);
2133
c2abccec
MK
2134 if (ret) {
2135 return 1;
2136 }
ea2384d3
FB
2137 return 0;
2138}
2139
57d1a2b6 2140
faea38e7
FB
2141static void dump_snapshots(BlockDriverState *bs)
2142{
2143 QEMUSnapshotInfo *sn_tab, *sn;
2144 int nb_sns, i;
faea38e7
FB
2145
2146 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2147 if (nb_sns <= 0)
2148 return;
2149 printf("Snapshot list:\n");
5b917044
WX
2150 bdrv_snapshot_dump(fprintf, stdout, NULL);
2151 printf("\n");
faea38e7
FB
2152 for(i = 0; i < nb_sns; i++) {
2153 sn = &sn_tab[i];
5b917044
WX
2154 bdrv_snapshot_dump(fprintf, stdout, sn);
2155 printf("\n");
faea38e7 2156 }
7267c094 2157 g_free(sn_tab);
faea38e7
FB
2158}
2159
9699bf0d
SH
2160static void dump_json_image_info_list(ImageInfoList *list)
2161{
4399c438 2162 Error *local_err = NULL;
9699bf0d
SH
2163 QString *str;
2164 QmpOutputVisitor *ov = qmp_output_visitor_new();
2165 QObject *obj;
51e72bc1
EB
2166 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2167 &local_err);
9699bf0d
SH
2168 obj = qmp_output_get_qobject(ov);
2169 str = qobject_to_json_pretty(obj);
2170 assert(str != NULL);
2171 printf("%s\n", qstring_get_str(str));
2172 qobject_decref(obj);
2173 qmp_output_visitor_cleanup(ov);
2174 QDECREF(str);
2175}
2176
c054b3fd
BC
2177static void dump_json_image_info(ImageInfo *info)
2178{
4399c438 2179 Error *local_err = NULL;
c054b3fd
BC
2180 QString *str;
2181 QmpOutputVisitor *ov = qmp_output_visitor_new();
2182 QObject *obj;
51e72bc1 2183 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
c054b3fd
BC
2184 obj = qmp_output_get_qobject(ov);
2185 str = qobject_to_json_pretty(obj);
2186 assert(str != NULL);
2187 printf("%s\n", qstring_get_str(str));
2188 qobject_decref(obj);
2189 qmp_output_visitor_cleanup(ov);
2190 QDECREF(str);
2191}
2192
9699bf0d
SH
2193static void dump_human_image_info_list(ImageInfoList *list)
2194{
2195 ImageInfoList *elem;
2196 bool delim = false;
2197
2198 for (elem = list; elem; elem = elem->next) {
2199 if (delim) {
2200 printf("\n");
2201 }
2202 delim = true;
2203
5b917044 2204 bdrv_image_info_dump(fprintf, stdout, elem->value);
9699bf0d
SH
2205 }
2206}
2207
2208static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2209{
2210 return strcmp(a, b) == 0;
2211}
2212
2213/**
2214 * Open an image file chain and return an ImageInfoList
2215 *
2216 * @filename: topmost image filename
2217 * @fmt: topmost image format (may be NULL to autodetect)
2218 * @chain: true - enumerate entire backing file chain
2219 * false - only topmost image file
2220 *
2221 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2222 * image file. If there was an error a message will have been printed to
2223 * stderr.
2224 */
eb769f74
DB
2225static ImageInfoList *collect_image_info_list(bool image_opts,
2226 const char *filename,
9699bf0d
SH
2227 const char *fmt,
2228 bool chain)
2229{
2230 ImageInfoList *head = NULL;
2231 ImageInfoList **last = &head;
2232 GHashTable *filenames;
43526ec8 2233 Error *err = NULL;
9699bf0d
SH
2234
2235 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2236
2237 while (filename) {
26f54e9a 2238 BlockBackend *blk;
9699bf0d
SH
2239 BlockDriverState *bs;
2240 ImageInfo *info;
2241 ImageInfoList *elem;
2242
2243 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2244 error_report("Backing file '%s' creates an infinite loop.",
2245 filename);
2246 goto err;
2247 }
2248 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2249
efaa7c4e 2250 blk = img_open(image_opts, filename, fmt,
ce099547 2251 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
7e7d56d9 2252 if (!blk) {
9699bf0d
SH
2253 goto err;
2254 }
7e7d56d9 2255 bs = blk_bs(blk);
9699bf0d 2256
43526ec8 2257 bdrv_query_image_info(bs, &info, &err);
84d18f06 2258 if (err) {
565f65d2 2259 error_report_err(err);
26f54e9a 2260 blk_unref(blk);
43526ec8 2261 goto err;
fb0ed453 2262 }
9699bf0d
SH
2263
2264 elem = g_new0(ImageInfoList, 1);
2265 elem->value = info;
2266 *last = elem;
2267 last = &elem->next;
2268
26f54e9a 2269 blk_unref(blk);
9699bf0d
SH
2270
2271 filename = fmt = NULL;
2272 if (chain) {
2273 if (info->has_full_backing_filename) {
2274 filename = info->full_backing_filename;
2275 } else if (info->has_backing_filename) {
92d617ab
JS
2276 error_report("Could not determine absolute backing filename,"
2277 " but backing filename '%s' present",
2278 info->backing_filename);
2279 goto err;
9699bf0d
SH
2280 }
2281 if (info->has_backing_filename_format) {
2282 fmt = info->backing_filename_format;
2283 }
2284 }
2285 }
2286 g_hash_table_destroy(filenames);
2287 return head;
2288
2289err:
2290 qapi_free_ImageInfoList(head);
2291 g_hash_table_destroy(filenames);
2292 return NULL;
2293}
2294
c054b3fd
BC
2295static int img_info(int argc, char **argv)
2296{
2297 int c;
2298 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 2299 bool chain = false;
c054b3fd 2300 const char *filename, *fmt, *output;
9699bf0d 2301 ImageInfoList *list;
3babeb15 2302 Error *local_err = NULL;
eb769f74 2303 bool image_opts = false;
c054b3fd 2304
ea2384d3 2305 fmt = NULL;
c054b3fd 2306 output = NULL;
ea2384d3 2307 for(;;) {
c054b3fd
BC
2308 int option_index = 0;
2309 static const struct option long_options[] = {
2310 {"help", no_argument, 0, 'h'},
2311 {"format", required_argument, 0, 'f'},
2312 {"output", required_argument, 0, OPTION_OUTPUT},
9699bf0d 2313 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3babeb15 2314 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2315 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
c054b3fd
BC
2316 {0, 0, 0, 0}
2317 };
2318 c = getopt_long(argc, argv, "f:h",
2319 long_options, &option_index);
b8fb60da 2320 if (c == -1) {
ea2384d3 2321 break;
b8fb60da 2322 }
ea2384d3 2323 switch(c) {
ef87394c 2324 case '?':
ea2384d3
FB
2325 case 'h':
2326 help();
2327 break;
2328 case 'f':
2329 fmt = optarg;
2330 break;
c054b3fd
BC
2331 case OPTION_OUTPUT:
2332 output = optarg;
2333 break;
9699bf0d
SH
2334 case OPTION_BACKING_CHAIN:
2335 chain = true;
2336 break;
3babeb15
DB
2337 case OPTION_OBJECT: {
2338 QemuOpts *opts;
2339 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2340 optarg, true);
2341 if (!opts) {
2342 return 1;
2343 }
2344 } break;
eb769f74
DB
2345 case OPTION_IMAGE_OPTS:
2346 image_opts = true;
2347 break;
ea2384d3
FB
2348 }
2349 }
fc11eb26 2350 if (optind != argc - 1) {
ac1307ab 2351 error_exit("Expecting one image file name");
b8fb60da 2352 }
ea2384d3
FB
2353 filename = argv[optind++];
2354
c054b3fd
BC
2355 if (output && !strcmp(output, "json")) {
2356 output_format = OFORMAT_JSON;
2357 } else if (output && !strcmp(output, "human")) {
2358 output_format = OFORMAT_HUMAN;
2359 } else if (output) {
2360 error_report("--output must be used with human or json as argument.");
c2abccec
MK
2361 return 1;
2362 }
c054b3fd 2363
3babeb15
DB
2364 if (qemu_opts_foreach(&qemu_object_opts,
2365 user_creatable_add_opts_foreach,
2366 NULL, &local_err)) {
2367 error_report_err(local_err);
2368 return 1;
2369 }
2370
eb769f74 2371 list = collect_image_info_list(image_opts, filename, fmt, chain);
9699bf0d 2372 if (!list) {
c2abccec 2373 return 1;
faea38e7 2374 }
c054b3fd 2375
c054b3fd
BC
2376 switch (output_format) {
2377 case OFORMAT_HUMAN:
9699bf0d 2378 dump_human_image_info_list(list);
c054b3fd
BC
2379 break;
2380 case OFORMAT_JSON:
9699bf0d
SH
2381 if (chain) {
2382 dump_json_image_info_list(list);
2383 } else {
2384 dump_json_image_info(list->value);
2385 }
c054b3fd 2386 break;
faea38e7 2387 }
c054b3fd 2388
9699bf0d 2389 qapi_free_ImageInfoList(list);
ea2384d3
FB
2390 return 0;
2391}
2392
4c93a13b
PB
2393static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2394 MapEntry *next)
2395{
2396 switch (output_format) {
2397 case OFORMAT_HUMAN:
16b0d555 2398 if (e->data && !e->has_offset) {
4c93a13b
PB
2399 error_report("File contains external, encrypted or compressed clusters.");
2400 exit(1);
2401 }
16b0d555 2402 if (e->data && !e->zero) {
4c93a13b 2403 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
16b0d555
FZ
2404 e->start, e->length,
2405 e->has_offset ? e->offset : 0,
2406 e->has_filename ? e->filename : "");
4c93a13b
PB
2407 }
2408 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2409 * Modify the flags here to allow more coalescing.
2410 */
16b0d555
FZ
2411 if (next && (!next->data || next->zero)) {
2412 next->data = false;
2413 next->zero = true;
4c93a13b
PB
2414 }
2415 break;
2416 case OFORMAT_JSON:
16b0d555
FZ
2417 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2418 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
4c93a13b
PB
2419 (e->start == 0 ? "[" : ",\n"),
2420 e->start, e->length, e->depth,
16b0d555
FZ
2421 e->zero ? "true" : "false",
2422 e->data ? "true" : "false");
2423 if (e->has_offset) {
c745bfb4 2424 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2425 }
2426 putchar('}');
2427
2428 if (!next) {
2429 printf("]\n");
2430 }
2431 break;
2432 }
2433}
2434
2435static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2436 int nb_sectors, MapEntry *e)
2437{
2438 int64_t ret;
2439 int depth;
67a0fd2a 2440 BlockDriverState *file;
2875645b 2441 bool has_offset;
4c93a13b
PB
2442
2443 /* As an optimization, we could cache the current range of unallocated
2444 * clusters in each file of the chain, and avoid querying the same
2445 * range repeatedly.
2446 */
2447
2448 depth = 0;
2449 for (;;) {
67a0fd2a
FZ
2450 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2451 &file);
4c93a13b
PB
2452 if (ret < 0) {
2453 return ret;
2454 }
2455 assert(nb_sectors);
2456 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2457 break;
2458 }
760e0063 2459 bs = backing_bs(bs);
4c93a13b
PB
2460 if (bs == NULL) {
2461 ret = 0;
2462 break;
2463 }
2464
2465 depth++;
2466 }
2467
2875645b
JS
2468 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2469
2470 *e = (MapEntry) {
2471 .start = sector_num * BDRV_SECTOR_SIZE,
2472 .length = nb_sectors * BDRV_SECTOR_SIZE,
2473 .data = !!(ret & BDRV_BLOCK_DATA),
2474 .zero = !!(ret & BDRV_BLOCK_ZERO),
2475 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2476 .has_offset = has_offset,
2477 .depth = depth,
2478 .has_filename = file && has_offset,
2479 .filename = file && has_offset ? file->filename : NULL,
2480 };
2481
4c93a13b
PB
2482 return 0;
2483}
2484
16b0d555
FZ
2485static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2486{
2487 if (curr->length == 0) {
2488 return false;
2489 }
2490 if (curr->zero != next->zero ||
2491 curr->data != next->data ||
2492 curr->depth != next->depth ||
2493 curr->has_filename != next->has_filename ||
2494 curr->has_offset != next->has_offset) {
2495 return false;
2496 }
2497 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2498 return false;
2499 }
2500 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2501 return false;
2502 }
2503 return true;
2504}
2505
4c93a13b
PB
2506static int img_map(int argc, char **argv)
2507{
2508 int c;
2509 OutputFormat output_format = OFORMAT_HUMAN;
26f54e9a 2510 BlockBackend *blk;
4c93a13b
PB
2511 BlockDriverState *bs;
2512 const char *filename, *fmt, *output;
2513 int64_t length;
2514 MapEntry curr = { .length = 0 }, next;
2515 int ret = 0;
3babeb15 2516 Error *local_err = NULL;
eb769f74 2517 bool image_opts = false;
4c93a13b
PB
2518
2519 fmt = NULL;
2520 output = NULL;
2521 for (;;) {
2522 int option_index = 0;
2523 static const struct option long_options[] = {
2524 {"help", no_argument, 0, 'h'},
2525 {"format", required_argument, 0, 'f'},
2526 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 2527 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2528 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4c93a13b
PB
2529 {0, 0, 0, 0}
2530 };
2531 c = getopt_long(argc, argv, "f:h",
2532 long_options, &option_index);
2533 if (c == -1) {
2534 break;
2535 }
2536 switch (c) {
2537 case '?':
2538 case 'h':
2539 help();
2540 break;
2541 case 'f':
2542 fmt = optarg;
2543 break;
2544 case OPTION_OUTPUT:
2545 output = optarg;
2546 break;
3babeb15
DB
2547 case OPTION_OBJECT: {
2548 QemuOpts *opts;
2549 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2550 optarg, true);
2551 if (!opts) {
2552 return 1;
2553 }
2554 } break;
eb769f74
DB
2555 case OPTION_IMAGE_OPTS:
2556 image_opts = true;
2557 break;
4c93a13b
PB
2558 }
2559 }
ac1307ab
FZ
2560 if (optind != argc - 1) {
2561 error_exit("Expecting one image file name");
4c93a13b 2562 }
ac1307ab 2563 filename = argv[optind];
4c93a13b
PB
2564
2565 if (output && !strcmp(output, "json")) {
2566 output_format = OFORMAT_JSON;
2567 } else if (output && !strcmp(output, "human")) {
2568 output_format = OFORMAT_HUMAN;
2569 } else if (output) {
2570 error_report("--output must be used with human or json as argument.");
2571 return 1;
2572 }
2573
3babeb15
DB
2574 if (qemu_opts_foreach(&qemu_object_opts,
2575 user_creatable_add_opts_foreach,
2576 NULL, &local_err)) {
2577 error_report_err(local_err);
2578 return 1;
2579 }
2580
ce099547 2581 blk = img_open(image_opts, filename, fmt, 0, false, false);
7e7d56d9
MA
2582 if (!blk) {
2583 return 1;
4c93a13b 2584 }
7e7d56d9 2585 bs = blk_bs(blk);
4c93a13b
PB
2586
2587 if (output_format == OFORMAT_HUMAN) {
2588 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2589 }
2590
f1d3cd79 2591 length = blk_getlength(blk);
4c93a13b
PB
2592 while (curr.start + curr.length < length) {
2593 int64_t nsectors_left;
2594 int64_t sector_num;
2595 int n;
2596
2597 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2598
2599 /* Probe up to 1 GiB at a time. */
2600 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2601 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2602 ret = get_block_status(bs, sector_num, n, &next);
2603
2604 if (ret < 0) {
2605 error_report("Could not read file metadata: %s", strerror(-ret));
2606 goto out;
2607 }
2608
16b0d555 2609 if (entry_mergeable(&curr, &next)) {
4c93a13b
PB
2610 curr.length += next.length;
2611 continue;
2612 }
2613
2614 if (curr.length > 0) {
2615 dump_map_entry(output_format, &curr, &next);
2616 }
2617 curr = next;
2618 }
2619
2620 dump_map_entry(output_format, &curr, NULL);
2621
2622out:
26f54e9a 2623 blk_unref(blk);
4c93a13b
PB
2624 return ret < 0;
2625}
2626
f7b4a940
AL
2627#define SNAPSHOT_LIST 1
2628#define SNAPSHOT_CREATE 2
2629#define SNAPSHOT_APPLY 3
2630#define SNAPSHOT_DELETE 4
2631
153859be 2632static int img_snapshot(int argc, char **argv)
f7b4a940 2633{
26f54e9a 2634 BlockBackend *blk;
f7b4a940
AL
2635 BlockDriverState *bs;
2636 QEMUSnapshotInfo sn;
2637 char *filename, *snapshot_name = NULL;
c2abccec 2638 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
2639 int action = 0;
2640 qemu_timeval tv;
f382d43a 2641 bool quiet = false;
a89d89d3 2642 Error *err = NULL;
eb769f74 2643 bool image_opts = false;
f7b4a940 2644
ce099547 2645 bdrv_oflags = BDRV_O_RDWR;
f7b4a940
AL
2646 /* Parse commandline parameters */
2647 for(;;) {
3babeb15
DB
2648 static const struct option long_options[] = {
2649 {"help", no_argument, 0, 'h'},
2650 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2651 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2652 {0, 0, 0, 0}
2653 };
2654 c = getopt_long(argc, argv, "la:c:d:hq",
2655 long_options, NULL);
b8fb60da 2656 if (c == -1) {
f7b4a940 2657 break;
b8fb60da 2658 }
f7b4a940 2659 switch(c) {
ef87394c 2660 case '?':
f7b4a940
AL
2661 case 'h':
2662 help();
153859be 2663 return 0;
f7b4a940
AL
2664 case 'l':
2665 if (action) {
ac1307ab 2666 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2667 return 0;
f7b4a940
AL
2668 }
2669 action = SNAPSHOT_LIST;
f5edb014 2670 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
2671 break;
2672 case 'a':
2673 if (action) {
ac1307ab 2674 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2675 return 0;
f7b4a940
AL
2676 }
2677 action = SNAPSHOT_APPLY;
2678 snapshot_name = optarg;
2679 break;
2680 case 'c':
2681 if (action) {
ac1307ab 2682 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2683 return 0;
f7b4a940
AL
2684 }
2685 action = SNAPSHOT_CREATE;
2686 snapshot_name = optarg;
2687 break;
2688 case 'd':
2689 if (action) {
ac1307ab 2690 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2691 return 0;
f7b4a940
AL
2692 }
2693 action = SNAPSHOT_DELETE;
2694 snapshot_name = optarg;
2695 break;
f382d43a
MR
2696 case 'q':
2697 quiet = true;
2698 break;
3babeb15
DB
2699 case OPTION_OBJECT: {
2700 QemuOpts *opts;
2701 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2702 optarg, true);
2703 if (!opts) {
2704 return 1;
2705 }
2706 } break;
eb769f74
DB
2707 case OPTION_IMAGE_OPTS:
2708 image_opts = true;
2709 break;
f7b4a940
AL
2710 }
2711 }
2712
fc11eb26 2713 if (optind != argc - 1) {
ac1307ab 2714 error_exit("Expecting one image file name");
b8fb60da 2715 }
f7b4a940
AL
2716 filename = argv[optind++];
2717
3babeb15
DB
2718 if (qemu_opts_foreach(&qemu_object_opts,
2719 user_creatable_add_opts_foreach,
2720 NULL, &err)) {
2721 error_report_err(err);
2722 return 1;
2723 }
2724
f7b4a940 2725 /* Open the image */
ce099547 2726 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
7e7d56d9
MA
2727 if (!blk) {
2728 return 1;
c2abccec 2729 }
7e7d56d9 2730 bs = blk_bs(blk);
f7b4a940
AL
2731
2732 /* Perform the requested action */
2733 switch(action) {
2734 case SNAPSHOT_LIST:
2735 dump_snapshots(bs);
2736 break;
2737
2738 case SNAPSHOT_CREATE:
2739 memset(&sn, 0, sizeof(sn));
2740 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2741
2742 qemu_gettimeofday(&tv);
2743 sn.date_sec = tv.tv_sec;
2744 sn.date_nsec = tv.tv_usec * 1000;
2745
2746 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 2747 if (ret) {
15654a6d 2748 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 2749 snapshot_name, ret, strerror(-ret));
b8fb60da 2750 }
f7b4a940
AL
2751 break;
2752
2753 case SNAPSHOT_APPLY:
2754 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 2755 if (ret) {
15654a6d 2756 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 2757 snapshot_name, ret, strerror(-ret));
b8fb60da 2758 }
f7b4a940
AL
2759 break;
2760
2761 case SNAPSHOT_DELETE:
a89d89d3 2762 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
84d18f06 2763 if (err) {
c29b77f9
MA
2764 error_reportf_err(err, "Could not delete snapshot '%s': ",
2765 snapshot_name);
a89d89d3 2766 ret = 1;
b8fb60da 2767 }
f7b4a940
AL
2768 break;
2769 }
2770
2771 /* Cleanup */
26f54e9a 2772 blk_unref(blk);
c2abccec
MK
2773 if (ret) {
2774 return 1;
2775 }
153859be 2776 return 0;
f7b4a940
AL
2777}
2778
3e85c6fd
KW
2779static int img_rebase(int argc, char **argv)
2780{
26f54e9a 2781 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
396374ca
PB
2782 uint8_t *buf_old = NULL;
2783 uint8_t *buf_new = NULL;
f1d3cd79 2784 BlockDriverState *bs = NULL;
3e85c6fd 2785 char *filename;
40055951
HR
2786 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2787 int c, flags, src_flags, ret;
ce099547 2788 bool writethrough, src_writethrough;
3e85c6fd 2789 int unsafe = 0;
6b837bc4 2790 int progress = 0;
f382d43a 2791 bool quiet = false;
34b5d2c6 2792 Error *local_err = NULL;
eb769f74 2793 bool image_opts = false;
3e85c6fd
KW
2794
2795 /* Parse commandline parameters */
e53dbee0 2796 fmt = NULL;
661a0f71 2797 cache = BDRV_DEFAULT_CACHE;
40055951 2798 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
2799 out_baseimg = NULL;
2800 out_basefmt = NULL;
3e85c6fd 2801 for(;;) {
3babeb15
DB
2802 static const struct option long_options[] = {
2803 {"help", no_argument, 0, 'h'},
2804 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2805 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2806 {0, 0, 0, 0}
2807 };
2808 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2809 long_options, NULL);
b8fb60da 2810 if (c == -1) {
3e85c6fd 2811 break;
b8fb60da 2812 }
3e85c6fd 2813 switch(c) {
ef87394c 2814 case '?':
3e85c6fd
KW
2815 case 'h':
2816 help();
2817 return 0;
e53dbee0
KW
2818 case 'f':
2819 fmt = optarg;
2820 break;
3e85c6fd
KW
2821 case 'F':
2822 out_basefmt = optarg;
2823 break;
2824 case 'b':
2825 out_baseimg = optarg;
2826 break;
2827 case 'u':
2828 unsafe = 1;
2829 break;
6b837bc4
JS
2830 case 'p':
2831 progress = 1;
2832 break;
661a0f71
FS
2833 case 't':
2834 cache = optarg;
2835 break;
40055951
HR
2836 case 'T':
2837 src_cache = optarg;
2838 break;
f382d43a
MR
2839 case 'q':
2840 quiet = true;
2841 break;
3babeb15
DB
2842 case OPTION_OBJECT: {
2843 QemuOpts *opts;
2844 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2845 optarg, true);
2846 if (!opts) {
2847 return 1;
2848 }
2849 } break;
eb769f74
DB
2850 case OPTION_IMAGE_OPTS:
2851 image_opts = true;
2852 break;
3e85c6fd
KW
2853 }
2854 }
2855
f382d43a
MR
2856 if (quiet) {
2857 progress = 0;
2858 }
2859
ac1307ab
FZ
2860 if (optind != argc - 1) {
2861 error_exit("Expecting one image file name");
2862 }
2863 if (!unsafe && !out_baseimg) {
2864 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
b8fb60da 2865 }
3e85c6fd
KW
2866 filename = argv[optind++];
2867
3babeb15
DB
2868 if (qemu_opts_foreach(&qemu_object_opts,
2869 user_creatable_add_opts_foreach,
2870 NULL, &local_err)) {
2871 error_report_err(local_err);
2872 return 1;
2873 }
2874
6b837bc4
JS
2875 qemu_progress_init(progress, 2.0);
2876 qemu_progress_print(0, 100);
2877
661a0f71 2878 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
ce099547 2879 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2880 if (ret < 0) {
2881 error_report("Invalid cache option: %s", cache);
40ed35a3 2882 goto out;
661a0f71
FS
2883 }
2884
ce099547
KW
2885 src_flags = 0;
2886 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
2887 if (ret < 0) {
2888 error_report("Invalid source cache option: %s", src_cache);
40ed35a3 2889 goto out;
40055951
HR
2890 }
2891
ce099547
KW
2892 /* The source files are opened read-only, don't care about WCE */
2893 assert((src_flags & BDRV_O_RDWR) == 0);
2894 (void) src_writethrough;
2895
3e85c6fd
KW
2896 /*
2897 * Open the images.
2898 *
2899 * Ignore the old backing file for unsafe rebase in case we want to correct
2900 * the reference to a renamed or moved backing file.
2901 */
ce099547 2902 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 2903 if (!blk) {
40ed35a3
SH
2904 ret = -1;
2905 goto out;
c2abccec 2906 }
7e7d56d9 2907 bs = blk_bs(blk);
3e85c6fd 2908
3e85c6fd 2909 if (out_basefmt != NULL) {
644483d9 2910 if (bdrv_find_format(out_basefmt) == NULL) {
15654a6d 2911 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
2912 ret = -1;
2913 goto out;
3e85c6fd
KW
2914 }
2915 }
2916
2917 /* For safe rebasing we need to compare old and new backing file */
40ed35a3 2918 if (!unsafe) {
9a29e18f 2919 char backing_name[PATH_MAX];
644483d9
HR
2920 QDict *options = NULL;
2921
2922 if (bs->backing_format[0] != '\0') {
2923 options = qdict_new();
2924 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2925 }
3e85c6fd 2926
3e85c6fd 2927 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
efaa7c4e 2928 blk_old_backing = blk_new_open(backing_name, NULL,
644483d9
HR
2929 options, src_flags, &local_err);
2930 if (!blk_old_backing) {
c29b77f9
MA
2931 error_reportf_err(local_err,
2932 "Could not open old backing file '%s': ",
2933 backing_name);
c2abccec 2934 goto out;
3e85c6fd 2935 }
644483d9 2936
a616673d 2937 if (out_baseimg[0]) {
644483d9
HR
2938 if (out_basefmt) {
2939 options = qdict_new();
2940 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2941 } else {
2942 options = NULL;
2943 }
2944
efaa7c4e 2945 blk_new_backing = blk_new_open(out_baseimg, NULL,
644483d9
HR
2946 options, src_flags, &local_err);
2947 if (!blk_new_backing) {
c29b77f9
MA
2948 error_reportf_err(local_err,
2949 "Could not open new backing file '%s': ",
2950 out_baseimg);
a616673d
AB
2951 goto out;
2952 }
3e85c6fd
KW
2953 }
2954 }
2955
2956 /*
2957 * Check each unallocated cluster in the COW file. If it is unallocated,
2958 * accesses go to the backing file. We must therefore compare this cluster
2959 * in the old and new backing file, and if they differ we need to copy it
2960 * from the old backing file into the COW file.
2961 *
2962 * If qemu-img crashes during this step, no harm is done. The content of
2963 * the image is the same as the original one at any time.
2964 */
2965 if (!unsafe) {
52bf1e72
MA
2966 int64_t num_sectors;
2967 int64_t old_backing_num_sectors;
2968 int64_t new_backing_num_sectors = 0;
3e85c6fd 2969 uint64_t sector;
cc60e327 2970 int n;
1f710495 2971 float local_progress = 0;
d6771bfa 2972
f1d3cd79
HR
2973 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2974 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3e85c6fd 2975
f1d3cd79 2976 num_sectors = blk_nb_sectors(blk);
52bf1e72
MA
2977 if (num_sectors < 0) {
2978 error_report("Could not get size of '%s': %s",
2979 filename, strerror(-num_sectors));
2980 ret = -1;
2981 goto out;
2982 }
f1d3cd79 2983 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
52bf1e72 2984 if (old_backing_num_sectors < 0) {
9a29e18f 2985 char backing_name[PATH_MAX];
52bf1e72
MA
2986
2987 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2988 error_report("Could not get size of '%s': %s",
2989 backing_name, strerror(-old_backing_num_sectors));
2990 ret = -1;
2991 goto out;
2992 }
f1d3cd79
HR
2993 if (blk_new_backing) {
2994 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
52bf1e72
MA
2995 if (new_backing_num_sectors < 0) {
2996 error_report("Could not get size of '%s': %s",
2997 out_baseimg, strerror(-new_backing_num_sectors));
2998 ret = -1;
2999 goto out;
3000 }
a616673d 3001 }
3e85c6fd 3002
1f710495
KW
3003 if (num_sectors != 0) {
3004 local_progress = (float)100 /
3005 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3006 }
3007
3e85c6fd
KW
3008 for (sector = 0; sector < num_sectors; sector += n) {
3009
3010 /* How many sectors can we handle with the next read? */
3011 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3012 n = (IO_BUF_SIZE / 512);
3013 } else {
3014 n = num_sectors - sector;
3015 }
3016
3017 /* If the cluster is allocated, we don't need to take action */
cc60e327 3018 ret = bdrv_is_allocated(bs, sector, n, &n);
d663640c
PB
3019 if (ret < 0) {
3020 error_report("error while reading image metadata: %s",
3021 strerror(-ret));
3022 goto out;
3023 }
cc60e327 3024 if (ret) {
3e85c6fd
KW
3025 continue;
3026 }
3027
87a1b3e3
KW
3028 /*
3029 * Read old and new backing file and take into consideration that
3030 * backing files may be smaller than the COW image.
3031 */
3032 if (sector >= old_backing_num_sectors) {
3033 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3034 } else {
3035 if (sector + n > old_backing_num_sectors) {
3036 n = old_backing_num_sectors - sector;
3037 }
3038
f1d3cd79 3039 ret = blk_read(blk_old_backing, sector, buf_old, n);
87a1b3e3
KW
3040 if (ret < 0) {
3041 error_report("error while reading from old backing file");
3042 goto out;
3043 }
3e85c6fd 3044 }
87a1b3e3 3045
f1d3cd79 3046 if (sector >= new_backing_num_sectors || !blk_new_backing) {
87a1b3e3
KW
3047 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3048 } else {
3049 if (sector + n > new_backing_num_sectors) {
3050 n = new_backing_num_sectors - sector;
3051 }
3052
f1d3cd79 3053 ret = blk_read(blk_new_backing, sector, buf_new, n);
87a1b3e3
KW
3054 if (ret < 0) {
3055 error_report("error while reading from new backing file");
3056 goto out;
3057 }
3e85c6fd
KW
3058 }
3059
3060 /* If they differ, we need to write to the COW file */
3061 uint64_t written = 0;
3062
3063 while (written < n) {
3064 int pnum;
3065
3066 if (compare_sectors(buf_old + written * 512,
60b1bd4f 3067 buf_new + written * 512, n - written, &pnum))
3e85c6fd 3068 {
f1d3cd79
HR
3069 ret = blk_write(blk, sector + written,
3070 buf_old + written * 512, pnum);
3e85c6fd 3071 if (ret < 0) {
15654a6d 3072 error_report("Error while writing to COW image: %s",
3e85c6fd 3073 strerror(-ret));
c2abccec 3074 goto out;
3e85c6fd
KW
3075 }
3076 }
3077
3078 written += pnum;
3079 }
6b837bc4 3080 qemu_progress_print(local_progress, 100);
3e85c6fd
KW
3081 }
3082 }
3083
3084 /*
3085 * Change the backing file. All clusters that are different from the old
3086 * backing file are overwritten in the COW file now, so the visible content
3087 * doesn't change when we switch the backing file.
3088 */
a616673d
AB
3089 if (out_baseimg && *out_baseimg) {
3090 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3091 } else {
3092 ret = bdrv_change_backing_file(bs, NULL, NULL);
3093 }
3094
3e85c6fd 3095 if (ret == -ENOSPC) {
15654a6d
JS
3096 error_report("Could not change the backing file to '%s': No "
3097 "space left in the file header", out_baseimg);
3e85c6fd 3098 } else if (ret < 0) {
15654a6d 3099 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
3100 out_baseimg, strerror(-ret));
3101 }
3102
6b837bc4 3103 qemu_progress_print(100, 0);
3e85c6fd
KW
3104 /*
3105 * TODO At this point it is possible to check if any clusters that are
3106 * allocated in the COW file are the same in the backing file. If so, they
3107 * could be dropped from the COW file. Don't do this before switching the
3108 * backing file, in case of a crash this would lead to corruption.
3109 */
c2abccec 3110out:
6b837bc4 3111 qemu_progress_end();
3e85c6fd
KW
3112 /* Cleanup */
3113 if (!unsafe) {
26f54e9a 3114 blk_unref(blk_old_backing);
26f54e9a 3115 blk_unref(blk_new_backing);
3e85c6fd 3116 }
396374ca
PB
3117 qemu_vfree(buf_old);
3118 qemu_vfree(buf_new);
3e85c6fd 3119
26f54e9a 3120 blk_unref(blk);
c2abccec
MK
3121 if (ret) {
3122 return 1;
3123 }
3e85c6fd
KW
3124 return 0;
3125}
3126
ae6b0ed6
SH
3127static int img_resize(int argc, char **argv)
3128{
6750e795 3129 Error *err = NULL;
ae6b0ed6
SH
3130 int c, ret, relative;
3131 const char *filename, *fmt, *size;
3132 int64_t n, total_size;
f382d43a 3133 bool quiet = false;
26f54e9a 3134 BlockBackend *blk = NULL;
20caf0f7 3135 QemuOpts *param;
3babeb15
DB
3136 Error *local_err = NULL;
3137
20caf0f7
DXW
3138 static QemuOptsList resize_options = {
3139 .name = "resize_options",
3140 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3141 .desc = {
3142 {
3143 .name = BLOCK_OPT_SIZE,
3144 .type = QEMU_OPT_SIZE,
3145 .help = "Virtual disk size"
3146 }, {
3147 /* end of list */
3148 }
ae6b0ed6 3149 },
ae6b0ed6 3150 };
eb769f74 3151 bool image_opts = false;
ae6b0ed6 3152
e80fec7f
KW
3153 /* Remove size from argv manually so that negative numbers are not treated
3154 * as options by getopt. */
3155 if (argc < 3) {
ac1307ab 3156 error_exit("Not enough arguments");
e80fec7f
KW
3157 return 1;
3158 }
3159
3160 size = argv[--argc];
3161
3162 /* Parse getopt arguments */
ae6b0ed6
SH
3163 fmt = NULL;
3164 for(;;) {
3babeb15
DB
3165 static const struct option long_options[] = {
3166 {"help", no_argument, 0, 'h'},
3167 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3168 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3169 {0, 0, 0, 0}
3170 };
3171 c = getopt_long(argc, argv, "f:hq",
3172 long_options, NULL);
ae6b0ed6
SH
3173 if (c == -1) {
3174 break;
3175 }
3176 switch(c) {
ef87394c 3177 case '?':
ae6b0ed6
SH
3178 case 'h':
3179 help();
3180 break;
3181 case 'f':
3182 fmt = optarg;
3183 break;
f382d43a
MR
3184 case 'q':
3185 quiet = true;
3186 break;
3babeb15
DB
3187 case OPTION_OBJECT: {
3188 QemuOpts *opts;
3189 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3190 optarg, true);
3191 if (!opts) {
3192 return 1;
3193 }
3194 } break;
eb769f74
DB
3195 case OPTION_IMAGE_OPTS:
3196 image_opts = true;
3197 break;
ae6b0ed6
SH
3198 }
3199 }
fc11eb26 3200 if (optind != argc - 1) {
ac1307ab 3201 error_exit("Expecting one image file name");
ae6b0ed6
SH
3202 }
3203 filename = argv[optind++];
ae6b0ed6 3204
3babeb15
DB
3205 if (qemu_opts_foreach(&qemu_object_opts,
3206 user_creatable_add_opts_foreach,
3207 NULL, &local_err)) {
3208 error_report_err(local_err);
3209 return 1;
3210 }
3211
ae6b0ed6
SH
3212 /* Choose grow, shrink, or absolute resize mode */
3213 switch (size[0]) {
3214 case '+':
3215 relative = 1;
3216 size++;
3217 break;
3218 case '-':
3219 relative = -1;
3220 size++;
3221 break;
3222 default:
3223 relative = 0;
3224 break;
3225 }
3226
3227 /* Parse size */
87ea75d5 3228 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
f43e47db 3229 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
6750e795
MA
3230 if (err) {
3231 error_report_err(err);
2a81998a 3232 ret = -1;
20caf0f7 3233 qemu_opts_del(param);
2a81998a 3234 goto out;
ae6b0ed6 3235 }
20caf0f7
DXW
3236 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3237 qemu_opts_del(param);
ae6b0ed6 3238
efaa7c4e 3239 blk = img_open(image_opts, filename, fmt,
ce099547 3240 BDRV_O_RDWR, false, quiet);
7e7d56d9 3241 if (!blk) {
2a81998a
JS
3242 ret = -1;
3243 goto out;
c2abccec 3244 }
ae6b0ed6
SH
3245
3246 if (relative) {
f1d3cd79 3247 total_size = blk_getlength(blk) + n * relative;
ae6b0ed6
SH
3248 } else {
3249 total_size = n;
3250 }
3251 if (total_size <= 0) {
15654a6d 3252 error_report("New image size must be positive");
c2abccec
MK
3253 ret = -1;
3254 goto out;
ae6b0ed6
SH
3255 }
3256
f1d3cd79 3257 ret = blk_truncate(blk, total_size);
ae6b0ed6
SH
3258 switch (ret) {
3259 case 0:
f382d43a 3260 qprintf(quiet, "Image resized.\n");
ae6b0ed6
SH
3261 break;
3262 case -ENOTSUP:
259b2173 3263 error_report("This image does not support resize");
ae6b0ed6
SH
3264 break;
3265 case -EACCES:
15654a6d 3266 error_report("Image is read-only");
ae6b0ed6
SH
3267 break;
3268 default:
15654a6d 3269 error_report("Error resizing image (%d)", -ret);
ae6b0ed6
SH
3270 break;
3271 }
c2abccec 3272out:
26f54e9a 3273 blk_unref(blk);
c2abccec
MK
3274 if (ret) {
3275 return 1;
3276 }
ae6b0ed6
SH
3277 return 0;
3278}
3279
76a3a34d 3280static void amend_status_cb(BlockDriverState *bs,
8b13976d
HR
3281 int64_t offset, int64_t total_work_size,
3282 void *opaque)
76a3a34d
HR
3283{
3284 qemu_progress_print(100.f * offset / total_work_size, 0);
3285}
3286
6f176b48
HR
3287static int img_amend(int argc, char **argv)
3288{
dc523cd3 3289 Error *err = NULL;
6f176b48
HR
3290 int c, ret = 0;
3291 char *options = NULL;
83d0521a
CL
3292 QemuOptsList *create_opts = NULL;
3293 QemuOpts *opts = NULL;
bd39e6ed
HR
3294 const char *fmt = NULL, *filename, *cache;
3295 int flags;
ce099547 3296 bool writethrough;
76a3a34d 3297 bool quiet = false, progress = false;
26f54e9a 3298 BlockBackend *blk = NULL;
6f176b48 3299 BlockDriverState *bs = NULL;
3babeb15 3300 Error *local_err = NULL;
eb769f74 3301 bool image_opts = false;
6f176b48 3302
bd39e6ed 3303 cache = BDRV_DEFAULT_CACHE;
6f176b48 3304 for (;;) {
3babeb15
DB
3305 static const struct option long_options[] = {
3306 {"help", no_argument, 0, 'h'},
3307 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3308 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3309 {0, 0, 0, 0}
3310 };
3311 c = getopt_long(argc, argv, "ho:f:t:pq",
3312 long_options, NULL);
6f176b48
HR
3313 if (c == -1) {
3314 break;
3315 }
3316
3317 switch (c) {
3318 case 'h':
3319 case '?':
3320 help();
3321 break;
3322 case 'o':
626f84f3
KW
3323 if (!is_valid_option_list(optarg)) {
3324 error_report("Invalid option list: %s", optarg);
3325 ret = -1;
e814dffc 3326 goto out_no_progress;
626f84f3
KW
3327 }
3328 if (!options) {
3329 options = g_strdup(optarg);
3330 } else {
3331 char *old_options = options;
3332 options = g_strdup_printf("%s,%s", options, optarg);
3333 g_free(old_options);
3334 }
6f176b48
HR
3335 break;
3336 case 'f':
3337 fmt = optarg;
3338 break;
bd39e6ed
HR
3339 case 't':
3340 cache = optarg;
3341 break;
76a3a34d
HR
3342 case 'p':
3343 progress = true;
3344 break;
6f176b48
HR
3345 case 'q':
3346 quiet = true;
3347 break;
3babeb15
DB
3348 case OPTION_OBJECT:
3349 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3350 optarg, true);
3351 if (!opts) {
3352 ret = -1;
3353 goto out_no_progress;
3354 }
3355 break;
eb769f74
DB
3356 case OPTION_IMAGE_OPTS:
3357 image_opts = true;
3358 break;
6f176b48
HR
3359 }
3360 }
3361
a283cb6e 3362 if (!options) {
ac1307ab 3363 error_exit("Must specify options (-o)");
6f176b48
HR
3364 }
3365
3babeb15
DB
3366 if (qemu_opts_foreach(&qemu_object_opts,
3367 user_creatable_add_opts_foreach,
3368 NULL, &local_err)) {
3369 error_report_err(local_err);
3370 ret = -1;
3371 goto out_no_progress;
3372 }
3373
76a3a34d
HR
3374 if (quiet) {
3375 progress = false;
3376 }
3377 qemu_progress_init(progress, 1.0);
3378
a283cb6e
KW
3379 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3380 if (fmt && has_help_option(options)) {
3381 /* If a format is explicitly specified (and possibly no filename is
3382 * given), print option help here */
3383 ret = print_block_option_help(filename, fmt);
3384 goto out;
6f176b48
HR
3385 }
3386
a283cb6e 3387 if (optind != argc - 1) {
b2f27e44
HR
3388 error_report("Expecting one image file name");
3389 ret = -1;
3390 goto out;
a283cb6e 3391 }
6f176b48 3392
ce099547
KW
3393 flags = BDRV_O_RDWR;
3394 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
bd39e6ed
HR
3395 if (ret < 0) {
3396 error_report("Invalid cache option: %s", cache);
3397 goto out;
3398 }
3399
ce099547 3400 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 3401 if (!blk) {
6f176b48
HR
3402 ret = -1;
3403 goto out;
3404 }
7e7d56d9 3405 bs = blk_bs(blk);
6f176b48
HR
3406
3407 fmt = bs->drv->format_name;
3408
626f84f3 3409 if (has_help_option(options)) {
a283cb6e 3410 /* If the format was auto-detected, print option help here */
6f176b48
HR
3411 ret = print_block_option_help(filename, fmt);
3412 goto out;
3413 }
3414
b2439d26
HR
3415 if (!bs->drv->create_opts) {
3416 error_report("Format driver '%s' does not support any options to amend",
3417 fmt);
3418 ret = -1;
3419 goto out;
3420 }
3421
c282e1fd 3422 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a 3423 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
3424 if (options) {
3425 qemu_opts_do_parse(opts, options, NULL, &err);
3426 if (err) {
97a2ca7a 3427 error_report_err(err);
dc523cd3
MA
3428 ret = -1;
3429 goto out;
3430 }
6f176b48
HR
3431 }
3432
76a3a34d
HR
3433 /* In case the driver does not call amend_status_cb() */
3434 qemu_progress_print(0.f, 0);
8b13976d 3435 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
76a3a34d 3436 qemu_progress_print(100.f, 0);
6f176b48
HR
3437 if (ret < 0) {
3438 error_report("Error while amending options: %s", strerror(-ret));
3439 goto out;
3440 }
3441
3442out:
76a3a34d
HR
3443 qemu_progress_end();
3444
e814dffc 3445out_no_progress:
26f54e9a 3446 blk_unref(blk);
83d0521a
CL
3447 qemu_opts_del(opts);
3448 qemu_opts_free(create_opts);
626f84f3
KW
3449 g_free(options);
3450
6f176b48
HR
3451 if (ret) {
3452 return 1;
3453 }
3454 return 0;
3455}
3456
c227f099 3457static const img_cmd_t img_cmds[] = {
153859be
SB
3458#define DEF(option, callback, arg_string) \
3459 { option, callback },
3460#include "qemu-img-cmds.h"
3461#undef DEF
3462#undef GEN_DOCS
3463 { NULL, NULL, },
3464};
3465
ea2384d3
FB
3466int main(int argc, char **argv)
3467{
c227f099 3468 const img_cmd_t *cmd;
153859be 3469 const char *cmdname;
2f78e491 3470 Error *local_error = NULL;
7db1689c 3471 int c;
7db1689c
JC
3472 static const struct option long_options[] = {
3473 {"help", no_argument, 0, 'h'},
5f6979cb 3474 {"version", no_argument, 0, 'v'},
7db1689c
JC
3475 {0, 0, 0, 0}
3476 };
ea2384d3 3477
526eda14
MK
3478#ifdef CONFIG_POSIX
3479 signal(SIGPIPE, SIG_IGN);
3480#endif
3481
53f76e58 3482 error_set_progname(argv[0]);
10f5bff6 3483 qemu_init_exec_dir(argv[0]);
53f76e58 3484
2f78e491 3485 if (qemu_init_main_loop(&local_error)) {
565f65d2 3486 error_report_err(local_error);
2f78e491
CN
3487 exit(EXIT_FAILURE);
3488 }
3489
c2297088
DB
3490 if (qcrypto_init(&local_error) < 0) {
3491 error_reportf_err(local_error, "cannot initialize crypto: ");
3492 exit(1);
3493 }
3494
064097d9 3495 module_call_init(MODULE_INIT_QOM);
ea2384d3 3496 bdrv_init();
ac1307ab
FZ
3497 if (argc < 2) {
3498 error_exit("Not enough arguments");
3499 }
153859be 3500 cmdname = argv[1];
153859be 3501
3babeb15 3502 qemu_add_opts(&qemu_object_opts);
eb769f74 3503 qemu_add_opts(&qemu_source_opts);
3babeb15 3504
153859be 3505 /* find the command */
5f6979cb 3506 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
153859be 3507 if (!strcmp(cmdname, cmd->name)) {
7db1689c 3508 return cmd->handler(argc - 1, argv + 1);
153859be 3509 }
ea2384d3 3510 }
153859be 3511
5f6979cb 3512 c = getopt_long(argc, argv, "h", long_options, NULL);
7db1689c
JC
3513
3514 if (c == 'h') {
3515 help();
3516 }
5f6979cb
JC
3517 if (c == 'v') {
3518 printf(QEMU_IMG_VERSION);
3519 return 0;
3520 }
7db1689c 3521
153859be 3522 /* not found */
ac1307ab 3523 error_exit("Command not found: %s", cmdname);
ea2384d3 3524}