]> git.proxmox.com Git - qemu.git/blame - qemu-img.c
block: parse cache mode flags in a single place
[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 */
faf07963 24#include "qemu-common.h"
9ea2ea71 25#include "qemu-option.h"
53f76e58 26#include "qemu-error.h"
f7b4a940 27#include "osdep.h"
dc786bc9 28#include "sysemu.h"
ec36ba14 29#include "block_int.h"
9230eaf6 30#include <stdio.h>
ea2384d3 31
e8445331
FB
32#ifdef _WIN32
33#include <windows.h>
34#endif
35
c227f099 36typedef struct img_cmd_t {
153859be
SB
37 const char *name;
38 int (*handler)(int argc, char **argv);
c227f099 39} img_cmd_t;
153859be 40
137519ce 41/* Default to cache=writeback as data integrity is not important for qemu-tcg. */
adfe078e 42#define BDRV_O_FLAGS BDRV_O_CACHE_WB
661a0f71 43#define BDRV_DEFAULT_CACHE "writeback"
137519ce 44
ea2384d3
FB
45static void format_print(void *opaque, const char *name)
46{
47 printf(" %s", name);
48}
49
d2c639d6 50/* Please keep in synch with qemu-img.texi */
3f379ab1 51static void help(void)
ea2384d3 52{
e00291c0
PB
53 const char *help_msg =
54 "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
3f020d70 55 "usage: qemu-img command [command options]\n"
56 "QEMU disk image utility\n"
57 "\n"
58 "Command syntax:\n"
153859be
SB
59#define DEF(option, callback, arg_string) \
60 " " arg_string "\n"
61#include "qemu-img-cmds.h"
62#undef DEF
63#undef GEN_DOCS
3f020d70 64 "\n"
65 "Command parameters:\n"
66 " 'filename' is a disk image filename\n"
67 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
661a0f71
FS
68 " 'cache' is the cache mode used to write the output disk image, the valid\n"
69 " options are: 'none', 'writeback' (default), 'writethrough' and 'unsafe'\n"
3f020d70 70 " 'size' is the disk image size in bytes. Optional suffixes\n"
71 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
72 " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
73 " 'output_filename' is the destination disk image filename\n"
74 " 'output_fmt' is the destination format\n"
75 " 'options' is a comma separated list of format specific options in a\n"
76 " name=value format. Use -o ? for an overview of the options supported by the\n"
77 " used format\n"
78 " '-c' indicates that target image must be compressed (qcow format only)\n"
79 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
80 " match exactly. The image doesn't need a working backing file before\n"
81 " rebasing in this case (useful for renaming the backing file)\n"
82 " '-h' with or without a command shows this help and lists the supported formats\n"
6b837bc4 83 " '-p' show progress of command (only certain commands)\n"
3f020d70 84 "\n"
85 "Parameters to snapshot subcommand:\n"
86 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
87 " '-a' applies a snapshot (revert disk to saved state)\n"
88 " '-c' creates a snapshot\n"
89 " '-d' deletes a snapshot\n"
e00291c0
PB
90 " '-l' lists all snapshots in the given image\n";
91
92 printf("%s\nSupported formats:", help_msg);
ea2384d3
FB
93 bdrv_iterate_format(format_print, NULL);
94 printf("\n");
95 exit(1);
96}
97
ea2384d3
FB
98#if defined(WIN32)
99/* XXX: put correct support for win32 */
100static int read_password(char *buf, int buf_size)
101{
102 int c, i;
103 printf("Password: ");
104 fflush(stdout);
105 i = 0;
106 for(;;) {
107 c = getchar();
108 if (c == '\n')
109 break;
110 if (i < (buf_size - 1))
111 buf[i++] = c;
112 }
113 buf[i] = '\0';
114 return 0;
115}
116
117#else
118
119#include <termios.h>
120
121static struct termios oldtty;
122
123static void term_exit(void)
124{
125 tcsetattr (0, TCSANOW, &oldtty);
126}
127
128static void term_init(void)
129{
130 struct termios tty;
131
132 tcgetattr (0, &tty);
133 oldtty = tty;
134
135 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
136 |INLCR|IGNCR|ICRNL|IXON);
137 tty.c_oflag |= OPOST;
138 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
139 tty.c_cflag &= ~(CSIZE|PARENB);
140 tty.c_cflag |= CS8;
141 tty.c_cc[VMIN] = 1;
142 tty.c_cc[VTIME] = 0;
3b46e624 143
ea2384d3
FB
144 tcsetattr (0, TCSANOW, &tty);
145
146 atexit(term_exit);
147}
148
3f379ab1 149static int read_password(char *buf, int buf_size)
ea2384d3
FB
150{
151 uint8_t ch;
152 int i, ret;
153
154 printf("password: ");
155 fflush(stdout);
156 term_init();
157 i = 0;
158 for(;;) {
159 ret = read(0, &ch, 1);
160 if (ret == -1) {
161 if (errno == EAGAIN || errno == EINTR) {
162 continue;
163 } else {
164 ret = -1;
165 break;
166 }
167 } else if (ret == 0) {
168 ret = -1;
169 break;
170 } else {
171 if (ch == '\r') {
172 ret = 0;
173 break;
174 }
175 if (i < (buf_size - 1))
176 buf[i++] = ch;
177 }
178 }
179 term_exit();
180 buf[i] = '\0';
181 printf("\n");
182 return ret;
183}
184#endif
185
4ac8aacd
JS
186static int print_block_option_help(const char *filename, const char *fmt)
187{
188 BlockDriver *drv, *proto_drv;
189 QEMUOptionParameter *create_options = NULL;
190
191 /* Find driver and parse its options */
192 drv = bdrv_find_format(fmt);
193 if (!drv) {
15654a6d 194 error_report("Unknown file format '%s'", fmt);
4ac8aacd
JS
195 return 1;
196 }
197
198 proto_drv = bdrv_find_protocol(filename);
199 if (!proto_drv) {
15654a6d 200 error_report("Unknown protocol '%s'", filename);
4ac8aacd
JS
201 return 1;
202 }
203
204 create_options = append_option_parameters(create_options,
205 drv->create_options);
206 create_options = append_option_parameters(create_options,
207 proto_drv->create_options);
208 print_option_help(create_options);
209 free_option_parameters(create_options);
210 return 0;
211}
212
75c23805 213static BlockDriverState *bdrv_new_open(const char *filename,
9bc378c1 214 const char *fmt,
f163d073 215 int flags)
75c23805
FB
216{
217 BlockDriverState *bs;
218 BlockDriver *drv;
219 char password[256];
b9eaf9ec 220 int ret;
75c23805 221
b9eaf9ec 222 bs = bdrv_new("image");
ad717139 223
75c23805
FB
224 if (fmt) {
225 drv = bdrv_find_format(fmt);
c2abccec 226 if (!drv) {
15654a6d 227 error_report("Unknown file format '%s'", fmt);
c2abccec
MK
228 goto fail;
229 }
75c23805
FB
230 } else {
231 drv = NULL;
232 }
b9eaf9ec
KW
233
234 ret = bdrv_open(bs, filename, flags, drv);
235 if (ret < 0) {
236 error_report("Could not open '%s': %s", filename, strerror(-ret));
c2abccec 237 goto fail;
75c23805 238 }
b9eaf9ec 239
75c23805
FB
240 if (bdrv_is_encrypted(bs)) {
241 printf("Disk image '%s' is encrypted.\n", filename);
c2abccec 242 if (read_password(password, sizeof(password)) < 0) {
15654a6d 243 error_report("No password given");
c2abccec
MK
244 goto fail;
245 }
246 if (bdrv_set_key(bs, password) < 0) {
15654a6d 247 error_report("invalid password");
c2abccec
MK
248 goto fail;
249 }
75c23805
FB
250 }
251 return bs;
c2abccec
MK
252fail:
253 if (bs) {
254 bdrv_delete(bs);
255 }
256 return NULL;
75c23805
FB
257}
258
c2abccec 259static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
eec77d9e
JS
260 const char *base_filename,
261 const char *base_fmt)
efa84d43 262{
efa84d43
KW
263 if (base_filename) {
264 if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
15654a6d
JS
265 error_report("Backing file not supported for file format '%s'",
266 fmt);
c2abccec 267 return -1;
efa84d43
KW
268 }
269 }
270 if (base_fmt) {
271 if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
15654a6d
JS
272 error_report("Backing file format not supported for file "
273 "format '%s'", fmt);
c2abccec 274 return -1;
efa84d43
KW
275 }
276 }
c2abccec 277 return 0;
efa84d43
KW
278}
279
ea2384d3
FB
280static int img_create(int argc, char **argv)
281{
eec77d9e 282 int c, ret = 0;
1da7cfbd 283 uint64_t img_size = -1;
ea2384d3 284 const char *fmt = "raw";
9230eaf6 285 const char *base_fmt = NULL;
ea2384d3
FB
286 const char *filename;
287 const char *base_filename = NULL;
9ea2ea71 288 char *options = NULL;
3b46e624 289
ea2384d3 290 for(;;) {
9ea2ea71 291 c = getopt(argc, argv, "F:b:f:he6o:");
b8fb60da 292 if (c == -1) {
ea2384d3 293 break;
b8fb60da 294 }
ea2384d3 295 switch(c) {
ef87394c 296 case '?':
ea2384d3
FB
297 case 'h':
298 help();
299 break;
9230eaf6
AL
300 case 'F':
301 base_fmt = optarg;
302 break;
ea2384d3
FB
303 case 'b':
304 base_filename = optarg;
305 break;
306 case 'f':
307 fmt = optarg;
308 break;
309 case 'e':
9d42e15d 310 error_report("option -e is deprecated, please use \'-o "
eec77d9e
JS
311 "encryption\' instead!");
312 return 1;
d8871c5a 313 case '6':
9d42e15d 314 error_report("option -6 is deprecated, please use \'-o "
eec77d9e
JS
315 "compat6\' instead!");
316 return 1;
9ea2ea71
KW
317 case 'o':
318 options = optarg;
319 break;
ea2384d3
FB
320 }
321 }
9230eaf6 322
b50cbabc 323 /* Get the filename */
b8fb60da 324 if (optind >= argc) {
b50cbabc 325 help();
b8fb60da 326 }
b50cbabc
MK
327 filename = argv[optind++];
328
1da7cfbd
JS
329 /* Get image size, if specified */
330 if (optind < argc) {
70b4f4bb 331 int64_t sval;
1da7cfbd
JS
332 sval = strtosz_suffix(argv[optind++], NULL, STRTOSZ_DEFSUFFIX_B);
333 if (sval < 0) {
15654a6d 334 error_report("Invalid image size specified! You may use k, M, G or "
1da7cfbd 335 "T suffixes for ");
15654a6d 336 error_report("kilobytes, megabytes, gigabytes and terabytes.");
1da7cfbd
JS
337 ret = -1;
338 goto out;
339 }
340 img_size = (uint64_t)sval;
341 }
342
4ac8aacd
JS
343 if (options && !strcmp(options, "?")) {
344 ret = print_block_option_help(filename, fmt);
345 goto out;
346 }
347
f88e1a42
JS
348 ret = bdrv_img_create(filename, fmt, base_filename, base_fmt,
349 options, img_size, BDRV_O_FLAGS);
c2abccec
MK
350out:
351 if (ret) {
352 return 1;
353 }
ea2384d3
FB
354 return 0;
355}
356
e076f338
KW
357/*
358 * Checks an image for consistency. Exit codes:
359 *
360 * 0 - Check completed, image is good
361 * 1 - Check not completed because of internal errors
362 * 2 - Check completed, image is corrupted
363 * 3 - Check completed, image has leaked clusters, but is good otherwise
364 */
1585969c
AL
365static int img_check(int argc, char **argv)
366{
367 int c, ret;
368 const char *filename, *fmt;
1585969c 369 BlockDriverState *bs;
e076f338 370 BdrvCheckResult result;
1585969c
AL
371
372 fmt = NULL;
373 for(;;) {
374 c = getopt(argc, argv, "f:h");
b8fb60da 375 if (c == -1) {
1585969c 376 break;
b8fb60da 377 }
1585969c 378 switch(c) {
ef87394c 379 case '?':
1585969c
AL
380 case 'h':
381 help();
382 break;
383 case 'f':
384 fmt = optarg;
385 break;
386 }
387 }
b8fb60da 388 if (optind >= argc) {
1585969c 389 help();
b8fb60da 390 }
1585969c
AL
391 filename = argv[optind++];
392
adfe078e 393 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS);
c2abccec
MK
394 if (!bs) {
395 return 1;
396 }
e076f338
KW
397 ret = bdrv_check(bs, &result);
398
399 if (ret == -ENOTSUP) {
15654a6d 400 error_report("This image format does not support checks");
e076f338
KW
401 bdrv_delete(bs);
402 return 1;
403 }
404
405 if (!(result.corruptions || result.leaks || result.check_errors)) {
406 printf("No errors were found on the image.\n");
407 } else {
408 if (result.corruptions) {
409 printf("\n%d errors were found on the image.\n"
410 "Data may be corrupted, or further writes to the image "
411 "may corrupt it.\n",
412 result.corruptions);
413 }
414
415 if (result.leaks) {
416 printf("\n%d leaked clusters were found on the image.\n"
417 "This means waste of disk space, but no harm to data.\n",
418 result.leaks);
419 }
420
421 if (result.check_errors) {
422 printf("\n%d internal errors have occurred during the check.\n",
423 result.check_errors);
1585969c 424 }
1585969c
AL
425 }
426
427 bdrv_delete(bs);
e076f338
KW
428
429 if (ret < 0 || result.check_errors) {
430 printf("\nAn error has occurred during the check: %s\n"
431 "The check is not complete and may have missed error.\n",
432 strerror(-ret));
c2abccec
MK
433 return 1;
434 }
e076f338
KW
435
436 if (result.corruptions) {
437 return 2;
438 } else if (result.leaks) {
439 return 3;
440 } else {
441 return 0;
442 }
1585969c
AL
443}
444
ea2384d3
FB
445static int img_commit(int argc, char **argv)
446{
661a0f71
FS
447 int c, ret, flags;
448 const char *filename, *fmt, *cache;
ea2384d3
FB
449 BlockDriverState *bs;
450
451 fmt = NULL;
661a0f71 452 cache = BDRV_DEFAULT_CACHE;
ea2384d3 453 for(;;) {
661a0f71 454 c = getopt(argc, argv, "f:ht:");
b8fb60da 455 if (c == -1) {
ea2384d3 456 break;
b8fb60da 457 }
ea2384d3 458 switch(c) {
ef87394c 459 case '?':
ea2384d3
FB
460 case 'h':
461 help();
462 break;
463 case 'f':
464 fmt = optarg;
465 break;
661a0f71
FS
466 case 't':
467 cache = optarg;
468 break;
ea2384d3
FB
469 }
470 }
b8fb60da 471 if (optind >= argc) {
ea2384d3 472 help();
b8fb60da 473 }
ea2384d3
FB
474 filename = argv[optind++];
475
661a0f71 476 flags = BDRV_O_RDWR;
c3993cdc 477 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
478 if (ret < 0) {
479 error_report("Invalid cache option: %s", cache);
480 return -1;
481 }
482
483 bs = bdrv_new_open(filename, fmt, flags);
c2abccec
MK
484 if (!bs) {
485 return 1;
486 }
ea2384d3
FB
487 ret = bdrv_commit(bs);
488 switch(ret) {
489 case 0:
490 printf("Image committed.\n");
491 break;
492 case -ENOENT:
15654a6d 493 error_report("No disk inserted");
ea2384d3
FB
494 break;
495 case -EACCES:
15654a6d 496 error_report("Image is read-only");
ea2384d3
FB
497 break;
498 case -ENOTSUP:
15654a6d 499 error_report("Image is already committed");
ea2384d3
FB
500 break;
501 default:
15654a6d 502 error_report("Error while committing image");
ea2384d3
FB
503 break;
504 }
505
506 bdrv_delete(bs);
c2abccec
MK
507 if (ret) {
508 return 1;
509 }
ea2384d3
FB
510 return 0;
511}
512
f6a00aa1
DK
513/*
514 * Checks whether the sector is not a zero sector.
515 *
516 * Attention! The len must be a multiple of 4 * sizeof(long) due to
517 * restriction of optimizations in this function.
518 */
ea2384d3
FB
519static int is_not_zero(const uint8_t *sector, int len)
520{
f6a00aa1
DK
521 /*
522 * Use long as the biggest available internal data type that fits into the
523 * CPU register and unroll the loop to smooth out the effect of memory
524 * latency.
525 */
526
ea2384d3 527 int i;
f6a00aa1
DK
528 long d0, d1, d2, d3;
529 const long * const data = (const long *) sector;
530
531 len /= sizeof(long);
532
533 for(i = 0; i < len; i += 4) {
534 d0 = data[i + 0];
535 d1 = data[i + 1];
536 d2 = data[i + 2];
537 d3 = data[i + 3];
538
539 if (d0 || d1 || d2 || d3) {
ea2384d3 540 return 1;
f6a00aa1 541 }
ea2384d3 542 }
f6a00aa1 543
ea2384d3
FB
544 return 0;
545}
546
f58c7b35
TS
547/*
548 * Returns true iff the first sector pointed to by 'buf' contains at least
549 * a non-NUL byte.
550 *
551 * 'pnum' is set to the number of sectors (including and immediately following
552 * the first one) that are known to be in the same allocated/unallocated state.
553 */
ea2384d3
FB
554static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
555{
556 int v, i;
557
558 if (n <= 0) {
559 *pnum = 0;
560 return 0;
561 }
562 v = is_not_zero(buf, 512);
563 for(i = 1; i < n; i++) {
564 buf += 512;
565 if (v != is_not_zero(buf, 512))
566 break;
567 }
568 *pnum = i;
569 return v;
570}
571
3e85c6fd
KW
572/*
573 * Compares two buffers sector by sector. Returns 0 if the first sector of both
574 * buffers matches, non-zero otherwise.
575 *
576 * pnum is set to the number of sectors (including and immediately following
577 * the first one) that are known to have the same comparison result
578 */
579static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
580 int *pnum)
581{
582 int res, i;
583
584 if (n <= 0) {
585 *pnum = 0;
586 return 0;
587 }
588
589 res = !!memcmp(buf1, buf2, 512);
590 for(i = 1; i < n; i++) {
591 buf1 += 512;
592 buf2 += 512;
593
594 if (!!memcmp(buf1, buf2, 512) != res) {
595 break;
596 }
597 }
598
599 *pnum = i;
600 return res;
601}
602
80ee15a6 603#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3
FB
604
605static int img_convert(int argc, char **argv)
606{
eec77d9e 607 int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
661a0f71
FS
608 int progress = 0, flags;
609 const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
b50cbabc 610 BlockDriver *drv, *proto_drv;
c2abccec 611 BlockDriverState **bs = NULL, *out_bs = NULL;
96b8f136
TS
612 int64_t total_sectors, nb_sectors, sector_num, bs_offset;
613 uint64_t bs_sectors;
c2abccec 614 uint8_t * buf = NULL;
ea2384d3 615 const uint8_t *buf1;
faea38e7 616 BlockDriverInfo bdi;
b50cbabc 617 QEMUOptionParameter *param = NULL, *create_options = NULL;
a18953fb 618 QEMUOptionParameter *out_baseimg_param;
efa84d43 619 char *options = NULL;
51ef6727 620 const char *snapshot_name = NULL;
6b837bc4 621 float local_progress;
ea2384d3
FB
622
623 fmt = NULL;
624 out_fmt = "raw";
661a0f71 625 cache = "unsafe";
f58c7b35 626 out_baseimg = NULL;
eec77d9e 627 compress = 0;
ea2384d3 628 for(;;) {
661a0f71 629 c = getopt(argc, argv, "f:O:B:s:hce6o:pt:");
b8fb60da 630 if (c == -1) {
ea2384d3 631 break;
b8fb60da 632 }
ea2384d3 633 switch(c) {
ef87394c 634 case '?':
ea2384d3
FB
635 case 'h':
636 help();
637 break;
638 case 'f':
639 fmt = optarg;
640 break;
641 case 'O':
642 out_fmt = optarg;
643 break;
f58c7b35
TS
644 case 'B':
645 out_baseimg = optarg;
646 break;
ea2384d3 647 case 'c':
eec77d9e 648 compress = 1;
ea2384d3
FB
649 break;
650 case 'e':
9d42e15d 651 error_report("option -e is deprecated, please use \'-o "
eec77d9e
JS
652 "encryption\' instead!");
653 return 1;
ec36ba14 654 case '6':
9d42e15d 655 error_report("option -6 is deprecated, please use \'-o "
eec77d9e
JS
656 "compat6\' instead!");
657 return 1;
efa84d43
KW
658 case 'o':
659 options = optarg;
660 break;
51ef6727 661 case 's':
662 snapshot_name = optarg;
663 break;
6b837bc4
JS
664 case 'p':
665 progress = 1;
666 break;
661a0f71
FS
667 case 't':
668 cache = optarg;
669 break;
ea2384d3
FB
670 }
671 }
3b46e624 672
926c2d23 673 bs_n = argc - optind - 1;
b8fb60da
JS
674 if (bs_n < 1) {
675 help();
676 }
926c2d23
AZ
677
678 out_filename = argv[argc - 1];
f58c7b35 679
4ac8aacd
JS
680 if (options && !strcmp(options, "?")) {
681 ret = print_block_option_help(out_filename, out_fmt);
682 goto out;
683 }
684
c2abccec 685 if (bs_n > 1 && out_baseimg) {
15654a6d
JS
686 error_report("-B makes no sense when concatenating multiple input "
687 "images");
31ca34b8
JS
688 ret = -1;
689 goto out;
c2abccec 690 }
926c2d23 691
6b837bc4
JS
692 qemu_progress_init(progress, 2.0);
693 qemu_progress_print(0, 100);
694
7267c094 695 bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
926c2d23
AZ
696
697 total_sectors = 0;
698 for (bs_i = 0; bs_i < bs_n; bs_i++) {
adfe078e 699 bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS);
c2abccec 700 if (!bs[bs_i]) {
15654a6d 701 error_report("Could not open '%s'", argv[optind + bs_i]);
c2abccec
MK
702 ret = -1;
703 goto out;
704 }
926c2d23
AZ
705 bdrv_get_geometry(bs[bs_i], &bs_sectors);
706 total_sectors += bs_sectors;
707 }
ea2384d3 708
51ef6727 709 if (snapshot_name != NULL) {
710 if (bs_n > 1) {
6daf194d 711 error_report("No support for concatenating multiple snapshot");
51ef6727 712 ret = -1;
713 goto out;
714 }
715 if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
6daf194d 716 error_report("Failed to load snapshot");
51ef6727 717 ret = -1;
718 goto out;
719 }
720 }
721
efa84d43 722 /* Find driver and parse its options */
ea2384d3 723 drv = bdrv_find_format(out_fmt);
c2abccec 724 if (!drv) {
15654a6d 725 error_report("Unknown file format '%s'", out_fmt);
c2abccec
MK
726 ret = -1;
727 goto out;
728 }
efa84d43 729
b50cbabc 730 proto_drv = bdrv_find_protocol(out_filename);
c2abccec 731 if (!proto_drv) {
15654a6d 732 error_report("Unknown protocol '%s'", out_filename);
c2abccec
MK
733 ret = -1;
734 goto out;
735 }
b50cbabc
MK
736
737 create_options = append_option_parameters(create_options,
738 drv->create_options);
739 create_options = append_option_parameters(create_options,
740 proto_drv->create_options);
db08adf5 741
efa84d43 742 if (options) {
b50cbabc 743 param = parse_option_parameters(options, create_options, param);
efa84d43 744 if (param == NULL) {
15654a6d 745 error_report("Invalid options for file format '%s'.", out_fmt);
c2abccec
MK
746 ret = -1;
747 goto out;
efa84d43
KW
748 }
749 } else {
b50cbabc 750 param = parse_option_parameters("", create_options, param);
efa84d43
KW
751 }
752
753 set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
eec77d9e 754 ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
c2abccec
MK
755 if (ret < 0) {
756 goto out;
757 }
efa84d43 758
a18953fb
KW
759 /* Get backing file name if -o backing_file was used */
760 out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
761 if (out_baseimg_param) {
762 out_baseimg = out_baseimg_param->value.s;
763 }
764
efa84d43 765 /* Check if compression is supported */
eec77d9e 766 if (compress) {
efa84d43
KW
767 QEMUOptionParameter *encryption =
768 get_option_parameter(param, BLOCK_OPT_ENCRYPT);
769
770 if (!drv->bdrv_write_compressed) {
15654a6d 771 error_report("Compression not supported for this file format");
c2abccec
MK
772 ret = -1;
773 goto out;
efa84d43
KW
774 }
775
776 if (encryption && encryption->value.n) {
15654a6d
JS
777 error_report("Compression and encryption not supported at "
778 "the same time");
c2abccec
MK
779 ret = -1;
780 goto out;
efa84d43
KW
781 }
782 }
783
784 /* Create the new image */
785 ret = bdrv_create(drv, out_filename, param);
ea2384d3
FB
786 if (ret < 0) {
787 if (ret == -ENOTSUP) {
15654a6d
JS
788 error_report("Formatting not supported for file format '%s'",
789 out_fmt);
6e9ea0c0 790 } else if (ret == -EFBIG) {
15654a6d
JS
791 error_report("The image size is too large for file format '%s'",
792 out_fmt);
ea2384d3 793 } else {
15654a6d
JS
794 error_report("%s: error while converting %s: %s",
795 out_filename, out_fmt, strerror(-ret));
ea2384d3 796 }
c2abccec 797 goto out;
ea2384d3 798 }
3b46e624 799
661a0f71 800 flags = BDRV_O_RDWR;
c3993cdc 801 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
802 if (ret < 0) {
803 error_report("Invalid cache option: %s", cache);
804 return -1;
805 }
806
807 out_bs = bdrv_new_open(out_filename, out_fmt, flags);
c2abccec
MK
808 if (!out_bs) {
809 ret = -1;
810 goto out;
811 }
ea2384d3 812
926c2d23
AZ
813 bs_i = 0;
814 bs_offset = 0;
815 bdrv_get_geometry(bs[0], &bs_sectors);
7267c094 816 buf = g_malloc(IO_BUF_SIZE);
926c2d23 817
eec77d9e 818 if (compress) {
c2abccec
MK
819 ret = bdrv_get_info(out_bs, &bdi);
820 if (ret < 0) {
15654a6d 821 error_report("could not get block driver info");
c2abccec
MK
822 goto out;
823 }
faea38e7 824 cluster_size = bdi.cluster_size;
c2abccec 825 if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
15654a6d 826 error_report("invalid cluster size");
c2abccec
MK
827 ret = -1;
828 goto out;
829 }
ea2384d3
FB
830 cluster_sectors = cluster_size >> 9;
831 sector_num = 0;
6b837bc4
JS
832
833 nb_sectors = total_sectors;
834 local_progress = (float)100 /
4ee96418 835 (nb_sectors / MIN(nb_sectors, cluster_sectors));
6b837bc4 836
ea2384d3 837 for(;;) {
926c2d23
AZ
838 int64_t bs_num;
839 int remainder;
840 uint8_t *buf2;
841
ea2384d3
FB
842 nb_sectors = total_sectors - sector_num;
843 if (nb_sectors <= 0)
844 break;
845 if (nb_sectors >= cluster_sectors)
846 n = cluster_sectors;
847 else
848 n = nb_sectors;
926c2d23
AZ
849
850 bs_num = sector_num - bs_offset;
851 assert (bs_num >= 0);
852 remainder = n;
853 buf2 = buf;
854 while (remainder > 0) {
855 int nlow;
856 while (bs_num == bs_sectors) {
857 bs_i++;
858 assert (bs_i < bs_n);
859 bs_offset += bs_sectors;
860 bdrv_get_geometry(bs[bs_i], &bs_sectors);
861 bs_num = 0;
0bfcd599
BS
862 /* printf("changing part: sector_num=%" PRId64 ", "
863 "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
864 "\n", sector_num, bs_i, bs_offset, bs_sectors); */
926c2d23
AZ
865 }
866 assert (bs_num < bs_sectors);
867
868 nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
869
c2abccec
MK
870 ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
871 if (ret < 0) {
15654a6d 872 error_report("error while reading");
c2abccec
MK
873 goto out;
874 }
926c2d23
AZ
875
876 buf2 += nlow * 512;
877 bs_num += nlow;
878
879 remainder -= nlow;
880 }
881 assert (remainder == 0);
882
b8fb60da 883 if (n < cluster_sectors) {
ea2384d3 884 memset(buf + n * 512, 0, cluster_size - n * 512);
b8fb60da 885 }
ea2384d3 886 if (is_not_zero(buf, cluster_size)) {
c2abccec
MK
887 ret = bdrv_write_compressed(out_bs, sector_num, buf,
888 cluster_sectors);
889 if (ret != 0) {
15654a6d 890 error_report("error while compressing sector %" PRId64,
ec3757de 891 sector_num);
c2abccec
MK
892 goto out;
893 }
ea2384d3
FB
894 }
895 sector_num += n;
6b837bc4 896 qemu_progress_print(local_progress, 100);
ea2384d3 897 }
faea38e7
FB
898 /* signal EOF to align */
899 bdrv_write_compressed(out_bs, 0, NULL, 0);
ea2384d3 900 } else {
f2feebbd
KW
901 int has_zero_init = bdrv_has_zero_init(out_bs);
902
f58c7b35 903 sector_num = 0; // total number of sectors converted so far
6b837bc4
JS
904 nb_sectors = total_sectors - sector_num;
905 local_progress = (float)100 /
4ee96418 906 (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
6b837bc4 907
ea2384d3
FB
908 for(;;) {
909 nb_sectors = total_sectors - sector_num;
b8fb60da 910 if (nb_sectors <= 0) {
ea2384d3 911 break;
b8fb60da
JS
912 }
913 if (nb_sectors >= (IO_BUF_SIZE / 512)) {
ea2384d3 914 n = (IO_BUF_SIZE / 512);
b8fb60da 915 } else {
ea2384d3 916 n = nb_sectors;
b8fb60da 917 }
926c2d23
AZ
918
919 while (sector_num - bs_offset >= bs_sectors) {
920 bs_i ++;
921 assert (bs_i < bs_n);
922 bs_offset += bs_sectors;
923 bdrv_get_geometry(bs[bs_i], &bs_sectors);
0bfcd599
BS
924 /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
925 "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
926c2d23
AZ
926 sector_num, bs_i, bs_offset, bs_sectors); */
927 }
928
b8fb60da 929 if (n > bs_offset + bs_sectors - sector_num) {
926c2d23 930 n = bs_offset + bs_sectors - sector_num;
b8fb60da 931 }
926c2d23 932
f2feebbd 933 if (has_zero_init) {
d032044f
AS
934 /* If the output image is being created as a copy on write image,
935 assume that sectors which are unallocated in the input image
936 are present in both the output's and input's base images (no
937 need to copy them). */
938 if (out_baseimg) {
939 if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
940 n, &n1)) {
941 sector_num += n1;
942 continue;
943 }
944 /* The next 'n1' sectors are allocated in the input image. Copy
945 only those as they may be followed by unallocated sectors. */
946 n = n1;
93c65b47 947 }
93c65b47
AL
948 } else {
949 n1 = n;
f58c7b35
TS
950 }
951
c2abccec
MK
952 ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
953 if (ret < 0) {
15654a6d 954 error_report("error while reading");
c2abccec
MK
955 goto out;
956 }
ea2384d3
FB
957 /* NOTE: at the same time we convert, we do not write zero
958 sectors to have a chance to compress the image. Ideally, we
959 should add a specific call to have the info to go faster */
960 buf1 = buf;
961 while (n > 0) {
f58c7b35
TS
962 /* If the output image is being created as a copy on write image,
963 copy all sectors even the ones containing only NUL bytes,
93c65b47
AL
964 because they may differ from the sectors in the base image.
965
966 If the output is to a host device, we also write out
967 sectors that are entirely 0, since whatever data was
968 already there is garbage, not 0s. */
f2feebbd 969 if (!has_zero_init || out_baseimg ||
93c65b47 970 is_allocated_sectors(buf1, n, &n1)) {
c2abccec
MK
971 ret = bdrv_write(out_bs, sector_num, buf1, n1);
972 if (ret < 0) {
15654a6d 973 error_report("error while writing");
c2abccec
MK
974 goto out;
975 }
ea2384d3
FB
976 }
977 sector_num += n1;
978 n -= n1;
979 buf1 += n1 * 512;
980 }
6b837bc4 981 qemu_progress_print(local_progress, 100);
ea2384d3
FB
982 }
983 }
c2abccec 984out:
6b837bc4 985 qemu_progress_end();
c2abccec
MK
986 free_option_parameters(create_options);
987 free_option_parameters(param);
7267c094 988 g_free(buf);
c2abccec
MK
989 if (out_bs) {
990 bdrv_delete(out_bs);
991 }
31ca34b8
JS
992 if (bs) {
993 for (bs_i = 0; bs_i < bs_n; bs_i++) {
994 if (bs[bs_i]) {
995 bdrv_delete(bs[bs_i]);
996 }
c2abccec 997 }
7267c094 998 g_free(bs);
c2abccec 999 }
c2abccec
MK
1000 if (ret) {
1001 return 1;
1002 }
ea2384d3
FB
1003 return 0;
1004}
1005
57d1a2b6 1006
faea38e7
FB
1007static void dump_snapshots(BlockDriverState *bs)
1008{
1009 QEMUSnapshotInfo *sn_tab, *sn;
1010 int nb_sns, i;
1011 char buf[256];
1012
1013 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1014 if (nb_sns <= 0)
1015 return;
1016 printf("Snapshot list:\n");
1017 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1018 for(i = 0; i < nb_sns; i++) {
1019 sn = &sn_tab[i];
1020 printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1021 }
7267c094 1022 g_free(sn_tab);
faea38e7
FB
1023}
1024
ea2384d3
FB
1025static int img_info(int argc, char **argv)
1026{
1027 int c;
1028 const char *filename, *fmt;
ea2384d3
FB
1029 BlockDriverState *bs;
1030 char fmt_name[128], size_buf[128], dsize_buf[128];
96b8f136
TS
1031 uint64_t total_sectors;
1032 int64_t allocated_size;
93b6b2a3
FB
1033 char backing_filename[1024];
1034 char backing_filename2[1024];
faea38e7 1035 BlockDriverInfo bdi;
ea2384d3
FB
1036
1037 fmt = NULL;
1038 for(;;) {
1039 c = getopt(argc, argv, "f:h");
b8fb60da 1040 if (c == -1) {
ea2384d3 1041 break;
b8fb60da 1042 }
ea2384d3 1043 switch(c) {
ef87394c 1044 case '?':
ea2384d3
FB
1045 case 'h':
1046 help();
1047 break;
1048 case 'f':
1049 fmt = optarg;
1050 break;
1051 }
1052 }
b8fb60da 1053 if (optind >= argc) {
ea2384d3 1054 help();
b8fb60da 1055 }
ea2384d3
FB
1056 filename = argv[optind++];
1057
adfe078e 1058 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING);
c2abccec
MK
1059 if (!bs) {
1060 return 1;
1061 }
ea2384d3
FB
1062 bdrv_get_format(bs, fmt_name, sizeof(fmt_name));
1063 bdrv_get_geometry(bs, &total_sectors);
1064 get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
4a1d5e1f 1065 allocated_size = bdrv_get_allocated_file_size(bs);
b8fb60da 1066 if (allocated_size < 0) {
a10ea30b 1067 snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
b8fb60da 1068 } else {
5fafdf24 1069 get_human_readable_size(dsize_buf, sizeof(dsize_buf),
de167e41 1070 allocated_size);
b8fb60da 1071 }
ea2384d3
FB
1072 printf("image: %s\n"
1073 "file format: %s\n"
ec3757de 1074 "virtual size: %s (%" PRId64 " bytes)\n"
ea2384d3 1075 "disk size: %s\n",
5fafdf24 1076 filename, fmt_name, size_buf,
ec3757de 1077 (total_sectors * 512),
ea2384d3 1078 dsize_buf);
b8fb60da 1079 if (bdrv_is_encrypted(bs)) {
ea2384d3 1080 printf("encrypted: yes\n");
b8fb60da 1081 }
faea38e7 1082 if (bdrv_get_info(bs, &bdi) >= 0) {
b8fb60da 1083 if (bdi.cluster_size != 0) {
faea38e7 1084 printf("cluster_size: %d\n", bdi.cluster_size);
b8fb60da 1085 }
faea38e7 1086 }
93b6b2a3 1087 bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
faea38e7 1088 if (backing_filename[0] != '\0') {
93b6b2a3
FB
1089 path_combine(backing_filename2, sizeof(backing_filename2),
1090 filename, backing_filename);
5fafdf24 1091 printf("backing file: %s (actual path: %s)\n",
93b6b2a3
FB
1092 backing_filename,
1093 backing_filename2);
faea38e7
FB
1094 }
1095 dump_snapshots(bs);
ea2384d3
FB
1096 bdrv_delete(bs);
1097 return 0;
1098}
1099
f7b4a940
AL
1100#define SNAPSHOT_LIST 1
1101#define SNAPSHOT_CREATE 2
1102#define SNAPSHOT_APPLY 3
1103#define SNAPSHOT_DELETE 4
1104
153859be 1105static int img_snapshot(int argc, char **argv)
f7b4a940
AL
1106{
1107 BlockDriverState *bs;
1108 QEMUSnapshotInfo sn;
1109 char *filename, *snapshot_name = NULL;
c2abccec 1110 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
1111 int action = 0;
1112 qemu_timeval tv;
1113
710da702 1114 bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
f7b4a940
AL
1115 /* Parse commandline parameters */
1116 for(;;) {
1117 c = getopt(argc, argv, "la:c:d:h");
b8fb60da 1118 if (c == -1) {
f7b4a940 1119 break;
b8fb60da 1120 }
f7b4a940 1121 switch(c) {
ef87394c 1122 case '?':
f7b4a940
AL
1123 case 'h':
1124 help();
153859be 1125 return 0;
f7b4a940
AL
1126 case 'l':
1127 if (action) {
1128 help();
153859be 1129 return 0;
f7b4a940
AL
1130 }
1131 action = SNAPSHOT_LIST;
f5edb014 1132 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
1133 break;
1134 case 'a':
1135 if (action) {
1136 help();
153859be 1137 return 0;
f7b4a940
AL
1138 }
1139 action = SNAPSHOT_APPLY;
1140 snapshot_name = optarg;
1141 break;
1142 case 'c':
1143 if (action) {
1144 help();
153859be 1145 return 0;
f7b4a940
AL
1146 }
1147 action = SNAPSHOT_CREATE;
1148 snapshot_name = optarg;
1149 break;
1150 case 'd':
1151 if (action) {
1152 help();
153859be 1153 return 0;
f7b4a940
AL
1154 }
1155 action = SNAPSHOT_DELETE;
1156 snapshot_name = optarg;
1157 break;
1158 }
1159 }
1160
b8fb60da 1161 if (optind >= argc) {
f7b4a940 1162 help();
b8fb60da 1163 }
f7b4a940
AL
1164 filename = argv[optind++];
1165
1166 /* Open the image */
f163d073 1167 bs = bdrv_new_open(filename, NULL, bdrv_oflags);
c2abccec
MK
1168 if (!bs) {
1169 return 1;
1170 }
f7b4a940
AL
1171
1172 /* Perform the requested action */
1173 switch(action) {
1174 case SNAPSHOT_LIST:
1175 dump_snapshots(bs);
1176 break;
1177
1178 case SNAPSHOT_CREATE:
1179 memset(&sn, 0, sizeof(sn));
1180 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
1181
1182 qemu_gettimeofday(&tv);
1183 sn.date_sec = tv.tv_sec;
1184 sn.date_nsec = tv.tv_usec * 1000;
1185
1186 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 1187 if (ret) {
15654a6d 1188 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 1189 snapshot_name, ret, strerror(-ret));
b8fb60da 1190 }
f7b4a940
AL
1191 break;
1192
1193 case SNAPSHOT_APPLY:
1194 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 1195 if (ret) {
15654a6d 1196 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 1197 snapshot_name, ret, strerror(-ret));
b8fb60da 1198 }
f7b4a940
AL
1199 break;
1200
1201 case SNAPSHOT_DELETE:
1202 ret = bdrv_snapshot_delete(bs, snapshot_name);
b8fb60da 1203 if (ret) {
15654a6d 1204 error_report("Could not delete snapshot '%s': %d (%s)",
f7b4a940 1205 snapshot_name, ret, strerror(-ret));
b8fb60da 1206 }
f7b4a940
AL
1207 break;
1208 }
1209
1210 /* Cleanup */
1211 bdrv_delete(bs);
c2abccec
MK
1212 if (ret) {
1213 return 1;
1214 }
153859be 1215 return 0;
f7b4a940
AL
1216}
1217
3e85c6fd
KW
1218static int img_rebase(int argc, char **argv)
1219{
c2abccec 1220 BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
f163d073 1221 BlockDriver *old_backing_drv, *new_backing_drv;
3e85c6fd 1222 char *filename;
661a0f71 1223 const char *fmt, *cache, *out_basefmt, *out_baseimg;
3e85c6fd
KW
1224 int c, flags, ret;
1225 int unsafe = 0;
6b837bc4 1226 int progress = 0;
3e85c6fd
KW
1227
1228 /* Parse commandline parameters */
e53dbee0 1229 fmt = NULL;
661a0f71 1230 cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
1231 out_baseimg = NULL;
1232 out_basefmt = NULL;
3e85c6fd 1233 for(;;) {
661a0f71 1234 c = getopt(argc, argv, "uhf:F:b:pt:");
b8fb60da 1235 if (c == -1) {
3e85c6fd 1236 break;
b8fb60da 1237 }
3e85c6fd 1238 switch(c) {
ef87394c 1239 case '?':
3e85c6fd
KW
1240 case 'h':
1241 help();
1242 return 0;
e53dbee0
KW
1243 case 'f':
1244 fmt = optarg;
1245 break;
3e85c6fd
KW
1246 case 'F':
1247 out_basefmt = optarg;
1248 break;
1249 case 'b':
1250 out_baseimg = optarg;
1251 break;
1252 case 'u':
1253 unsafe = 1;
1254 break;
6b837bc4
JS
1255 case 'p':
1256 progress = 1;
1257 break;
661a0f71
FS
1258 case 't':
1259 cache = optarg;
1260 break;
3e85c6fd
KW
1261 }
1262 }
1263
9a9d9dba 1264 if ((optind >= argc) || (!unsafe && !out_baseimg)) {
3e85c6fd 1265 help();
b8fb60da 1266 }
3e85c6fd
KW
1267 filename = argv[optind++];
1268
6b837bc4
JS
1269 qemu_progress_init(progress, 2.0);
1270 qemu_progress_print(0, 100);
1271
661a0f71 1272 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
c3993cdc 1273 ret = bdrv_parse_cache_flags(cache, &flags);
661a0f71
FS
1274 if (ret < 0) {
1275 error_report("Invalid cache option: %s", cache);
1276 return -1;
1277 }
1278
3e85c6fd
KW
1279 /*
1280 * Open the images.
1281 *
1282 * Ignore the old backing file for unsafe rebase in case we want to correct
1283 * the reference to a renamed or moved backing file.
1284 */
f163d073 1285 bs = bdrv_new_open(filename, fmt, flags);
c2abccec
MK
1286 if (!bs) {
1287 return 1;
1288 }
3e85c6fd
KW
1289
1290 /* Find the right drivers for the backing files */
1291 old_backing_drv = NULL;
1292 new_backing_drv = NULL;
1293
1294 if (!unsafe && bs->backing_format[0] != '\0') {
1295 old_backing_drv = bdrv_find_format(bs->backing_format);
1296 if (old_backing_drv == NULL) {
15654a6d 1297 error_report("Invalid format name: '%s'", bs->backing_format);
c2abccec
MK
1298 ret = -1;
1299 goto out;
3e85c6fd
KW
1300 }
1301 }
1302
1303 if (out_basefmt != NULL) {
1304 new_backing_drv = bdrv_find_format(out_basefmt);
1305 if (new_backing_drv == NULL) {
15654a6d 1306 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
1307 ret = -1;
1308 goto out;
3e85c6fd
KW
1309 }
1310 }
1311
1312 /* For safe rebasing we need to compare old and new backing file */
1313 if (unsafe) {
1314 /* Make the compiler happy */
1315 bs_old_backing = NULL;
1316 bs_new_backing = NULL;
1317 } else {
1318 char backing_name[1024];
1319
1320 bs_old_backing = bdrv_new("old_backing");
1321 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
c2abccec
MK
1322 ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
1323 old_backing_drv);
1324 if (ret) {
15654a6d 1325 error_report("Could not open old backing file '%s'", backing_name);
c2abccec 1326 goto out;
3e85c6fd
KW
1327 }
1328
1329 bs_new_backing = bdrv_new("new_backing");
cdbae851 1330 ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
c2abccec
MK
1331 new_backing_drv);
1332 if (ret) {
15654a6d 1333 error_report("Could not open new backing file '%s'", out_baseimg);
c2abccec 1334 goto out;
3e85c6fd
KW
1335 }
1336 }
1337
1338 /*
1339 * Check each unallocated cluster in the COW file. If it is unallocated,
1340 * accesses go to the backing file. We must therefore compare this cluster
1341 * in the old and new backing file, and if they differ we need to copy it
1342 * from the old backing file into the COW file.
1343 *
1344 * If qemu-img crashes during this step, no harm is done. The content of
1345 * the image is the same as the original one at any time.
1346 */
1347 if (!unsafe) {
1348 uint64_t num_sectors;
1349 uint64_t sector;
cc60e327 1350 int n;
d6771bfa
T
1351 uint8_t * buf_old;
1352 uint8_t * buf_new;
6b837bc4 1353 float local_progress;
d6771bfa 1354
7267c094
AL
1355 buf_old = g_malloc(IO_BUF_SIZE);
1356 buf_new = g_malloc(IO_BUF_SIZE);
3e85c6fd
KW
1357
1358 bdrv_get_geometry(bs, &num_sectors);
1359
6b837bc4 1360 local_progress = (float)100 /
4ee96418 1361 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3e85c6fd
KW
1362 for (sector = 0; sector < num_sectors; sector += n) {
1363
1364 /* How many sectors can we handle with the next read? */
1365 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
1366 n = (IO_BUF_SIZE / 512);
1367 } else {
1368 n = num_sectors - sector;
1369 }
1370
1371 /* If the cluster is allocated, we don't need to take action */
cc60e327
KW
1372 ret = bdrv_is_allocated(bs, sector, n, &n);
1373 if (ret) {
3e85c6fd
KW
1374 continue;
1375 }
1376
1377 /* Read old and new backing file */
c2abccec
MK
1378 ret = bdrv_read(bs_old_backing, sector, buf_old, n);
1379 if (ret < 0) {
15654a6d 1380 error_report("error while reading from old backing file");
c2abccec 1381 goto out;
3e85c6fd 1382 }
c2abccec
MK
1383 ret = bdrv_read(bs_new_backing, sector, buf_new, n);
1384 if (ret < 0) {
15654a6d 1385 error_report("error while reading from new backing file");
c2abccec 1386 goto out;
3e85c6fd
KW
1387 }
1388
1389 /* If they differ, we need to write to the COW file */
1390 uint64_t written = 0;
1391
1392 while (written < n) {
1393 int pnum;
1394
1395 if (compare_sectors(buf_old + written * 512,
60b1bd4f 1396 buf_new + written * 512, n - written, &pnum))
3e85c6fd
KW
1397 {
1398 ret = bdrv_write(bs, sector + written,
1399 buf_old + written * 512, pnum);
1400 if (ret < 0) {
15654a6d 1401 error_report("Error while writing to COW image: %s",
3e85c6fd 1402 strerror(-ret));
c2abccec 1403 goto out;
3e85c6fd
KW
1404 }
1405 }
1406
1407 written += pnum;
1408 }
6b837bc4 1409 qemu_progress_print(local_progress, 100);
3e85c6fd 1410 }
d6771bfa 1411
7267c094
AL
1412 g_free(buf_old);
1413 g_free(buf_new);
3e85c6fd
KW
1414 }
1415
1416 /*
1417 * Change the backing file. All clusters that are different from the old
1418 * backing file are overwritten in the COW file now, so the visible content
1419 * doesn't change when we switch the backing file.
1420 */
1421 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
1422 if (ret == -ENOSPC) {
15654a6d
JS
1423 error_report("Could not change the backing file to '%s': No "
1424 "space left in the file header", out_baseimg);
3e85c6fd 1425 } else if (ret < 0) {
15654a6d 1426 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
1427 out_baseimg, strerror(-ret));
1428 }
1429
6b837bc4 1430 qemu_progress_print(100, 0);
3e85c6fd
KW
1431 /*
1432 * TODO At this point it is possible to check if any clusters that are
1433 * allocated in the COW file are the same in the backing file. If so, they
1434 * could be dropped from the COW file. Don't do this before switching the
1435 * backing file, in case of a crash this would lead to corruption.
1436 */
c2abccec 1437out:
6b837bc4 1438 qemu_progress_end();
3e85c6fd
KW
1439 /* Cleanup */
1440 if (!unsafe) {
eb863add
KW
1441 if (bs_old_backing != NULL) {
1442 bdrv_delete(bs_old_backing);
1443 }
1444 if (bs_new_backing != NULL) {
1445 bdrv_delete(bs_new_backing);
1446 }
3e85c6fd
KW
1447 }
1448
1449 bdrv_delete(bs);
c2abccec
MK
1450 if (ret) {
1451 return 1;
1452 }
3e85c6fd
KW
1453 return 0;
1454}
1455
ae6b0ed6
SH
1456static int img_resize(int argc, char **argv)
1457{
1458 int c, ret, relative;
1459 const char *filename, *fmt, *size;
1460 int64_t n, total_size;
2a81998a 1461 BlockDriverState *bs = NULL;
ae6b0ed6
SH
1462 QEMUOptionParameter *param;
1463 QEMUOptionParameter resize_options[] = {
1464 {
1465 .name = BLOCK_OPT_SIZE,
1466 .type = OPT_SIZE,
1467 .help = "Virtual disk size"
1468 },
1469 { NULL }
1470 };
1471
e80fec7f
KW
1472 /* Remove size from argv manually so that negative numbers are not treated
1473 * as options by getopt. */
1474 if (argc < 3) {
1475 help();
1476 return 1;
1477 }
1478
1479 size = argv[--argc];
1480
1481 /* Parse getopt arguments */
ae6b0ed6
SH
1482 fmt = NULL;
1483 for(;;) {
1484 c = getopt(argc, argv, "f:h");
1485 if (c == -1) {
1486 break;
1487 }
1488 switch(c) {
ef87394c 1489 case '?':
ae6b0ed6
SH
1490 case 'h':
1491 help();
1492 break;
1493 case 'f':
1494 fmt = optarg;
1495 break;
1496 }
1497 }
e80fec7f 1498 if (optind >= argc) {
ae6b0ed6
SH
1499 help();
1500 }
1501 filename = argv[optind++];
ae6b0ed6
SH
1502
1503 /* Choose grow, shrink, or absolute resize mode */
1504 switch (size[0]) {
1505 case '+':
1506 relative = 1;
1507 size++;
1508 break;
1509 case '-':
1510 relative = -1;
1511 size++;
1512 break;
1513 default:
1514 relative = 0;
1515 break;
1516 }
1517
1518 /* Parse size */
1519 param = parse_option_parameters("", resize_options, NULL);
1520 if (set_option_parameter(param, BLOCK_OPT_SIZE, size)) {
1521 /* Error message already printed when size parsing fails */
2a81998a
JS
1522 ret = -1;
1523 goto out;
ae6b0ed6
SH
1524 }
1525 n = get_option_parameter(param, BLOCK_OPT_SIZE)->value.n;
1526 free_option_parameters(param);
1527
1528 bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR);
c2abccec 1529 if (!bs) {
2a81998a
JS
1530 ret = -1;
1531 goto out;
c2abccec 1532 }
ae6b0ed6
SH
1533
1534 if (relative) {
1535 total_size = bdrv_getlength(bs) + n * relative;
1536 } else {
1537 total_size = n;
1538 }
1539 if (total_size <= 0) {
15654a6d 1540 error_report("New image size must be positive");
c2abccec
MK
1541 ret = -1;
1542 goto out;
ae6b0ed6
SH
1543 }
1544
1545 ret = bdrv_truncate(bs, total_size);
1546 switch (ret) {
1547 case 0:
1548 printf("Image resized.\n");
1549 break;
1550 case -ENOTSUP:
15654a6d 1551 error_report("This image format does not support resize");
ae6b0ed6
SH
1552 break;
1553 case -EACCES:
15654a6d 1554 error_report("Image is read-only");
ae6b0ed6
SH
1555 break;
1556 default:
15654a6d 1557 error_report("Error resizing image (%d)", -ret);
ae6b0ed6
SH
1558 break;
1559 }
c2abccec 1560out:
2a81998a
JS
1561 if (bs) {
1562 bdrv_delete(bs);
1563 }
c2abccec
MK
1564 if (ret) {
1565 return 1;
1566 }
ae6b0ed6
SH
1567 return 0;
1568}
1569
c227f099 1570static const img_cmd_t img_cmds[] = {
153859be
SB
1571#define DEF(option, callback, arg_string) \
1572 { option, callback },
1573#include "qemu-img-cmds.h"
1574#undef DEF
1575#undef GEN_DOCS
1576 { NULL, NULL, },
1577};
1578
ea2384d3
FB
1579int main(int argc, char **argv)
1580{
c227f099 1581 const img_cmd_t *cmd;
153859be 1582 const char *cmdname;
ea2384d3 1583
53f76e58
KW
1584 error_set_progname(argv[0]);
1585
ea2384d3
FB
1586 bdrv_init();
1587 if (argc < 2)
1588 help();
153859be 1589 cmdname = argv[1];
8f9b157e 1590 argc--; argv++;
153859be
SB
1591
1592 /* find the command */
1593 for(cmd = img_cmds; cmd->name != NULL; cmd++) {
1594 if (!strcmp(cmdname, cmd->name)) {
1595 return cmd->handler(argc, argv);
1596 }
ea2384d3 1597 }
153859be
SB
1598
1599 /* not found */
1600 help();
ea2384d3
FB
1601 return 0;
1602}