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