]> git.ipfire.org Git - thirdparty/qemu.git/blame - qemu-img.c
qemu-img: fix img_compare() flags error path
[thirdparty/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 */
c054b3fd
BC
24#include "qapi-visit.h"
25#include "qapi/qmp-output-visitor.h"
7b1b5d19 26#include "qapi/qmp/qjson.h"
faf07963 27#include "qemu-common.h"
1de7afc9
PB
28#include "qemu/option.h"
29#include "qemu/error-report.h"
30#include "qemu/osdep.h"
9c17d615 31#include "sysemu/sysemu.h"
737e150e 32#include "block/block_int.h"
f364ec65 33#include "block/qapi.h"
c054b3fd 34#include <getopt.h>
e8445331 35
5f6979cb
JC
36#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
37 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
38
c227f099 39typedef struct img_cmd_t {
153859be
SB
40 const char *name;
41 int (*handler)(int argc, char **argv);
c227f099 42} img_cmd_t;
153859be 43
8599ea4c
FS
44enum {
45 OPTION_OUTPUT = 256,
46 OPTION_BACKING_CHAIN = 257,
47};
48
49typedef enum OutputFormat {
50 OFORMAT_JSON,
51 OFORMAT_HUMAN,
52} OutputFormat;
53
137519ce 54/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
adfe078e 55#define BDRV_O_FLAGS BDRV_O_CACHE_WB
661a0f71 56#define BDRV_DEFAULT_CACHE "writeback"
137519ce 57
00c6d403 58static void format_print(void *opaque, const char *name)
ea2384d3 59{
00c6d403 60 printf(" %s", name);
ea2384d3
FB
61}
62
ac1307ab
FZ
63static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
64{
65 va_list ap;
66
67 error_printf("qemu-img: ");
68
69 va_start(ap, fmt);
70 error_vprintf(fmt, ap);
71 va_end(ap);
72
73 error_printf("\nTry 'qemu-img --help' for more information\n");
74 exit(EXIT_FAILURE);
75}
76
d2c639d6 77/* Please keep in synch with qemu-img.texi */
ac1307ab 78static void QEMU_NORETURN help(void)
ea2384d3 79{
e00291c0 80 const char *help_msg =
5f6979cb 81 QEMU_IMG_VERSION
3f020d70 82 "usage: qemu-img command [command options]\n"
83 "QEMU disk image utility\n"
84 "\n"
85 "Command syntax:\n"
153859be
SB
86#define DEF(option, callback, arg_string) \
87 " " arg_string "\n"
88#include "qemu-img-cmds.h"
89#undef DEF
90#undef GEN_DOCS
3f020d70 91 "\n"
92 "Command parameters:\n"
93 " 'filename' is a disk image filename\n"
94 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
661a0f71 95 " 'cache' is the cache mode used to write the output disk image, the valid\n"
80ccf93b
LY
96 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
97 " 'directsync' and 'unsafe' (default for convert)\n"
40055951 98 " 'src_cache' in contrast is the cache mode used to read input disk images\n"
3f020d70 99 " 'size' is the disk image size in bytes. Optional suffixes\n"
5e00984a
KW
100 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
101 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
102 " supported. 'b' is ignored.\n"
3f020d70 103 " 'output_filename' is the destination disk image filename\n"
104 " 'output_fmt' is the destination format\n"
105 " 'options' is a comma separated list of format specific options in a\n"
106 " name=value format. Use -o ? for an overview of the options supported by the\n"
107 " used format\n"
ef80654d
WX
108 " 'snapshot_param' is param used for internal snapshot, format\n"
109 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
110 " '[ID_OR_NAME]'\n"
111 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
112 " instead\n"
3f020d70 113 " '-c' indicates that target image must be compressed (qcow format only)\n"
114 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
115 " match exactly. The image doesn't need a working backing file before\n"
116 " rebasing in this case (useful for renaming the backing file)\n"
117 " '-h' with or without a command shows this help and lists the supported formats\n"
6b837bc4 118 " '-p' show progress of command (only certain commands)\n"
f382d43a 119 " '-q' use Quiet mode - do not print any output (except errors)\n"
11b6699a
PL
120 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
121 " contain only zeros for qemu-img to create a sparse image during\n"
122 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
123 " unallocated or zero sectors, and the destination image will always be\n"
124 " fully allocated\n"
c054b3fd 125 " '--output' takes the format in which the output must be done (human or json)\n"
b2e10493
AD
126 " '-n' skips the target volume creation (useful if the volume is created\n"
127 " prior to running qemu-img)\n"
3f020d70 128 "\n"
4534ff54
KW
129 "Parameters to check subcommand:\n"
130 " '-r' tries to repair any inconsistencies that are found during the check.\n"
131 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
132 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
0546b8c2 133 " hiding corruption that has already occurred.\n"
4534ff54 134 "\n"
3f020d70 135 "Parameters to snapshot subcommand:\n"
136 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
137 " '-a' applies a snapshot (revert disk to saved state)\n"
138 " '-c' creates a snapshot\n"
139 " '-d' deletes a snapshot\n"
d14ed18c
MR
140 " '-l' lists all snapshots in the given image\n"
141 "\n"
142 "Parameters to compare subcommand:\n"
143 " '-f' first image format\n"
144 " '-F' second image format\n"
145 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
e00291c0
PB
146
147 printf("%s\nSupported formats:", help_msg);
00c6d403 148 bdrv_iterate_format(format_print, NULL);
ea2384d3 149 printf("\n");
ac1307ab 150 exit(EXIT_SUCCESS);
ea2384d3
FB
151}
152
7c30f657 153static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
f382d43a
MR
154{
155 int ret = 0;
156 if (!quiet) {
157 va_list args;
158 va_start(args, fmt);
159 ret = vprintf(fmt, args);
160 va_end(args);
161 }
162 return ret;
163}
164
ea2384d3
FB
165#if defined(WIN32)
166/* XXX: put correct support for win32 */
167static int read_password(char *buf, int buf_size)
168{
169 int c, i;
fdcf6e65 170
ea2384d3
FB
171 printf("Password: ");
172 fflush(stdout);
173 i = 0;
174 for(;;) {
175 c = getchar();
fdcf6e65
CG
176 if (c < 0) {
177 buf[i] = '\0';
178 return -1;
179 } else if (c == '\n') {
ea2384d3 180 break;
fdcf6e65 181 } else if (i < (buf_size - 1)) {
ea2384d3 182 buf[i++] = c;
fdcf6e65 183 }
ea2384d3
FB
184 }
185 buf[i] = '\0';
186 return 0;
187}
188
189#else
190
191#include <termios.h>
192
193static struct termios oldtty;
194
195static void term_exit(void)
196{
197 tcsetattr (0, TCSANOW, &oldtty);
198}
199
200static void term_init(void)
201{
202 struct termios tty;
203
204 tcgetattr (0, &tty);
205 oldtty = tty;
206
207 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
208 |INLCR|IGNCR|ICRNL|IXON);
209 tty.c_oflag |= OPOST;
210 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
211 tty.c_cflag &= ~(CSIZE|PARENB);
212 tty.c_cflag |= CS8;
213 tty.c_cc[VMIN] = 1;
214 tty.c_cc[VTIME] = 0;
3b46e624 215
ea2384d3
FB
216 tcsetattr (0, TCSANOW, &tty);
217
218 atexit(term_exit);
219}
220
3f379ab1 221static int read_password(char *buf, int buf_size)
ea2384d3
FB
222{
223 uint8_t ch;
224 int i, ret;
225
226 printf("password: ");
227 fflush(stdout);
228 term_init();
229 i = 0;
230 for(;;) {
231 ret = read(0, &ch, 1);
232 if (ret == -1) {
233 if (errno == EAGAIN || errno == EINTR) {
234 continue;
235 } else {
ea2384d3
FB
236 break;
237 }
238 } else if (ret == 0) {
239 ret = -1;
240 break;
241 } else {
242 if (ch == '\r') {
243 ret = 0;
244 break;
245 }
246 if (i < (buf_size - 1))
247 buf[i++] = ch;
248 }
249 }
250 term_exit();
251 buf[i] = '\0';
252 printf("\n");
253 return ret;
254}
255#endif
256
4ac8aacd
JS
257static int print_block_option_help(const char *filename, const char *fmt)
258{
259 BlockDriver *drv, *proto_drv;
83d0521a 260 QemuOptsList *create_opts = NULL;
4ac8aacd
JS
261
262 /* Find driver and parse its options */
263 drv = bdrv_find_format(fmt);
264 if (!drv) {
15654a6d 265 error_report("Unknown file format '%s'", fmt);
4ac8aacd
JS
266 return 1;
267 }
268
c282e1fd 269 create_opts = qemu_opts_append(create_opts, drv->create_opts);
a283cb6e
KW
270 if (filename) {
271 proto_drv = bdrv_find_protocol(filename, true);
272 if (!proto_drv) {
273 error_report("Unknown protocol '%s'", filename);
83d0521a 274 qemu_opts_free(create_opts);
a283cb6e
KW
275 return 1;
276 }
c282e1fd 277 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
a283cb6e
KW
278 }
279
83d0521a
CL
280 qemu_opts_print_help(create_opts);
281 qemu_opts_free(create_opts);
4ac8aacd
JS
282 return 0;
283}
284
9ffe3332
KW
285static BlockDriverState *bdrv_new_open(const char *id,
286 const char *filename,
9bc378c1 287 const char *fmt,
f0536bb8 288 int flags,
f382d43a
MR
289 bool require_io,
290 bool quiet)
75c23805
FB
291{
292 BlockDriverState *bs;
293 BlockDriver *drv;
294 char password[256];
34b5d2c6 295 Error *local_err = NULL;
b9eaf9ec 296 int ret;
75c23805 297
9ffe3332 298 bs = bdrv_new(id, &error_abort);
ad717139 299
75c23805
FB
300 if (fmt) {
301 drv = bdrv_find_format(fmt);
c2abccec 302 if (!drv) {
15654a6d 303 error_report("Unknown file format '%s'", fmt);
c2abccec
MK
304 goto fail;
305 }
75c23805
FB
306 } else {
307 drv = NULL;
308 }
b9eaf9ec 309
ddf5636d 310 ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
b9eaf9ec 311 if (ret < 0) {
34b5d2c6
HR
312 error_report("Could not open '%s': %s", filename,
313 error_get_pretty(local_err));
314 error_free(local_err);
c2abccec 315 goto fail;
75c23805 316 }
b9eaf9ec 317
f0536bb8 318 if (bdrv_is_encrypted(bs) && require_io) {
f382d43a 319 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
c2abccec 320 if (read_password(password, sizeof(password)) < 0) {
15654a6d 321 error_report("No password given");
c2abccec
MK
322 goto fail;
323 }
324 if (bdrv_set_key(bs, password) < 0) {
15654a6d 325 error_report("invalid password");
c2abccec
MK
326 goto fail;
327 }
75c23805
FB
328 }
329 return bs;
c2abccec 330fail:
f67503e5 331 bdrv_unref(bs);
c2abccec 332 return NULL;
75c23805
FB
333}
334
83d0521a 335static int add_old_style_options(const char *fmt, QemuOpts *opts,
eec77d9e
JS
336 const char *base_filename,
337 const char *base_fmt)
efa84d43 338{
efa84d43 339 if (base_filename) {
83d0521a 340 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
15654a6d
JS
341 error_report("Backing file not supported for file format '%s'",
342 fmt);
c2abccec 343 return -1;
efa84d43
KW
344 }
345 }
346 if (base_fmt) {
83d0521a 347 if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
15654a6d
JS
348 error_report("Backing file format not supported for file "
349 "format '%s'", fmt);
c2abccec 350 return -1;
efa84d43
KW
351 }
352 }
c2abccec 353 return 0;
efa84d43
KW
354}
355
ea2384d3
FB
356static int img_create(int argc, char **argv)
357{
a9300911 358 int c;
1da7cfbd 359 uint64_t img_size = -1;
ea2384d3 360 const char *fmt = "raw";
9230eaf6 361 const char *base_fmt = NULL;
ea2384d3
FB
362 const char *filename;
363 const char *base_filename = NULL;
9ea2ea71 364 char *options = NULL;
9b37525a 365 Error *local_err = NULL;
f382d43a 366 bool quiet = false;
3b46e624 367
ea2384d3 368 for(;;) {
f382d43a 369 c = getopt(argc, argv, "F:b:f:he6o:q");
b8fb60da 370 if (c == -1) {
ea2384d3 371 break;
b8fb60da 372 }
ea2384d3 373 switch(c) {
ef87394c 374 case '?':
ea2384d3
FB
375 case 'h':
376 help();
377 break;
9230eaf6
AL
378 case 'F':
379 base_fmt = optarg;
380 break;
ea2384d3
FB
381 case 'b':
382 base_filename = optarg;
383 break;
384 case 'f':
385 fmt = optarg;
386 break;
387 case 'e':
9d42e15d 388 error_report("option -e is deprecated, please use \'-o "
eec77d9e 389 "encryption\' instead!");
77386bf6 390 goto fail;
d8871c5a 391 case '6':
9d42e15d 392 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 393 "compat6\' instead!");
77386bf6 394 goto fail;
9ea2ea71 395 case 'o':
77386bf6
KW
396 if (!is_valid_option_list(optarg)) {
397 error_report("Invalid option list: %s", optarg);
398 goto fail;
399 }
400 if (!options) {
401 options = g_strdup(optarg);
402 } else {
403 char *old_options = options;
404 options = g_strdup_printf("%s,%s", options, optarg);
405 g_free(old_options);
406 }
9ea2ea71 407 break;
f382d43a
MR
408 case 'q':
409 quiet = true;
410 break;
ea2384d3
FB
411 }
412 }
9230eaf6 413
b50cbabc 414 /* Get the filename */
a283cb6e
KW
415 filename = (optind < argc) ? argv[optind] : NULL;
416 if (options && has_help_option(options)) {
417 g_free(options);
418 return print_block_option_help(filename, fmt);
419 }
420
b8fb60da 421 if (optind >= argc) {
ac1307ab 422 error_exit("Expecting image file name");
b8fb60da 423 }
a283cb6e 424 optind++;
b50cbabc 425
1da7cfbd
JS
426 /* Get image size, if specified */
427 if (optind < argc) {
70b4f4bb 428 int64_t sval;
e36b3695
MA
429 char *end;
430 sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
431 if (sval < 0 || *end) {
79443397
LG
432 if (sval == -ERANGE) {
433 error_report("Image size must be less than 8 EiB!");
434 } else {
435 error_report("Invalid image size specified! You may use k, M, "
5e00984a
KW
436 "G, T, P or E suffixes for ");
437 error_report("kilobytes, megabytes, gigabytes, terabytes, "
438 "petabytes and exabytes.");
79443397 439 }
77386bf6 440 goto fail;
1da7cfbd
JS
441 }
442 img_size = (uint64_t)sval;
443 }
fc11eb26 444 if (optind != argc) {
ac1307ab 445 error_exit("Unexpected argument: %s", argv[optind]);
fc11eb26 446 }
1da7cfbd 447
9b37525a 448 bdrv_img_create(filename, fmt, base_filename, base_fmt,
f382d43a 449 options, img_size, BDRV_O_FLAGS, &local_err, quiet);
84d18f06 450 if (local_err) {
b70d8c23 451 error_report("%s: %s", filename, error_get_pretty(local_err));
9b37525a 452 error_free(local_err);
77386bf6 453 goto fail;
c2abccec 454 }
a9300911 455
77386bf6 456 g_free(options);
ea2384d3 457 return 0;
77386bf6
KW
458
459fail:
460 g_free(options);
461 return 1;
ea2384d3
FB
462}
463
f382d43a 464static void dump_json_image_check(ImageCheck *check, bool quiet)
8599ea4c 465{
4399c438 466 Error *local_err = NULL;
8599ea4c
FS
467 QString *str;
468 QmpOutputVisitor *ov = qmp_output_visitor_new();
469 QObject *obj;
470 visit_type_ImageCheck(qmp_output_get_visitor(ov),
4399c438 471 &check, NULL, &local_err);
8599ea4c
FS
472 obj = qmp_output_get_qobject(ov);
473 str = qobject_to_json_pretty(obj);
474 assert(str != NULL);
f382d43a 475 qprintf(quiet, "%s\n", qstring_get_str(str));
8599ea4c
FS
476 qobject_decref(obj);
477 qmp_output_visitor_cleanup(ov);
478 QDECREF(str);
479}
480
f382d43a 481static void dump_human_image_check(ImageCheck *check, bool quiet)
8599ea4c
FS
482{
483 if (!(check->corruptions || check->leaks || check->check_errors)) {
f382d43a 484 qprintf(quiet, "No errors were found on the image.\n");
8599ea4c
FS
485 } else {
486 if (check->corruptions) {
f382d43a
MR
487 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
488 "Data may be corrupted, or further writes to the image "
489 "may corrupt it.\n",
490 check->corruptions);
8599ea4c
FS
491 }
492
493 if (check->leaks) {
f382d43a
MR
494 qprintf(quiet,
495 "\n%" PRId64 " leaked clusters were found on the image.\n"
496 "This means waste of disk space, but no harm to data.\n",
497 check->leaks);
8599ea4c
FS
498 }
499
500 if (check->check_errors) {
f382d43a
MR
501 qprintf(quiet,
502 "\n%" PRId64
503 " internal errors have occurred during the check.\n",
504 check->check_errors);
8599ea4c
FS
505 }
506 }
507
508 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
f382d43a
MR
509 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
510 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
511 check->allocated_clusters, check->total_clusters,
512 check->allocated_clusters * 100.0 / check->total_clusters,
513 check->fragmented_clusters * 100.0 / check->allocated_clusters,
514 check->compressed_clusters * 100.0 /
515 check->allocated_clusters);
8599ea4c
FS
516 }
517
518 if (check->image_end_offset) {
f382d43a
MR
519 qprintf(quiet,
520 "Image end offset: %" PRId64 "\n", check->image_end_offset);
8599ea4c
FS
521 }
522}
523
524static int collect_image_check(BlockDriverState *bs,
525 ImageCheck *check,
526 const char *filename,
527 const char *fmt,
528 int fix)
529{
530 int ret;
531 BdrvCheckResult result;
532
533 ret = bdrv_check(bs, &result, fix);
534 if (ret < 0) {
535 return ret;
536 }
537
538 check->filename = g_strdup(filename);
539 check->format = g_strdup(bdrv_get_format_name(bs));
540 check->check_errors = result.check_errors;
541 check->corruptions = result.corruptions;
542 check->has_corruptions = result.corruptions != 0;
543 check->leaks = result.leaks;
544 check->has_leaks = result.leaks != 0;
545 check->corruptions_fixed = result.corruptions_fixed;
546 check->has_corruptions_fixed = result.corruptions != 0;
547 check->leaks_fixed = result.leaks_fixed;
548 check->has_leaks_fixed = result.leaks != 0;
549 check->image_end_offset = result.image_end_offset;
550 check->has_image_end_offset = result.image_end_offset != 0;
551 check->total_clusters = result.bfi.total_clusters;
552 check->has_total_clusters = result.bfi.total_clusters != 0;
553 check->allocated_clusters = result.bfi.allocated_clusters;
554 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
555 check->fragmented_clusters = result.bfi.fragmented_clusters;
556 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
e6439d78
SH
557 check->compressed_clusters = result.bfi.compressed_clusters;
558 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
8599ea4c
FS
559
560 return 0;
561}
562
e076f338
KW
563/*
564 * Checks an image for consistency. Exit codes:
565 *
d6635c4d
HR
566 * 0 - Check completed, image is good
567 * 1 - Check not completed because of internal errors
568 * 2 - Check completed, image is corrupted
569 * 3 - Check completed, image has leaked clusters, but is good otherwise
570 * 63 - Checks are not supported by the image format
e076f338 571 */
1585969c
AL
572static int img_check(int argc, char **argv)
573{
574 int c, ret;
8599ea4c 575 OutputFormat output_format = OFORMAT_HUMAN;
40055951 576 const char *filename, *fmt, *output, *cache;
1585969c 577 BlockDriverState *bs;
4534ff54 578 int fix = 0;
058f8f16 579 int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
8599ea4c 580 ImageCheck *check;
f382d43a 581 bool quiet = false;
1585969c
AL
582
583 fmt = NULL;
8599ea4c 584 output = NULL;
40055951 585 cache = BDRV_DEFAULT_CACHE;
1585969c 586 for(;;) {
8599ea4c
FS
587 int option_index = 0;
588 static const struct option long_options[] = {
589 {"help", no_argument, 0, 'h'},
590 {"format", required_argument, 0, 'f'},
4fd6a984 591 {"repair", required_argument, 0, 'r'},
8599ea4c
FS
592 {"output", required_argument, 0, OPTION_OUTPUT},
593 {0, 0, 0, 0}
594 };
40055951 595 c = getopt_long(argc, argv, "hf:r:T:q",
8599ea4c 596 long_options, &option_index);
b8fb60da 597 if (c == -1) {
1585969c 598 break;
b8fb60da 599 }
1585969c 600 switch(c) {
ef87394c 601 case '?':
1585969c
AL
602 case 'h':
603 help();
604 break;
605 case 'f':
606 fmt = optarg;
607 break;
4534ff54
KW
608 case 'r':
609 flags |= BDRV_O_RDWR;
610
611 if (!strcmp(optarg, "leaks")) {
612 fix = BDRV_FIX_LEAKS;
613 } else if (!strcmp(optarg, "all")) {
614 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
615 } else {
ac1307ab
FZ
616 error_exit("Unknown option value for -r "
617 "(expecting 'leaks' or 'all'): %s", optarg);
4534ff54
KW
618 }
619 break;
8599ea4c
FS
620 case OPTION_OUTPUT:
621 output = optarg;
622 break;
40055951
HR
623 case 'T':
624 cache = optarg;
625 break;
f382d43a
MR
626 case 'q':
627 quiet = true;
628 break;
1585969c
AL
629 }
630 }
fc11eb26 631 if (optind != argc - 1) {
ac1307ab 632 error_exit("Expecting one image file name");
b8fb60da 633 }
1585969c
AL
634 filename = argv[optind++];
635
8599ea4c
FS
636 if (output && !strcmp(output, "json")) {
637 output_format = OFORMAT_JSON;
638 } else if (output && !strcmp(output, "human")) {
639 output_format = OFORMAT_HUMAN;
640 } else if (output) {
641 error_report("--output must be used with human or json as argument.");
642 return 1;
643 }
644
40055951
HR
645 ret = bdrv_parse_cache_flags(cache, &flags);
646 if (ret < 0) {
647 error_report("Invalid source cache option: %s", cache);
648 return 1;
649 }
650
9ffe3332 651 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
c2abccec
MK
652 if (!bs) {
653 return 1;
654 }
8599ea4c
FS
655
656 check = g_new0(ImageCheck, 1);
657 ret = collect_image_check(bs, check, filename, fmt, fix);
e076f338
KW
658
659 if (ret == -ENOTSUP) {
55d492d7 660 error_report("This image format does not support checks");
fefddf95 661 ret = 63;
8599ea4c 662 goto fail;
e076f338
KW
663 }
664
8599ea4c
FS
665 if (check->corruptions_fixed || check->leaks_fixed) {
666 int corruptions_fixed, leaks_fixed;
ccf34716 667
8599ea4c
FS
668 leaks_fixed = check->leaks_fixed;
669 corruptions_fixed = check->corruptions_fixed;
e076f338 670
8599ea4c 671 if (output_format == OFORMAT_HUMAN) {
f382d43a
MR
672 qprintf(quiet,
673 "The following inconsistencies were found and repaired:\n\n"
674 " %" PRId64 " leaked clusters\n"
675 " %" PRId64 " corruptions\n\n"
676 "Double checking the fixed image now...\n",
677 check->leaks_fixed,
678 check->corruptions_fixed);
e076f338
KW
679 }
680
8599ea4c 681 ret = collect_image_check(bs, check, filename, fmt, 0);
1585969c 682
8599ea4c
FS
683 check->leaks_fixed = leaks_fixed;
684 check->corruptions_fixed = corruptions_fixed;
f8111c24
DXW
685 }
686
8599ea4c
FS
687 switch (output_format) {
688 case OFORMAT_HUMAN:
f382d43a 689 dump_human_image_check(check, quiet);
8599ea4c
FS
690 break;
691 case OFORMAT_JSON:
f382d43a 692 dump_json_image_check(check, quiet);
8599ea4c 693 break;
c6bb9ad1
FS
694 }
695
8599ea4c
FS
696 if (ret || check->check_errors) {
697 ret = 1;
698 goto fail;
c2abccec 699 }
e076f338 700
8599ea4c
FS
701 if (check->corruptions) {
702 ret = 2;
703 } else if (check->leaks) {
704 ret = 3;
e076f338 705 } else {
8599ea4c 706 ret = 0;
e076f338 707 }
8599ea4c
FS
708
709fail:
710 qapi_free_ImageCheck(check);
4f6fd349 711 bdrv_unref(bs);
8599ea4c
FS
712
713 return ret;
1585969c
AL
714}
715
ea2384d3
FB
716static int img_commit(int argc, char **argv)
717{
661a0f71
FS
718 int c, ret, flags;
719 const char *filename, *fmt, *cache;
ea2384d3 720 BlockDriverState *bs;
f382d43a 721 bool quiet = false;
ea2384d3
FB
722
723 fmt = NULL;
661a0f71 724 cache = BDRV_DEFAULT_CACHE;
ea2384d3 725 for(;;) {
f382d43a 726 c = getopt(argc, argv, "f:ht:q");
b8fb60da 727 if (c == -1) {
ea2384d3 728 break;
b8fb60da 729 }
ea2384d3 730 switch(c) {
ef87394c 731 case '?':
ea2384d3
FB
732 case 'h':
733 help();
734 break;
735 case 'f':
736 fmt = optarg;
737 break;
661a0f71
FS
738 case 't':
739 cache = optarg;
740 break;
f382d43a
MR
741 case 'q':
742 quiet = true;
743 break;
ea2384d3
FB
744 }
745 }
fc11eb26 746 if (optind != argc - 1) {
ac1307ab 747 error_exit("Expecting one image file name");
b8fb60da 748 }
ea2384d3
FB
749 filename = argv[optind++];
750
661a0f71 751 flags = BDRV_O_RDWR;
c3993cdc 752 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
753 if (ret < 0) {
754 error_report("Invalid cache option: %s", cache);
a3981eb9 755 return 1;
661a0f71
FS
756 }
757
9ffe3332 758 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
c2abccec
MK
759 if (!bs) {
760 return 1;
761 }
ea2384d3
FB
762 ret = bdrv_commit(bs);
763 switch(ret) {
764 case 0:
f382d43a 765 qprintf(quiet, "Image committed.\n");
ea2384d3
FB
766 break;
767 case -ENOENT:
15654a6d 768 error_report("No disk inserted");
ea2384d3
FB
769 break;
770 case -EACCES:
15654a6d 771 error_report("Image is read-only");
ea2384d3
FB
772 break;
773 case -ENOTSUP:
15654a6d 774 error_report("Image is already committed");
ea2384d3
FB
775 break;
776 default:
15654a6d 777 error_report("Error while committing image");
ea2384d3
FB
778 break;
779 }
780
4f6fd349 781 bdrv_unref(bs);
c2abccec
MK
782 if (ret) {
783 return 1;
784 }
ea2384d3
FB
785 return 0;
786}
787
f58c7b35
TS
788/*
789 * Returns true iff the first sector pointed to by 'buf' contains at least
790 * a non-NUL byte.
791 *
792 * 'pnum' is set to the number of sectors (including and immediately following
793 * the first one) that are known to be in the same allocated/unallocated state.
794 */
ea2384d3
FB
795static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
796{
1a6d39fd
SH
797 bool is_zero;
798 int i;
ea2384d3
FB
799
800 if (n <= 0) {
801 *pnum = 0;
802 return 0;
803 }
1a6d39fd 804 is_zero = buffer_is_zero(buf, 512);
ea2384d3
FB
805 for(i = 1; i < n; i++) {
806 buf += 512;
1a6d39fd 807 if (is_zero != buffer_is_zero(buf, 512)) {
ea2384d3 808 break;
1a6d39fd 809 }
ea2384d3
FB
810 }
811 *pnum = i;
1a6d39fd 812 return !is_zero;
ea2384d3
FB
813}
814
a22f123c
KW
815/*
816 * Like is_allocated_sectors, but if the buffer starts with a used sector,
817 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
818 * breaking up write requests for only small sparse areas.
819 */
820static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
821 int min)
822{
823 int ret;
824 int num_checked, num_used;
825
826 if (n < min) {
827 min = n;
828 }
829
830 ret = is_allocated_sectors(buf, n, pnum);
831 if (!ret) {
832 return ret;
833 }
834
835 num_used = *pnum;
836 buf += BDRV_SECTOR_SIZE * *pnum;
837 n -= *pnum;
838 num_checked = num_used;
839
840 while (n > 0) {
841 ret = is_allocated_sectors(buf, n, pnum);
842
843 buf += BDRV_SECTOR_SIZE * *pnum;
844 n -= *pnum;
845 num_checked += *pnum;
846 if (ret) {
847 num_used = num_checked;
848 } else if (*pnum >= min) {
849 break;
850 }
851 }
852
853 *pnum = num_used;
854 return 1;
855}
856
3e85c6fd
KW
857/*
858 * Compares two buffers sector by sector. Returns 0 if the first sector of both
859 * buffers matches, non-zero otherwise.
860 *
861 * pnum is set to the number of sectors (including and immediately following
862 * the first one) that are known to have the same comparison result
863 */
864static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
865 int *pnum)
866{
867 int res, i;
868
869 if (n <= 0) {
870 *pnum = 0;
871 return 0;
872 }
873
874 res = !!memcmp(buf1, buf2, 512);
875 for(i = 1; i < n; i++) {
876 buf1 += 512;
877 buf2 += 512;
878
879 if (!!memcmp(buf1, buf2, 512) != res) {
880 break;
881 }
882 }
883
884 *pnum = i;
885 return res;
886}
887
80ee15a6 888#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3 889
d14ed18c
MR
890static int64_t sectors_to_bytes(int64_t sectors)
891{
892 return sectors << BDRV_SECTOR_BITS;
893}
894
895static int64_t sectors_to_process(int64_t total, int64_t from)
896{
897 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
898}
899
900/*
901 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
902 *
903 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
904 * data and negative value on error.
905 *
906 * @param bs: Driver used for accessing file
907 * @param sect_num: Number of first sector to check
908 * @param sect_count: Number of sectors to check
909 * @param filename: Name of disk file we are checking (logging purpose)
910 * @param buffer: Allocated buffer for storing read data
911 * @param quiet: Flag for quiet mode
912 */
913static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
914 int sect_count, const char *filename,
915 uint8_t *buffer, bool quiet)
916{
917 int pnum, ret = 0;
918 ret = bdrv_read(bs, sect_num, buffer, sect_count);
919 if (ret < 0) {
920 error_report("Error while reading offset %" PRId64 " of %s: %s",
921 sectors_to_bytes(sect_num), filename, strerror(-ret));
922 return ret;
923 }
924 ret = is_allocated_sectors(buffer, sect_count, &pnum);
925 if (ret || pnum != sect_count) {
926 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
927 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
928 return 1;
929 }
930
931 return 0;
932}
933
934/*
935 * Compares two images. Exit codes:
936 *
937 * 0 - Images are identical
938 * 1 - Images differ
939 * >1 - Error occurred
940 */
941static int img_compare(int argc, char **argv)
942{
40055951 943 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
d14ed18c
MR
944 BlockDriverState *bs1, *bs2;
945 int64_t total_sectors1, total_sectors2;
946 uint8_t *buf1 = NULL, *buf2 = NULL;
947 int pnum1, pnum2;
948 int allocated1, allocated2;
949 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
950 bool progress = false, quiet = false, strict = false;
40055951 951 int flags;
d14ed18c
MR
952 int64_t total_sectors;
953 int64_t sector_num = 0;
954 int64_t nb_sectors;
955 int c, pnum;
d14ed18c
MR
956 uint64_t progress_base;
957
40055951 958 cache = BDRV_DEFAULT_CACHE;
d14ed18c 959 for (;;) {
40055951 960 c = getopt(argc, argv, "hf:F:T:pqs");
d14ed18c
MR
961 if (c == -1) {
962 break;
963 }
964 switch (c) {
965 case '?':
966 case 'h':
967 help();
968 break;
969 case 'f':
970 fmt1 = optarg;
971 break;
972 case 'F':
973 fmt2 = optarg;
974 break;
40055951
HR
975 case 'T':
976 cache = optarg;
977 break;
d14ed18c
MR
978 case 'p':
979 progress = true;
980 break;
981 case 'q':
982 quiet = true;
983 break;
984 case 's':
985 strict = true;
986 break;
987 }
988 }
989
990 /* Progress is not shown in Quiet mode */
991 if (quiet) {
992 progress = false;
993 }
994
995
fc11eb26 996 if (optind != argc - 2) {
ac1307ab 997 error_exit("Expecting two image file names");
d14ed18c
MR
998 }
999 filename1 = argv[optind++];
1000 filename2 = argv[optind++];
1001
cbda016d
SH
1002 /* Initialize before goto out */
1003 qemu_progress_init(progress, 2.0);
1004
40055951
HR
1005 flags = BDRV_O_FLAGS;
1006 ret = bdrv_parse_cache_flags(cache, &flags);
1007 if (ret < 0) {
1008 error_report("Invalid source cache option: %s", cache);
1009 ret = 2;
1010 goto out3;
1011 }
1012
40055951 1013 bs1 = bdrv_new_open("image 1", filename1, fmt1, flags, true, quiet);
d14ed18c
MR
1014 if (!bs1) {
1015 error_report("Can't open file %s", filename1);
1016 ret = 2;
1017 goto out3;
1018 }
1019
40055951 1020 bs2 = bdrv_new_open("image 2", filename2, fmt2, flags, true, quiet);
d14ed18c
MR
1021 if (!bs2) {
1022 error_report("Can't open file %s", filename2);
1023 ret = 2;
1024 goto out2;
1025 }
1026
1027 buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
1028 buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
52bf1e72
MA
1029 total_sectors1 = bdrv_nb_sectors(bs1);
1030 if (total_sectors1 < 0) {
1031 error_report("Can't get size of %s: %s",
1032 filename1, strerror(-total_sectors1));
1033 ret = 4;
1034 goto out;
1035 }
1036 total_sectors2 = bdrv_nb_sectors(bs2);
1037 if (total_sectors2 < 0) {
1038 error_report("Can't get size of %s: %s",
1039 filename2, strerror(-total_sectors2));
1040 ret = 4;
1041 goto out;
1042 }
d14ed18c
MR
1043 total_sectors = MIN(total_sectors1, total_sectors2);
1044 progress_base = MAX(total_sectors1, total_sectors2);
1045
1046 qemu_progress_print(0, 100);
1047
1048 if (strict && total_sectors1 != total_sectors2) {
1049 ret = 1;
1050 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1051 goto out;
1052 }
1053
1054 for (;;) {
1055 nb_sectors = sectors_to_process(total_sectors, sector_num);
1056 if (nb_sectors <= 0) {
1057 break;
1058 }
1059 allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
1060 &pnum1);
1061 if (allocated1 < 0) {
1062 ret = 3;
1063 error_report("Sector allocation test failed for %s", filename1);
1064 goto out;
1065 }
1066
1067 allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
1068 &pnum2);
1069 if (allocated2 < 0) {
1070 ret = 3;
1071 error_report("Sector allocation test failed for %s", filename2);
1072 goto out;
1073 }
1074 nb_sectors = MIN(pnum1, pnum2);
1075
1076 if (allocated1 == allocated2) {
1077 if (allocated1) {
1078 ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
1079 if (ret < 0) {
1080 error_report("Error while reading offset %" PRId64 " of %s:"
1081 " %s", sectors_to_bytes(sector_num), filename1,
1082 strerror(-ret));
1083 ret = 4;
1084 goto out;
1085 }
1086 ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
1087 if (ret < 0) {
1088 error_report("Error while reading offset %" PRId64
1089 " of %s: %s", sectors_to_bytes(sector_num),
1090 filename2, strerror(-ret));
1091 ret = 4;
1092 goto out;
1093 }
1094 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1095 if (ret || pnum != nb_sectors) {
d14ed18c
MR
1096 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1097 sectors_to_bytes(
1098 ret ? sector_num : sector_num + pnum));
36452f12 1099 ret = 1;
d14ed18c
MR
1100 goto out;
1101 }
1102 }
1103 } else {
1104 if (strict) {
1105 ret = 1;
1106 qprintf(quiet, "Strict mode: Offset %" PRId64
1107 " allocation mismatch!\n",
1108 sectors_to_bytes(sector_num));
1109 goto out;
1110 }
1111
1112 if (allocated1) {
1113 ret = check_empty_sectors(bs1, sector_num, nb_sectors,
1114 filename1, buf1, quiet);
1115 } else {
1116 ret = check_empty_sectors(bs2, sector_num, nb_sectors,
1117 filename2, buf1, quiet);
1118 }
1119 if (ret) {
1120 if (ret < 0) {
d14ed18c
MR
1121 error_report("Error while reading offset %" PRId64 ": %s",
1122 sectors_to_bytes(sector_num), strerror(-ret));
36452f12 1123 ret = 4;
d14ed18c
MR
1124 }
1125 goto out;
1126 }
1127 }
1128 sector_num += nb_sectors;
1129 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1130 }
1131
1132 if (total_sectors1 != total_sectors2) {
1133 BlockDriverState *bs_over;
1134 int64_t total_sectors_over;
1135 const char *filename_over;
1136
1137 qprintf(quiet, "Warning: Image size mismatch!\n");
1138 if (total_sectors1 > total_sectors2) {
1139 total_sectors_over = total_sectors1;
1140 bs_over = bs1;
1141 filename_over = filename1;
1142 } else {
1143 total_sectors_over = total_sectors2;
1144 bs_over = bs2;
1145 filename_over = filename2;
1146 }
1147
1148 for (;;) {
1149 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1150 if (nb_sectors <= 0) {
1151 break;
1152 }
1153 ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
1154 nb_sectors, &pnum);
1155 if (ret < 0) {
1156 ret = 3;
1157 error_report("Sector allocation test failed for %s",
1158 filename_over);
1159 goto out;
1160
1161 }
1162 nb_sectors = pnum;
1163 if (ret) {
1164 ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
1165 filename_over, buf1, quiet);
1166 if (ret) {
1167 if (ret < 0) {
d14ed18c
MR
1168 error_report("Error while reading offset %" PRId64
1169 " of %s: %s", sectors_to_bytes(sector_num),
1170 filename_over, strerror(-ret));
36452f12 1171 ret = 4;
d14ed18c
MR
1172 }
1173 goto out;
1174 }
1175 }
1176 sector_num += nb_sectors;
1177 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1178 }
1179 }
1180
1181 qprintf(quiet, "Images are identical.\n");
1182 ret = 0;
1183
1184out:
4f6fd349 1185 bdrv_unref(bs2);
d14ed18c
MR
1186 qemu_vfree(buf1);
1187 qemu_vfree(buf2);
1188out2:
4f6fd349 1189 bdrv_unref(bs1);
d14ed18c
MR
1190out3:
1191 qemu_progress_end();
1192 return ret;
1193}
1194
ea2384d3
FB
1195static int img_convert(int argc, char **argv)
1196{
24f833cd 1197 int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
13c28af8 1198 int64_t ret = 0;
40055951
HR
1199 int progress = 0, flags, src_flags;
1200 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
b50cbabc 1201 BlockDriver *drv, *proto_drv;
c2abccec 1202 BlockDriverState **bs = NULL, *out_bs = NULL;
802c3d4c 1203 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
52bf1e72 1204 int64_t *bs_sectors = NULL;
c2abccec 1205 uint8_t * buf = NULL;
f2521c90 1206 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
ea2384d3 1207 const uint8_t *buf1;
faea38e7 1208 BlockDriverInfo bdi;
83d0521a
CL
1209 QemuOpts *opts = NULL;
1210 QemuOptsList *create_opts = NULL;
1211 const char *out_baseimg_param;
efa84d43 1212 char *options = NULL;
51ef6727 1213 const char *snapshot_name = NULL;
a22f123c 1214 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
f382d43a 1215 bool quiet = false;
cc84d90f 1216 Error *local_err = NULL;
ef80654d 1217 QemuOpts *sn_opts = NULL;
ea2384d3
FB
1218
1219 fmt = NULL;
1220 out_fmt = "raw";
661a0f71 1221 cache = "unsafe";
40055951 1222 src_cache = BDRV_DEFAULT_CACHE;
f58c7b35 1223 out_baseimg = NULL;
eec77d9e 1224 compress = 0;
b2e10493 1225 skip_create = 0;
ea2384d3 1226 for(;;) {
40055951 1227 c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
b8fb60da 1228 if (c == -1) {
ea2384d3 1229 break;
b8fb60da 1230 }
ea2384d3 1231 switch(c) {
ef87394c 1232 case '?':
ea2384d3
FB
1233 case 'h':
1234 help();
1235 break;
1236 case 'f':
1237 fmt = optarg;
1238 break;
1239 case 'O':
1240 out_fmt = optarg;
1241 break;
f58c7b35
TS
1242 case 'B':
1243 out_baseimg = optarg;
1244 break;
ea2384d3 1245 case 'c':
eec77d9e 1246 compress = 1;
ea2384d3
FB
1247 break;
1248 case 'e':
9d42e15d 1249 error_report("option -e is deprecated, please use \'-o "
eec77d9e 1250 "encryption\' instead!");
2dc8328b 1251 ret = -1;
64bb01aa 1252 goto fail_getopt;
ec36ba14 1253 case '6':
9d42e15d 1254 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 1255 "compat6\' instead!");
2dc8328b 1256 ret = -1;
64bb01aa 1257 goto fail_getopt;
efa84d43 1258 case 'o':
2dc8328b
KW
1259 if (!is_valid_option_list(optarg)) {
1260 error_report("Invalid option list: %s", optarg);
1261 ret = -1;
64bb01aa 1262 goto fail_getopt;
2dc8328b
KW
1263 }
1264 if (!options) {
1265 options = g_strdup(optarg);
1266 } else {
1267 char *old_options = options;
1268 options = g_strdup_printf("%s,%s", options, optarg);
1269 g_free(old_options);
1270 }
efa84d43 1271 break;
51ef6727 1272 case 's':
1273 snapshot_name = optarg;
1274 break;
ef80654d
WX
1275 case 'l':
1276 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
1277 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
1278 if (!sn_opts) {
1279 error_report("Failed in parsing snapshot param '%s'",
1280 optarg);
2dc8328b 1281 ret = -1;
64bb01aa 1282 goto fail_getopt;
ef80654d
WX
1283 }
1284 } else {
1285 snapshot_name = optarg;
1286 }
1287 break;
a22f123c
KW
1288 case 'S':
1289 {
1290 int64_t sval;
e36b3695
MA
1291 char *end;
1292 sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
1293 if (sval < 0 || *end) {
a22f123c 1294 error_report("Invalid minimum zero buffer size for sparse output specified");
2dc8328b 1295 ret = -1;
64bb01aa 1296 goto fail_getopt;
a22f123c
KW
1297 }
1298
1299 min_sparse = sval / BDRV_SECTOR_SIZE;
1300 break;
1301 }
6b837bc4
JS
1302 case 'p':
1303 progress = 1;
1304 break;
661a0f71
FS
1305 case 't':
1306 cache = optarg;
1307 break;
40055951
HR
1308 case 'T':
1309 src_cache = optarg;
1310 break;
f382d43a
MR
1311 case 'q':
1312 quiet = true;
1313 break;
b2e10493
AD
1314 case 'n':
1315 skip_create = 1;
1316 break;
ea2384d3
FB
1317 }
1318 }
3b46e624 1319
64bb01aa 1320 /* Initialize before goto out */
f382d43a
MR
1321 if (quiet) {
1322 progress = 0;
1323 }
64bb01aa
KW
1324 qemu_progress_init(progress, 1.0);
1325
f382d43a 1326
926c2d23 1327 bs_n = argc - optind - 1;
a283cb6e 1328 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
f58c7b35 1329
2dc8328b 1330 if (options && has_help_option(options)) {
4ac8aacd
JS
1331 ret = print_block_option_help(out_filename, out_fmt);
1332 goto out;
1333 }
1334
a283cb6e 1335 if (bs_n < 1) {
ac1307ab 1336 error_exit("Must specify image file name");
a283cb6e
KW
1337 }
1338
1339
c2abccec 1340 if (bs_n > 1 && out_baseimg) {
15654a6d
JS
1341 error_report("-B makes no sense when concatenating multiple input "
1342 "images");
31ca34b8
JS
1343 ret = -1;
1344 goto out;
c2abccec 1345 }
f8111c24 1346
40055951
HR
1347 src_flags = BDRV_O_FLAGS;
1348 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
1349 if (ret < 0) {
1350 error_report("Invalid source cache option: %s", src_cache);
1351 goto out;
1352 }
1353
6b837bc4
JS
1354 qemu_progress_print(0, 100);
1355
d739f1c4 1356 bs = g_new0(BlockDriverState *, bs_n);
52bf1e72 1357 bs_sectors = g_new(int64_t, bs_n);
926c2d23
AZ
1358
1359 total_sectors = 0;
1360 for (bs_i = 0; bs_i < bs_n; bs_i++) {
9ffe3332
KW
1361 char *id = bs_n > 1 ? g_strdup_printf("source %d", bs_i)
1362 : g_strdup("source");
40055951 1363 bs[bs_i] = bdrv_new_open(id, argv[optind + bs_i], fmt, src_flags,
9ffe3332
KW
1364 true, quiet);
1365 g_free(id);
c2abccec 1366 if (!bs[bs_i]) {
15654a6d 1367 error_report("Could not open '%s'", argv[optind + bs_i]);
c2abccec
MK
1368 ret = -1;
1369 goto out;
1370 }
52bf1e72
MA
1371 bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
1372 if (bs_sectors[bs_i] < 0) {
1373 error_report("Could not get size of %s: %s",
1374 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1375 ret = -1;
1376 goto out;
1377 }
d739f1c4 1378 total_sectors += bs_sectors[bs_i];
926c2d23 1379 }
ea2384d3 1380
ef80654d
WX
1381 if (sn_opts) {
1382 ret = bdrv_snapshot_load_tmp(bs[0],
1383 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1384 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1385 &local_err);
1386 } else if (snapshot_name != NULL) {
51ef6727 1387 if (bs_n > 1) {
6daf194d 1388 error_report("No support for concatenating multiple snapshot");
51ef6727 1389 ret = -1;
1390 goto out;
1391 }
7b4c4781
WX
1392
1393 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
ef80654d 1394 }
84d18f06 1395 if (local_err) {
ef80654d
WX
1396 error_report("Failed to load snapshot: %s",
1397 error_get_pretty(local_err));
1398 error_free(local_err);
1399 ret = -1;
1400 goto out;
51ef6727 1401 }
1402
efa84d43 1403 /* Find driver and parse its options */
ea2384d3 1404 drv = bdrv_find_format(out_fmt);
c2abccec 1405 if (!drv) {
15654a6d 1406 error_report("Unknown file format '%s'", out_fmt);
c2abccec
MK
1407 ret = -1;
1408 goto out;
1409 }
efa84d43 1410
98289620 1411 proto_drv = bdrv_find_protocol(out_filename, true);
c2abccec 1412 if (!proto_drv) {
15654a6d 1413 error_report("Unknown protocol '%s'", out_filename);
c2abccec
MK
1414 ret = -1;
1415 goto out;
1416 }
b50cbabc 1417
c282e1fd
CL
1418 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1419 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 1420
83d0521a
CL
1421 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
1422 if (options && qemu_opts_do_parse(opts, options, NULL)) {
1423 error_report("Invalid options for file format '%s'", out_fmt);
1424 ret = -1;
1425 goto out;
efa84d43
KW
1426 }
1427
83d0521a
CL
1428 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
1429 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
c2abccec
MK
1430 if (ret < 0) {
1431 goto out;
1432 }
efa84d43 1433
a18953fb 1434 /* Get backing file name if -o backing_file was used */
83d0521a 1435 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 1436 if (out_baseimg_param) {
83d0521a 1437 out_baseimg = out_baseimg_param;
a18953fb
KW
1438 }
1439
efa84d43 1440 /* Check if compression is supported */
eec77d9e 1441 if (compress) {
83d0521a
CL
1442 bool encryption =
1443 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
1444 const char *preallocation =
1445 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
efa84d43
KW
1446
1447 if (!drv->bdrv_write_compressed) {
15654a6d 1448 error_report("Compression not supported for this file format");
c2abccec
MK
1449 ret = -1;
1450 goto out;
efa84d43
KW
1451 }
1452
83d0521a 1453 if (encryption) {
15654a6d
JS
1454 error_report("Compression and encryption not supported at "
1455 "the same time");
c2abccec
MK
1456 ret = -1;
1457 goto out;
efa84d43 1458 }
41521fa4 1459
83d0521a
CL
1460 if (preallocation
1461 && strcmp(preallocation, "off"))
41521fa4
KW
1462 {
1463 error_report("Compression and preallocation not supported at "
1464 "the same time");
1465 ret = -1;
1466 goto out;
1467 }
efa84d43
KW
1468 }
1469
b2e10493
AD
1470 if (!skip_create) {
1471 /* Create the new image */
c282e1fd 1472 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 1473 if (ret < 0) {
cc84d90f
HR
1474 error_report("%s: error while converting %s: %s",
1475 out_filename, out_fmt, error_get_pretty(local_err));
1476 error_free(local_err);
b2e10493 1477 goto out;
ea2384d3
FB
1478 }
1479 }
3b46e624 1480
5a37b60a 1481 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
c3993cdc 1482 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
1483 if (ret < 0) {
1484 error_report("Invalid cache option: %s", cache);
bb9cd2ee 1485 goto out;
661a0f71
FS
1486 }
1487
9ffe3332 1488 out_bs = bdrv_new_open("target", out_filename, out_fmt, flags, true, quiet);
c2abccec
MK
1489 if (!out_bs) {
1490 ret = -1;
1491 goto out;
1492 }
ea2384d3 1493
926c2d23
AZ
1494 bs_i = 0;
1495 bs_offset = 0;
f2521c90
PL
1496
1497 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
1498 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
1499 * as maximum. */
1500 bufsectors = MIN(32768,
1501 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
1502 out_bs->bl.discard_alignment))
1503 );
1504
1505 buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
926c2d23 1506
b2e10493 1507 if (skip_create) {
43716fa8
MA
1508 int64_t output_sectors = bdrv_nb_sectors(out_bs);
1509 if (output_sectors < 0) {
b2e10493 1510 error_report("unable to get output image length: %s\n",
43716fa8 1511 strerror(-output_sectors));
b2e10493
AD
1512 ret = -1;
1513 goto out;
43716fa8 1514 } else if (output_sectors < total_sectors) {
b2e10493
AD
1515 error_report("output file is smaller than input file");
1516 ret = -1;
1517 goto out;
1518 }
1519 }
1520
24f833cd
PL
1521 cluster_sectors = 0;
1522 ret = bdrv_get_info(out_bs, &bdi);
1523 if (ret < 0) {
1524 if (compress) {
15654a6d 1525 error_report("could not get block driver info");
c2abccec
MK
1526 goto out;
1527 }
24f833cd 1528 } else {
85f49cad 1529 compress = compress || bdi.needs_compressed_writes;
24f833cd
PL
1530 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
1531 }
1532
1533 if (compress) {
1534 if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
15654a6d 1535 error_report("invalid cluster size");
c2abccec
MK
1536 ret = -1;
1537 goto out;
1538 }
ea2384d3 1539 sector_num = 0;
6b837bc4
JS
1540
1541 nb_sectors = total_sectors;
6b837bc4 1542
ea2384d3 1543 for(;;) {
926c2d23
AZ
1544 int64_t bs_num;
1545 int remainder;
1546 uint8_t *buf2;
1547
ea2384d3
FB
1548 nb_sectors = total_sectors - sector_num;
1549 if (nb_sectors <= 0)
1550 break;
1551 if (nb_sectors >= cluster_sectors)
1552 n = cluster_sectors;
1553 else
1554 n = nb_sectors;
926c2d23
AZ
1555
1556 bs_num = sector_num - bs_offset;
1557 assert (bs_num >= 0);
1558 remainder = n;
1559 buf2 = buf;
1560 while (remainder > 0) {
1561 int nlow;
d739f1c4
MA
1562 while (bs_num == bs_sectors[bs_i]) {
1563 bs_offset += bs_sectors[bs_i];
926c2d23
AZ
1564 bs_i++;
1565 assert (bs_i < bs_n);
926c2d23 1566 bs_num = 0;
0bfcd599
BS
1567 /* printf("changing part: sector_num=%" PRId64 ", "
1568 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
d739f1c4 1569 "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
926c2d23 1570 }
d739f1c4 1571 assert (bs_num < bs_sectors[bs_i]);
926c2d23 1572
d739f1c4
MA
1573 nlow = remainder > bs_sectors[bs_i] - bs_num
1574 ? bs_sectors[bs_i] - bs_num : remainder;
926c2d23 1575
c2abccec
MK
1576 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
1577 if (ret < 0) {
3fba9d81
SH
1578 error_report("error while reading sector %" PRId64 ": %s",
1579 bs_num, strerror(-ret));
c2abccec
MK
1580 goto out;
1581 }
926c2d23
AZ
1582
1583 buf2 += nlow * 512;
1584 bs_num += nlow;
1585
1586 remainder -= nlow;
1587 }
1588 assert (remainder == 0);
1589
54f106d5
SH
1590 if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
1591 ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
c2abccec 1592 if (ret != 0) {
3fba9d81
SH
1593 error_report("error while compressing sector %" PRId64
1594 ": %s", sector_num, strerror(-ret));
c2abccec
MK
1595 goto out;
1596 }
ea2384d3
FB
1597 }
1598 sector_num += n;
13c28af8 1599 qemu_progress_print(100.0 * sector_num / total_sectors, 0);
ea2384d3 1600 }
faea38e7
FB
1601 /* signal EOF to align */
1602 bdrv_write_compressed(out_bs, 0, NULL, 0);
ea2384d3 1603 } else {
802c3d4c
PL
1604 int64_t sectors_to_read, sectors_read, sector_num_next_status;
1605 bool count_allocated_sectors;
11b6699a 1606 int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
f2feebbd 1607
5a37b60a
PL
1608 if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
1609 ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
1610 if (ret < 0) {
1611 goto out;
1612 }
1613 has_zero_init = 1;
1614 }
1615
802c3d4c
PL
1616 sectors_to_read = total_sectors;
1617 count_allocated_sectors = progress && (out_baseimg || has_zero_init);
1618restart:
f58c7b35 1619 sector_num = 0; // total number of sectors converted so far
802c3d4c
PL
1620 sectors_read = 0;
1621 sector_num_next_status = 0;
6b837bc4 1622
ea2384d3
FB
1623 for(;;) {
1624 nb_sectors = total_sectors - sector_num;
b8fb60da 1625 if (nb_sectors <= 0) {
802c3d4c
PL
1626 if (count_allocated_sectors) {
1627 sectors_to_read = sectors_read;
1628 count_allocated_sectors = false;
1629 goto restart;
1630 }
13c28af8 1631 ret = 0;
ea2384d3 1632 break;
b8fb60da 1633 }
926c2d23 1634
d739f1c4
MA
1635 while (sector_num - bs_offset >= bs_sectors[bs_i]) {
1636 bs_offset += bs_sectors[bs_i];
926c2d23
AZ
1637 bs_i ++;
1638 assert (bs_i < bs_n);
0bfcd599
BS
1639 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
1640 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
d739f1c4 1641 sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
926c2d23
AZ
1642 }
1643
13c28af8
PL
1644 if ((out_baseimg || has_zero_init) &&
1645 sector_num >= sector_num_next_status) {
1646 n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
1647 ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
1648 n, &n1);
e4a86f88 1649 if (ret < 0) {
13c28af8
PL
1650 error_report("error while reading block status of sector %"
1651 PRId64 ": %s", sector_num - bs_offset,
1652 strerror(-ret));
e4a86f88
PB
1653 goto out;
1654 }
13c28af8
PL
1655 /* If the output image is zero initialized, we are not working
1656 * on a shared base and the input is zero we can skip the next
1657 * n1 sectors */
1658 if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
e4a86f88
PB
1659 sector_num += n1;
1660 continue;
93c65b47 1661 }
13c28af8
PL
1662 /* If the output image is being created as a copy on write
1663 * image, assume that sectors which are unallocated in the
1664 * input image are present in both the output's and input's
1665 * base images (no need to copy them). */
1666 if (out_baseimg) {
1667 if (!(ret & BDRV_BLOCK_DATA)) {
1668 sector_num += n1;
1669 continue;
1670 }
1671 /* The next 'n1' sectors are allocated in the input image.
1672 * Copy only those as they may be followed by unallocated
1673 * sectors. */
1674 nb_sectors = n1;
1675 }
1676 /* avoid redundant callouts to get_block_status */
1677 sector_num_next_status = sector_num + n1;
f58c7b35
TS
1678 }
1679
f2521c90 1680 n = MIN(nb_sectors, bufsectors);
24f833cd
PL
1681
1682 /* round down request length to an aligned sector, but
1683 * do not bother doing this on short requests. They happen
1684 * when we found an all-zero area, and the next sector to
1685 * write will not be sector_num + n. */
1686 if (cluster_sectors > 0 && n >= cluster_sectors) {
1687 int64_t next_aligned_sector = (sector_num + n);
1688 next_aligned_sector -= next_aligned_sector % cluster_sectors;
1689 if (sector_num + n > next_aligned_sector) {
1690 n = next_aligned_sector - sector_num;
1691 }
1692 }
1693
d739f1c4 1694 n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
13c28af8 1695
802c3d4c
PL
1696 sectors_read += n;
1697 if (count_allocated_sectors) {
1698 sector_num += n;
1699 continue;
1700 }
1701
1702 n1 = n;
c2abccec
MK
1703 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
1704 if (ret < 0) {
3fba9d81
SH
1705 error_report("error while reading sector %" PRId64 ": %s",
1706 sector_num - bs_offset, strerror(-ret));
c2abccec
MK
1707 goto out;
1708 }
ea2384d3
FB
1709 /* NOTE: at the same time we convert, we do not write zero
1710 sectors to have a chance to compress the image. Ideally, we
1711 should add a specific call to have the info to go faster */
1712 buf1 = buf;
1713 while (n > 0) {
11212d8f 1714 if (!has_zero_init ||
a22f123c 1715 is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
c2abccec
MK
1716 ret = bdrv_write(out_bs, sector_num, buf1, n1);
1717 if (ret < 0) {
3fba9d81
SH
1718 error_report("error while writing sector %" PRId64
1719 ": %s", sector_num, strerror(-ret));
c2abccec
MK
1720 goto out;
1721 }
ea2384d3
FB
1722 }
1723 sector_num += n1;
1724 n -= n1;
1725 buf1 += n1 * 512;
1726 }
802c3d4c 1727 qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
ea2384d3
FB
1728 }
1729 }
c2abccec 1730out:
13c28af8
PL
1731 if (!ret) {
1732 qemu_progress_print(100, 0);
1733 }
6b837bc4 1734 qemu_progress_end();
83d0521a
CL
1735 qemu_opts_del(opts);
1736 qemu_opts_free(create_opts);
bb1c0597 1737 qemu_vfree(buf);
ef80654d
WX
1738 if (sn_opts) {
1739 qemu_opts_del(sn_opts);
1740 }
c2abccec 1741 if (out_bs) {
4f6fd349 1742 bdrv_unref(out_bs);
c2abccec 1743 }
31ca34b8
JS
1744 if (bs) {
1745 for (bs_i = 0; bs_i < bs_n; bs_i++) {
1746 if (bs[bs_i]) {
4f6fd349 1747 bdrv_unref(bs[bs_i]);
31ca34b8 1748 }
c2abccec 1749 }
7267c094 1750 g_free(bs);
c2abccec 1751 }
d739f1c4 1752 g_free(bs_sectors);
64bb01aa
KW
1753fail_getopt:
1754 g_free(options);
1755
c2abccec
MK
1756 if (ret) {
1757 return 1;
1758 }
ea2384d3
FB
1759 return 0;
1760}
1761
57d1a2b6 1762
faea38e7
FB
1763static void dump_snapshots(BlockDriverState *bs)
1764{
1765 QEMUSnapshotInfo *sn_tab, *sn;
1766 int nb_sns, i;
faea38e7
FB
1767
1768 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1769 if (nb_sns <= 0)
1770 return;
1771 printf("Snapshot list:\n");
5b917044
WX
1772 bdrv_snapshot_dump(fprintf, stdout, NULL);
1773 printf("\n");
faea38e7
FB
1774 for(i = 0; i < nb_sns; i++) {
1775 sn = &sn_tab[i];
5b917044
WX
1776 bdrv_snapshot_dump(fprintf, stdout, sn);
1777 printf("\n");
faea38e7 1778 }
7267c094 1779 g_free(sn_tab);
faea38e7
FB
1780}
1781
9699bf0d
SH
1782static void dump_json_image_info_list(ImageInfoList *list)
1783{
4399c438 1784 Error *local_err = NULL;
9699bf0d
SH
1785 QString *str;
1786 QmpOutputVisitor *ov = qmp_output_visitor_new();
1787 QObject *obj;
1788 visit_type_ImageInfoList(qmp_output_get_visitor(ov),
4399c438 1789 &list, NULL, &local_err);
9699bf0d
SH
1790 obj = qmp_output_get_qobject(ov);
1791 str = qobject_to_json_pretty(obj);
1792 assert(str != NULL);
1793 printf("%s\n", qstring_get_str(str));
1794 qobject_decref(obj);
1795 qmp_output_visitor_cleanup(ov);
1796 QDECREF(str);
1797}
1798
c054b3fd
BC
1799static void dump_json_image_info(ImageInfo *info)
1800{
4399c438 1801 Error *local_err = NULL;
c054b3fd
BC
1802 QString *str;
1803 QmpOutputVisitor *ov = qmp_output_visitor_new();
1804 QObject *obj;
1805 visit_type_ImageInfo(qmp_output_get_visitor(ov),
4399c438 1806 &info, NULL, &local_err);
c054b3fd
BC
1807 obj = qmp_output_get_qobject(ov);
1808 str = qobject_to_json_pretty(obj);
1809 assert(str != NULL);
1810 printf("%s\n", qstring_get_str(str));
1811 qobject_decref(obj);
1812 qmp_output_visitor_cleanup(ov);
1813 QDECREF(str);
1814}
1815
9699bf0d
SH
1816static void dump_human_image_info_list(ImageInfoList *list)
1817{
1818 ImageInfoList *elem;
1819 bool delim = false;
1820
1821 for (elem = list; elem; elem = elem->next) {
1822 if (delim) {
1823 printf("\n");
1824 }
1825 delim = true;
1826
5b917044 1827 bdrv_image_info_dump(fprintf, stdout, elem->value);
9699bf0d
SH
1828 }
1829}
1830
1831static gboolean str_equal_func(gconstpointer a, gconstpointer b)
1832{
1833 return strcmp(a, b) == 0;
1834}
1835
1836/**
1837 * Open an image file chain and return an ImageInfoList
1838 *
1839 * @filename: topmost image filename
1840 * @fmt: topmost image format (may be NULL to autodetect)
1841 * @chain: true - enumerate entire backing file chain
1842 * false - only topmost image file
1843 *
1844 * Returns a list of ImageInfo objects or NULL if there was an error opening an
1845 * image file. If there was an error a message will have been printed to
1846 * stderr.
1847 */
1848static ImageInfoList *collect_image_info_list(const char *filename,
1849 const char *fmt,
1850 bool chain)
1851{
1852 ImageInfoList *head = NULL;
1853 ImageInfoList **last = &head;
1854 GHashTable *filenames;
43526ec8 1855 Error *err = NULL;
9699bf0d
SH
1856
1857 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
1858
1859 while (filename) {
1860 BlockDriverState *bs;
1861 ImageInfo *info;
1862 ImageInfoList *elem;
1863
1864 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
1865 error_report("Backing file '%s' creates an infinite loop.",
1866 filename);
1867 goto err;
1868 }
1869 g_hash_table_insert(filenames, (gpointer)filename, NULL);
1870
9ffe3332
KW
1871 bs = bdrv_new_open("image", filename, fmt,
1872 BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
9699bf0d
SH
1873 if (!bs) {
1874 goto err;
1875 }
1876
43526ec8 1877 bdrv_query_image_info(bs, &info, &err);
84d18f06 1878 if (err) {
43526ec8
WX
1879 error_report("%s", error_get_pretty(err));
1880 error_free(err);
bdf866fe 1881 bdrv_unref(bs);
43526ec8 1882 goto err;
fb0ed453 1883 }
9699bf0d
SH
1884
1885 elem = g_new0(ImageInfoList, 1);
1886 elem->value = info;
1887 *last = elem;
1888 last = &elem->next;
1889
4f6fd349 1890 bdrv_unref(bs);
9699bf0d
SH
1891
1892 filename = fmt = NULL;
1893 if (chain) {
1894 if (info->has_full_backing_filename) {
1895 filename = info->full_backing_filename;
1896 } else if (info->has_backing_filename) {
1897 filename = info->backing_filename;
1898 }
1899 if (info->has_backing_filename_format) {
1900 fmt = info->backing_filename_format;
1901 }
1902 }
1903 }
1904 g_hash_table_destroy(filenames);
1905 return head;
1906
1907err:
1908 qapi_free_ImageInfoList(head);
1909 g_hash_table_destroy(filenames);
1910 return NULL;
1911}
1912
c054b3fd
BC
1913static int img_info(int argc, char **argv)
1914{
1915 int c;
1916 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 1917 bool chain = false;
c054b3fd 1918 const char *filename, *fmt, *output;
9699bf0d 1919 ImageInfoList *list;
c054b3fd 1920
ea2384d3 1921 fmt = NULL;
c054b3fd 1922 output = NULL;
ea2384d3 1923 for(;;) {
c054b3fd
BC
1924 int option_index = 0;
1925 static const struct option long_options[] = {
1926 {"help", no_argument, 0, 'h'},
1927 {"format", required_argument, 0, 'f'},
1928 {"output", required_argument, 0, OPTION_OUTPUT},
9699bf0d 1929 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
c054b3fd
BC
1930 {0, 0, 0, 0}
1931 };
1932 c = getopt_long(argc, argv, "f:h",
1933 long_options, &option_index);
b8fb60da 1934 if (c == -1) {
ea2384d3 1935 break;
b8fb60da 1936 }
ea2384d3 1937 switch(c) {
ef87394c 1938 case '?':
ea2384d3
FB
1939 case 'h':
1940 help();
1941 break;
1942 case 'f':
1943 fmt = optarg;
1944 break;
c054b3fd
BC
1945 case OPTION_OUTPUT:
1946 output = optarg;
1947 break;
9699bf0d
SH
1948 case OPTION_BACKING_CHAIN:
1949 chain = true;
1950 break;
ea2384d3
FB
1951 }
1952 }
fc11eb26 1953 if (optind != argc - 1) {
ac1307ab 1954 error_exit("Expecting one image file name");
b8fb60da 1955 }
ea2384d3
FB
1956 filename = argv[optind++];
1957
c054b3fd
BC
1958 if (output && !strcmp(output, "json")) {
1959 output_format = OFORMAT_JSON;
1960 } else if (output && !strcmp(output, "human")) {
1961 output_format = OFORMAT_HUMAN;
1962 } else if (output) {
1963 error_report("--output must be used with human or json as argument.");
c2abccec
MK
1964 return 1;
1965 }
c054b3fd 1966
9699bf0d
SH
1967 list = collect_image_info_list(filename, fmt, chain);
1968 if (!list) {
c2abccec 1969 return 1;
faea38e7 1970 }
c054b3fd 1971
c054b3fd
BC
1972 switch (output_format) {
1973 case OFORMAT_HUMAN:
9699bf0d 1974 dump_human_image_info_list(list);
c054b3fd
BC
1975 break;
1976 case OFORMAT_JSON:
9699bf0d
SH
1977 if (chain) {
1978 dump_json_image_info_list(list);
1979 } else {
1980 dump_json_image_info(list->value);
1981 }
c054b3fd 1982 break;
faea38e7 1983 }
c054b3fd 1984
9699bf0d 1985 qapi_free_ImageInfoList(list);
ea2384d3
FB
1986 return 0;
1987}
1988
4c93a13b
PB
1989
1990typedef struct MapEntry {
1991 int flags;
1992 int depth;
1993 int64_t start;
1994 int64_t length;
1995 int64_t offset;
1996 BlockDriverState *bs;
1997} MapEntry;
1998
1999static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2000 MapEntry *next)
2001{
2002 switch (output_format) {
2003 case OFORMAT_HUMAN:
2004 if ((e->flags & BDRV_BLOCK_DATA) &&
2005 !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
2006 error_report("File contains external, encrypted or compressed clusters.");
2007 exit(1);
2008 }
2009 if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
2010 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
2011 e->start, e->length, e->offset, e->bs->filename);
2012 }
2013 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2014 * Modify the flags here to allow more coalescing.
2015 */
2016 if (next &&
2017 (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
2018 next->flags &= ~BDRV_BLOCK_DATA;
2019 next->flags |= BDRV_BLOCK_ZERO;
2020 }
2021 break;
2022 case OFORMAT_JSON:
2023 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
2024 " \"zero\": %s, \"data\": %s",
2025 (e->start == 0 ? "[" : ",\n"),
2026 e->start, e->length, e->depth,
2027 (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
2028 (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
2029 if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
c745bfb4 2030 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2031 }
2032 putchar('}');
2033
2034 if (!next) {
2035 printf("]\n");
2036 }
2037 break;
2038 }
2039}
2040
2041static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2042 int nb_sectors, MapEntry *e)
2043{
2044 int64_t ret;
2045 int depth;
2046
2047 /* As an optimization, we could cache the current range of unallocated
2048 * clusters in each file of the chain, and avoid querying the same
2049 * range repeatedly.
2050 */
2051
2052 depth = 0;
2053 for (;;) {
2054 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
2055 if (ret < 0) {
2056 return ret;
2057 }
2058 assert(nb_sectors);
2059 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2060 break;
2061 }
2062 bs = bs->backing_hd;
2063 if (bs == NULL) {
2064 ret = 0;
2065 break;
2066 }
2067
2068 depth++;
2069 }
2070
2071 e->start = sector_num * BDRV_SECTOR_SIZE;
2072 e->length = nb_sectors * BDRV_SECTOR_SIZE;
2073 e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
2074 e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
2075 e->depth = depth;
2076 e->bs = bs;
2077 return 0;
2078}
2079
2080static int img_map(int argc, char **argv)
2081{
2082 int c;
2083 OutputFormat output_format = OFORMAT_HUMAN;
2084 BlockDriverState *bs;
2085 const char *filename, *fmt, *output;
2086 int64_t length;
2087 MapEntry curr = { .length = 0 }, next;
2088 int ret = 0;
2089
2090 fmt = NULL;
2091 output = NULL;
2092 for (;;) {
2093 int option_index = 0;
2094 static const struct option long_options[] = {
2095 {"help", no_argument, 0, 'h'},
2096 {"format", required_argument, 0, 'f'},
2097 {"output", required_argument, 0, OPTION_OUTPUT},
2098 {0, 0, 0, 0}
2099 };
2100 c = getopt_long(argc, argv, "f:h",
2101 long_options, &option_index);
2102 if (c == -1) {
2103 break;
2104 }
2105 switch (c) {
2106 case '?':
2107 case 'h':
2108 help();
2109 break;
2110 case 'f':
2111 fmt = optarg;
2112 break;
2113 case OPTION_OUTPUT:
2114 output = optarg;
2115 break;
2116 }
2117 }
ac1307ab
FZ
2118 if (optind != argc - 1) {
2119 error_exit("Expecting one image file name");
4c93a13b 2120 }
ac1307ab 2121 filename = argv[optind];
4c93a13b
PB
2122
2123 if (output && !strcmp(output, "json")) {
2124 output_format = OFORMAT_JSON;
2125 } else if (output && !strcmp(output, "human")) {
2126 output_format = OFORMAT_HUMAN;
2127 } else if (output) {
2128 error_report("--output must be used with human or json as argument.");
2129 return 1;
2130 }
2131
9ffe3332 2132 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
4c93a13b
PB
2133 if (!bs) {
2134 return 1;
2135 }
2136
2137 if (output_format == OFORMAT_HUMAN) {
2138 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2139 }
2140
2141 length = bdrv_getlength(bs);
2142 while (curr.start + curr.length < length) {
2143 int64_t nsectors_left;
2144 int64_t sector_num;
2145 int n;
2146
2147 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2148
2149 /* Probe up to 1 GiB at a time. */
2150 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2151 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2152 ret = get_block_status(bs, sector_num, n, &next);
2153
2154 if (ret < 0) {
2155 error_report("Could not read file metadata: %s", strerror(-ret));
2156 goto out;
2157 }
2158
2159 if (curr.length != 0 && curr.flags == next.flags &&
2160 curr.depth == next.depth &&
2161 ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
2162 curr.offset + curr.length == next.offset)) {
2163 curr.length += next.length;
2164 continue;
2165 }
2166
2167 if (curr.length > 0) {
2168 dump_map_entry(output_format, &curr, &next);
2169 }
2170 curr = next;
2171 }
2172
2173 dump_map_entry(output_format, &curr, NULL);
2174
2175out:
2176 bdrv_unref(bs);
2177 return ret < 0;
2178}
2179
f7b4a940
AL
2180#define SNAPSHOT_LIST 1
2181#define SNAPSHOT_CREATE 2
2182#define SNAPSHOT_APPLY 3
2183#define SNAPSHOT_DELETE 4
2184
153859be 2185static int img_snapshot(int argc, char **argv)
f7b4a940
AL
2186{
2187 BlockDriverState *bs;
2188 QEMUSnapshotInfo sn;
2189 char *filename, *snapshot_name = NULL;
c2abccec 2190 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
2191 int action = 0;
2192 qemu_timeval tv;
f382d43a 2193 bool quiet = false;
a89d89d3 2194 Error *err = NULL;
f7b4a940 2195
710da702 2196 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
f7b4a940
AL
2197 /* Parse commandline parameters */
2198 for(;;) {
f382d43a 2199 c = getopt(argc, argv, "la:c:d:hq");
b8fb60da 2200 if (c == -1) {
f7b4a940 2201 break;
b8fb60da 2202 }
f7b4a940 2203 switch(c) {
ef87394c 2204 case '?':
f7b4a940
AL
2205 case 'h':
2206 help();
153859be 2207 return 0;
f7b4a940
AL
2208 case 'l':
2209 if (action) {
ac1307ab 2210 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2211 return 0;
f7b4a940
AL
2212 }
2213 action = SNAPSHOT_LIST;
f5edb014 2214 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
2215 break;
2216 case 'a':
2217 if (action) {
ac1307ab 2218 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2219 return 0;
f7b4a940
AL
2220 }
2221 action = SNAPSHOT_APPLY;
2222 snapshot_name = optarg;
2223 break;
2224 case 'c':
2225 if (action) {
ac1307ab 2226 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2227 return 0;
f7b4a940
AL
2228 }
2229 action = SNAPSHOT_CREATE;
2230 snapshot_name = optarg;
2231 break;
2232 case 'd':
2233 if (action) {
ac1307ab 2234 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2235 return 0;
f7b4a940
AL
2236 }
2237 action = SNAPSHOT_DELETE;
2238 snapshot_name = optarg;
2239 break;
f382d43a
MR
2240 case 'q':
2241 quiet = true;
2242 break;
f7b4a940
AL
2243 }
2244 }
2245
fc11eb26 2246 if (optind != argc - 1) {
ac1307ab 2247 error_exit("Expecting one image file name");
b8fb60da 2248 }
f7b4a940
AL
2249 filename = argv[optind++];
2250
2251 /* Open the image */
9ffe3332 2252 bs = bdrv_new_open("image", filename, NULL, bdrv_oflags, true, quiet);
c2abccec
MK
2253 if (!bs) {
2254 return 1;
2255 }
f7b4a940
AL
2256
2257 /* Perform the requested action */
2258 switch(action) {
2259 case SNAPSHOT_LIST:
2260 dump_snapshots(bs);
2261 break;
2262
2263 case SNAPSHOT_CREATE:
2264 memset(&sn, 0, sizeof(sn));
2265 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2266
2267 qemu_gettimeofday(&tv);
2268 sn.date_sec = tv.tv_sec;
2269 sn.date_nsec = tv.tv_usec * 1000;
2270
2271 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 2272 if (ret) {
15654a6d 2273 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 2274 snapshot_name, ret, strerror(-ret));
b8fb60da 2275 }
f7b4a940
AL
2276 break;
2277
2278 case SNAPSHOT_APPLY:
2279 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 2280 if (ret) {
15654a6d 2281 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 2282 snapshot_name, ret, strerror(-ret));
b8fb60da 2283 }
f7b4a940
AL
2284 break;
2285
2286 case SNAPSHOT_DELETE:
a89d89d3 2287 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
84d18f06 2288 if (err) {
a89d89d3
WX
2289 error_report("Could not delete snapshot '%s': (%s)",
2290 snapshot_name, error_get_pretty(err));
2291 error_free(err);
2292 ret = 1;
b8fb60da 2293 }
f7b4a940
AL
2294 break;
2295 }
2296
2297 /* Cleanup */
4f6fd349 2298 bdrv_unref(bs);
c2abccec
MK
2299 if (ret) {
2300 return 1;
2301 }
153859be 2302 return 0;
f7b4a940
AL
2303}
2304
3e85c6fd
KW
2305static int img_rebase(int argc, char **argv)
2306{
c2abccec 2307 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
f163d073 2308 BlockDriver *old_backing_drv, *new_backing_drv;
3e85c6fd 2309 char *filename;
40055951
HR
2310 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2311 int c, flags, src_flags, ret;
3e85c6fd 2312 int unsafe = 0;
6b837bc4 2313 int progress = 0;
f382d43a 2314 bool quiet = false;
34b5d2c6 2315 Error *local_err = NULL;
3e85c6fd
KW
2316
2317 /* Parse commandline parameters */
e53dbee0 2318 fmt = NULL;
661a0f71 2319 cache = BDRV_DEFAULT_CACHE;
40055951 2320 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
2321 out_baseimg = NULL;
2322 out_basefmt = NULL;
3e85c6fd 2323 for(;;) {
40055951 2324 c = getopt(argc, argv, "hf:F:b:upt:T:q");
b8fb60da 2325 if (c == -1) {
3e85c6fd 2326 break;
b8fb60da 2327 }
3e85c6fd 2328 switch(c) {
ef87394c 2329 case '?':
3e85c6fd
KW
2330 case 'h':
2331 help();
2332 return 0;
e53dbee0
KW
2333 case 'f':
2334 fmt = optarg;
2335 break;
3e85c6fd
KW
2336 case 'F':
2337 out_basefmt = optarg;
2338 break;
2339 case 'b':
2340 out_baseimg = optarg;
2341 break;
2342 case 'u':
2343 unsafe = 1;
2344 break;
6b837bc4
JS
2345 case 'p':
2346 progress = 1;
2347 break;
661a0f71
FS
2348 case 't':
2349 cache = optarg;
2350 break;
40055951
HR
2351 case 'T':
2352 src_cache = optarg;
2353 break;
f382d43a
MR
2354 case 'q':
2355 quiet = true;
2356 break;
3e85c6fd
KW
2357 }
2358 }
2359
f382d43a
MR
2360 if (quiet) {
2361 progress = 0;
2362 }
2363
ac1307ab
FZ
2364 if (optind != argc - 1) {
2365 error_exit("Expecting one image file name");
2366 }
2367 if (!unsafe && !out_baseimg) {
2368 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
b8fb60da 2369 }
3e85c6fd
KW
2370 filename = argv[optind++];
2371
6b837bc4
JS
2372 qemu_progress_init(progress, 2.0);
2373 qemu_progress_print(0, 100);
2374
661a0f71 2375 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
c3993cdc 2376 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
2377 if (ret < 0) {
2378 error_report("Invalid cache option: %s", cache);
2379 return -1;
2380 }
2381
40055951
HR
2382 src_flags = BDRV_O_FLAGS;
2383 ret = bdrv_parse_cache_flags(src_cache, &src_flags);
2384 if (ret < 0) {
2385 error_report("Invalid source cache option: %s", src_cache);
2386 return -1;
2387 }
2388
3e85c6fd
KW
2389 /*
2390 * Open the images.
2391 *
2392 * Ignore the old backing file for unsafe rebase in case we want to correct
2393 * the reference to a renamed or moved backing file.
2394 */
9ffe3332 2395 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
c2abccec
MK
2396 if (!bs) {
2397 return 1;
2398 }
3e85c6fd
KW
2399
2400 /* Find the right drivers for the backing files */
2401 old_backing_drv = NULL;
2402 new_backing_drv = NULL;
2403
2404 if (!unsafe && bs->backing_format[0] != '\0') {
2405 old_backing_drv = bdrv_find_format(bs->backing_format);
2406 if (old_backing_drv == NULL) {
15654a6d 2407 error_report("Invalid format name: '%s'", bs->backing_format);
c2abccec
MK
2408 ret = -1;
2409 goto out;
3e85c6fd
KW
2410 }
2411 }
2412
2413 if (out_basefmt != NULL) {
2414 new_backing_drv = bdrv_find_format(out_basefmt);
2415 if (new_backing_drv == NULL) {
15654a6d 2416 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
2417 ret = -1;
2418 goto out;
3e85c6fd
KW
2419 }
2420 }
2421
2422 /* For safe rebasing we need to compare old and new backing file */
2423 if (unsafe) {
2424 /* Make the compiler happy */
2425 bs_old_backing = NULL;
2426 bs_new_backing = NULL;
2427 } else {
2428 char backing_name[1024];
2429
98522f63 2430 bs_old_backing = bdrv_new("old_backing", &error_abort);
3e85c6fd 2431 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
40055951 2432 ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
34b5d2c6 2433 old_backing_drv, &local_err);
c2abccec 2434 if (ret) {
34b5d2c6
HR
2435 error_report("Could not open old backing file '%s': %s",
2436 backing_name, error_get_pretty(local_err));
2437 error_free(local_err);
c2abccec 2438 goto out;
3e85c6fd 2439 }
a616673d 2440 if (out_baseimg[0]) {
98522f63 2441 bs_new_backing = bdrv_new("new_backing", &error_abort);
40055951
HR
2442 ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
2443 new_backing_drv, &local_err);
a616673d 2444 if (ret) {
34b5d2c6
HR
2445 error_report("Could not open new backing file '%s': %s",
2446 out_baseimg, error_get_pretty(local_err));
2447 error_free(local_err);
a616673d
AB
2448 goto out;
2449 }
3e85c6fd
KW
2450 }
2451 }
2452
2453 /*
2454 * Check each unallocated cluster in the COW file. If it is unallocated,
2455 * accesses go to the backing file. We must therefore compare this cluster
2456 * in the old and new backing file, and if they differ we need to copy it
2457 * from the old backing file into the COW file.
2458 *
2459 * If qemu-img crashes during this step, no harm is done. The content of
2460 * the image is the same as the original one at any time.
2461 */
2462 if (!unsafe) {
52bf1e72
MA
2463 int64_t num_sectors;
2464 int64_t old_backing_num_sectors;
2465 int64_t new_backing_num_sectors = 0;
3e85c6fd 2466 uint64_t sector;
cc60e327 2467 int n;
d6771bfa
T
2468 uint8_t * buf_old;
2469 uint8_t * buf_new;
1f710495 2470 float local_progress = 0;
d6771bfa 2471
bb1c0597
KW
2472 buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
2473 buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
3e85c6fd 2474
52bf1e72
MA
2475 num_sectors = bdrv_nb_sectors(bs);
2476 if (num_sectors < 0) {
2477 error_report("Could not get size of '%s': %s",
2478 filename, strerror(-num_sectors));
2479 ret = -1;
2480 goto out;
2481 }
2482 old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
2483 if (old_backing_num_sectors < 0) {
2484 char backing_name[1024];
2485
2486 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2487 error_report("Could not get size of '%s': %s",
2488 backing_name, strerror(-old_backing_num_sectors));
2489 ret = -1;
2490 goto out;
2491 }
a616673d 2492 if (bs_new_backing) {
52bf1e72
MA
2493 new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
2494 if (new_backing_num_sectors < 0) {
2495 error_report("Could not get size of '%s': %s",
2496 out_baseimg, strerror(-new_backing_num_sectors));
2497 ret = -1;
2498 goto out;
2499 }
a616673d 2500 }
3e85c6fd 2501
1f710495
KW
2502 if (num_sectors != 0) {
2503 local_progress = (float)100 /
2504 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
2505 }
2506
3e85c6fd
KW
2507 for (sector = 0; sector < num_sectors; sector += n) {
2508
2509 /* How many sectors can we handle with the next read? */
2510 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
2511 n = (IO_BUF_SIZE / 512);
2512 } else {
2513 n = num_sectors - sector;
2514 }
2515
2516 /* If the cluster is allocated, we don't need to take action */
cc60e327 2517 ret = bdrv_is_allocated(bs, sector, n, &n);
d663640c
PB
2518 if (ret < 0) {
2519 error_report("error while reading image metadata: %s",
2520 strerror(-ret));
2521 goto out;
2522 }
cc60e327 2523 if (ret) {
3e85c6fd
KW
2524 continue;
2525 }
2526
87a1b3e3
KW
2527 /*
2528 * Read old and new backing file and take into consideration that
2529 * backing files may be smaller than the COW image.
2530 */
2531 if (sector >= old_backing_num_sectors) {
2532 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
2533 } else {
2534 if (sector + n > old_backing_num_sectors) {
2535 n = old_backing_num_sectors - sector;
2536 }
2537
2538 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
2539 if (ret < 0) {
2540 error_report("error while reading from old backing file");
2541 goto out;
2542 }
3e85c6fd 2543 }
87a1b3e3 2544
a616673d 2545 if (sector >= new_backing_num_sectors || !bs_new_backing) {
87a1b3e3
KW
2546 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
2547 } else {
2548 if (sector + n > new_backing_num_sectors) {
2549 n = new_backing_num_sectors - sector;
2550 }
2551
2552 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
2553 if (ret < 0) {
2554 error_report("error while reading from new backing file");
2555 goto out;
2556 }
3e85c6fd
KW
2557 }
2558
2559 /* If they differ, we need to write to the COW file */
2560 uint64_t written = 0;
2561
2562 while (written < n) {
2563 int pnum;
2564
2565 if (compare_sectors(buf_old + written * 512,
60b1bd4f 2566 buf_new + written * 512, n - written, &pnum))
3e85c6fd
KW
2567 {
2568 ret = bdrv_write(bs, sector + written,
2569 buf_old + written * 512, pnum);
2570 if (ret < 0) {
15654a6d 2571 error_report("Error while writing to COW image: %s",
3e85c6fd 2572 strerror(-ret));
c2abccec 2573 goto out;
3e85c6fd
KW
2574 }
2575 }
2576
2577 written += pnum;
2578 }
6b837bc4 2579 qemu_progress_print(local_progress, 100);
3e85c6fd 2580 }
d6771bfa 2581
bb1c0597
KW
2582 qemu_vfree(buf_old);
2583 qemu_vfree(buf_new);
3e85c6fd
KW
2584 }
2585
2586 /*
2587 * Change the backing file. All clusters that are different from the old
2588 * backing file are overwritten in the COW file now, so the visible content
2589 * doesn't change when we switch the backing file.
2590 */
a616673d
AB
2591 if (out_baseimg && *out_baseimg) {
2592 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
2593 } else {
2594 ret = bdrv_change_backing_file(bs, NULL, NULL);
2595 }
2596
3e85c6fd 2597 if (ret == -ENOSPC) {
15654a6d
JS
2598 error_report("Could not change the backing file to '%s': No "
2599 "space left in the file header", out_baseimg);
3e85c6fd 2600 } else if (ret < 0) {
15654a6d 2601 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
2602 out_baseimg, strerror(-ret));
2603 }
2604
6b837bc4 2605 qemu_progress_print(100, 0);
3e85c6fd
KW
2606 /*
2607 * TODO At this point it is possible to check if any clusters that are
2608 * allocated in the COW file are the same in the backing file. If so, they
2609 * could be dropped from the COW file. Don't do this before switching the
2610 * backing file, in case of a crash this would lead to corruption.
2611 */
c2abccec 2612out:
6b837bc4 2613 qemu_progress_end();
3e85c6fd
KW
2614 /* Cleanup */
2615 if (!unsafe) {
eb863add 2616 if (bs_old_backing != NULL) {
4f6fd349 2617 bdrv_unref(bs_old_backing);
eb863add
KW
2618 }
2619 if (bs_new_backing != NULL) {
4f6fd349 2620 bdrv_unref(bs_new_backing);
eb863add 2621 }
3e85c6fd
KW
2622 }
2623
4f6fd349 2624 bdrv_unref(bs);
c2abccec
MK
2625 if (ret) {
2626 return 1;
2627 }
3e85c6fd
KW
2628 return 0;
2629}
2630
ae6b0ed6
SH
2631static int img_resize(int argc, char **argv)
2632{
2633 int c, ret, relative;
2634 const char *filename, *fmt, *size;
2635 int64_t n, total_size;
f382d43a 2636 bool quiet = false;
2a81998a 2637 BlockDriverState *bs = NULL;
20caf0f7
DXW
2638 QemuOpts *param;
2639 static QemuOptsList resize_options = {
2640 .name = "resize_options",
2641 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
2642 .desc = {
2643 {
2644 .name = BLOCK_OPT_SIZE,
2645 .type = QEMU_OPT_SIZE,
2646 .help = "Virtual disk size"
2647 }, {
2648 /* end of list */
2649 }
ae6b0ed6 2650 },
ae6b0ed6
SH
2651 };
2652
e80fec7f
KW
2653 /* Remove size from argv manually so that negative numbers are not treated
2654 * as options by getopt. */
2655 if (argc < 3) {
ac1307ab 2656 error_exit("Not enough arguments");
e80fec7f
KW
2657 return 1;
2658 }
2659
2660 size = argv[--argc];
2661
2662 /* Parse getopt arguments */
ae6b0ed6
SH
2663 fmt = NULL;
2664 for(;;) {
f382d43a 2665 c = getopt(argc, argv, "f:hq");
ae6b0ed6
SH
2666 if (c == -1) {
2667 break;
2668 }
2669 switch(c) {
ef87394c 2670 case '?':
ae6b0ed6
SH
2671 case 'h':
2672 help();
2673 break;
2674 case 'f':
2675 fmt = optarg;
2676 break;
f382d43a
MR
2677 case 'q':
2678 quiet = true;
2679 break;
ae6b0ed6
SH
2680 }
2681 }
fc11eb26 2682 if (optind != argc - 1) {
ac1307ab 2683 error_exit("Expecting one image file name");
ae6b0ed6
SH
2684 }
2685 filename = argv[optind++];
ae6b0ed6
SH
2686
2687 /* Choose grow, shrink, or absolute resize mode */
2688 switch (size[0]) {
2689 case '+':
2690 relative = 1;
2691 size++;
2692 break;
2693 case '-':
2694 relative = -1;
2695 size++;
2696 break;
2697 default:
2698 relative = 0;
2699 break;
2700 }
2701
2702 /* Parse size */
87ea75d5 2703 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
20caf0f7 2704 if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
ae6b0ed6 2705 /* Error message already printed when size parsing fails */
2a81998a 2706 ret = -1;
20caf0f7 2707 qemu_opts_del(param);
2a81998a 2708 goto out;
ae6b0ed6 2709 }
20caf0f7
DXW
2710 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
2711 qemu_opts_del(param);
ae6b0ed6 2712
9ffe3332
KW
2713 bs = bdrv_new_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
2714 true, quiet);
c2abccec 2715 if (!bs) {
2a81998a
JS
2716 ret = -1;
2717 goto out;
c2abccec 2718 }
ae6b0ed6
SH
2719
2720 if (relative) {
2721 total_size = bdrv_getlength(bs) + n * relative;
2722 } else {
2723 total_size = n;
2724 }
2725 if (total_size <= 0) {
15654a6d 2726 error_report("New image size must be positive");
c2abccec
MK
2727 ret = -1;
2728 goto out;
ae6b0ed6
SH
2729 }
2730
2731 ret = bdrv_truncate(bs, total_size);
2732 switch (ret) {
2733 case 0:
f382d43a 2734 qprintf(quiet, "Image resized.\n");
ae6b0ed6
SH
2735 break;
2736 case -ENOTSUP:
259b2173 2737 error_report("This image does not support resize");
ae6b0ed6
SH
2738 break;
2739 case -EACCES:
15654a6d 2740 error_report("Image is read-only");
ae6b0ed6
SH
2741 break;
2742 default:
15654a6d 2743 error_report("Error resizing image (%d)", -ret);
ae6b0ed6
SH
2744 break;
2745 }
c2abccec 2746out:
2a81998a 2747 if (bs) {
4f6fd349 2748 bdrv_unref(bs);
2a81998a 2749 }
c2abccec
MK
2750 if (ret) {
2751 return 1;
2752 }
ae6b0ed6
SH
2753 return 0;
2754}
2755
6f176b48
HR
2756static int img_amend(int argc, char **argv)
2757{
2758 int c, ret = 0;
2759 char *options = NULL;
83d0521a
CL
2760 QemuOptsList *create_opts = NULL;
2761 QemuOpts *opts = NULL;
bd39e6ed
HR
2762 const char *fmt = NULL, *filename, *cache;
2763 int flags;
6f176b48
HR
2764 bool quiet = false;
2765 BlockDriverState *bs = NULL;
2766
bd39e6ed 2767 cache = BDRV_DEFAULT_CACHE;
6f176b48 2768 for (;;) {
bd39e6ed 2769 c = getopt(argc, argv, "ho:f:t:q");
6f176b48
HR
2770 if (c == -1) {
2771 break;
2772 }
2773
2774 switch (c) {
2775 case 'h':
2776 case '?':
2777 help();
2778 break;
2779 case 'o':
626f84f3
KW
2780 if (!is_valid_option_list(optarg)) {
2781 error_report("Invalid option list: %s", optarg);
2782 ret = -1;
2783 goto out;
2784 }
2785 if (!options) {
2786 options = g_strdup(optarg);
2787 } else {
2788 char *old_options = options;
2789 options = g_strdup_printf("%s,%s", options, optarg);
2790 g_free(old_options);
2791 }
6f176b48
HR
2792 break;
2793 case 'f':
2794 fmt = optarg;
2795 break;
bd39e6ed
HR
2796 case 't':
2797 cache = optarg;
2798 break;
6f176b48
HR
2799 case 'q':
2800 quiet = true;
2801 break;
2802 }
2803 }
2804
a283cb6e 2805 if (!options) {
ac1307ab 2806 error_exit("Must specify options (-o)");
6f176b48
HR
2807 }
2808
a283cb6e
KW
2809 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
2810 if (fmt && has_help_option(options)) {
2811 /* If a format is explicitly specified (and possibly no filename is
2812 * given), print option help here */
2813 ret = print_block_option_help(filename, fmt);
2814 goto out;
6f176b48
HR
2815 }
2816
a283cb6e 2817 if (optind != argc - 1) {
ac1307ab 2818 error_exit("Expecting one image file name");
a283cb6e 2819 }
6f176b48 2820
bd39e6ed
HR
2821 flags = BDRV_O_FLAGS | BDRV_O_RDWR;
2822 ret = bdrv_parse_cache_flags(cache, &flags);
2823 if (ret < 0) {
2824 error_report("Invalid cache option: %s", cache);
2825 goto out;
2826 }
2827
2828 bs = bdrv_new_open("image", filename, fmt, flags, true, quiet);
6f176b48
HR
2829 if (!bs) {
2830 error_report("Could not open image '%s'", filename);
2831 ret = -1;
2832 goto out;
2833 }
2834
2835 fmt = bs->drv->format_name;
2836
626f84f3 2837 if (has_help_option(options)) {
a283cb6e 2838 /* If the format was auto-detected, print option help here */
6f176b48
HR
2839 ret = print_block_option_help(filename, fmt);
2840 goto out;
2841 }
2842
c282e1fd 2843 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a
CL
2844 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
2845 if (options && qemu_opts_do_parse(opts, options, NULL)) {
6f176b48
HR
2846 error_report("Invalid options for file format '%s'", fmt);
2847 ret = -1;
2848 goto out;
2849 }
2850
c282e1fd 2851 ret = bdrv_amend_options(bs, opts);
6f176b48
HR
2852 if (ret < 0) {
2853 error_report("Error while amending options: %s", strerror(-ret));
2854 goto out;
2855 }
2856
2857out:
2858 if (bs) {
2859 bdrv_unref(bs);
2860 }
83d0521a
CL
2861 qemu_opts_del(opts);
2862 qemu_opts_free(create_opts);
626f84f3
KW
2863 g_free(options);
2864
6f176b48
HR
2865 if (ret) {
2866 return 1;
2867 }
2868 return 0;
2869}
2870
c227f099 2871static const img_cmd_t img_cmds[] = {
153859be
SB
2872#define DEF(option, callback, arg_string) \
2873 { option, callback },
2874#include "qemu-img-cmds.h"
2875#undef DEF
2876#undef GEN_DOCS
2877 { NULL, NULL, },
2878};
2879
ea2384d3
FB
2880int main(int argc, char **argv)
2881{
c227f099 2882 const img_cmd_t *cmd;
153859be 2883 const char *cmdname;
7db1689c 2884 int c;
7db1689c
JC
2885 static const struct option long_options[] = {
2886 {"help", no_argument, 0, 'h'},
5f6979cb 2887 {"version", no_argument, 0, 'v'},
7db1689c
JC
2888 {0, 0, 0, 0}
2889 };
ea2384d3 2890
526eda14
MK
2891#ifdef CONFIG_POSIX
2892 signal(SIGPIPE, SIG_IGN);
2893#endif
2894
53f76e58 2895 error_set_progname(argv[0]);
10f5bff6 2896 qemu_init_exec_dir(argv[0]);
53f76e58 2897
2592c59a 2898 qemu_init_main_loop();
ea2384d3 2899 bdrv_init();
ac1307ab
FZ
2900 if (argc < 2) {
2901 error_exit("Not enough arguments");
2902 }
153859be 2903 cmdname = argv[1];
153859be
SB
2904
2905 /* find the command */
5f6979cb 2906 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
153859be 2907 if (!strcmp(cmdname, cmd->name)) {
7db1689c 2908 return cmd->handler(argc - 1, argv + 1);
153859be 2909 }
ea2384d3 2910 }
153859be 2911
5f6979cb 2912 c = getopt_long(argc, argv, "h", long_options, NULL);
7db1689c
JC
2913
2914 if (c == 'h') {
2915 help();
2916 }
5f6979cb
JC
2917 if (c == 'v') {
2918 printf(QEMU_IMG_VERSION);
2919 return 0;
2920 }
7db1689c 2921
153859be 2922 /* not found */
ac1307ab 2923 error_exit("Command not found: %s", cmdname);
ea2384d3 2924}