]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-img.c
smbios: Move table build tools into an include file.
[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 */
80c71a24 24#include "qemu/osdep.h"
67a1de0d 25#include "qemu-version.h"
da34e65c 26#include "qapi/error.h"
c054b3fd
BC
27#include "qapi-visit.h"
28#include "qapi/qmp-output-visitor.h"
cc7a8ea7 29#include "qapi/qmp/qerror.h"
7b1b5d19 30#include "qapi/qmp/qjson.h"
f348b6d1 31#include "qemu/cutils.h"
3babeb15 32#include "qemu/config-file.h"
1de7afc9
PB
33#include "qemu/option.h"
34#include "qemu/error-report.h"
3babeb15 35#include "qom/object_interfaces.h"
9c17d615 36#include "sysemu/sysemu.h"
26f54e9a 37#include "sysemu/block-backend.h"
737e150e 38#include "block/block_int.h"
d4a3238a 39#include "block/blockjob.h"
f364ec65 40#include "block/qapi.h"
c2297088 41#include "crypto/init.h"
c054b3fd 42#include <getopt.h>
e8445331 43
61979a6a 44#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
5f6979cb
JC
45 ", Copyright (c) 2004-2008 Fabrice Bellard\n"
46
c227f099 47typedef struct img_cmd_t {
153859be
SB
48 const char *name;
49 int (*handler)(int argc, char **argv);
c227f099 50} img_cmd_t;
153859be 51
8599ea4c
FS
52enum {
53 OPTION_OUTPUT = 256,
54 OPTION_BACKING_CHAIN = 257,
3babeb15 55 OPTION_OBJECT = 258,
eb769f74 56 OPTION_IMAGE_OPTS = 259,
b6495fa8 57 OPTION_PATTERN = 260,
55d539c8
KW
58 OPTION_FLUSH_INTERVAL = 261,
59 OPTION_NO_DRAIN = 262,
8599ea4c
FS
60};
61
62typedef enum OutputFormat {
63 OFORMAT_JSON,
64 OFORMAT_HUMAN,
65} OutputFormat;
66
e6996143 67/* Default to cache=writeback as data integrity is not important for qemu-img */
661a0f71 68#define BDRV_DEFAULT_CACHE "writeback"
137519ce 69
00c6d403 70static void format_print(void *opaque, const char *name)
ea2384d3 71{
00c6d403 72 printf(" %s", name);
ea2384d3
FB
73}
74
ac1307ab
FZ
75static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
76{
77 va_list ap;
78
79 error_printf("qemu-img: ");
80
81 va_start(ap, fmt);
82 error_vprintf(fmt, ap);
83 va_end(ap);
84
85 error_printf("\nTry 'qemu-img --help' for more information\n");
86 exit(EXIT_FAILURE);
87}
88
d2c639d6 89/* Please keep in synch with qemu-img.texi */
ac1307ab 90static void QEMU_NORETURN help(void)
ea2384d3 91{
e00291c0 92 const char *help_msg =
5f6979cb 93 QEMU_IMG_VERSION
3f020d70 94 "usage: qemu-img command [command options]\n"
95 "QEMU disk image utility\n"
96 "\n"
97 "Command syntax:\n"
153859be
SB
98#define DEF(option, callback, arg_string) \
99 " " arg_string "\n"
100#include "qemu-img-cmds.h"
101#undef DEF
102#undef GEN_DOCS
3f020d70 103 "\n"
104 "Command parameters:\n"
105 " 'filename' is a disk image filename\n"
3babeb15
DB
106 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
107 " manual page for a description of the object properties. The most common\n"
108 " object type is a 'secret', which is used to supply passwords and/or\n"
109 " encryption keys.\n"
3f020d70 110 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
661a0f71 111 " 'cache' is the cache mode used to write the output disk image, the valid\n"
80ccf93b
LY
112 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
113 " 'directsync' and 'unsafe' (default for convert)\n"
bb87fdf8
SH
114 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
115 " options are the same as for the 'cache' option\n"
3f020d70 116 " 'size' is the disk image size in bytes. Optional suffixes\n"
5e00984a
KW
117 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
118 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
119 " supported. 'b' is ignored.\n"
3f020d70 120 " 'output_filename' is the destination disk image filename\n"
121 " 'output_fmt' is the destination format\n"
122 " 'options' is a comma separated list of format specific options in a\n"
123 " name=value format. Use -o ? for an overview of the options supported by the\n"
124 " used format\n"
ef80654d
WX
125 " 'snapshot_param' is param used for internal snapshot, format\n"
126 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
127 " '[ID_OR_NAME]'\n"
128 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
129 " instead\n"
3f020d70 130 " '-c' indicates that target image must be compressed (qcow format only)\n"
131 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
132 " match exactly. The image doesn't need a working backing file before\n"
133 " rebasing in this case (useful for renaming the backing file)\n"
134 " '-h' with or without a command shows this help and lists the supported formats\n"
6b837bc4 135 " '-p' show progress of command (only certain commands)\n"
f382d43a 136 " '-q' use Quiet mode - do not print any output (except errors)\n"
11b6699a
PL
137 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
138 " contain only zeros for qemu-img to create a sparse image during\n"
139 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
140 " unallocated or zero sectors, and the destination image will always be\n"
141 " fully allocated\n"
c054b3fd 142 " '--output' takes the format in which the output must be done (human or json)\n"
b2e10493
AD
143 " '-n' skips the target volume creation (useful if the volume is created\n"
144 " prior to running qemu-img)\n"
3f020d70 145 "\n"
4534ff54
KW
146 "Parameters to check subcommand:\n"
147 " '-r' tries to repair any inconsistencies that are found during the check.\n"
148 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
149 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
0546b8c2 150 " hiding corruption that has already occurred.\n"
4534ff54 151 "\n"
3f020d70 152 "Parameters to snapshot subcommand:\n"
153 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
154 " '-a' applies a snapshot (revert disk to saved state)\n"
155 " '-c' creates a snapshot\n"
156 " '-d' deletes a snapshot\n"
d14ed18c
MR
157 " '-l' lists all snapshots in the given image\n"
158 "\n"
159 "Parameters to compare subcommand:\n"
160 " '-f' first image format\n"
161 " '-F' second image format\n"
162 " '-s' run in Strict mode - fail on different image size or sector allocation\n";
e00291c0
PB
163
164 printf("%s\nSupported formats:", help_msg);
00c6d403 165 bdrv_iterate_format(format_print, NULL);
ea2384d3 166 printf("\n");
ac1307ab 167 exit(EXIT_SUCCESS);
ea2384d3
FB
168}
169
3babeb15
DB
170static QemuOptsList qemu_object_opts = {
171 .name = "object",
172 .implied_opt_name = "qom-type",
173 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
174 .desc = {
175 { }
176 },
177};
178
eb769f74
DB
179static QemuOptsList qemu_source_opts = {
180 .name = "source",
181 .implied_opt_name = "file",
182 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
183 .desc = {
184 { }
185 },
186};
187
7c30f657 188static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
f382d43a
MR
189{
190 int ret = 0;
191 if (!quiet) {
192 va_list args;
193 va_start(args, fmt);
194 ret = vprintf(fmt, args);
195 va_end(args);
196 }
197 return ret;
198}
199
ea2384d3 200
4ac8aacd
JS
201static int print_block_option_help(const char *filename, const char *fmt)
202{
203 BlockDriver *drv, *proto_drv;
83d0521a 204 QemuOptsList *create_opts = NULL;
b65a5e12 205 Error *local_err = NULL;
4ac8aacd
JS
206
207 /* Find driver and parse its options */
208 drv = bdrv_find_format(fmt);
209 if (!drv) {
15654a6d 210 error_report("Unknown file format '%s'", fmt);
4ac8aacd
JS
211 return 1;
212 }
213
c282e1fd 214 create_opts = qemu_opts_append(create_opts, drv->create_opts);
a283cb6e 215 if (filename) {
b65a5e12 216 proto_drv = bdrv_find_protocol(filename, true, &local_err);
a283cb6e 217 if (!proto_drv) {
2867ce4a 218 error_report_err(local_err);
83d0521a 219 qemu_opts_free(create_opts);
a283cb6e
KW
220 return 1;
221 }
c282e1fd 222 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
a283cb6e
KW
223 }
224
83d0521a
CL
225 qemu_opts_print_help(create_opts);
226 qemu_opts_free(create_opts);
4ac8aacd
JS
227 return 0;
228}
229
eb769f74
DB
230
231static int img_open_password(BlockBackend *blk, const char *filename,
abb06c5a 232 int flags, bool quiet)
75c23805
FB
233{
234 BlockDriverState *bs;
75c23805 235 char password[256];
eb769f74
DB
236
237 bs = blk_bs(blk);
4ef130fc
DB
238 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
239 !(flags & BDRV_O_NO_IO)) {
eb769f74
DB
240 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
241 if (qemu_read_password(password, sizeof(password)) < 0) {
242 error_report("No password given");
243 return -1;
244 }
245 if (bdrv_set_key(bs, password) < 0) {
246 error_report("invalid password");
247 return -1;
248 }
249 }
250 return 0;
251}
252
253
efaa7c4e 254static BlockBackend *img_open_opts(const char *optstr,
ce099547 255 QemuOpts *opts, int flags, bool writethrough,
abb06c5a 256 bool quiet)
eb769f74
DB
257{
258 QDict *options;
259 Error *local_err = NULL;
260 BlockBackend *blk;
261 options = qemu_opts_to_qdict(opts, NULL);
efaa7c4e 262 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
eb769f74 263 if (!blk) {
143605a2 264 error_reportf_err(local_err, "Could not open '%s': ", optstr);
eb769f74
DB
265 return NULL;
266 }
ce099547 267 blk_set_enable_write_cache(blk, !writethrough);
eb769f74 268
abb06c5a 269 if (img_open_password(blk, optstr, flags, quiet) < 0) {
eb769f74
DB
270 blk_unref(blk);
271 return NULL;
272 }
273 return blk;
274}
275
efaa7c4e 276static BlockBackend *img_open_file(const char *filename,
eb769f74 277 const char *fmt, int flags,
ce099547 278 bool writethrough, bool quiet)
eb769f74
DB
279{
280 BlockBackend *blk;
34b5d2c6 281 Error *local_err = NULL;
5bd31326 282 QDict *options = NULL;
ad717139 283
75c23805 284 if (fmt) {
5bd31326
HR
285 options = qdict_new();
286 qdict_put(options, "driver", qstring_from_str(fmt));
75c23805 287 }
b9eaf9ec 288
efaa7c4e 289 blk = blk_new_open(filename, NULL, options, flags, &local_err);
5bd31326 290 if (!blk) {
c29b77f9 291 error_reportf_err(local_err, "Could not open '%s': ", filename);
eb769f74 292 return NULL;
75c23805 293 }
ce099547 294 blk_set_enable_write_cache(blk, !writethrough);
b9eaf9ec 295
abb06c5a 296 if (img_open_password(blk, filename, flags, quiet) < 0) {
eb769f74
DB
297 blk_unref(blk);
298 return NULL;
299 }
300 return blk;
301}
302
303
efaa7c4e 304static BlockBackend *img_open(bool image_opts,
eb769f74 305 const char *filename,
ce099547 306 const char *fmt, int flags, bool writethrough,
abb06c5a 307 bool quiet)
eb769f74
DB
308{
309 BlockBackend *blk;
310 if (image_opts) {
311 QemuOpts *opts;
312 if (fmt) {
313 error_report("--image-opts and --format are mutually exclusive");
314 return NULL;
315 }
316 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
317 filename, true);
318 if (!opts) {
319 return NULL;
320 }
ce099547 321 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
eb769f74 322 } else {
ce099547 323 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
75c23805 324 }
7e7d56d9 325 return blk;
75c23805
FB
326}
327
eb769f74 328
83d0521a 329static int add_old_style_options(const char *fmt, QemuOpts *opts,
eec77d9e
JS
330 const char *base_filename,
331 const char *base_fmt)
efa84d43 332{
6750e795
MA
333 Error *err = NULL;
334
efa84d43 335 if (base_filename) {
f43e47db 336 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
6750e795 337 if (err) {
15654a6d
JS
338 error_report("Backing file not supported for file format '%s'",
339 fmt);
6750e795 340 error_free(err);
c2abccec 341 return -1;
efa84d43
KW
342 }
343 }
344 if (base_fmt) {
f43e47db 345 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
6750e795 346 if (err) {
15654a6d
JS
347 error_report("Backing file format not supported for file "
348 "format '%s'", fmt);
6750e795 349 error_free(err);
c2abccec 350 return -1;
efa84d43
KW
351 }
352 }
c2abccec 353 return 0;
efa84d43
KW
354}
355
ea2384d3
FB
356static int img_create(int argc, char **argv)
357{
a9300911 358 int c;
1da7cfbd 359 uint64_t img_size = -1;
ea2384d3 360 const char *fmt = "raw";
9230eaf6 361 const char *base_fmt = NULL;
ea2384d3
FB
362 const char *filename;
363 const char *base_filename = NULL;
9ea2ea71 364 char *options = NULL;
9b37525a 365 Error *local_err = NULL;
f382d43a 366 bool quiet = false;
3b46e624 367
ea2384d3 368 for(;;) {
3babeb15
DB
369 static const struct option long_options[] = {
370 {"help", no_argument, 0, 'h'},
371 {"object", required_argument, 0, OPTION_OBJECT},
372 {0, 0, 0, 0}
373 };
374 c = getopt_long(argc, argv, "F:b:f:he6o:q",
375 long_options, NULL);
b8fb60da 376 if (c == -1) {
ea2384d3 377 break;
b8fb60da 378 }
ea2384d3 379 switch(c) {
ef87394c 380 case '?':
ea2384d3
FB
381 case 'h':
382 help();
383 break;
9230eaf6
AL
384 case 'F':
385 base_fmt = optarg;
386 break;
ea2384d3
FB
387 case 'b':
388 base_filename = optarg;
389 break;
390 case 'f':
391 fmt = optarg;
392 break;
393 case 'e':
9d42e15d 394 error_report("option -e is deprecated, please use \'-o "
eec77d9e 395 "encryption\' instead!");
77386bf6 396 goto fail;
d8871c5a 397 case '6':
9d42e15d 398 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 399 "compat6\' instead!");
77386bf6 400 goto fail;
9ea2ea71 401 case 'o':
77386bf6
KW
402 if (!is_valid_option_list(optarg)) {
403 error_report("Invalid option list: %s", optarg);
404 goto fail;
405 }
406 if (!options) {
407 options = g_strdup(optarg);
408 } else {
409 char *old_options = options;
410 options = g_strdup_printf("%s,%s", options, optarg);
411 g_free(old_options);
412 }
9ea2ea71 413 break;
f382d43a
MR
414 case 'q':
415 quiet = true;
416 break;
3babeb15
DB
417 case OPTION_OBJECT: {
418 QemuOpts *opts;
419 opts = qemu_opts_parse_noisily(&qemu_object_opts,
420 optarg, true);
421 if (!opts) {
422 goto fail;
423 }
424 } break;
ea2384d3
FB
425 }
426 }
9230eaf6 427
b50cbabc 428 /* Get the filename */
a283cb6e
KW
429 filename = (optind < argc) ? argv[optind] : NULL;
430 if (options && has_help_option(options)) {
431 g_free(options);
432 return print_block_option_help(filename, fmt);
433 }
434
b8fb60da 435 if (optind >= argc) {
ac1307ab 436 error_exit("Expecting image file name");
b8fb60da 437 }
a283cb6e 438 optind++;
b50cbabc 439
3babeb15
DB
440 if (qemu_opts_foreach(&qemu_object_opts,
441 user_creatable_add_opts_foreach,
51b9b478 442 NULL, NULL)) {
3babeb15
DB
443 goto fail;
444 }
445
1da7cfbd
JS
446 /* Get image size, if specified */
447 if (optind < argc) {
70b4f4bb 448 int64_t sval;
e36b3695 449 char *end;
4677bb40
MAL
450 sval = qemu_strtosz_suffix(argv[optind++], &end,
451 QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 452 if (sval < 0 || *end) {
79443397
LG
453 if (sval == -ERANGE) {
454 error_report("Image size must be less than 8 EiB!");
455 } else {
456 error_report("Invalid image size specified! You may use k, M, "
5e00984a
KW
457 "G, T, P or E suffixes for ");
458 error_report("kilobytes, megabytes, gigabytes, terabytes, "
459 "petabytes and exabytes.");
79443397 460 }
77386bf6 461 goto fail;
1da7cfbd
JS
462 }
463 img_size = (uint64_t)sval;
464 }
fc11eb26 465 if (optind != argc) {
ac1307ab 466 error_exit("Unexpected argument: %s", argv[optind]);
fc11eb26 467 }
1da7cfbd 468
9b37525a 469 bdrv_img_create(filename, fmt, base_filename, base_fmt,
61de4c68 470 options, img_size, 0, &local_err, quiet);
84d18f06 471 if (local_err) {
c29b77f9 472 error_reportf_err(local_err, "%s: ", filename);
77386bf6 473 goto fail;
c2abccec 474 }
a9300911 475
77386bf6 476 g_free(options);
ea2384d3 477 return 0;
77386bf6
KW
478
479fail:
480 g_free(options);
481 return 1;
ea2384d3
FB
482}
483
f382d43a 484static void dump_json_image_check(ImageCheck *check, bool quiet)
8599ea4c 485{
4399c438 486 Error *local_err = NULL;
8599ea4c
FS
487 QString *str;
488 QmpOutputVisitor *ov = qmp_output_visitor_new();
489 QObject *obj;
51e72bc1
EB
490 visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,
491 &local_err);
8599ea4c
FS
492 obj = qmp_output_get_qobject(ov);
493 str = qobject_to_json_pretty(obj);
494 assert(str != NULL);
f382d43a 495 qprintf(quiet, "%s\n", qstring_get_str(str));
8599ea4c
FS
496 qobject_decref(obj);
497 qmp_output_visitor_cleanup(ov);
498 QDECREF(str);
499}
500
f382d43a 501static void dump_human_image_check(ImageCheck *check, bool quiet)
8599ea4c
FS
502{
503 if (!(check->corruptions || check->leaks || check->check_errors)) {
f382d43a 504 qprintf(quiet, "No errors were found on the image.\n");
8599ea4c
FS
505 } else {
506 if (check->corruptions) {
f382d43a
MR
507 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
508 "Data may be corrupted, or further writes to the image "
509 "may corrupt it.\n",
510 check->corruptions);
8599ea4c
FS
511 }
512
513 if (check->leaks) {
f382d43a
MR
514 qprintf(quiet,
515 "\n%" PRId64 " leaked clusters were found on the image.\n"
516 "This means waste of disk space, but no harm to data.\n",
517 check->leaks);
8599ea4c
FS
518 }
519
520 if (check->check_errors) {
f382d43a
MR
521 qprintf(quiet,
522 "\n%" PRId64
523 " internal errors have occurred during the check.\n",
524 check->check_errors);
8599ea4c
FS
525 }
526 }
527
528 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
f382d43a
MR
529 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
530 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
531 check->allocated_clusters, check->total_clusters,
532 check->allocated_clusters * 100.0 / check->total_clusters,
533 check->fragmented_clusters * 100.0 / check->allocated_clusters,
534 check->compressed_clusters * 100.0 /
535 check->allocated_clusters);
8599ea4c
FS
536 }
537
538 if (check->image_end_offset) {
f382d43a
MR
539 qprintf(quiet,
540 "Image end offset: %" PRId64 "\n", check->image_end_offset);
8599ea4c
FS
541 }
542}
543
544static int collect_image_check(BlockDriverState *bs,
545 ImageCheck *check,
546 const char *filename,
547 const char *fmt,
548 int fix)
549{
550 int ret;
551 BdrvCheckResult result;
552
553 ret = bdrv_check(bs, &result, fix);
554 if (ret < 0) {
555 return ret;
556 }
557
558 check->filename = g_strdup(filename);
559 check->format = g_strdup(bdrv_get_format_name(bs));
560 check->check_errors = result.check_errors;
561 check->corruptions = result.corruptions;
562 check->has_corruptions = result.corruptions != 0;
563 check->leaks = result.leaks;
564 check->has_leaks = result.leaks != 0;
565 check->corruptions_fixed = result.corruptions_fixed;
566 check->has_corruptions_fixed = result.corruptions != 0;
567 check->leaks_fixed = result.leaks_fixed;
568 check->has_leaks_fixed = result.leaks != 0;
569 check->image_end_offset = result.image_end_offset;
570 check->has_image_end_offset = result.image_end_offset != 0;
571 check->total_clusters = result.bfi.total_clusters;
572 check->has_total_clusters = result.bfi.total_clusters != 0;
573 check->allocated_clusters = result.bfi.allocated_clusters;
574 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
575 check->fragmented_clusters = result.bfi.fragmented_clusters;
576 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
e6439d78
SH
577 check->compressed_clusters = result.bfi.compressed_clusters;
578 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
8599ea4c
FS
579
580 return 0;
581}
582
e076f338
KW
583/*
584 * Checks an image for consistency. Exit codes:
585 *
d6635c4d
HR
586 * 0 - Check completed, image is good
587 * 1 - Check not completed because of internal errors
588 * 2 - Check completed, image is corrupted
589 * 3 - Check completed, image has leaked clusters, but is good otherwise
590 * 63 - Checks are not supported by the image format
e076f338 591 */
1585969c
AL
592static int img_check(int argc, char **argv)
593{
594 int c, ret;
8599ea4c 595 OutputFormat output_format = OFORMAT_HUMAN;
40055951 596 const char *filename, *fmt, *output, *cache;
26f54e9a 597 BlockBackend *blk;
1585969c 598 BlockDriverState *bs;
4534ff54 599 int fix = 0;
ce099547
KW
600 int flags = BDRV_O_CHECK;
601 bool writethrough;
7e7d56d9 602 ImageCheck *check;
f382d43a 603 bool quiet = false;
eb769f74 604 bool image_opts = false;
1585969c
AL
605
606 fmt = NULL;
8599ea4c 607 output = NULL;
40055951 608 cache = BDRV_DEFAULT_CACHE;
ce099547 609
1585969c 610 for(;;) {
8599ea4c
FS
611 int option_index = 0;
612 static const struct option long_options[] = {
613 {"help", no_argument, 0, 'h'},
614 {"format", required_argument, 0, 'f'},
4fd6a984 615 {"repair", required_argument, 0, 'r'},
8599ea4c 616 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 617 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 618 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
8599ea4c
FS
619 {0, 0, 0, 0}
620 };
40055951 621 c = getopt_long(argc, argv, "hf:r:T:q",
8599ea4c 622 long_options, &option_index);
b8fb60da 623 if (c == -1) {
1585969c 624 break;
b8fb60da 625 }
1585969c 626 switch(c) {
ef87394c 627 case '?':
1585969c
AL
628 case 'h':
629 help();
630 break;
631 case 'f':
632 fmt = optarg;
633 break;
4534ff54
KW
634 case 'r':
635 flags |= BDRV_O_RDWR;
636
637 if (!strcmp(optarg, "leaks")) {
638 fix = BDRV_FIX_LEAKS;
639 } else if (!strcmp(optarg, "all")) {
640 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
641 } else {
ac1307ab
FZ
642 error_exit("Unknown option value for -r "
643 "(expecting 'leaks' or 'all'): %s", optarg);
4534ff54
KW
644 }
645 break;
8599ea4c
FS
646 case OPTION_OUTPUT:
647 output = optarg;
648 break;
40055951
HR
649 case 'T':
650 cache = optarg;
651 break;
f382d43a
MR
652 case 'q':
653 quiet = true;
654 break;
3babeb15
DB
655 case OPTION_OBJECT: {
656 QemuOpts *opts;
657 opts = qemu_opts_parse_noisily(&qemu_object_opts,
658 optarg, true);
659 if (!opts) {
660 return 1;
661 }
662 } break;
eb769f74
DB
663 case OPTION_IMAGE_OPTS:
664 image_opts = true;
665 break;
1585969c
AL
666 }
667 }
fc11eb26 668 if (optind != argc - 1) {
ac1307ab 669 error_exit("Expecting one image file name");
b8fb60da 670 }
1585969c
AL
671 filename = argv[optind++];
672
8599ea4c
FS
673 if (output && !strcmp(output, "json")) {
674 output_format = OFORMAT_JSON;
675 } else if (output && !strcmp(output, "human")) {
676 output_format = OFORMAT_HUMAN;
677 } else if (output) {
678 error_report("--output must be used with human or json as argument.");
679 return 1;
680 }
681
3babeb15
DB
682 if (qemu_opts_foreach(&qemu_object_opts,
683 user_creatable_add_opts_foreach,
51b9b478 684 NULL, NULL)) {
3babeb15
DB
685 return 1;
686 }
687
ce099547 688 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
689 if (ret < 0) {
690 error_report("Invalid source cache option: %s", cache);
691 return 1;
692 }
693
ce099547 694 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
695 if (!blk) {
696 return 1;
c2abccec 697 }
7e7d56d9 698 bs = blk_bs(blk);
8599ea4c
FS
699
700 check = g_new0(ImageCheck, 1);
701 ret = collect_image_check(bs, check, filename, fmt, fix);
e076f338
KW
702
703 if (ret == -ENOTSUP) {
55d492d7 704 error_report("This image format does not support checks");
fefddf95 705 ret = 63;
8599ea4c 706 goto fail;
e076f338
KW
707 }
708
8599ea4c
FS
709 if (check->corruptions_fixed || check->leaks_fixed) {
710 int corruptions_fixed, leaks_fixed;
ccf34716 711
8599ea4c
FS
712 leaks_fixed = check->leaks_fixed;
713 corruptions_fixed = check->corruptions_fixed;
e076f338 714
8599ea4c 715 if (output_format == OFORMAT_HUMAN) {
f382d43a
MR
716 qprintf(quiet,
717 "The following inconsistencies were found and repaired:\n\n"
718 " %" PRId64 " leaked clusters\n"
719 " %" PRId64 " corruptions\n\n"
720 "Double checking the fixed image now...\n",
721 check->leaks_fixed,
722 check->corruptions_fixed);
e076f338
KW
723 }
724
8599ea4c 725 ret = collect_image_check(bs, check, filename, fmt, 0);
1585969c 726
8599ea4c
FS
727 check->leaks_fixed = leaks_fixed;
728 check->corruptions_fixed = corruptions_fixed;
f8111c24
DXW
729 }
730
832390a5
HR
731 if (!ret) {
732 switch (output_format) {
733 case OFORMAT_HUMAN:
734 dump_human_image_check(check, quiet);
735 break;
736 case OFORMAT_JSON:
737 dump_json_image_check(check, quiet);
738 break;
739 }
c6bb9ad1
FS
740 }
741
8599ea4c 742 if (ret || check->check_errors) {
832390a5
HR
743 if (ret) {
744 error_report("Check failed: %s", strerror(-ret));
745 } else {
746 error_report("Check failed");
747 }
8599ea4c
FS
748 ret = 1;
749 goto fail;
c2abccec 750 }
e076f338 751
8599ea4c
FS
752 if (check->corruptions) {
753 ret = 2;
754 } else if (check->leaks) {
755 ret = 3;
e076f338 756 } else {
8599ea4c 757 ret = 0;
e076f338 758 }
8599ea4c
FS
759
760fail:
761 qapi_free_ImageCheck(check);
26f54e9a 762 blk_unref(blk);
8599ea4c 763 return ret;
1585969c
AL
764}
765
d4a3238a
HR
766typedef struct CommonBlockJobCBInfo {
767 BlockDriverState *bs;
768 Error **errp;
769} CommonBlockJobCBInfo;
770
771static void common_block_job_cb(void *opaque, int ret)
772{
773 CommonBlockJobCBInfo *cbi = opaque;
774
775 if (ret < 0) {
776 error_setg_errno(cbi->errp, -ret, "Block job failed");
777 }
d4a3238a
HR
778}
779
780static void run_block_job(BlockJob *job, Error **errp)
781{
b75536c9 782 AioContext *aio_context = blk_get_aio_context(job->blk);
d4a3238a
HR
783
784 do {
785 aio_poll(aio_context, true);
62547b8a
JS
786 qemu_progress_print(job->len ?
787 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
d4a3238a
HR
788 } while (!job->ready);
789
790 block_job_complete_sync(job, errp);
687fa1d8
HR
791
792 /* A block job may finish instantaneously without publishing any progress,
793 * so just signal completion here */
794 qemu_progress_print(100.f, 0);
d4a3238a
HR
795}
796
ea2384d3
FB
797static int img_commit(int argc, char **argv)
798{
661a0f71 799 int c, ret, flags;
1b22bffd 800 const char *filename, *fmt, *cache, *base;
26f54e9a 801 BlockBackend *blk;
d4a3238a 802 BlockDriverState *bs, *base_bs;
687fa1d8 803 bool progress = false, quiet = false, drop = false;
ce099547 804 bool writethrough;
d4a3238a
HR
805 Error *local_err = NULL;
806 CommonBlockJobCBInfo cbi;
eb769f74 807 bool image_opts = false;
ea2384d3
FB
808
809 fmt = NULL;
661a0f71 810 cache = BDRV_DEFAULT_CACHE;
1b22bffd 811 base = NULL;
ea2384d3 812 for(;;) {
3babeb15
DB
813 static const struct option long_options[] = {
814 {"help", no_argument, 0, 'h'},
815 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 816 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
817 {0, 0, 0, 0}
818 };
819 c = getopt_long(argc, argv, "f:ht:b:dpq",
820 long_options, NULL);
b8fb60da 821 if (c == -1) {
ea2384d3 822 break;
b8fb60da 823 }
ea2384d3 824 switch(c) {
ef87394c 825 case '?':
ea2384d3
FB
826 case 'h':
827 help();
828 break;
829 case 'f':
830 fmt = optarg;
831 break;
661a0f71
FS
832 case 't':
833 cache = optarg;
834 break;
1b22bffd
HR
835 case 'b':
836 base = optarg;
837 /* -b implies -d */
838 drop = true;
839 break;
9a86fe48
HR
840 case 'd':
841 drop = true;
842 break;
687fa1d8
HR
843 case 'p':
844 progress = true;
845 break;
f382d43a
MR
846 case 'q':
847 quiet = true;
848 break;
3babeb15
DB
849 case OPTION_OBJECT: {
850 QemuOpts *opts;
851 opts = qemu_opts_parse_noisily(&qemu_object_opts,
852 optarg, true);
853 if (!opts) {
854 return 1;
855 }
856 } break;
eb769f74
DB
857 case OPTION_IMAGE_OPTS:
858 image_opts = true;
859 break;
ea2384d3
FB
860 }
861 }
687fa1d8
HR
862
863 /* Progress is not shown in Quiet mode */
864 if (quiet) {
865 progress = false;
866 }
867
fc11eb26 868 if (optind != argc - 1) {
ac1307ab 869 error_exit("Expecting one image file name");
b8fb60da 870 }
ea2384d3
FB
871 filename = argv[optind++];
872
3babeb15
DB
873 if (qemu_opts_foreach(&qemu_object_opts,
874 user_creatable_add_opts_foreach,
51b9b478 875 NULL, NULL)) {
3babeb15
DB
876 return 1;
877 }
878
9a86fe48 879 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
ce099547 880 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
881 if (ret < 0) {
882 error_report("Invalid cache option: %s", cache);
a3981eb9 883 return 1;
661a0f71
FS
884 }
885
ce099547 886 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9
MA
887 if (!blk) {
888 return 1;
c2abccec 889 }
7e7d56d9
MA
890 bs = blk_bs(blk);
891
687fa1d8
HR
892 qemu_progress_init(progress, 1.f);
893 qemu_progress_print(0.f, 100);
894
1b22bffd
HR
895 if (base) {
896 base_bs = bdrv_find_backing_image(bs, base);
897 if (!base_bs) {
c6bd8c70 898 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
1b22bffd
HR
899 goto done;
900 }
901 } else {
902 /* This is different from QMP, which by default uses the deepest file in
903 * the backing chain (i.e., the very base); however, the traditional
904 * behavior of qemu-img commit is using the immediate backing file. */
760e0063 905 base_bs = backing_bs(bs);
1b22bffd
HR
906 if (!base_bs) {
907 error_setg(&local_err, "Image does not have a backing file");
908 goto done;
909 }
d4a3238a
HR
910 }
911
912 cbi = (CommonBlockJobCBInfo){
913 .errp = &local_err,
914 .bs = bs,
915 };
916
917 commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
918 common_block_job_cb, &cbi, &local_err);
919 if (local_err) {
920 goto done;
ea2384d3
FB
921 }
922
3f09bfbc
KW
923 /* When the block job completes, the BlockBackend reference will point to
924 * the old backing file. In order to avoid that the top image is already
925 * deleted, so we can still empty it afterwards, increment the reference
926 * counter here preemptively. */
9a86fe48 927 if (!drop) {
3f09bfbc 928 bdrv_ref(bs);
9a86fe48
HR
929 }
930
d4a3238a 931 run_block_job(bs->job, &local_err);
9a86fe48
HR
932 if (local_err) {
933 goto unref_backing;
934 }
935
3f09bfbc
KW
936 if (!drop && bs->drv->bdrv_make_empty) {
937 ret = bs->drv->bdrv_make_empty(bs);
9a86fe48
HR
938 if (ret) {
939 error_setg_errno(&local_err, -ret, "Could not empty %s",
940 filename);
941 goto unref_backing;
942 }
943 }
944
945unref_backing:
946 if (!drop) {
3f09bfbc 947 bdrv_unref(bs);
9a86fe48 948 }
d4a3238a
HR
949
950done:
687fa1d8
HR
951 qemu_progress_end();
952
26f54e9a 953 blk_unref(blk);
d4a3238a
HR
954
955 if (local_err) {
6936f299 956 error_report_err(local_err);
c2abccec
MK
957 return 1;
958 }
d4a3238a
HR
959
960 qprintf(quiet, "Image committed.\n");
ea2384d3
FB
961 return 0;
962}
963
f58c7b35
TS
964/*
965 * Returns true iff the first sector pointed to by 'buf' contains at least
966 * a non-NUL byte.
967 *
968 * 'pnum' is set to the number of sectors (including and immediately following
969 * the first one) that are known to be in the same allocated/unallocated state.
970 */
ea2384d3
FB
971static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
972{
1a6d39fd
SH
973 bool is_zero;
974 int i;
ea2384d3
FB
975
976 if (n <= 0) {
977 *pnum = 0;
978 return 0;
979 }
1a6d39fd 980 is_zero = buffer_is_zero(buf, 512);
ea2384d3
FB
981 for(i = 1; i < n; i++) {
982 buf += 512;
1a6d39fd 983 if (is_zero != buffer_is_zero(buf, 512)) {
ea2384d3 984 break;
1a6d39fd 985 }
ea2384d3
FB
986 }
987 *pnum = i;
1a6d39fd 988 return !is_zero;
ea2384d3
FB
989}
990
a22f123c
KW
991/*
992 * Like is_allocated_sectors, but if the buffer starts with a used sector,
993 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
994 * breaking up write requests for only small sparse areas.
995 */
996static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
997 int min)
998{
999 int ret;
1000 int num_checked, num_used;
1001
1002 if (n < min) {
1003 min = n;
1004 }
1005
1006 ret = is_allocated_sectors(buf, n, pnum);
1007 if (!ret) {
1008 return ret;
1009 }
1010
1011 num_used = *pnum;
1012 buf += BDRV_SECTOR_SIZE * *pnum;
1013 n -= *pnum;
1014 num_checked = num_used;
1015
1016 while (n > 0) {
1017 ret = is_allocated_sectors(buf, n, pnum);
1018
1019 buf += BDRV_SECTOR_SIZE * *pnum;
1020 n -= *pnum;
1021 num_checked += *pnum;
1022 if (ret) {
1023 num_used = num_checked;
1024 } else if (*pnum >= min) {
1025 break;
1026 }
1027 }
1028
1029 *pnum = num_used;
1030 return 1;
1031}
1032
3e85c6fd
KW
1033/*
1034 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1035 * buffers matches, non-zero otherwise.
1036 *
1037 * pnum is set to the number of sectors (including and immediately following
1038 * the first one) that are known to have the same comparison result
1039 */
1040static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1041 int *pnum)
1042{
8c1ac475
RK
1043 bool res;
1044 int i;
3e85c6fd
KW
1045
1046 if (n <= 0) {
1047 *pnum = 0;
1048 return 0;
1049 }
1050
1051 res = !!memcmp(buf1, buf2, 512);
1052 for(i = 1; i < n; i++) {
1053 buf1 += 512;
1054 buf2 += 512;
1055
1056 if (!!memcmp(buf1, buf2, 512) != res) {
1057 break;
1058 }
1059 }
1060
1061 *pnum = i;
1062 return res;
1063}
1064
80ee15a6 1065#define IO_BUF_SIZE (2 * 1024 * 1024)
ea2384d3 1066
d14ed18c
MR
1067static int64_t sectors_to_bytes(int64_t sectors)
1068{
1069 return sectors << BDRV_SECTOR_BITS;
1070}
1071
1072static int64_t sectors_to_process(int64_t total, int64_t from)
1073{
1074 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1075}
1076
1077/*
1078 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1079 *
1080 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1081 * data and negative value on error.
1082 *
f1d3cd79 1083 * @param blk: BlockBackend for the image
d14ed18c
MR
1084 * @param sect_num: Number of first sector to check
1085 * @param sect_count: Number of sectors to check
1086 * @param filename: Name of disk file we are checking (logging purpose)
1087 * @param buffer: Allocated buffer for storing read data
1088 * @param quiet: Flag for quiet mode
1089 */
f1d3cd79 1090static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
d14ed18c
MR
1091 int sect_count, const char *filename,
1092 uint8_t *buffer, bool quiet)
1093{
1094 int pnum, ret = 0;
9166920a
EB
1095 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1096 sect_count << BDRV_SECTOR_BITS);
d14ed18c
MR
1097 if (ret < 0) {
1098 error_report("Error while reading offset %" PRId64 " of %s: %s",
1099 sectors_to_bytes(sect_num), filename, strerror(-ret));
1100 return ret;
1101 }
1102 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1103 if (ret || pnum != sect_count) {
1104 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1105 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1106 return 1;
1107 }
1108
1109 return 0;
1110}
1111
1112/*
1113 * Compares two images. Exit codes:
1114 *
1115 * 0 - Images are identical
1116 * 1 - Images differ
1117 * >1 - Error occurred
1118 */
1119static int img_compare(int argc, char **argv)
1120{
40055951 1121 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
26f54e9a 1122 BlockBackend *blk1, *blk2;
d14ed18c
MR
1123 BlockDriverState *bs1, *bs2;
1124 int64_t total_sectors1, total_sectors2;
1125 uint8_t *buf1 = NULL, *buf2 = NULL;
1126 int pnum1, pnum2;
1127 int allocated1, allocated2;
1128 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1129 bool progress = false, quiet = false, strict = false;
40055951 1130 int flags;
ce099547 1131 bool writethrough;
d14ed18c
MR
1132 int64_t total_sectors;
1133 int64_t sector_num = 0;
1134 int64_t nb_sectors;
1135 int c, pnum;
d14ed18c 1136 uint64_t progress_base;
eb769f74 1137 bool image_opts = false;
d14ed18c 1138
40055951 1139 cache = BDRV_DEFAULT_CACHE;
d14ed18c 1140 for (;;) {
3babeb15
DB
1141 static const struct option long_options[] = {
1142 {"help", no_argument, 0, 'h'},
1143 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1144 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
1145 {0, 0, 0, 0}
1146 };
1147 c = getopt_long(argc, argv, "hf:F:T:pqs",
1148 long_options, NULL);
d14ed18c
MR
1149 if (c == -1) {
1150 break;
1151 }
1152 switch (c) {
1153 case '?':
1154 case 'h':
1155 help();
1156 break;
1157 case 'f':
1158 fmt1 = optarg;
1159 break;
1160 case 'F':
1161 fmt2 = optarg;
1162 break;
40055951
HR
1163 case 'T':
1164 cache = optarg;
1165 break;
d14ed18c
MR
1166 case 'p':
1167 progress = true;
1168 break;
1169 case 'q':
1170 quiet = true;
1171 break;
1172 case 's':
1173 strict = true;
1174 break;
3babeb15
DB
1175 case OPTION_OBJECT: {
1176 QemuOpts *opts;
1177 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1178 optarg, true);
1179 if (!opts) {
1180 ret = 2;
1181 goto out4;
1182 }
1183 } break;
eb769f74
DB
1184 case OPTION_IMAGE_OPTS:
1185 image_opts = true;
1186 break;
d14ed18c
MR
1187 }
1188 }
1189
1190 /* Progress is not shown in Quiet mode */
1191 if (quiet) {
1192 progress = false;
1193 }
1194
1195
fc11eb26 1196 if (optind != argc - 2) {
ac1307ab 1197 error_exit("Expecting two image file names");
d14ed18c
MR
1198 }
1199 filename1 = argv[optind++];
1200 filename2 = argv[optind++];
1201
3babeb15
DB
1202 if (qemu_opts_foreach(&qemu_object_opts,
1203 user_creatable_add_opts_foreach,
51b9b478 1204 NULL, NULL)) {
3babeb15
DB
1205 ret = 2;
1206 goto out4;
1207 }
1208
cbda016d
SH
1209 /* Initialize before goto out */
1210 qemu_progress_init(progress, 2.0);
1211
ce099547
KW
1212 flags = 0;
1213 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
40055951
HR
1214 if (ret < 0) {
1215 error_report("Invalid source cache option: %s", cache);
1216 ret = 2;
1217 goto out3;
1218 }
1219
ce099547 1220 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
7e7d56d9 1221 if (!blk1) {
d14ed18c 1222 ret = 2;
7e7d56d9 1223 goto out3;
d14ed18c
MR
1224 }
1225
ce099547 1226 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
7e7d56d9 1227 if (!blk2) {
d14ed18c 1228 ret = 2;
7e7d56d9 1229 goto out2;
d14ed18c 1230 }
eb769f74 1231 bs1 = blk_bs(blk1);
7e7d56d9 1232 bs2 = blk_bs(blk2);
d14ed18c 1233
f1d3cd79
HR
1234 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1235 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1236 total_sectors1 = blk_nb_sectors(blk1);
52bf1e72
MA
1237 if (total_sectors1 < 0) {
1238 error_report("Can't get size of %s: %s",
1239 filename1, strerror(-total_sectors1));
1240 ret = 4;
1241 goto out;
1242 }
f1d3cd79 1243 total_sectors2 = blk_nb_sectors(blk2);
52bf1e72
MA
1244 if (total_sectors2 < 0) {
1245 error_report("Can't get size of %s: %s",
1246 filename2, strerror(-total_sectors2));
1247 ret = 4;
1248 goto out;
1249 }
d14ed18c
MR
1250 total_sectors = MIN(total_sectors1, total_sectors2);
1251 progress_base = MAX(total_sectors1, total_sectors2);
1252
1253 qemu_progress_print(0, 100);
1254
1255 if (strict && total_sectors1 != total_sectors2) {
1256 ret = 1;
1257 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1258 goto out;
1259 }
1260
1261 for (;;) {
25ad8e6e 1262 int64_t status1, status2;
67a0fd2a
FZ
1263 BlockDriverState *file;
1264
d14ed18c
MR
1265 nb_sectors = sectors_to_process(total_sectors, sector_num);
1266 if (nb_sectors <= 0) {
1267 break;
1268 }
25ad8e6e
FZ
1269 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1270 total_sectors1 - sector_num,
67a0fd2a 1271 &pnum1, &file);
25ad8e6e 1272 if (status1 < 0) {
d14ed18c
MR
1273 ret = 3;
1274 error_report("Sector allocation test failed for %s", filename1);
1275 goto out;
1276 }
25ad8e6e 1277 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
d14ed18c 1278
25ad8e6e
FZ
1279 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1280 total_sectors2 - sector_num,
67a0fd2a 1281 &pnum2, &file);
25ad8e6e 1282 if (status2 < 0) {
d14ed18c
MR
1283 ret = 3;
1284 error_report("Sector allocation test failed for %s", filename2);
1285 goto out;
1286 }
25ad8e6e
FZ
1287 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1288 if (pnum1) {
1289 nb_sectors = MIN(nb_sectors, pnum1);
1290 }
1291 if (pnum2) {
1292 nb_sectors = MIN(nb_sectors, pnum2);
1293 }
d14ed18c 1294
25ad8e6e
FZ
1295 if (strict) {
1296 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1297 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1298 ret = 1;
1299 qprintf(quiet, "Strict mode: Offset %" PRId64
1300 " block status mismatch!\n",
1301 sectors_to_bytes(sector_num));
1302 goto out;
1303 }
1304 }
1305 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1306 nb_sectors = MIN(pnum1, pnum2);
1307 } else if (allocated1 == allocated2) {
d14ed18c 1308 if (allocated1) {
9166920a
EB
1309 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1310 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
1311 if (ret < 0) {
1312 error_report("Error while reading offset %" PRId64 " of %s:"
1313 " %s", sectors_to_bytes(sector_num), filename1,
1314 strerror(-ret));
1315 ret = 4;
1316 goto out;
1317 }
9166920a
EB
1318 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1319 nb_sectors << BDRV_SECTOR_BITS);
d14ed18c
MR
1320 if (ret < 0) {
1321 error_report("Error while reading offset %" PRId64
1322 " of %s: %s", sectors_to_bytes(sector_num),
1323 filename2, strerror(-ret));
1324 ret = 4;
1325 goto out;
1326 }
1327 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1328 if (ret || pnum != nb_sectors) {
d14ed18c
MR
1329 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1330 sectors_to_bytes(
1331 ret ? sector_num : sector_num + pnum));
36452f12 1332 ret = 1;
d14ed18c
MR
1333 goto out;
1334 }
1335 }
1336 } else {
d14ed18c
MR
1337
1338 if (allocated1) {
f1d3cd79 1339 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
d14ed18c
MR
1340 filename1, buf1, quiet);
1341 } else {
f1d3cd79 1342 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
d14ed18c
MR
1343 filename2, buf1, quiet);
1344 }
1345 if (ret) {
1346 if (ret < 0) {
d14ed18c
MR
1347 error_report("Error while reading offset %" PRId64 ": %s",
1348 sectors_to_bytes(sector_num), strerror(-ret));
36452f12 1349 ret = 4;
d14ed18c
MR
1350 }
1351 goto out;
1352 }
1353 }
1354 sector_num += nb_sectors;
1355 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1356 }
1357
1358 if (total_sectors1 != total_sectors2) {
f1d3cd79 1359 BlockBackend *blk_over;
d14ed18c
MR
1360 int64_t total_sectors_over;
1361 const char *filename_over;
1362
1363 qprintf(quiet, "Warning: Image size mismatch!\n");
1364 if (total_sectors1 > total_sectors2) {
1365 total_sectors_over = total_sectors1;
f1d3cd79 1366 blk_over = blk1;
d14ed18c
MR
1367 filename_over = filename1;
1368 } else {
1369 total_sectors_over = total_sectors2;
f1d3cd79 1370 blk_over = blk2;
d14ed18c
MR
1371 filename_over = filename2;
1372 }
1373
1374 for (;;) {
1375 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1376 if (nb_sectors <= 0) {
1377 break;
1378 }
f1d3cd79 1379 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
d14ed18c
MR
1380 nb_sectors, &pnum);
1381 if (ret < 0) {
1382 ret = 3;
1383 error_report("Sector allocation test failed for %s",
1384 filename_over);
1385 goto out;
1386
1387 }
1388 nb_sectors = pnum;
1389 if (ret) {
f1d3cd79 1390 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
d14ed18c
MR
1391 filename_over, buf1, quiet);
1392 if (ret) {
1393 if (ret < 0) {
d14ed18c
MR
1394 error_report("Error while reading offset %" PRId64
1395 " of %s: %s", sectors_to_bytes(sector_num),
1396 filename_over, strerror(-ret));
36452f12 1397 ret = 4;
d14ed18c
MR
1398 }
1399 goto out;
1400 }
1401 }
1402 sector_num += nb_sectors;
1403 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1404 }
1405 }
1406
1407 qprintf(quiet, "Images are identical.\n");
1408 ret = 0;
1409
1410out:
d14ed18c
MR
1411 qemu_vfree(buf1);
1412 qemu_vfree(buf2);
26f54e9a 1413 blk_unref(blk2);
d14ed18c 1414out2:
26f54e9a 1415 blk_unref(blk1);
d14ed18c
MR
1416out3:
1417 qemu_progress_end();
3babeb15 1418out4:
d14ed18c
MR
1419 return ret;
1420}
1421
690c7301
KW
1422enum ImgConvertBlockStatus {
1423 BLK_DATA,
1424 BLK_ZERO,
1425 BLK_BACKING_FILE,
1426};
1427
1428typedef struct ImgConvertState {
1429 BlockBackend **src;
1430 int64_t *src_sectors;
1431 int src_cur, src_num;
1432 int64_t src_cur_offset;
1433 int64_t total_sectors;
1434 int64_t allocated_sectors;
1435 enum ImgConvertBlockStatus status;
1436 int64_t sector_next_status;
1437 BlockBackend *target;
1438 bool has_zero_init;
1439 bool compressed;
1440 bool target_has_backing;
1441 int min_sparse;
1442 size_t cluster_sectors;
1443 size_t buf_sectors;
1444} ImgConvertState;
1445
1446static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1447{
1448 assert(sector_num >= s->src_cur_offset);
1449 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1450 s->src_cur_offset += s->src_sectors[s->src_cur];
1451 s->src_cur++;
1452 assert(s->src_cur < s->src_num);
1453 }
1454}
1455
1456static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1457{
1458 int64_t ret;
1459 int n;
1460
1461 convert_select_part(s, sector_num);
1462
1463 assert(s->total_sectors > sector_num);
1464 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1465
1466 if (s->sector_next_status <= sector_num) {
67a0fd2a 1467 BlockDriverState *file;
690c7301
KW
1468 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1469 sector_num - s->src_cur_offset,
67a0fd2a 1470 n, &n, &file);
690c7301
KW
1471 if (ret < 0) {
1472 return ret;
1473 }
1474
1475 if (ret & BDRV_BLOCK_ZERO) {
1476 s->status = BLK_ZERO;
1477 } else if (ret & BDRV_BLOCK_DATA) {
1478 s->status = BLK_DATA;
1479 } else if (!s->target_has_backing) {
1480 /* Without a target backing file we must copy over the contents of
1481 * the backing file as well. */
263a6f4c 1482 /* Check block status of the backing file chain to avoid
690c7301
KW
1483 * needlessly reading zeroes and limiting the iteration to the
1484 * buffer size */
263a6f4c
RK
1485 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1486 sector_num - s->src_cur_offset,
1487 n, &n, &file);
1488 if (ret < 0) {
1489 return ret;
1490 }
1491
1492 if (ret & BDRV_BLOCK_ZERO) {
1493 s->status = BLK_ZERO;
1494 } else {
1495 s->status = BLK_DATA;
1496 }
690c7301
KW
1497 } else {
1498 s->status = BLK_BACKING_FILE;
1499 }
1500
1501 s->sector_next_status = sector_num + n;
1502 }
1503
1504 n = MIN(n, s->sector_next_status - sector_num);
1505 if (s->status == BLK_DATA) {
1506 n = MIN(n, s->buf_sectors);
1507 }
1508
1509 /* We need to write complete clusters for compressed images, so if an
1510 * unallocated area is shorter than that, we must consider the whole
1511 * cluster allocated. */
1512 if (s->compressed) {
1513 if (n < s->cluster_sectors) {
1514 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1515 s->status = BLK_DATA;
1516 } else {
1517 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1518 }
1519 }
1520
1521 return n;
1522}
1523
1524static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1525 uint8_t *buf)
1526{
1527 int n;
1528 int ret;
1529
690c7301
KW
1530 assert(nb_sectors <= s->buf_sectors);
1531 while (nb_sectors > 0) {
1532 BlockBackend *blk;
1533 int64_t bs_sectors;
1534
1535 /* In the case of compression with multiple source files, we can get a
1536 * nb_sectors that spreads into the next part. So we must be able to
1537 * read across multiple BDSes for one convert_read() call. */
1538 convert_select_part(s, sector_num);
1539 blk = s->src[s->src_cur];
1540 bs_sectors = s->src_sectors[s->src_cur];
1541
1542 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
9166920a
EB
1543 ret = blk_pread(blk,
1544 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1545 buf, n << BDRV_SECTOR_BITS);
690c7301
KW
1546 if (ret < 0) {
1547 return ret;
1548 }
1549
1550 sector_num += n;
1551 nb_sectors -= n;
1552 buf += n * BDRV_SECTOR_SIZE;
1553 }
1554
1555 return 0;
1556}
1557
1558static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1559 const uint8_t *buf)
1560{
1561 int ret;
1562
1563 while (nb_sectors > 0) {
1564 int n = nb_sectors;
1565
1566 switch (s->status) {
1567 case BLK_BACKING_FILE:
1568 /* If we have a backing file, leave clusters unallocated that are
1569 * unallocated in the source image, so that the backing file is
1570 * visible at the respective offset. */
1571 assert(s->target_has_backing);
1572 break;
1573
1574 case BLK_DATA:
1575 /* We must always write compressed clusters as a whole, so don't
1576 * try to find zeroed parts in the buffer. We can only save the
1577 * write if the buffer is completely zeroed and we're allowed to
1578 * keep the target sparse. */
1579 if (s->compressed) {
1580 if (s->has_zero_init && s->min_sparse &&
1581 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1582 {
1583 assert(!s->target_has_backing);
1584 break;
1585 }
1586
1587 ret = blk_write_compressed(s->target, sector_num, buf, n);
1588 if (ret < 0) {
1589 return ret;
1590 }
1591 break;
1592 }
1593
1594 /* If there is real non-zero data or we're told to keep the target
1595 * fully allocated (-S 0), we must write it. Otherwise we can treat
1596 * it as zero sectors. */
1597 if (!s->min_sparse ||
1598 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1599 {
9166920a
EB
1600 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1601 buf, n << BDRV_SECTOR_BITS, 0);
690c7301
KW
1602 if (ret < 0) {
1603 return ret;
1604 }
1605 break;
1606 }
1607 /* fall-through */
1608
1609 case BLK_ZERO:
1610 if (s->has_zero_init) {
1611 break;
1612 }
d004bd52
EB
1613 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1614 n << BDRV_SECTOR_BITS, 0);
690c7301
KW
1615 if (ret < 0) {
1616 return ret;
1617 }
1618 break;
1619 }
1620
1621 sector_num += n;
1622 nb_sectors -= n;
1623 buf += n * BDRV_SECTOR_SIZE;
1624 }
1625
1626 return 0;
1627}
1628
1629static int convert_do_copy(ImgConvertState *s)
1630{
1631 uint8_t *buf = NULL;
1632 int64_t sector_num, allocated_done;
1633 int ret;
1634 int n;
1635
1636 /* Check whether we have zero initialisation or can get it efficiently */
1637 s->has_zero_init = s->min_sparse && !s->target_has_backing
1638 ? bdrv_has_zero_init(blk_bs(s->target))
1639 : false;
1640
1641 if (!s->has_zero_init && !s->target_has_backing &&
1642 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1643 {
1644 ret = bdrv_make_zero(blk_bs(s->target), BDRV_REQ_MAY_UNMAP);
1645 if (ret == 0) {
1646 s->has_zero_init = true;
1647 }
1648 }
1649
1650 /* Allocate buffer for copied data. For compressed images, only one cluster
1651 * can be copied at a time. */
1652 if (s->compressed) {
1653 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1654 error_report("invalid cluster size");
1655 ret = -EINVAL;
1656 goto fail;
1657 }
1658 s->buf_sectors = s->cluster_sectors;
1659 }
1660 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1661
1662 /* Calculate allocated sectors for progress */
1663 s->allocated_sectors = 0;
1664 sector_num = 0;
1665 while (sector_num < s->total_sectors) {
1666 n = convert_iteration_sectors(s, sector_num);
1667 if (n < 0) {
1668 ret = n;
1669 goto fail;
1670 }
aad15de4
HR
1671 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1672 {
690c7301
KW
1673 s->allocated_sectors += n;
1674 }
1675 sector_num += n;
1676 }
1677
1678 /* Do the copy */
1679 s->src_cur = 0;
1680 s->src_cur_offset = 0;
1681 s->sector_next_status = 0;
1682
1683 sector_num = 0;
1684 allocated_done = 0;
1685
1686 while (sector_num < s->total_sectors) {
1687 n = convert_iteration_sectors(s, sector_num);
1688 if (n < 0) {
1689 ret = n;
1690 goto fail;
1691 }
aad15de4
HR
1692 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1693 {
690c7301
KW
1694 allocated_done += n;
1695 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1696 0);
1697 }
1698
aad15de4
HR
1699 if (s->status == BLK_DATA) {
1700 ret = convert_read(s, sector_num, n, buf);
1701 if (ret < 0) {
1702 error_report("error while reading sector %" PRId64
1703 ": %s", sector_num, strerror(-ret));
1704 goto fail;
1705 }
1706 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1707 n = MIN(n, s->buf_sectors);
1708 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1709 s->status = BLK_DATA;
690c7301
KW
1710 }
1711
1712 ret = convert_write(s, sector_num, n, buf);
1713 if (ret < 0) {
1714 error_report("error while writing sector %" PRId64
1715 ": %s", sector_num, strerror(-ret));
1716 goto fail;
1717 }
1718
1719 sector_num += n;
1720 }
1721
1722 if (s->compressed) {
1723 /* signal EOF to align */
1724 ret = blk_write_compressed(s->target, 0, NULL, 0);
1725 if (ret < 0) {
1726 goto fail;
1727 }
1728 }
1729
1730 ret = 0;
1731fail:
1732 qemu_vfree(buf);
1733 return ret;
1734}
1735
ea2384d3
FB
1736static int img_convert(int argc, char **argv)
1737{
690c7301 1738 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
13c28af8 1739 int64_t ret = 0;
40055951 1740 int progress = 0, flags, src_flags;
ce099547 1741 bool writethrough, src_writethrough;
40055951 1742 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
b50cbabc 1743 BlockDriver *drv, *proto_drv;
26f54e9a 1744 BlockBackend **blk = NULL, *out_blk = NULL;
c2abccec 1745 BlockDriverState **bs = NULL, *out_bs = NULL;
690c7301 1746 int64_t total_sectors;
52bf1e72 1747 int64_t *bs_sectors = NULL;
f2521c90 1748 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
faea38e7 1749 BlockDriverInfo bdi;
83d0521a
CL
1750 QemuOpts *opts = NULL;
1751 QemuOptsList *create_opts = NULL;
1752 const char *out_baseimg_param;
efa84d43 1753 char *options = NULL;
51ef6727 1754 const char *snapshot_name = NULL;
a22f123c 1755 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
f382d43a 1756 bool quiet = false;
cc84d90f 1757 Error *local_err = NULL;
ef80654d 1758 QemuOpts *sn_opts = NULL;
690c7301 1759 ImgConvertState state;
eb769f74 1760 bool image_opts = false;
ea2384d3
FB
1761
1762 fmt = NULL;
1763 out_fmt = "raw";
661a0f71 1764 cache = "unsafe";
40055951 1765 src_cache = BDRV_DEFAULT_CACHE;
f58c7b35 1766 out_baseimg = NULL;
eec77d9e 1767 compress = 0;
b2e10493 1768 skip_create = 0;
ea2384d3 1769 for(;;) {
3babeb15
DB
1770 static const struct option long_options[] = {
1771 {"help", no_argument, 0, 'h'},
1772 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 1773 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
1774 {0, 0, 0, 0}
1775 };
1776 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1777 long_options, NULL);
b8fb60da 1778 if (c == -1) {
ea2384d3 1779 break;
b8fb60da 1780 }
ea2384d3 1781 switch(c) {
ef87394c 1782 case '?':
ea2384d3
FB
1783 case 'h':
1784 help();
1785 break;
1786 case 'f':
1787 fmt = optarg;
1788 break;
1789 case 'O':
1790 out_fmt = optarg;
1791 break;
f58c7b35
TS
1792 case 'B':
1793 out_baseimg = optarg;
1794 break;
ea2384d3 1795 case 'c':
eec77d9e 1796 compress = 1;
ea2384d3
FB
1797 break;
1798 case 'e':
9d42e15d 1799 error_report("option -e is deprecated, please use \'-o "
eec77d9e 1800 "encryption\' instead!");
2dc8328b 1801 ret = -1;
64bb01aa 1802 goto fail_getopt;
ec36ba14 1803 case '6':
9d42e15d 1804 error_report("option -6 is deprecated, please use \'-o "
eec77d9e 1805 "compat6\' instead!");
2dc8328b 1806 ret = -1;
64bb01aa 1807 goto fail_getopt;
efa84d43 1808 case 'o':
2dc8328b
KW
1809 if (!is_valid_option_list(optarg)) {
1810 error_report("Invalid option list: %s", optarg);
1811 ret = -1;
64bb01aa 1812 goto fail_getopt;
2dc8328b
KW
1813 }
1814 if (!options) {
1815 options = g_strdup(optarg);
1816 } else {
1817 char *old_options = options;
1818 options = g_strdup_printf("%s,%s", options, optarg);
1819 g_free(old_options);
1820 }
efa84d43 1821 break;
51ef6727 1822 case 's':
1823 snapshot_name = optarg;
1824 break;
ef80654d
WX
1825 case 'l':
1826 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
1827 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1828 optarg, false);
ef80654d
WX
1829 if (!sn_opts) {
1830 error_report("Failed in parsing snapshot param '%s'",
1831 optarg);
2dc8328b 1832 ret = -1;
64bb01aa 1833 goto fail_getopt;
ef80654d
WX
1834 }
1835 } else {
1836 snapshot_name = optarg;
1837 }
1838 break;
a22f123c
KW
1839 case 'S':
1840 {
1841 int64_t sval;
e36b3695 1842 char *end;
4677bb40 1843 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
e36b3695 1844 if (sval < 0 || *end) {
a22f123c 1845 error_report("Invalid minimum zero buffer size for sparse output specified");
2dc8328b 1846 ret = -1;
64bb01aa 1847 goto fail_getopt;
a22f123c
KW
1848 }
1849
1850 min_sparse = sval / BDRV_SECTOR_SIZE;
1851 break;
1852 }
6b837bc4
JS
1853 case 'p':
1854 progress = 1;
1855 break;
661a0f71
FS
1856 case 't':
1857 cache = optarg;
1858 break;
40055951
HR
1859 case 'T':
1860 src_cache = optarg;
1861 break;
f382d43a
MR
1862 case 'q':
1863 quiet = true;
1864 break;
b2e10493
AD
1865 case 'n':
1866 skip_create = 1;
1867 break;
3babeb15
DB
1868 case OPTION_OBJECT:
1869 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1870 optarg, true);
1871 if (!opts) {
1872 goto fail_getopt;
1873 }
1874 break;
eb769f74
DB
1875 case OPTION_IMAGE_OPTS:
1876 image_opts = true;
1877 break;
ea2384d3
FB
1878 }
1879 }
3b46e624 1880
3babeb15
DB
1881 if (qemu_opts_foreach(&qemu_object_opts,
1882 user_creatable_add_opts_foreach,
51b9b478 1883 NULL, NULL)) {
3babeb15
DB
1884 goto fail_getopt;
1885 }
1886
64bb01aa 1887 /* Initialize before goto out */
f382d43a
MR
1888 if (quiet) {
1889 progress = 0;
1890 }
64bb01aa
KW
1891 qemu_progress_init(progress, 1.0);
1892
926c2d23 1893 bs_n = argc - optind - 1;
a283cb6e 1894 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
f58c7b35 1895
2dc8328b 1896 if (options && has_help_option(options)) {
4ac8aacd
JS
1897 ret = print_block_option_help(out_filename, out_fmt);
1898 goto out;
1899 }
1900
a283cb6e 1901 if (bs_n < 1) {
ac1307ab 1902 error_exit("Must specify image file name");
a283cb6e
KW
1903 }
1904
1905
c2abccec 1906 if (bs_n > 1 && out_baseimg) {
15654a6d
JS
1907 error_report("-B makes no sense when concatenating multiple input "
1908 "images");
31ca34b8
JS
1909 ret = -1;
1910 goto out;
c2abccec 1911 }
f8111c24 1912
ce099547
KW
1913 src_flags = 0;
1914 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
1915 if (ret < 0) {
1916 error_report("Invalid source cache option: %s", src_cache);
1917 goto out;
1918 }
1919
6b837bc4
JS
1920 qemu_progress_print(0, 100);
1921
26f54e9a 1922 blk = g_new0(BlockBackend *, bs_n);
d739f1c4 1923 bs = g_new0(BlockDriverState *, bs_n);
52bf1e72 1924 bs_sectors = g_new(int64_t, bs_n);
926c2d23
AZ
1925
1926 total_sectors = 0;
1927 for (bs_i = 0; bs_i < bs_n; bs_i++) {
efaa7c4e 1928 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
ce099547 1929 fmt, src_flags, src_writethrough, quiet);
7e7d56d9 1930 if (!blk[bs_i]) {
c2abccec
MK
1931 ret = -1;
1932 goto out;
1933 }
7e7d56d9 1934 bs[bs_i] = blk_bs(blk[bs_i]);
f1d3cd79 1935 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
52bf1e72
MA
1936 if (bs_sectors[bs_i] < 0) {
1937 error_report("Could not get size of %s: %s",
1938 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1939 ret = -1;
1940 goto out;
1941 }
d739f1c4 1942 total_sectors += bs_sectors[bs_i];
926c2d23 1943 }
ea2384d3 1944
ef80654d
WX
1945 if (sn_opts) {
1946 ret = bdrv_snapshot_load_tmp(bs[0],
1947 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1948 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1949 &local_err);
1950 } else if (snapshot_name != NULL) {
51ef6727 1951 if (bs_n > 1) {
6daf194d 1952 error_report("No support for concatenating multiple snapshot");
51ef6727 1953 ret = -1;
1954 goto out;
1955 }
7b4c4781
WX
1956
1957 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
ef80654d 1958 }
84d18f06 1959 if (local_err) {
c29b77f9 1960 error_reportf_err(local_err, "Failed to load snapshot: ");
ef80654d
WX
1961 ret = -1;
1962 goto out;
51ef6727 1963 }
1964
efa84d43 1965 /* Find driver and parse its options */
ea2384d3 1966 drv = bdrv_find_format(out_fmt);
c2abccec 1967 if (!drv) {
15654a6d 1968 error_report("Unknown file format '%s'", out_fmt);
c2abccec
MK
1969 ret = -1;
1970 goto out;
1971 }
efa84d43 1972
b65a5e12 1973 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
c2abccec 1974 if (!proto_drv) {
2867ce4a 1975 error_report_err(local_err);
c2abccec
MK
1976 ret = -1;
1977 goto out;
1978 }
b50cbabc 1979
2e024cde
HR
1980 if (!skip_create) {
1981 if (!drv->create_opts) {
1982 error_report("Format driver '%s' does not support image creation",
1983 drv->format_name);
1984 ret = -1;
1985 goto out;
1986 }
f75613cf 1987
2e024cde
HR
1988 if (!proto_drv->create_opts) {
1989 error_report("Protocol driver '%s' does not support image creation",
1990 proto_drv->format_name);
1991 ret = -1;
1992 goto out;
1993 }
f75613cf 1994
2e024cde
HR
1995 create_opts = qemu_opts_append(create_opts, drv->create_opts);
1996 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
db08adf5 1997
2e024cde 1998 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
1999 if (options) {
2000 qemu_opts_do_parse(opts, options, NULL, &local_err);
2001 if (local_err) {
97a2ca7a 2002 error_report_err(local_err);
dc523cd3
MA
2003 ret = -1;
2004 goto out;
2005 }
2e024cde 2006 }
efa84d43 2007
39101f25
MA
2008 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2009 &error_abort);
2e024cde
HR
2010 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2011 if (ret < 0) {
2012 goto out;
2013 }
c2abccec 2014 }
efa84d43 2015
a18953fb 2016 /* Get backing file name if -o backing_file was used */
83d0521a 2017 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
a18953fb 2018 if (out_baseimg_param) {
83d0521a 2019 out_baseimg = out_baseimg_param;
a18953fb
KW
2020 }
2021
efa84d43 2022 /* Check if compression is supported */
eec77d9e 2023 if (compress) {
83d0521a
CL
2024 bool encryption =
2025 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2026 const char *preallocation =
2027 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
efa84d43
KW
2028
2029 if (!drv->bdrv_write_compressed) {
15654a6d 2030 error_report("Compression not supported for this file format");
c2abccec
MK
2031 ret = -1;
2032 goto out;
efa84d43
KW
2033 }
2034
83d0521a 2035 if (encryption) {
15654a6d
JS
2036 error_report("Compression and encryption not supported at "
2037 "the same time");
c2abccec
MK
2038 ret = -1;
2039 goto out;
efa84d43 2040 }
41521fa4 2041
83d0521a
CL
2042 if (preallocation
2043 && strcmp(preallocation, "off"))
41521fa4
KW
2044 {
2045 error_report("Compression and preallocation not supported at "
2046 "the same time");
2047 ret = -1;
2048 goto out;
2049 }
efa84d43
KW
2050 }
2051
b2e10493
AD
2052 if (!skip_create) {
2053 /* Create the new image */
c282e1fd 2054 ret = bdrv_create(drv, out_filename, opts, &local_err);
b2e10493 2055 if (ret < 0) {
c29b77f9
MA
2056 error_reportf_err(local_err, "%s: error while converting %s: ",
2057 out_filename, out_fmt);
b2e10493 2058 goto out;
ea2384d3
FB
2059 }
2060 }
3b46e624 2061
5a37b60a 2062 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
ce099547 2063 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2064 if (ret < 0) {
2065 error_report("Invalid cache option: %s", cache);
bb9cd2ee 2066 goto out;
661a0f71
FS
2067 }
2068
eb769f74
DB
2069 /* XXX we should allow --image-opts to trigger use of
2070 * img_open() here, but then we have trouble with
2071 * the bdrv_create() call which takes different params.
2072 * Not critical right now, so fix can wait...
2073 */
ce099547 2074 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
7e7d56d9 2075 if (!out_blk) {
c2abccec
MK
2076 ret = -1;
2077 goto out;
2078 }
7e7d56d9 2079 out_bs = blk_bs(out_blk);
ea2384d3 2080
f2521c90
PL
2081 /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
2082 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2083 * as maximum. */
2084 bufsectors = MIN(32768,
2085 MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
2086 out_bs->bl.discard_alignment))
2087 );
2088
b2e10493 2089 if (skip_create) {
f1d3cd79 2090 int64_t output_sectors = blk_nb_sectors(out_blk);
43716fa8 2091 if (output_sectors < 0) {
eec5eb42 2092 error_report("unable to get output image length: %s",
43716fa8 2093 strerror(-output_sectors));
b2e10493
AD
2094 ret = -1;
2095 goto out;
43716fa8 2096 } else if (output_sectors < total_sectors) {
b2e10493
AD
2097 error_report("output file is smaller than input file");
2098 ret = -1;
2099 goto out;
2100 }
2101 }
2102
24f833cd
PL
2103 cluster_sectors = 0;
2104 ret = bdrv_get_info(out_bs, &bdi);
2105 if (ret < 0) {
2106 if (compress) {
15654a6d 2107 error_report("could not get block driver info");
c2abccec
MK
2108 goto out;
2109 }
24f833cd 2110 } else {
85f49cad 2111 compress = compress || bdi.needs_compressed_writes;
24f833cd
PL
2112 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2113 }
2114
690c7301
KW
2115 state = (ImgConvertState) {
2116 .src = blk,
2117 .src_sectors = bs_sectors,
2118 .src_num = bs_n,
2119 .total_sectors = total_sectors,
2120 .target = out_blk,
2121 .compressed = compress,
2122 .target_has_backing = (bool) out_baseimg,
2123 .min_sparse = min_sparse,
2124 .cluster_sectors = cluster_sectors,
2125 .buf_sectors = bufsectors,
2126 };
2127 ret = convert_do_copy(&state);
802c3d4c 2128
c2abccec 2129out:
13c28af8
PL
2130 if (!ret) {
2131 qemu_progress_print(100, 0);
2132 }
6b837bc4 2133 qemu_progress_end();
83d0521a
CL
2134 qemu_opts_del(opts);
2135 qemu_opts_free(create_opts);
fbf28a43 2136 qemu_opts_del(sn_opts);
26f54e9a 2137 blk_unref(out_blk);
9ba10c95 2138 g_free(bs);
26f54e9a
MA
2139 if (blk) {
2140 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2141 blk_unref(blk[bs_i]);
2142 }
2143 g_free(blk);
2144 }
d739f1c4 2145 g_free(bs_sectors);
64bb01aa
KW
2146fail_getopt:
2147 g_free(options);
2148
c2abccec
MK
2149 if (ret) {
2150 return 1;
2151 }
ea2384d3
FB
2152 return 0;
2153}
2154
57d1a2b6 2155
faea38e7
FB
2156static void dump_snapshots(BlockDriverState *bs)
2157{
2158 QEMUSnapshotInfo *sn_tab, *sn;
2159 int nb_sns, i;
faea38e7
FB
2160
2161 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2162 if (nb_sns <= 0)
2163 return;
2164 printf("Snapshot list:\n");
5b917044
WX
2165 bdrv_snapshot_dump(fprintf, stdout, NULL);
2166 printf("\n");
faea38e7
FB
2167 for(i = 0; i < nb_sns; i++) {
2168 sn = &sn_tab[i];
5b917044
WX
2169 bdrv_snapshot_dump(fprintf, stdout, sn);
2170 printf("\n");
faea38e7 2171 }
7267c094 2172 g_free(sn_tab);
faea38e7
FB
2173}
2174
9699bf0d
SH
2175static void dump_json_image_info_list(ImageInfoList *list)
2176{
4399c438 2177 Error *local_err = NULL;
9699bf0d
SH
2178 QString *str;
2179 QmpOutputVisitor *ov = qmp_output_visitor_new();
2180 QObject *obj;
51e72bc1
EB
2181 visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,
2182 &local_err);
9699bf0d
SH
2183 obj = qmp_output_get_qobject(ov);
2184 str = qobject_to_json_pretty(obj);
2185 assert(str != NULL);
2186 printf("%s\n", qstring_get_str(str));
2187 qobject_decref(obj);
2188 qmp_output_visitor_cleanup(ov);
2189 QDECREF(str);
2190}
2191
c054b3fd
BC
2192static void dump_json_image_info(ImageInfo *info)
2193{
4399c438 2194 Error *local_err = NULL;
c054b3fd
BC
2195 QString *str;
2196 QmpOutputVisitor *ov = qmp_output_visitor_new();
2197 QObject *obj;
51e72bc1 2198 visit_type_ImageInfo(qmp_output_get_visitor(ov), NULL, &info, &local_err);
c054b3fd
BC
2199 obj = qmp_output_get_qobject(ov);
2200 str = qobject_to_json_pretty(obj);
2201 assert(str != NULL);
2202 printf("%s\n", qstring_get_str(str));
2203 qobject_decref(obj);
2204 qmp_output_visitor_cleanup(ov);
2205 QDECREF(str);
2206}
2207
9699bf0d
SH
2208static void dump_human_image_info_list(ImageInfoList *list)
2209{
2210 ImageInfoList *elem;
2211 bool delim = false;
2212
2213 for (elem = list; elem; elem = elem->next) {
2214 if (delim) {
2215 printf("\n");
2216 }
2217 delim = true;
2218
5b917044 2219 bdrv_image_info_dump(fprintf, stdout, elem->value);
9699bf0d
SH
2220 }
2221}
2222
2223static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2224{
2225 return strcmp(a, b) == 0;
2226}
2227
2228/**
2229 * Open an image file chain and return an ImageInfoList
2230 *
2231 * @filename: topmost image filename
2232 * @fmt: topmost image format (may be NULL to autodetect)
2233 * @chain: true - enumerate entire backing file chain
2234 * false - only topmost image file
2235 *
2236 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2237 * image file. If there was an error a message will have been printed to
2238 * stderr.
2239 */
eb769f74
DB
2240static ImageInfoList *collect_image_info_list(bool image_opts,
2241 const char *filename,
9699bf0d
SH
2242 const char *fmt,
2243 bool chain)
2244{
2245 ImageInfoList *head = NULL;
2246 ImageInfoList **last = &head;
2247 GHashTable *filenames;
43526ec8 2248 Error *err = NULL;
9699bf0d
SH
2249
2250 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2251
2252 while (filename) {
26f54e9a 2253 BlockBackend *blk;
9699bf0d
SH
2254 BlockDriverState *bs;
2255 ImageInfo *info;
2256 ImageInfoList *elem;
2257
2258 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2259 error_report("Backing file '%s' creates an infinite loop.",
2260 filename);
2261 goto err;
2262 }
2263 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2264
efaa7c4e 2265 blk = img_open(image_opts, filename, fmt,
ce099547 2266 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
7e7d56d9 2267 if (!blk) {
9699bf0d
SH
2268 goto err;
2269 }
7e7d56d9 2270 bs = blk_bs(blk);
9699bf0d 2271
43526ec8 2272 bdrv_query_image_info(bs, &info, &err);
84d18f06 2273 if (err) {
565f65d2 2274 error_report_err(err);
26f54e9a 2275 blk_unref(blk);
43526ec8 2276 goto err;
fb0ed453 2277 }
9699bf0d
SH
2278
2279 elem = g_new0(ImageInfoList, 1);
2280 elem->value = info;
2281 *last = elem;
2282 last = &elem->next;
2283
26f54e9a 2284 blk_unref(blk);
9699bf0d
SH
2285
2286 filename = fmt = NULL;
2287 if (chain) {
2288 if (info->has_full_backing_filename) {
2289 filename = info->full_backing_filename;
2290 } else if (info->has_backing_filename) {
92d617ab
JS
2291 error_report("Could not determine absolute backing filename,"
2292 " but backing filename '%s' present",
2293 info->backing_filename);
2294 goto err;
9699bf0d
SH
2295 }
2296 if (info->has_backing_filename_format) {
2297 fmt = info->backing_filename_format;
2298 }
2299 }
2300 }
2301 g_hash_table_destroy(filenames);
2302 return head;
2303
2304err:
2305 qapi_free_ImageInfoList(head);
2306 g_hash_table_destroy(filenames);
2307 return NULL;
2308}
2309
c054b3fd
BC
2310static int img_info(int argc, char **argv)
2311{
2312 int c;
2313 OutputFormat output_format = OFORMAT_HUMAN;
9699bf0d 2314 bool chain = false;
c054b3fd 2315 const char *filename, *fmt, *output;
9699bf0d 2316 ImageInfoList *list;
eb769f74 2317 bool image_opts = false;
c054b3fd 2318
ea2384d3 2319 fmt = NULL;
c054b3fd 2320 output = NULL;
ea2384d3 2321 for(;;) {
c054b3fd
BC
2322 int option_index = 0;
2323 static const struct option long_options[] = {
2324 {"help", no_argument, 0, 'h'},
2325 {"format", required_argument, 0, 'f'},
2326 {"output", required_argument, 0, OPTION_OUTPUT},
9699bf0d 2327 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
3babeb15 2328 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2329 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
c054b3fd
BC
2330 {0, 0, 0, 0}
2331 };
2332 c = getopt_long(argc, argv, "f:h",
2333 long_options, &option_index);
b8fb60da 2334 if (c == -1) {
ea2384d3 2335 break;
b8fb60da 2336 }
ea2384d3 2337 switch(c) {
ef87394c 2338 case '?':
ea2384d3
FB
2339 case 'h':
2340 help();
2341 break;
2342 case 'f':
2343 fmt = optarg;
2344 break;
c054b3fd
BC
2345 case OPTION_OUTPUT:
2346 output = optarg;
2347 break;
9699bf0d
SH
2348 case OPTION_BACKING_CHAIN:
2349 chain = true;
2350 break;
3babeb15
DB
2351 case OPTION_OBJECT: {
2352 QemuOpts *opts;
2353 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2354 optarg, true);
2355 if (!opts) {
2356 return 1;
2357 }
2358 } break;
eb769f74
DB
2359 case OPTION_IMAGE_OPTS:
2360 image_opts = true;
2361 break;
ea2384d3
FB
2362 }
2363 }
fc11eb26 2364 if (optind != argc - 1) {
ac1307ab 2365 error_exit("Expecting one image file name");
b8fb60da 2366 }
ea2384d3
FB
2367 filename = argv[optind++];
2368
c054b3fd
BC
2369 if (output && !strcmp(output, "json")) {
2370 output_format = OFORMAT_JSON;
2371 } else if (output && !strcmp(output, "human")) {
2372 output_format = OFORMAT_HUMAN;
2373 } else if (output) {
2374 error_report("--output must be used with human or json as argument.");
c2abccec
MK
2375 return 1;
2376 }
c054b3fd 2377
3babeb15
DB
2378 if (qemu_opts_foreach(&qemu_object_opts,
2379 user_creatable_add_opts_foreach,
51b9b478 2380 NULL, NULL)) {
3babeb15
DB
2381 return 1;
2382 }
2383
eb769f74 2384 list = collect_image_info_list(image_opts, filename, fmt, chain);
9699bf0d 2385 if (!list) {
c2abccec 2386 return 1;
faea38e7 2387 }
c054b3fd 2388
c054b3fd
BC
2389 switch (output_format) {
2390 case OFORMAT_HUMAN:
9699bf0d 2391 dump_human_image_info_list(list);
c054b3fd
BC
2392 break;
2393 case OFORMAT_JSON:
9699bf0d
SH
2394 if (chain) {
2395 dump_json_image_info_list(list);
2396 } else {
2397 dump_json_image_info(list->value);
2398 }
c054b3fd 2399 break;
faea38e7 2400 }
c054b3fd 2401
9699bf0d 2402 qapi_free_ImageInfoList(list);
ea2384d3
FB
2403 return 0;
2404}
2405
4c93a13b
PB
2406static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2407 MapEntry *next)
2408{
2409 switch (output_format) {
2410 case OFORMAT_HUMAN:
16b0d555 2411 if (e->data && !e->has_offset) {
4c93a13b
PB
2412 error_report("File contains external, encrypted or compressed clusters.");
2413 exit(1);
2414 }
16b0d555 2415 if (e->data && !e->zero) {
4c93a13b 2416 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
16b0d555
FZ
2417 e->start, e->length,
2418 e->has_offset ? e->offset : 0,
2419 e->has_filename ? e->filename : "");
4c93a13b
PB
2420 }
2421 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2422 * Modify the flags here to allow more coalescing.
2423 */
16b0d555
FZ
2424 if (next && (!next->data || next->zero)) {
2425 next->data = false;
2426 next->zero = true;
4c93a13b
PB
2427 }
2428 break;
2429 case OFORMAT_JSON:
16b0d555
FZ
2430 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2431 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
4c93a13b
PB
2432 (e->start == 0 ? "[" : ",\n"),
2433 e->start, e->length, e->depth,
16b0d555
FZ
2434 e->zero ? "true" : "false",
2435 e->data ? "true" : "false");
2436 if (e->has_offset) {
c745bfb4 2437 printf(", \"offset\": %"PRId64"", e->offset);
4c93a13b
PB
2438 }
2439 putchar('}');
2440
2441 if (!next) {
2442 printf("]\n");
2443 }
2444 break;
2445 }
2446}
2447
2448static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2449 int nb_sectors, MapEntry *e)
2450{
2451 int64_t ret;
2452 int depth;
67a0fd2a 2453 BlockDriverState *file;
2875645b 2454 bool has_offset;
4c93a13b
PB
2455
2456 /* As an optimization, we could cache the current range of unallocated
2457 * clusters in each file of the chain, and avoid querying the same
2458 * range repeatedly.
2459 */
2460
2461 depth = 0;
2462 for (;;) {
67a0fd2a
FZ
2463 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2464 &file);
4c93a13b
PB
2465 if (ret < 0) {
2466 return ret;
2467 }
2468 assert(nb_sectors);
2469 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2470 break;
2471 }
760e0063 2472 bs = backing_bs(bs);
4c93a13b
PB
2473 if (bs == NULL) {
2474 ret = 0;
2475 break;
2476 }
2477
2478 depth++;
2479 }
2480
2875645b
JS
2481 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2482
2483 *e = (MapEntry) {
2484 .start = sector_num * BDRV_SECTOR_SIZE,
2485 .length = nb_sectors * BDRV_SECTOR_SIZE,
2486 .data = !!(ret & BDRV_BLOCK_DATA),
2487 .zero = !!(ret & BDRV_BLOCK_ZERO),
2488 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2489 .has_offset = has_offset,
2490 .depth = depth,
2491 .has_filename = file && has_offset,
2492 .filename = file && has_offset ? file->filename : NULL,
2493 };
2494
4c93a13b
PB
2495 return 0;
2496}
2497
16b0d555
FZ
2498static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2499{
2500 if (curr->length == 0) {
2501 return false;
2502 }
2503 if (curr->zero != next->zero ||
2504 curr->data != next->data ||
2505 curr->depth != next->depth ||
2506 curr->has_filename != next->has_filename ||
2507 curr->has_offset != next->has_offset) {
2508 return false;
2509 }
2510 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2511 return false;
2512 }
2513 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2514 return false;
2515 }
2516 return true;
2517}
2518
4c93a13b
PB
2519static int img_map(int argc, char **argv)
2520{
2521 int c;
2522 OutputFormat output_format = OFORMAT_HUMAN;
26f54e9a 2523 BlockBackend *blk;
4c93a13b
PB
2524 BlockDriverState *bs;
2525 const char *filename, *fmt, *output;
2526 int64_t length;
2527 MapEntry curr = { .length = 0 }, next;
2528 int ret = 0;
eb769f74 2529 bool image_opts = false;
4c93a13b
PB
2530
2531 fmt = NULL;
2532 output = NULL;
2533 for (;;) {
2534 int option_index = 0;
2535 static const struct option long_options[] = {
2536 {"help", no_argument, 0, 'h'},
2537 {"format", required_argument, 0, 'f'},
2538 {"output", required_argument, 0, OPTION_OUTPUT},
3babeb15 2539 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2540 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4c93a13b
PB
2541 {0, 0, 0, 0}
2542 };
2543 c = getopt_long(argc, argv, "f:h",
2544 long_options, &option_index);
2545 if (c == -1) {
2546 break;
2547 }
2548 switch (c) {
2549 case '?':
2550 case 'h':
2551 help();
2552 break;
2553 case 'f':
2554 fmt = optarg;
2555 break;
2556 case OPTION_OUTPUT:
2557 output = optarg;
2558 break;
3babeb15
DB
2559 case OPTION_OBJECT: {
2560 QemuOpts *opts;
2561 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2562 optarg, true);
2563 if (!opts) {
2564 return 1;
2565 }
2566 } break;
eb769f74
DB
2567 case OPTION_IMAGE_OPTS:
2568 image_opts = true;
2569 break;
4c93a13b
PB
2570 }
2571 }
ac1307ab
FZ
2572 if (optind != argc - 1) {
2573 error_exit("Expecting one image file name");
4c93a13b 2574 }
ac1307ab 2575 filename = argv[optind];
4c93a13b
PB
2576
2577 if (output && !strcmp(output, "json")) {
2578 output_format = OFORMAT_JSON;
2579 } else if (output && !strcmp(output, "human")) {
2580 output_format = OFORMAT_HUMAN;
2581 } else if (output) {
2582 error_report("--output must be used with human or json as argument.");
2583 return 1;
2584 }
2585
3babeb15
DB
2586 if (qemu_opts_foreach(&qemu_object_opts,
2587 user_creatable_add_opts_foreach,
51b9b478 2588 NULL, NULL)) {
3babeb15
DB
2589 return 1;
2590 }
2591
ce099547 2592 blk = img_open(image_opts, filename, fmt, 0, false, false);
7e7d56d9
MA
2593 if (!blk) {
2594 return 1;
4c93a13b 2595 }
7e7d56d9 2596 bs = blk_bs(blk);
4c93a13b
PB
2597
2598 if (output_format == OFORMAT_HUMAN) {
2599 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2600 }
2601
f1d3cd79 2602 length = blk_getlength(blk);
4c93a13b
PB
2603 while (curr.start + curr.length < length) {
2604 int64_t nsectors_left;
2605 int64_t sector_num;
2606 int n;
2607
2608 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2609
2610 /* Probe up to 1 GiB at a time. */
2611 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2612 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2613 ret = get_block_status(bs, sector_num, n, &next);
2614
2615 if (ret < 0) {
2616 error_report("Could not read file metadata: %s", strerror(-ret));
2617 goto out;
2618 }
2619
16b0d555 2620 if (entry_mergeable(&curr, &next)) {
4c93a13b
PB
2621 curr.length += next.length;
2622 continue;
2623 }
2624
2625 if (curr.length > 0) {
2626 dump_map_entry(output_format, &curr, &next);
2627 }
2628 curr = next;
2629 }
2630
2631 dump_map_entry(output_format, &curr, NULL);
2632
2633out:
26f54e9a 2634 blk_unref(blk);
4c93a13b
PB
2635 return ret < 0;
2636}
2637
f7b4a940
AL
2638#define SNAPSHOT_LIST 1
2639#define SNAPSHOT_CREATE 2
2640#define SNAPSHOT_APPLY 3
2641#define SNAPSHOT_DELETE 4
2642
153859be 2643static int img_snapshot(int argc, char **argv)
f7b4a940 2644{
26f54e9a 2645 BlockBackend *blk;
f7b4a940
AL
2646 BlockDriverState *bs;
2647 QEMUSnapshotInfo sn;
2648 char *filename, *snapshot_name = NULL;
c2abccec 2649 int c, ret = 0, bdrv_oflags;
f7b4a940
AL
2650 int action = 0;
2651 qemu_timeval tv;
f382d43a 2652 bool quiet = false;
a89d89d3 2653 Error *err = NULL;
eb769f74 2654 bool image_opts = false;
f7b4a940 2655
ce099547 2656 bdrv_oflags = BDRV_O_RDWR;
f7b4a940
AL
2657 /* Parse commandline parameters */
2658 for(;;) {
3babeb15
DB
2659 static const struct option long_options[] = {
2660 {"help", no_argument, 0, 'h'},
2661 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2662 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2663 {0, 0, 0, 0}
2664 };
2665 c = getopt_long(argc, argv, "la:c:d:hq",
2666 long_options, NULL);
b8fb60da 2667 if (c == -1) {
f7b4a940 2668 break;
b8fb60da 2669 }
f7b4a940 2670 switch(c) {
ef87394c 2671 case '?':
f7b4a940
AL
2672 case 'h':
2673 help();
153859be 2674 return 0;
f7b4a940
AL
2675 case 'l':
2676 if (action) {
ac1307ab 2677 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2678 return 0;
f7b4a940
AL
2679 }
2680 action = SNAPSHOT_LIST;
f5edb014 2681 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
f7b4a940
AL
2682 break;
2683 case 'a':
2684 if (action) {
ac1307ab 2685 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2686 return 0;
f7b4a940
AL
2687 }
2688 action = SNAPSHOT_APPLY;
2689 snapshot_name = optarg;
2690 break;
2691 case 'c':
2692 if (action) {
ac1307ab 2693 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2694 return 0;
f7b4a940
AL
2695 }
2696 action = SNAPSHOT_CREATE;
2697 snapshot_name = optarg;
2698 break;
2699 case 'd':
2700 if (action) {
ac1307ab 2701 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
153859be 2702 return 0;
f7b4a940
AL
2703 }
2704 action = SNAPSHOT_DELETE;
2705 snapshot_name = optarg;
2706 break;
f382d43a
MR
2707 case 'q':
2708 quiet = true;
2709 break;
3babeb15
DB
2710 case OPTION_OBJECT: {
2711 QemuOpts *opts;
2712 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2713 optarg, true);
2714 if (!opts) {
2715 return 1;
2716 }
2717 } break;
eb769f74
DB
2718 case OPTION_IMAGE_OPTS:
2719 image_opts = true;
2720 break;
f7b4a940
AL
2721 }
2722 }
2723
fc11eb26 2724 if (optind != argc - 1) {
ac1307ab 2725 error_exit("Expecting one image file name");
b8fb60da 2726 }
f7b4a940
AL
2727 filename = argv[optind++];
2728
3babeb15
DB
2729 if (qemu_opts_foreach(&qemu_object_opts,
2730 user_creatable_add_opts_foreach,
51b9b478 2731 NULL, NULL)) {
3babeb15
DB
2732 return 1;
2733 }
2734
f7b4a940 2735 /* Open the image */
ce099547 2736 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
7e7d56d9
MA
2737 if (!blk) {
2738 return 1;
c2abccec 2739 }
7e7d56d9 2740 bs = blk_bs(blk);
f7b4a940
AL
2741
2742 /* Perform the requested action */
2743 switch(action) {
2744 case SNAPSHOT_LIST:
2745 dump_snapshots(bs);
2746 break;
2747
2748 case SNAPSHOT_CREATE:
2749 memset(&sn, 0, sizeof(sn));
2750 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2751
2752 qemu_gettimeofday(&tv);
2753 sn.date_sec = tv.tv_sec;
2754 sn.date_nsec = tv.tv_usec * 1000;
2755
2756 ret = bdrv_snapshot_create(bs, &sn);
b8fb60da 2757 if (ret) {
15654a6d 2758 error_report("Could not create snapshot '%s': %d (%s)",
f7b4a940 2759 snapshot_name, ret, strerror(-ret));
b8fb60da 2760 }
f7b4a940
AL
2761 break;
2762
2763 case SNAPSHOT_APPLY:
2764 ret = bdrv_snapshot_goto(bs, snapshot_name);
b8fb60da 2765 if (ret) {
15654a6d 2766 error_report("Could not apply snapshot '%s': %d (%s)",
f7b4a940 2767 snapshot_name, ret, strerror(-ret));
b8fb60da 2768 }
f7b4a940
AL
2769 break;
2770
2771 case SNAPSHOT_DELETE:
a89d89d3 2772 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
84d18f06 2773 if (err) {
c29b77f9
MA
2774 error_reportf_err(err, "Could not delete snapshot '%s': ",
2775 snapshot_name);
a89d89d3 2776 ret = 1;
b8fb60da 2777 }
f7b4a940
AL
2778 break;
2779 }
2780
2781 /* Cleanup */
26f54e9a 2782 blk_unref(blk);
c2abccec
MK
2783 if (ret) {
2784 return 1;
2785 }
153859be 2786 return 0;
f7b4a940
AL
2787}
2788
3e85c6fd
KW
2789static int img_rebase(int argc, char **argv)
2790{
26f54e9a 2791 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
396374ca
PB
2792 uint8_t *buf_old = NULL;
2793 uint8_t *buf_new = NULL;
f1d3cd79 2794 BlockDriverState *bs = NULL;
3e85c6fd 2795 char *filename;
40055951
HR
2796 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2797 int c, flags, src_flags, ret;
ce099547 2798 bool writethrough, src_writethrough;
3e85c6fd 2799 int unsafe = 0;
6b837bc4 2800 int progress = 0;
f382d43a 2801 bool quiet = false;
34b5d2c6 2802 Error *local_err = NULL;
eb769f74 2803 bool image_opts = false;
3e85c6fd
KW
2804
2805 /* Parse commandline parameters */
e53dbee0 2806 fmt = NULL;
661a0f71 2807 cache = BDRV_DEFAULT_CACHE;
40055951 2808 src_cache = BDRV_DEFAULT_CACHE;
3e85c6fd
KW
2809 out_baseimg = NULL;
2810 out_basefmt = NULL;
3e85c6fd 2811 for(;;) {
3babeb15
DB
2812 static const struct option long_options[] = {
2813 {"help", no_argument, 0, 'h'},
2814 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 2815 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
2816 {0, 0, 0, 0}
2817 };
2818 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2819 long_options, NULL);
b8fb60da 2820 if (c == -1) {
3e85c6fd 2821 break;
b8fb60da 2822 }
3e85c6fd 2823 switch(c) {
ef87394c 2824 case '?':
3e85c6fd
KW
2825 case 'h':
2826 help();
2827 return 0;
e53dbee0
KW
2828 case 'f':
2829 fmt = optarg;
2830 break;
3e85c6fd
KW
2831 case 'F':
2832 out_basefmt = optarg;
2833 break;
2834 case 'b':
2835 out_baseimg = optarg;
2836 break;
2837 case 'u':
2838 unsafe = 1;
2839 break;
6b837bc4
JS
2840 case 'p':
2841 progress = 1;
2842 break;
661a0f71
FS
2843 case 't':
2844 cache = optarg;
2845 break;
40055951
HR
2846 case 'T':
2847 src_cache = optarg;
2848 break;
f382d43a
MR
2849 case 'q':
2850 quiet = true;
2851 break;
3babeb15
DB
2852 case OPTION_OBJECT: {
2853 QemuOpts *opts;
2854 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2855 optarg, true);
2856 if (!opts) {
2857 return 1;
2858 }
2859 } break;
eb769f74
DB
2860 case OPTION_IMAGE_OPTS:
2861 image_opts = true;
2862 break;
3e85c6fd
KW
2863 }
2864 }
2865
f382d43a
MR
2866 if (quiet) {
2867 progress = 0;
2868 }
2869
ac1307ab
FZ
2870 if (optind != argc - 1) {
2871 error_exit("Expecting one image file name");
2872 }
2873 if (!unsafe && !out_baseimg) {
2874 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
b8fb60da 2875 }
3e85c6fd
KW
2876 filename = argv[optind++];
2877
3babeb15
DB
2878 if (qemu_opts_foreach(&qemu_object_opts,
2879 user_creatable_add_opts_foreach,
51b9b478 2880 NULL, NULL)) {
3babeb15
DB
2881 return 1;
2882 }
2883
6b837bc4
JS
2884 qemu_progress_init(progress, 2.0);
2885 qemu_progress_print(0, 100);
2886
661a0f71 2887 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
ce099547 2888 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
661a0f71
FS
2889 if (ret < 0) {
2890 error_report("Invalid cache option: %s", cache);
40ed35a3 2891 goto out;
661a0f71
FS
2892 }
2893
ce099547
KW
2894 src_flags = 0;
2895 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
40055951
HR
2896 if (ret < 0) {
2897 error_report("Invalid source cache option: %s", src_cache);
40ed35a3 2898 goto out;
40055951
HR
2899 }
2900
ce099547
KW
2901 /* The source files are opened read-only, don't care about WCE */
2902 assert((src_flags & BDRV_O_RDWR) == 0);
2903 (void) src_writethrough;
2904
3e85c6fd
KW
2905 /*
2906 * Open the images.
2907 *
2908 * Ignore the old backing file for unsafe rebase in case we want to correct
2909 * the reference to a renamed or moved backing file.
2910 */
ce099547 2911 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 2912 if (!blk) {
40ed35a3
SH
2913 ret = -1;
2914 goto out;
c2abccec 2915 }
7e7d56d9 2916 bs = blk_bs(blk);
3e85c6fd 2917
3e85c6fd 2918 if (out_basefmt != NULL) {
644483d9 2919 if (bdrv_find_format(out_basefmt) == NULL) {
15654a6d 2920 error_report("Invalid format name: '%s'", out_basefmt);
c2abccec
MK
2921 ret = -1;
2922 goto out;
3e85c6fd
KW
2923 }
2924 }
2925
2926 /* For safe rebasing we need to compare old and new backing file */
40ed35a3 2927 if (!unsafe) {
9a29e18f 2928 char backing_name[PATH_MAX];
644483d9
HR
2929 QDict *options = NULL;
2930
2931 if (bs->backing_format[0] != '\0') {
2932 options = qdict_new();
2933 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2934 }
3e85c6fd 2935
3e85c6fd 2936 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
efaa7c4e 2937 blk_old_backing = blk_new_open(backing_name, NULL,
644483d9
HR
2938 options, src_flags, &local_err);
2939 if (!blk_old_backing) {
c29b77f9
MA
2940 error_reportf_err(local_err,
2941 "Could not open old backing file '%s': ",
2942 backing_name);
c2abccec 2943 goto out;
3e85c6fd 2944 }
644483d9 2945
a616673d 2946 if (out_baseimg[0]) {
644483d9
HR
2947 if (out_basefmt) {
2948 options = qdict_new();
2949 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2950 } else {
2951 options = NULL;
2952 }
2953
efaa7c4e 2954 blk_new_backing = blk_new_open(out_baseimg, NULL,
644483d9
HR
2955 options, src_flags, &local_err);
2956 if (!blk_new_backing) {
c29b77f9
MA
2957 error_reportf_err(local_err,
2958 "Could not open new backing file '%s': ",
2959 out_baseimg);
a616673d
AB
2960 goto out;
2961 }
3e85c6fd
KW
2962 }
2963 }
2964
2965 /*
2966 * Check each unallocated cluster in the COW file. If it is unallocated,
2967 * accesses go to the backing file. We must therefore compare this cluster
2968 * in the old and new backing file, and if they differ we need to copy it
2969 * from the old backing file into the COW file.
2970 *
2971 * If qemu-img crashes during this step, no harm is done. The content of
2972 * the image is the same as the original one at any time.
2973 */
2974 if (!unsafe) {
52bf1e72
MA
2975 int64_t num_sectors;
2976 int64_t old_backing_num_sectors;
2977 int64_t new_backing_num_sectors = 0;
3e85c6fd 2978 uint64_t sector;
cc60e327 2979 int n;
1f710495 2980 float local_progress = 0;
d6771bfa 2981
f1d3cd79
HR
2982 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
2983 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
3e85c6fd 2984
f1d3cd79 2985 num_sectors = blk_nb_sectors(blk);
52bf1e72
MA
2986 if (num_sectors < 0) {
2987 error_report("Could not get size of '%s': %s",
2988 filename, strerror(-num_sectors));
2989 ret = -1;
2990 goto out;
2991 }
f1d3cd79 2992 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
52bf1e72 2993 if (old_backing_num_sectors < 0) {
9a29e18f 2994 char backing_name[PATH_MAX];
52bf1e72
MA
2995
2996 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
2997 error_report("Could not get size of '%s': %s",
2998 backing_name, strerror(-old_backing_num_sectors));
2999 ret = -1;
3000 goto out;
3001 }
f1d3cd79
HR
3002 if (blk_new_backing) {
3003 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
52bf1e72
MA
3004 if (new_backing_num_sectors < 0) {
3005 error_report("Could not get size of '%s': %s",
3006 out_baseimg, strerror(-new_backing_num_sectors));
3007 ret = -1;
3008 goto out;
3009 }
a616673d 3010 }
3e85c6fd 3011
1f710495
KW
3012 if (num_sectors != 0) {
3013 local_progress = (float)100 /
3014 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3015 }
3016
3e85c6fd
KW
3017 for (sector = 0; sector < num_sectors; sector += n) {
3018
3019 /* How many sectors can we handle with the next read? */
3020 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3021 n = (IO_BUF_SIZE / 512);
3022 } else {
3023 n = num_sectors - sector;
3024 }
3025
3026 /* If the cluster is allocated, we don't need to take action */
cc60e327 3027 ret = bdrv_is_allocated(bs, sector, n, &n);
d663640c
PB
3028 if (ret < 0) {
3029 error_report("error while reading image metadata: %s",
3030 strerror(-ret));
3031 goto out;
3032 }
cc60e327 3033 if (ret) {
3e85c6fd
KW
3034 continue;
3035 }
3036
87a1b3e3
KW
3037 /*
3038 * Read old and new backing file and take into consideration that
3039 * backing files may be smaller than the COW image.
3040 */
3041 if (sector >= old_backing_num_sectors) {
3042 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3043 } else {
3044 if (sector + n > old_backing_num_sectors) {
3045 n = old_backing_num_sectors - sector;
3046 }
3047
9166920a
EB
3048 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3049 buf_old, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3050 if (ret < 0) {
3051 error_report("error while reading from old backing file");
3052 goto out;
3053 }
3e85c6fd 3054 }
87a1b3e3 3055
f1d3cd79 3056 if (sector >= new_backing_num_sectors || !blk_new_backing) {
87a1b3e3
KW
3057 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3058 } else {
3059 if (sector + n > new_backing_num_sectors) {
3060 n = new_backing_num_sectors - sector;
3061 }
3062
9166920a
EB
3063 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3064 buf_new, n << BDRV_SECTOR_BITS);
87a1b3e3
KW
3065 if (ret < 0) {
3066 error_report("error while reading from new backing file");
3067 goto out;
3068 }
3e85c6fd
KW
3069 }
3070
3071 /* If they differ, we need to write to the COW file */
3072 uint64_t written = 0;
3073
3074 while (written < n) {
3075 int pnum;
3076
3077 if (compare_sectors(buf_old + written * 512,
60b1bd4f 3078 buf_new + written * 512, n - written, &pnum))
3e85c6fd 3079 {
9166920a
EB
3080 ret = blk_pwrite(blk,
3081 (sector + written) << BDRV_SECTOR_BITS,
3082 buf_old + written * 512,
3083 pnum << BDRV_SECTOR_BITS, 0);
3e85c6fd 3084 if (ret < 0) {
15654a6d 3085 error_report("Error while writing to COW image: %s",
3e85c6fd 3086 strerror(-ret));
c2abccec 3087 goto out;
3e85c6fd
KW
3088 }
3089 }
3090
3091 written += pnum;
3092 }
6b837bc4 3093 qemu_progress_print(local_progress, 100);
3e85c6fd
KW
3094 }
3095 }
3096
3097 /*
3098 * Change the backing file. All clusters that are different from the old
3099 * backing file are overwritten in the COW file now, so the visible content
3100 * doesn't change when we switch the backing file.
3101 */
a616673d
AB
3102 if (out_baseimg && *out_baseimg) {
3103 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3104 } else {
3105 ret = bdrv_change_backing_file(bs, NULL, NULL);
3106 }
3107
3e85c6fd 3108 if (ret == -ENOSPC) {
15654a6d
JS
3109 error_report("Could not change the backing file to '%s': No "
3110 "space left in the file header", out_baseimg);
3e85c6fd 3111 } else if (ret < 0) {
15654a6d 3112 error_report("Could not change the backing file to '%s': %s",
3e85c6fd
KW
3113 out_baseimg, strerror(-ret));
3114 }
3115
6b837bc4 3116 qemu_progress_print(100, 0);
3e85c6fd
KW
3117 /*
3118 * TODO At this point it is possible to check if any clusters that are
3119 * allocated in the COW file are the same in the backing file. If so, they
3120 * could be dropped from the COW file. Don't do this before switching the
3121 * backing file, in case of a crash this would lead to corruption.
3122 */
c2abccec 3123out:
6b837bc4 3124 qemu_progress_end();
3e85c6fd
KW
3125 /* Cleanup */
3126 if (!unsafe) {
26f54e9a 3127 blk_unref(blk_old_backing);
26f54e9a 3128 blk_unref(blk_new_backing);
3e85c6fd 3129 }
396374ca
PB
3130 qemu_vfree(buf_old);
3131 qemu_vfree(buf_new);
3e85c6fd 3132
26f54e9a 3133 blk_unref(blk);
c2abccec
MK
3134 if (ret) {
3135 return 1;
3136 }
3e85c6fd
KW
3137 return 0;
3138}
3139
ae6b0ed6
SH
3140static int img_resize(int argc, char **argv)
3141{
6750e795 3142 Error *err = NULL;
ae6b0ed6
SH
3143 int c, ret, relative;
3144 const char *filename, *fmt, *size;
3145 int64_t n, total_size;
f382d43a 3146 bool quiet = false;
26f54e9a 3147 BlockBackend *blk = NULL;
20caf0f7 3148 QemuOpts *param;
3babeb15 3149
20caf0f7
DXW
3150 static QemuOptsList resize_options = {
3151 .name = "resize_options",
3152 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3153 .desc = {
3154 {
3155 .name = BLOCK_OPT_SIZE,
3156 .type = QEMU_OPT_SIZE,
3157 .help = "Virtual disk size"
3158 }, {
3159 /* end of list */
3160 }
ae6b0ed6 3161 },
ae6b0ed6 3162 };
eb769f74 3163 bool image_opts = false;
ae6b0ed6 3164
e80fec7f
KW
3165 /* Remove size from argv manually so that negative numbers are not treated
3166 * as options by getopt. */
3167 if (argc < 3) {
ac1307ab 3168 error_exit("Not enough arguments");
e80fec7f
KW
3169 return 1;
3170 }
3171
3172 size = argv[--argc];
3173
3174 /* Parse getopt arguments */
ae6b0ed6
SH
3175 fmt = NULL;
3176 for(;;) {
3babeb15
DB
3177 static const struct option long_options[] = {
3178 {"help", no_argument, 0, 'h'},
3179 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3180 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3181 {0, 0, 0, 0}
3182 };
3183 c = getopt_long(argc, argv, "f:hq",
3184 long_options, NULL);
ae6b0ed6
SH
3185 if (c == -1) {
3186 break;
3187 }
3188 switch(c) {
ef87394c 3189 case '?':
ae6b0ed6
SH
3190 case 'h':
3191 help();
3192 break;
3193 case 'f':
3194 fmt = optarg;
3195 break;
f382d43a
MR
3196 case 'q':
3197 quiet = true;
3198 break;
3babeb15
DB
3199 case OPTION_OBJECT: {
3200 QemuOpts *opts;
3201 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3202 optarg, true);
3203 if (!opts) {
3204 return 1;
3205 }
3206 } break;
eb769f74
DB
3207 case OPTION_IMAGE_OPTS:
3208 image_opts = true;
3209 break;
ae6b0ed6
SH
3210 }
3211 }
fc11eb26 3212 if (optind != argc - 1) {
ac1307ab 3213 error_exit("Expecting one image file name");
ae6b0ed6
SH
3214 }
3215 filename = argv[optind++];
ae6b0ed6 3216
3babeb15
DB
3217 if (qemu_opts_foreach(&qemu_object_opts,
3218 user_creatable_add_opts_foreach,
51b9b478 3219 NULL, NULL)) {
3babeb15
DB
3220 return 1;
3221 }
3222
ae6b0ed6
SH
3223 /* Choose grow, shrink, or absolute resize mode */
3224 switch (size[0]) {
3225 case '+':
3226 relative = 1;
3227 size++;
3228 break;
3229 case '-':
3230 relative = -1;
3231 size++;
3232 break;
3233 default:
3234 relative = 0;
3235 break;
3236 }
3237
3238 /* Parse size */
87ea75d5 3239 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
f43e47db 3240 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
6750e795
MA
3241 if (err) {
3242 error_report_err(err);
2a81998a 3243 ret = -1;
20caf0f7 3244 qemu_opts_del(param);
2a81998a 3245 goto out;
ae6b0ed6 3246 }
20caf0f7
DXW
3247 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3248 qemu_opts_del(param);
ae6b0ed6 3249
efaa7c4e 3250 blk = img_open(image_opts, filename, fmt,
ce099547 3251 BDRV_O_RDWR, false, quiet);
7e7d56d9 3252 if (!blk) {
2a81998a
JS
3253 ret = -1;
3254 goto out;
c2abccec 3255 }
ae6b0ed6
SH
3256
3257 if (relative) {
f1d3cd79 3258 total_size = blk_getlength(blk) + n * relative;
ae6b0ed6
SH
3259 } else {
3260 total_size = n;
3261 }
3262 if (total_size <= 0) {
15654a6d 3263 error_report("New image size must be positive");
c2abccec
MK
3264 ret = -1;
3265 goto out;
ae6b0ed6
SH
3266 }
3267
f1d3cd79 3268 ret = blk_truncate(blk, total_size);
ae6b0ed6
SH
3269 switch (ret) {
3270 case 0:
f382d43a 3271 qprintf(quiet, "Image resized.\n");
ae6b0ed6
SH
3272 break;
3273 case -ENOTSUP:
259b2173 3274 error_report("This image does not support resize");
ae6b0ed6
SH
3275 break;
3276 case -EACCES:
15654a6d 3277 error_report("Image is read-only");
ae6b0ed6
SH
3278 break;
3279 default:
15654a6d 3280 error_report("Error resizing image (%d)", -ret);
ae6b0ed6
SH
3281 break;
3282 }
c2abccec 3283out:
26f54e9a 3284 blk_unref(blk);
c2abccec
MK
3285 if (ret) {
3286 return 1;
3287 }
ae6b0ed6
SH
3288 return 0;
3289}
3290
76a3a34d 3291static void amend_status_cb(BlockDriverState *bs,
8b13976d
HR
3292 int64_t offset, int64_t total_work_size,
3293 void *opaque)
76a3a34d
HR
3294{
3295 qemu_progress_print(100.f * offset / total_work_size, 0);
3296}
3297
6f176b48
HR
3298static int img_amend(int argc, char **argv)
3299{
dc523cd3 3300 Error *err = NULL;
6f176b48
HR
3301 int c, ret = 0;
3302 char *options = NULL;
83d0521a
CL
3303 QemuOptsList *create_opts = NULL;
3304 QemuOpts *opts = NULL;
bd39e6ed
HR
3305 const char *fmt = NULL, *filename, *cache;
3306 int flags;
ce099547 3307 bool writethrough;
76a3a34d 3308 bool quiet = false, progress = false;
26f54e9a 3309 BlockBackend *blk = NULL;
6f176b48 3310 BlockDriverState *bs = NULL;
eb769f74 3311 bool image_opts = false;
6f176b48 3312
bd39e6ed 3313 cache = BDRV_DEFAULT_CACHE;
6f176b48 3314 for (;;) {
3babeb15
DB
3315 static const struct option long_options[] = {
3316 {"help", no_argument, 0, 'h'},
3317 {"object", required_argument, 0, OPTION_OBJECT},
eb769f74 3318 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3babeb15
DB
3319 {0, 0, 0, 0}
3320 };
3321 c = getopt_long(argc, argv, "ho:f:t:pq",
3322 long_options, NULL);
6f176b48
HR
3323 if (c == -1) {
3324 break;
3325 }
3326
3327 switch (c) {
3328 case 'h':
3329 case '?':
3330 help();
3331 break;
3332 case 'o':
626f84f3
KW
3333 if (!is_valid_option_list(optarg)) {
3334 error_report("Invalid option list: %s", optarg);
3335 ret = -1;
e814dffc 3336 goto out_no_progress;
626f84f3
KW
3337 }
3338 if (!options) {
3339 options = g_strdup(optarg);
3340 } else {
3341 char *old_options = options;
3342 options = g_strdup_printf("%s,%s", options, optarg);
3343 g_free(old_options);
3344 }
6f176b48
HR
3345 break;
3346 case 'f':
3347 fmt = optarg;
3348 break;
bd39e6ed
HR
3349 case 't':
3350 cache = optarg;
3351 break;
76a3a34d
HR
3352 case 'p':
3353 progress = true;
3354 break;
6f176b48
HR
3355 case 'q':
3356 quiet = true;
3357 break;
3babeb15
DB
3358 case OPTION_OBJECT:
3359 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3360 optarg, true);
3361 if (!opts) {
3362 ret = -1;
3363 goto out_no_progress;
3364 }
3365 break;
eb769f74
DB
3366 case OPTION_IMAGE_OPTS:
3367 image_opts = true;
3368 break;
6f176b48
HR
3369 }
3370 }
3371
a283cb6e 3372 if (!options) {
ac1307ab 3373 error_exit("Must specify options (-o)");
6f176b48
HR
3374 }
3375
3babeb15
DB
3376 if (qemu_opts_foreach(&qemu_object_opts,
3377 user_creatable_add_opts_foreach,
51b9b478 3378 NULL, NULL)) {
3babeb15
DB
3379 ret = -1;
3380 goto out_no_progress;
3381 }
3382
76a3a34d
HR
3383 if (quiet) {
3384 progress = false;
3385 }
3386 qemu_progress_init(progress, 1.0);
3387
a283cb6e
KW
3388 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3389 if (fmt && has_help_option(options)) {
3390 /* If a format is explicitly specified (and possibly no filename is
3391 * given), print option help here */
3392 ret = print_block_option_help(filename, fmt);
3393 goto out;
6f176b48
HR
3394 }
3395
a283cb6e 3396 if (optind != argc - 1) {
b2f27e44
HR
3397 error_report("Expecting one image file name");
3398 ret = -1;
3399 goto out;
a283cb6e 3400 }
6f176b48 3401
ce099547
KW
3402 flags = BDRV_O_RDWR;
3403 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
bd39e6ed
HR
3404 if (ret < 0) {
3405 error_report("Invalid cache option: %s", cache);
3406 goto out;
3407 }
3408
ce099547 3409 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
7e7d56d9 3410 if (!blk) {
6f176b48
HR
3411 ret = -1;
3412 goto out;
3413 }
7e7d56d9 3414 bs = blk_bs(blk);
6f176b48
HR
3415
3416 fmt = bs->drv->format_name;
3417
626f84f3 3418 if (has_help_option(options)) {
a283cb6e 3419 /* If the format was auto-detected, print option help here */
6f176b48
HR
3420 ret = print_block_option_help(filename, fmt);
3421 goto out;
3422 }
3423
b2439d26
HR
3424 if (!bs->drv->create_opts) {
3425 error_report("Format driver '%s' does not support any options to amend",
3426 fmt);
3427 ret = -1;
3428 goto out;
3429 }
3430
c282e1fd 3431 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
83d0521a 3432 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
dc523cd3
MA
3433 if (options) {
3434 qemu_opts_do_parse(opts, options, NULL, &err);
3435 if (err) {
97a2ca7a 3436 error_report_err(err);
dc523cd3
MA
3437 ret = -1;
3438 goto out;
3439 }
6f176b48
HR
3440 }
3441
76a3a34d
HR
3442 /* In case the driver does not call amend_status_cb() */
3443 qemu_progress_print(0.f, 0);
8b13976d 3444 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
76a3a34d 3445 qemu_progress_print(100.f, 0);
6f176b48
HR
3446 if (ret < 0) {
3447 error_report("Error while amending options: %s", strerror(-ret));
3448 goto out;
3449 }
3450
3451out:
76a3a34d
HR
3452 qemu_progress_end();
3453
e814dffc 3454out_no_progress:
26f54e9a 3455 blk_unref(blk);
83d0521a
CL
3456 qemu_opts_del(opts);
3457 qemu_opts_free(create_opts);
626f84f3
KW
3458 g_free(options);
3459
6f176b48
HR
3460 if (ret) {
3461 return 1;
3462 }
3463 return 0;
3464}
3465
b6133b8c
KW
3466typedef struct BenchData {
3467 BlockBackend *blk;
3468 uint64_t image_size;
b6495fa8 3469 bool write;
b6133b8c 3470 int bufsize;
83de9be0 3471 int step;
b6133b8c
KW
3472 int nrreq;
3473 int n;
55d539c8
KW
3474 int flush_interval;
3475 bool drain_on_flush;
b6133b8c
KW
3476 uint8_t *buf;
3477 QEMUIOVector *qiov;
3478
3479 int in_flight;
55d539c8 3480 bool in_flush;
b6133b8c
KW
3481 uint64_t offset;
3482} BenchData;
3483
55d539c8
KW
3484static void bench_undrained_flush_cb(void *opaque, int ret)
3485{
3486 if (ret < 0) {
3487 error_report("Failed flush request: %s\n", strerror(-ret));
3488 exit(EXIT_FAILURE);
3489 }
3490}
3491
b6133b8c
KW
3492static void bench_cb(void *opaque, int ret)
3493{
3494 BenchData *b = opaque;
3495 BlockAIOCB *acb;
3496
3497 if (ret < 0) {
3498 error_report("Failed request: %s\n", strerror(-ret));
3499 exit(EXIT_FAILURE);
3500 }
55d539c8
KW
3501
3502 if (b->in_flush) {
3503 /* Just finished a flush with drained queue: Start next requests */
3504 assert(b->in_flight == 0);
3505 b->in_flush = false;
3506 } else if (b->in_flight > 0) {
3507 int remaining = b->n - b->in_flight;
3508
b6133b8c
KW
3509 b->n--;
3510 b->in_flight--;
55d539c8
KW
3511
3512 /* Time for flush? Drain queue if requested, then flush */
3513 if (b->flush_interval && remaining % b->flush_interval == 0) {
3514 if (!b->in_flight || !b->drain_on_flush) {
3515 BlockCompletionFunc *cb;
3516
3517 if (b->drain_on_flush) {
3518 b->in_flush = true;
3519 cb = bench_cb;
3520 } else {
3521 cb = bench_undrained_flush_cb;
3522 }
3523
3524 acb = blk_aio_flush(b->blk, cb, b);
3525 if (!acb) {
3526 error_report("Failed to issue flush request");
3527 exit(EXIT_FAILURE);
3528 }
3529 }
3530 if (b->drain_on_flush) {
3531 return;
3532 }
3533 }
b6133b8c
KW
3534 }
3535
3536 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
b6495fa8
KW
3537 if (b->write) {
3538 acb = blk_aio_pwritev(b->blk, b->offset, b->qiov, 0,
3539 bench_cb, b);
3540 } else {
3541 acb = blk_aio_preadv(b->blk, b->offset, b->qiov, 0,
3542 bench_cb, b);
3543 }
b6133b8c
KW
3544 if (!acb) {
3545 error_report("Failed to issue request");
3546 exit(EXIT_FAILURE);
3547 }
3548 b->in_flight++;
83de9be0 3549 b->offset += b->step;
b6133b8c
KW
3550 b->offset %= b->image_size;
3551 }
3552}
3553
3554static int img_bench(int argc, char **argv)
3555{
3556 int c, ret = 0;
3557 const char *fmt = NULL, *filename;
3558 bool quiet = false;
3559 bool image_opts = false;
b6495fa8 3560 bool is_write = false;
b6133b8c
KW
3561 int count = 75000;
3562 int depth = 64;
d3199a31 3563 int64_t offset = 0;
b6133b8c 3564 size_t bufsize = 4096;
b6495fa8 3565 int pattern = 0;
83de9be0 3566 size_t step = 0;
55d539c8
KW
3567 int flush_interval = 0;
3568 bool drain_on_flush = true;
b6133b8c
KW
3569 int64_t image_size;
3570 BlockBackend *blk = NULL;
3571 BenchData data = {};
3572 int flags = 0;
604e8613 3573 bool writethrough = false;
b6133b8c
KW
3574 struct timeval t1, t2;
3575 int i;
3576
3577 for (;;) {
3578 static const struct option long_options[] = {
3579 {"help", no_argument, 0, 'h'},
55d539c8 3580 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
b6133b8c 3581 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
b6495fa8 3582 {"pattern", required_argument, 0, OPTION_PATTERN},
55d539c8 3583 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
b6133b8c
KW
3584 {0, 0, 0, 0}
3585 };
83de9be0 3586 c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL);
b6133b8c
KW
3587 if (c == -1) {
3588 break;
3589 }
3590
3591 switch (c) {
3592 case 'h':
3593 case '?':
3594 help();
3595 break;
3596 case 'c':
3597 {
3598 char *end;
3599 errno = 0;
3600 count = strtoul(optarg, &end, 0);
3601 if (errno || *end || count > INT_MAX) {
3602 error_report("Invalid request count specified");
3603 return 1;
3604 }
3605 break;
3606 }
3607 case 'd':
3608 {
3609 char *end;
3610 errno = 0;
3611 depth = strtoul(optarg, &end, 0);
3612 if (errno || *end || depth > INT_MAX) {
3613 error_report("Invalid queue depth specified");
3614 return 1;
3615 }
3616 break;
3617 }
3618 case 'f':
3619 fmt = optarg;
3620 break;
3621 case 'n':
3622 flags |= BDRV_O_NATIVE_AIO;
3623 break;
d3199a31
KW
3624 case 'o':
3625 {
3626 char *end;
3627 errno = 0;
3628 offset = qemu_strtosz_suffix(optarg, &end,
3629 QEMU_STRTOSZ_DEFSUFFIX_B);
3630 if (offset < 0|| *end) {
3631 error_report("Invalid offset specified");
3632 return 1;
3633 }
3634 break;
3635 }
3636 break;
b6133b8c
KW
3637 case 'q':
3638 quiet = true;
3639 break;
3640 case 's':
3641 {
3642 int64_t sval;
3643 char *end;
3644
3645 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3646 if (sval < 0 || sval > INT_MAX || *end) {
3647 error_report("Invalid buffer size specified");
3648 return 1;
3649 }
3650
3651 bufsize = sval;
3652 break;
3653 }
83de9be0
KW
3654 case 'S':
3655 {
3656 int64_t sval;
3657 char *end;
3658
3659 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3660 if (sval < 0 || sval > INT_MAX || *end) {
3661 error_report("Invalid step size specified");
3662 return 1;
3663 }
3664
3665 step = sval;
3666 break;
3667 }
b6133b8c
KW
3668 case 't':
3669 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3670 if (ret < 0) {
3671 error_report("Invalid cache mode");
3672 ret = -1;
3673 goto out;
3674 }
3675 break;
b6495fa8
KW
3676 case 'w':
3677 flags |= BDRV_O_RDWR;
3678 is_write = true;
3679 break;
3680 case OPTION_PATTERN:
3681 {
3682 char *end;
3683 errno = 0;
3684 pattern = strtoul(optarg, &end, 0);
3685 if (errno || *end || pattern > 0xff) {
3686 error_report("Invalid pattern byte specified");
3687 return 1;
3688 }
3689 break;
3690 }
55d539c8
KW
3691 case OPTION_FLUSH_INTERVAL:
3692 {
3693 char *end;
3694 errno = 0;
3695 flush_interval = strtoul(optarg, &end, 0);
3696 if (errno || *end || flush_interval > INT_MAX) {
3697 error_report("Invalid flush interval specified");
3698 return 1;
3699 }
3700 break;
3701 }
3702 case OPTION_NO_DRAIN:
3703 drain_on_flush = false;
3704 break;
b6133b8c
KW
3705 case OPTION_IMAGE_OPTS:
3706 image_opts = true;
3707 break;
3708 }
3709 }
3710
3711 if (optind != argc - 1) {
3712 error_exit("Expecting one image file name");
3713 }
3714 filename = argv[argc - 1];
3715
55d539c8
KW
3716 if (!is_write && flush_interval) {
3717 error_report("--flush-interval is only available in write tests");
3718 ret = -1;
3719 goto out;
3720 }
3721 if (flush_interval && flush_interval < depth) {
3722 error_report("Flush interval can't be smaller than depth");
3723 ret = -1;
3724 goto out;
3725 }
3726
b6133b8c
KW
3727 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3728 if (!blk) {
3729 ret = -1;
3730 goto out;
3731 }
3732
3733 image_size = blk_getlength(blk);
3734 if (image_size < 0) {
3735 ret = image_size;
3736 goto out;
3737 }
3738
3739 data = (BenchData) {
55d539c8
KW
3740 .blk = blk,
3741 .image_size = image_size,
3742 .bufsize = bufsize,
3743 .step = step ?: bufsize,
3744 .nrreq = depth,
3745 .n = count,
3746 .offset = offset,
3747 .write = is_write,
3748 .flush_interval = flush_interval,
3749 .drain_on_flush = drain_on_flush,
b6133b8c 3750 };
d3199a31 3751 printf("Sending %d %s requests, %d bytes each, %d in parallel "
83de9be0 3752 "(starting at offset %" PRId64 ", step size %d)\n",
d3199a31 3753 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
83de9be0 3754 data.offset, data.step);
55d539c8
KW
3755 if (flush_interval) {
3756 printf("Sending flush every %d requests\n", flush_interval);
3757 }
b6133b8c
KW
3758
3759 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
b6495fa8
KW
3760 memset(data.buf, pattern, data.nrreq * data.bufsize);
3761
b6133b8c
KW
3762 data.qiov = g_new(QEMUIOVector, data.nrreq);
3763 for (i = 0; i < data.nrreq; i++) {
3764 qemu_iovec_init(&data.qiov[i], 1);
3765 qemu_iovec_add(&data.qiov[i],
3766 data.buf + i * data.bufsize, data.bufsize);
3767 }
3768
3769 gettimeofday(&t1, NULL);
3770 bench_cb(&data, 0);
3771
3772 while (data.n > 0) {
3773 main_loop_wait(false);
3774 }
3775 gettimeofday(&t2, NULL);
3776
3777 printf("Run completed in %3.3f seconds.\n",
3778 (t2.tv_sec - t1.tv_sec)
3779 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3780
3781out:
3782 qemu_vfree(data.buf);
3783 blk_unref(blk);
3784
3785 if (ret) {
3786 return 1;
3787 }
3788 return 0;
3789}
3790
3791
c227f099 3792static const img_cmd_t img_cmds[] = {
153859be
SB
3793#define DEF(option, callback, arg_string) \
3794 { option, callback },
3795#include "qemu-img-cmds.h"
3796#undef DEF
3797#undef GEN_DOCS
3798 { NULL, NULL, },
3799};
3800
ea2384d3
FB
3801int main(int argc, char **argv)
3802{
c227f099 3803 const img_cmd_t *cmd;
153859be 3804 const char *cmdname;
2f78e491 3805 Error *local_error = NULL;
7db1689c 3806 int c;
7db1689c
JC
3807 static const struct option long_options[] = {
3808 {"help", no_argument, 0, 'h'},
5f6979cb 3809 {"version", no_argument, 0, 'v'},
7db1689c
JC
3810 {0, 0, 0, 0}
3811 };
ea2384d3 3812
526eda14
MK
3813#ifdef CONFIG_POSIX
3814 signal(SIGPIPE, SIG_IGN);
3815#endif
3816
53f76e58 3817 error_set_progname(argv[0]);
10f5bff6 3818 qemu_init_exec_dir(argv[0]);
53f76e58 3819
2f78e491 3820 if (qemu_init_main_loop(&local_error)) {
565f65d2 3821 error_report_err(local_error);
2f78e491
CN
3822 exit(EXIT_FAILURE);
3823 }
3824
e8f2d272 3825 qcrypto_init(&error_fatal);
c2297088 3826
064097d9 3827 module_call_init(MODULE_INIT_QOM);
ea2384d3 3828 bdrv_init();
ac1307ab
FZ
3829 if (argc < 2) {
3830 error_exit("Not enough arguments");
3831 }
153859be 3832 cmdname = argv[1];
153859be 3833
3babeb15 3834 qemu_add_opts(&qemu_object_opts);
eb769f74 3835 qemu_add_opts(&qemu_source_opts);
3babeb15 3836
153859be 3837 /* find the command */
5f6979cb 3838 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
153859be 3839 if (!strcmp(cmdname, cmd->name)) {
7db1689c 3840 return cmd->handler(argc - 1, argv + 1);
153859be 3841 }
ea2384d3 3842 }
153859be 3843
5f6979cb 3844 c = getopt_long(argc, argv, "h", long_options, NULL);
7db1689c
JC
3845
3846 if (c == 'h') {
3847 help();
3848 }
5f6979cb
JC
3849 if (c == 'v') {
3850 printf(QEMU_IMG_VERSION);
3851 return 0;
3852 }
7db1689c 3853
153859be 3854 /* not found */
ac1307ab 3855 error_exit("Command not found: %s", cmdname);
ea2384d3 3856}