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