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