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