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