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