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