blob: 37d1afb83919cd41ce4534f947c6134ef3f053b8 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * 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 */
Peter Maydell80c71a22016-01-18 18:01:42 +000024#include "qemu/osdep.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080025#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010026#include "qapi/error.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020027#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010028#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010029#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010030#include "qapi/qmp/qjson.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020031#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000032#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010033#include "qemu/option.h"
34#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030035#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010037#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020038#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010039#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020040#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080041#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010042#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030043#include "trace/control.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020044#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000045
Don Slutz61979a62015-01-09 10:17:35 -050046#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020047 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040048
Anthony Liguoric227f092009-10-01 16:12:16 -050049typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010050 const char *name;
51 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050052} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010053
Federico Simoncelli8599ea42013-01-28 06:59:47 -050054enum {
55 OPTION_OUTPUT = 256,
56 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000057 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000058 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020059 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020060 OPTION_FLUSH_INTERVAL = 261,
61 OPTION_NO_DRAIN = 262,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050062};
63
64typedef enum OutputFormat {
65 OFORMAT_JSON,
66 OFORMAT_HUMAN,
67} OutputFormat;
68
Kevin Wolfe6996142016-03-15 13:03:11 +010069/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040070#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000071
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010072static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000073{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010074 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000075}
76
Fam Zhengac1307a2014-04-22 13:36:11 +080077static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
78{
79 va_list ap;
80
81 error_printf("qemu-img: ");
82
83 va_start(ap, fmt);
84 error_vprintf(fmt, ap);
85 va_end(ap);
86
87 error_printf("\nTry 'qemu-img --help' for more information\n");
88 exit(EXIT_FAILURE);
89}
90
blueswir1d2c639d2009-01-24 18:19:25 +000091/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080092static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000093{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010094 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040095 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +030096 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +030097 "QEMU disk image utility\n"
98 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +030099 " '-h', '--help' display this help and exit\n"
100 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300101 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
102 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300103 "\n"
malc3f020d72010-02-08 12:04:56 +0300104 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100105#define DEF(option, callback, arg_string) \
106 " " arg_string "\n"
107#include "qemu-img-cmds.h"
108#undef DEF
109#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300110 "\n"
111 "Command parameters:\n"
112 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000113 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
114 " manual page for a description of the object properties. The most common\n"
115 " object type is a 'secret', which is used to supply passwords and/or\n"
116 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300117 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400118 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800119 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
120 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100121 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
122 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300123 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200124 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
125 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
126 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300127 " 'output_filename' is the destination disk image filename\n"
128 " 'output_fmt' is the destination format\n"
129 " 'options' is a comma separated list of format specific options in a\n"
130 " name=value format. Use -o ? for an overview of the options supported by the\n"
131 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800132 " 'snapshot_param' is param used for internal snapshot, format\n"
133 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
134 " '[ID_OR_NAME]'\n"
135 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
136 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300137 " '-c' indicates that target image must be compressed (qcow format only)\n"
138 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
139 " match exactly. The image doesn't need a working backing file before\n"
140 " rebasing in this case (useful for renaming the backing file)\n"
141 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200142 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100143 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200144 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
145 " contain only zeros for qemu-img to create a sparse image during\n"
146 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
147 " unallocated or zero sectors, and the destination image will always be\n"
148 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200149 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100150 " '-n' skips the target volume creation (useful if the volume is created\n"
151 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300152 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200153 "Parameters to check subcommand:\n"
154 " '-r' tries to repair any inconsistencies that are found during the check.\n"
155 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
156 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200157 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200158 "\n"
malc3f020d72010-02-08 12:04:56 +0300159 "Parameters to snapshot subcommand:\n"
160 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
161 " '-a' applies a snapshot (revert disk to saved state)\n"
162 " '-c' creates a snapshot\n"
163 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100164 " '-l' lists all snapshots in the given image\n"
165 "\n"
166 "Parameters to compare subcommand:\n"
167 " '-f' first image format\n"
168 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200169 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
170 "\n"
171 "Parameters to dd subcommand:\n"
172 " 'bs=BYTES' read and write up to BYTES bytes at a time "
173 "(default: 512)\n"
174 " 'count=N' copy only N input blocks\n"
175 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200176 " 'of=FILE' write to FILE\n"
177 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100178
179 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100180 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000181 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800182 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000183}
184
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000185static QemuOptsList qemu_object_opts = {
186 .name = "object",
187 .implied_opt_name = "qom-type",
188 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
189 .desc = {
190 { }
191 },
192};
193
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000194static QemuOptsList qemu_source_opts = {
195 .name = "source",
196 .implied_opt_name = "file",
197 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
198 .desc = {
199 { }
200 },
201};
202
Stefan Weil7c30f652013-06-16 17:01:05 +0200203static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100204{
205 int ret = 0;
206 if (!quiet) {
207 va_list args;
208 va_start(args, fmt);
209 ret = vprintf(fmt, args);
210 va_end(args);
211 }
212 return ret;
213}
214
bellardea2384d2004-08-01 21:59:26 +0000215
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100216static int print_block_option_help(const char *filename, const char *fmt)
217{
218 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800219 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500220 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100221
222 /* Find driver and parse its options */
223 drv = bdrv_find_format(fmt);
224 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100225 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100226 return 1;
227 }
228
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800229 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100230 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500231 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100232 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100233 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800234 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100235 return 1;
236 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800237 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100238 }
239
Chunyan Liu83d05212014-06-05 17:20:51 +0800240 qemu_opts_print_help(create_opts);
241 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242 return 0;
243}
244
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000245
246static int img_open_password(BlockBackend *blk, const char *filename,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000247 int flags, bool quiet)
bellard75c23802004-08-27 21:28:58 +0000248{
249 BlockDriverState *bs;
bellard75c23802004-08-27 21:28:58 +0000250 char password[256];
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000251
252 bs = blk_bs(blk);
Daniel P. Berrange4ef130f2016-03-21 14:11:43 +0000253 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
254 !(flags & BDRV_O_NO_IO)) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000255 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
256 if (qemu_read_password(password, sizeof(password)) < 0) {
257 error_report("No password given");
258 return -1;
259 }
260 if (bdrv_set_key(bs, password) < 0) {
261 error_report("invalid password");
262 return -1;
263 }
264 }
265 return 0;
266}
267
268
Max Reitzefaa7c42016-03-16 19:54:38 +0100269static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100270 QemuOpts *opts, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000271 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000272{
273 QDict *options;
274 Error *local_err = NULL;
275 BlockBackend *blk;
276 options = qemu_opts_to_qdict(opts, NULL);
Max Reitzefaa7c42016-03-16 19:54:38 +0100277 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000278 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100279 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000280 return NULL;
281 }
Kevin Wolfce099542016-03-15 13:01:04 +0100282 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000283
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000284 if (img_open_password(blk, optstr, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000285 blk_unref(blk);
286 return NULL;
287 }
288 return blk;
289}
290
Max Reitzefaa7c42016-03-16 19:54:38 +0100291static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292 const char *fmt, int flags,
Kevin Wolfce099542016-03-15 13:01:04 +0100293 bool writethrough, bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000294{
295 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200296 Error *local_err = NULL;
Max Reitz5bd31322015-02-05 13:58:16 -0500297 QDict *options = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100298
bellard75c23802004-08-27 21:28:58 +0000299 if (fmt) {
Max Reitz5bd31322015-02-05 13:58:16 -0500300 options = qdict_new();
301 qdict_put(options, "driver", qstring_from_str(fmt));
bellard75c23802004-08-27 21:28:58 +0000302 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100303
Max Reitzefaa7c42016-03-16 19:54:38 +0100304 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500305 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100306 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 return NULL;
bellard75c23802004-08-27 21:28:58 +0000308 }
Kevin Wolfce099542016-03-15 13:01:04 +0100309 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100310
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000311 if (img_open_password(blk, filename, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312 blk_unref(blk);
313 return NULL;
bellard75c23802004-08-27 21:28:58 +0000314 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200315 return blk;
bellard75c23802004-08-27 21:28:58 +0000316}
317
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318
Max Reitzefaa7c42016-03-16 19:54:38 +0100319static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100321 const char *fmt, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000322 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000323{
324 BlockBackend *blk;
325 if (image_opts) {
326 QemuOpts *opts;
327 if (fmt) {
328 error_report("--image-opts and --format are mutually exclusive");
329 return NULL;
330 }
331 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
332 filename, true);
333 if (!opts) {
334 return NULL;
335 }
Kevin Wolfce099542016-03-15 13:01:04 +0100336 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000337 } else {
Kevin Wolfce099542016-03-15 13:01:04 +0100338 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000339 }
340 return blk;
341}
342
343
Chunyan Liu83d05212014-06-05 17:20:51 +0800344static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100345 const char *base_filename,
346 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200347{
Markus Armbruster6750e792015-02-12 17:43:08 +0100348 Error *err = NULL;
349
Kevin Wolfefa84d42009-05-18 16:42:12 +0200350 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100351 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100352 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100353 error_report("Backing file not supported for file format '%s'",
354 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100355 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900356 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200357 }
358 }
359 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100360 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100361 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100362 error_report("Backing file format not supported for file "
363 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100364 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900365 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200366 }
367 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900368 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200369}
370
Markus Armbruster606caa02017-02-21 21:14:04 +0100371static int64_t cvtnum(const char *s)
372{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100373 int err;
374 int64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100375
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100376 err = qemu_strtosz(s, NULL, &value);
377 if (err < 0) {
378 return err;
379 }
380 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100381}
382
bellardea2384d2004-08-01 21:59:26 +0000383static int img_create(int argc, char **argv)
384{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200385 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100386 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000387 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000388 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000389 const char *filename;
390 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200391 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200392 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100393 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000394
bellardea2384d2004-08-01 21:59:26 +0000395 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000396 static const struct option long_options[] = {
397 {"help", no_argument, 0, 'h'},
398 {"object", required_argument, 0, OPTION_OBJECT},
399 {0, 0, 0, 0}
400 };
401 c = getopt_long(argc, argv, "F:b:f:he6o:q",
402 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100403 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000404 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100405 }
bellardea2384d2004-08-01 21:59:26 +0000406 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100407 case '?':
bellardea2384d2004-08-01 21:59:26 +0000408 case 'h':
409 help();
410 break;
aliguori9230eaf2009-03-28 17:55:19 +0000411 case 'F':
412 base_fmt = optarg;
413 break;
bellardea2384d2004-08-01 21:59:26 +0000414 case 'b':
415 base_filename = optarg;
416 break;
417 case 'f':
418 fmt = optarg;
419 break;
420 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200421 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100422 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100423 goto fail;
thsd8871c52007-10-24 16:11:42 +0000424 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200425 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100426 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100427 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200428 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100429 if (!is_valid_option_list(optarg)) {
430 error_report("Invalid option list: %s", optarg);
431 goto fail;
432 }
433 if (!options) {
434 options = g_strdup(optarg);
435 } else {
436 char *old_options = options;
437 options = g_strdup_printf("%s,%s", options, optarg);
438 g_free(old_options);
439 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200440 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100441 case 'q':
442 quiet = true;
443 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000444 case OPTION_OBJECT: {
445 QemuOpts *opts;
446 opts = qemu_opts_parse_noisily(&qemu_object_opts,
447 optarg, true);
448 if (!opts) {
449 goto fail;
450 }
451 } break;
bellardea2384d2004-08-01 21:59:26 +0000452 }
453 }
aliguori9230eaf2009-03-28 17:55:19 +0000454
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900455 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100456 filename = (optind < argc) ? argv[optind] : NULL;
457 if (options && has_help_option(options)) {
458 g_free(options);
459 return print_block_option_help(filename, fmt);
460 }
461
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100462 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800463 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100464 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100465 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900466
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000467 if (qemu_opts_foreach(&qemu_object_opts,
468 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200469 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000470 goto fail;
471 }
472
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100473 /* Get image size, if specified */
474 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100475 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100476
477 sval = cvtnum(argv[optind++]);
478 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800479 if (sval == -ERANGE) {
480 error_report("Image size must be less than 8 EiB!");
481 } else {
482 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200483 "G, T, P or E suffixes for ");
484 error_report("kilobytes, megabytes, gigabytes, terabytes, "
485 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800486 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100487 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100488 }
489 img_size = (uint64_t)sval;
490 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200491 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800492 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200493 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100494
Luiz Capitulino9b375252012-11-30 10:52:05 -0200495 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Kevin Wolf61de4c62016-03-18 17:46:45 +0100496 options, img_size, 0, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100497 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100498 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100499 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900500 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200501
Kevin Wolf77386bf2014-02-21 16:24:04 +0100502 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000503 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100504
505fail:
506 g_free(options);
507 return 1;
bellardea2384d2004-08-01 21:59:26 +0000508}
509
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100510static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500511{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500512 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500513 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100514 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600515
516 visit_type_ImageCheck(v, NULL, &check, &error_abort);
517 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500518 str = qobject_to_json_pretty(obj);
519 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100520 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500521 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600522 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500523 QDECREF(str);
524}
525
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100526static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500527{
528 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100529 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500530 } else {
531 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100532 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
533 "Data may be corrupted, or further writes to the image "
534 "may corrupt it.\n",
535 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500536 }
537
538 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100539 qprintf(quiet,
540 "\n%" PRId64 " leaked clusters were found on the image.\n"
541 "This means waste of disk space, but no harm to data.\n",
542 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500543 }
544
545 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100546 qprintf(quiet,
547 "\n%" PRId64
548 " internal errors have occurred during the check.\n",
549 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500550 }
551 }
552
553 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100554 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
555 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
556 check->allocated_clusters, check->total_clusters,
557 check->allocated_clusters * 100.0 / check->total_clusters,
558 check->fragmented_clusters * 100.0 / check->allocated_clusters,
559 check->compressed_clusters * 100.0 /
560 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500561 }
562
563 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100564 qprintf(quiet,
565 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 }
567}
568
569static int collect_image_check(BlockDriverState *bs,
570 ImageCheck *check,
571 const char *filename,
572 const char *fmt,
573 int fix)
574{
575 int ret;
576 BdrvCheckResult result;
577
578 ret = bdrv_check(bs, &result, fix);
579 if (ret < 0) {
580 return ret;
581 }
582
583 check->filename = g_strdup(filename);
584 check->format = g_strdup(bdrv_get_format_name(bs));
585 check->check_errors = result.check_errors;
586 check->corruptions = result.corruptions;
587 check->has_corruptions = result.corruptions != 0;
588 check->leaks = result.leaks;
589 check->has_leaks = result.leaks != 0;
590 check->corruptions_fixed = result.corruptions_fixed;
591 check->has_corruptions_fixed = result.corruptions != 0;
592 check->leaks_fixed = result.leaks_fixed;
593 check->has_leaks_fixed = result.leaks != 0;
594 check->image_end_offset = result.image_end_offset;
595 check->has_image_end_offset = result.image_end_offset != 0;
596 check->total_clusters = result.bfi.total_clusters;
597 check->has_total_clusters = result.bfi.total_clusters != 0;
598 check->allocated_clusters = result.bfi.allocated_clusters;
599 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
600 check->fragmented_clusters = result.bfi.fragmented_clusters;
601 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100602 check->compressed_clusters = result.bfi.compressed_clusters;
603 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500604
605 return 0;
606}
607
Kevin Wolfe076f332010-06-29 11:43:13 +0200608/*
609 * Checks an image for consistency. Exit codes:
610 *
Max Reitzd6635c42014-06-02 22:15:21 +0200611 * 0 - Check completed, image is good
612 * 1 - Check not completed because of internal errors
613 * 2 - Check completed, image is corrupted
614 * 3 - Check completed, image has leaked clusters, but is good otherwise
615 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200616 */
aliguori15859692009-04-21 23:11:53 +0000617static int img_check(int argc, char **argv)
618{
619 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200621 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200622 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000623 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200624 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100625 int flags = BDRV_O_CHECK;
626 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200627 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100628 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000629 bool image_opts = false;
aliguori15859692009-04-21 23:11:53 +0000630
631 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200633 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100634
aliguori15859692009-04-21 23:11:53 +0000635 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500636 int option_index = 0;
637 static const struct option long_options[] = {
638 {"help", no_argument, 0, 'h'},
639 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530640 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500641 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000642 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000643 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500644 {0, 0, 0, 0}
645 };
Max Reitz40055952014-07-22 22:58:42 +0200646 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100648 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000649 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100650 }
aliguori15859692009-04-21 23:11:53 +0000651 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100652 case '?':
aliguori15859692009-04-21 23:11:53 +0000653 case 'h':
654 help();
655 break;
656 case 'f':
657 fmt = optarg;
658 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200659 case 'r':
660 flags |= BDRV_O_RDWR;
661
662 if (!strcmp(optarg, "leaks")) {
663 fix = BDRV_FIX_LEAKS;
664 } else if (!strcmp(optarg, "all")) {
665 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
666 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800667 error_exit("Unknown option value for -r "
668 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200669 }
670 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500671 case OPTION_OUTPUT:
672 output = optarg;
673 break;
Max Reitz40055952014-07-22 22:58:42 +0200674 case 'T':
675 cache = optarg;
676 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100677 case 'q':
678 quiet = true;
679 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000680 case OPTION_OBJECT: {
681 QemuOpts *opts;
682 opts = qemu_opts_parse_noisily(&qemu_object_opts,
683 optarg, true);
684 if (!opts) {
685 return 1;
686 }
687 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000688 case OPTION_IMAGE_OPTS:
689 image_opts = true;
690 break;
aliguori15859692009-04-21 23:11:53 +0000691 }
692 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200693 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800694 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100695 }
aliguori15859692009-04-21 23:11:53 +0000696 filename = argv[optind++];
697
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500698 if (output && !strcmp(output, "json")) {
699 output_format = OFORMAT_JSON;
700 } else if (output && !strcmp(output, "human")) {
701 output_format = OFORMAT_HUMAN;
702 } else if (output) {
703 error_report("--output must be used with human or json as argument.");
704 return 1;
705 }
706
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000707 if (qemu_opts_foreach(&qemu_object_opts,
708 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200709 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000710 return 1;
711 }
712
Kevin Wolfce099542016-03-15 13:01:04 +0100713 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200714 if (ret < 0) {
715 error_report("Invalid source cache option: %s", cache);
716 return 1;
717 }
718
Kevin Wolfce099542016-03-15 13:01:04 +0100719 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200720 if (!blk) {
721 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900722 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200723 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500724
725 check = g_new0(ImageCheck, 1);
726 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200727
728 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200729 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200730 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500731 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200732 }
733
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500734 if (check->corruptions_fixed || check->leaks_fixed) {
735 int corruptions_fixed, leaks_fixed;
736
737 leaks_fixed = check->leaks_fixed;
738 corruptions_fixed = check->corruptions_fixed;
739
740 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100741 qprintf(quiet,
742 "The following inconsistencies were found and repaired:\n\n"
743 " %" PRId64 " leaked clusters\n"
744 " %" PRId64 " corruptions\n\n"
745 "Double checking the fixed image now...\n",
746 check->leaks_fixed,
747 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500748 }
749
750 ret = collect_image_check(bs, check, filename, fmt, 0);
751
752 check->leaks_fixed = leaks_fixed;
753 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200754 }
755
Max Reitz832390a2014-10-23 15:29:12 +0200756 if (!ret) {
757 switch (output_format) {
758 case OFORMAT_HUMAN:
759 dump_human_image_check(check, quiet);
760 break;
761 case OFORMAT_JSON:
762 dump_json_image_check(check, quiet);
763 break;
764 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500765 }
766
767 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200768 if (ret) {
769 error_report("Check failed: %s", strerror(-ret));
770 } else {
771 error_report("Check failed");
772 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500773 ret = 1;
774 goto fail;
775 }
776
777 if (check->corruptions) {
778 ret = 2;
779 } else if (check->leaks) {
780 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200781 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500782 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000783 }
784
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500785fail:
786 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200787 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500788 return ret;
aliguori15859692009-04-21 23:11:53 +0000789}
790
Max Reitzd4a32382014-10-24 15:57:37 +0200791typedef struct CommonBlockJobCBInfo {
792 BlockDriverState *bs;
793 Error **errp;
794} CommonBlockJobCBInfo;
795
796static void common_block_job_cb(void *opaque, int ret)
797{
798 CommonBlockJobCBInfo *cbi = opaque;
799
800 if (ret < 0) {
801 error_setg_errno(cbi->errp, -ret, "Block job failed");
802 }
Max Reitzd4a32382014-10-24 15:57:37 +0200803}
804
805static void run_block_job(BlockJob *job, Error **errp)
806{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200807 AioContext *aio_context = blk_get_aio_context(job->blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200808
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200809 aio_context_acquire(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200810 do {
811 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500812 qemu_progress_print(job->len ?
813 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200814 } while (!job->ready);
815
816 block_job_complete_sync(job, errp);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200817 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200818
819 /* A block job may finish instantaneously without publishing any progress,
820 * so just signal completion here */
821 qemu_progress_print(100.f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200822}
823
bellardea2384d2004-08-01 21:59:26 +0000824static int img_commit(int argc, char **argv)
825{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400826 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200827 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200828 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200829 BlockDriverState *bs, *base_bs;
Max Reitz687fa1d2014-10-24 15:57:39 +0200830 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100831 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200832 Error *local_err = NULL;
833 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000834 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200835 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000836
837 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400838 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200839 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000840 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000841 static const struct option long_options[] = {
842 {"help", no_argument, 0, 'h'},
843 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000844 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000845 {0, 0, 0, 0}
846 };
847 c = getopt_long(argc, argv, "f:ht:b:dpq",
848 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100849 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000850 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100851 }
bellardea2384d2004-08-01 21:59:26 +0000852 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100853 case '?':
bellardea2384d2004-08-01 21:59:26 +0000854 case 'h':
855 help();
856 break;
857 case 'f':
858 fmt = optarg;
859 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400860 case 't':
861 cache = optarg;
862 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200863 case 'b':
864 base = optarg;
865 /* -b implies -d */
866 drop = true;
867 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200868 case 'd':
869 drop = true;
870 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200871 case 'p':
872 progress = true;
873 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100874 case 'q':
875 quiet = true;
876 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000877 case OPTION_OBJECT: {
878 QemuOpts *opts;
879 opts = qemu_opts_parse_noisily(&qemu_object_opts,
880 optarg, true);
881 if (!opts) {
882 return 1;
883 }
884 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000885 case OPTION_IMAGE_OPTS:
886 image_opts = true;
887 break;
bellardea2384d2004-08-01 21:59:26 +0000888 }
889 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200890
891 /* Progress is not shown in Quiet mode */
892 if (quiet) {
893 progress = false;
894 }
895
Kevin Wolffc11eb22013-08-05 10:53:04 +0200896 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800897 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100898 }
bellardea2384d2004-08-01 21:59:26 +0000899 filename = argv[optind++];
900
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000901 if (qemu_opts_foreach(&qemu_object_opts,
902 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200903 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000904 return 1;
905 }
906
Max Reitz9a86fe42014-10-24 15:57:38 +0200907 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100908 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400909 if (ret < 0) {
910 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100911 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400912 }
913
Kevin Wolfce099542016-03-15 13:01:04 +0100914 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200915 if (!blk) {
916 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900917 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200918 bs = blk_bs(blk);
919
Max Reitz687fa1d2014-10-24 15:57:39 +0200920 qemu_progress_init(progress, 1.f);
921 qemu_progress_print(0.f, 100);
922
Max Reitz1b22bff2014-10-24 15:57:40 +0200923 if (base) {
924 base_bs = bdrv_find_backing_image(bs, base);
925 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100926 error_setg(&local_err,
927 "Did not find '%s' in the backing chain of '%s'",
928 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200929 goto done;
930 }
931 } else {
932 /* This is different from QMP, which by default uses the deepest file in
933 * the backing chain (i.e., the very base); however, the traditional
934 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +0200935 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +0200936 if (!base_bs) {
937 error_setg(&local_err, "Image does not have a backing file");
938 goto done;
939 }
bellardea2384d2004-08-01 21:59:26 +0000940 }
941
Max Reitzd4a32382014-10-24 15:57:37 +0200942 cbi = (CommonBlockJobCBInfo){
943 .errp = &local_err,
944 .bs = bs,
945 };
946
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200947 aio_context = bdrv_get_aio_context(bs);
948 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -0400949 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
950 BLOCKDEV_ON_ERROR_REPORT, common_block_job_cb, &cbi,
951 &local_err, false);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200952 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200953 if (local_err) {
954 goto done;
955 }
956
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200957 /* When the block job completes, the BlockBackend reference will point to
958 * the old backing file. In order to avoid that the top image is already
959 * deleted, so we can still empty it afterwards, increment the reference
960 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +0200961 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200962 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200963 }
964
Max Reitzd4a32382014-10-24 15:57:37 +0200965 run_block_job(bs->job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +0200966 if (local_err) {
967 goto unref_backing;
968 }
969
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200970 if (!drop && bs->drv->bdrv_make_empty) {
971 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200972 if (ret) {
973 error_setg_errno(&local_err, -ret, "Could not empty %s",
974 filename);
975 goto unref_backing;
976 }
977 }
978
979unref_backing:
980 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200981 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200982 }
Max Reitzd4a32382014-10-24 15:57:37 +0200983
984done:
Max Reitz687fa1d2014-10-24 15:57:39 +0200985 qemu_progress_end();
986
Markus Armbruster26f54e92014-10-07 13:59:04 +0200987 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200988
989 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +0100990 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900991 return 1;
992 }
Max Reitzd4a32382014-10-24 15:57:37 +0200993
994 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000995 return 0;
996}
997
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400998/*
thsf58c7b32008-06-05 21:53:49 +0000999 * Returns true iff the first sector pointed to by 'buf' contains at least
1000 * a non-NUL byte.
1001 *
1002 * 'pnum' is set to the number of sectors (including and immediately following
1003 * the first one) that are known to be in the same allocated/unallocated state.
1004 */
bellardea2384d2004-08-01 21:59:26 +00001005static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1006{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001007 bool is_zero;
1008 int i;
bellardea2384d2004-08-01 21:59:26 +00001009
1010 if (n <= 0) {
1011 *pnum = 0;
1012 return 0;
1013 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001014 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001015 for(i = 1; i < n; i++) {
1016 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001017 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001018 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001019 }
bellardea2384d2004-08-01 21:59:26 +00001020 }
1021 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001022 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001023}
1024
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001025/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001026 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1027 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1028 * breaking up write requests for only small sparse areas.
1029 */
1030static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1031 int min)
1032{
1033 int ret;
1034 int num_checked, num_used;
1035
1036 if (n < min) {
1037 min = n;
1038 }
1039
1040 ret = is_allocated_sectors(buf, n, pnum);
1041 if (!ret) {
1042 return ret;
1043 }
1044
1045 num_used = *pnum;
1046 buf += BDRV_SECTOR_SIZE * *pnum;
1047 n -= *pnum;
1048 num_checked = num_used;
1049
1050 while (n > 0) {
1051 ret = is_allocated_sectors(buf, n, pnum);
1052
1053 buf += BDRV_SECTOR_SIZE * *pnum;
1054 n -= *pnum;
1055 num_checked += *pnum;
1056 if (ret) {
1057 num_used = num_checked;
1058 } else if (*pnum >= min) {
1059 break;
1060 }
1061 }
1062
1063 *pnum = num_used;
1064 return 1;
1065}
1066
1067/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001068 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1069 * buffers matches, non-zero otherwise.
1070 *
1071 * pnum is set to the number of sectors (including and immediately following
1072 * the first one) that are known to have the same comparison result
1073 */
1074static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1075 int *pnum)
1076{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001077 bool res;
1078 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001079
1080 if (n <= 0) {
1081 *pnum = 0;
1082 return 0;
1083 }
1084
1085 res = !!memcmp(buf1, buf2, 512);
1086 for(i = 1; i < n; i++) {
1087 buf1 += 512;
1088 buf2 += 512;
1089
1090 if (!!memcmp(buf1, buf2, 512) != res) {
1091 break;
1092 }
1093 }
1094
1095 *pnum = i;
1096 return res;
1097}
1098
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001099#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001100
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001101static int64_t sectors_to_bytes(int64_t sectors)
1102{
1103 return sectors << BDRV_SECTOR_BITS;
1104}
1105
1106static int64_t sectors_to_process(int64_t total, int64_t from)
1107{
1108 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1109}
1110
1111/*
1112 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1113 *
1114 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1115 * data and negative value on error.
1116 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001117 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001118 * @param sect_num: Number of first sector to check
1119 * @param sect_count: Number of sectors to check
1120 * @param filename: Name of disk file we are checking (logging purpose)
1121 * @param buffer: Allocated buffer for storing read data
1122 * @param quiet: Flag for quiet mode
1123 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001124static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001125 int sect_count, const char *filename,
1126 uint8_t *buffer, bool quiet)
1127{
1128 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001129 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1130 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001131 if (ret < 0) {
1132 error_report("Error while reading offset %" PRId64 " of %s: %s",
1133 sectors_to_bytes(sect_num), filename, strerror(-ret));
1134 return ret;
1135 }
1136 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1137 if (ret || pnum != sect_count) {
1138 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1139 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1140 return 1;
1141 }
1142
1143 return 0;
1144}
1145
1146/*
1147 * Compares two images. Exit codes:
1148 *
1149 * 0 - Images are identical
1150 * 1 - Images differ
1151 * >1 - Error occurred
1152 */
1153static int img_compare(int argc, char **argv)
1154{
Max Reitz40055952014-07-22 22:58:42 +02001155 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001156 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001157 BlockDriverState *bs1, *bs2;
1158 int64_t total_sectors1, total_sectors2;
1159 uint8_t *buf1 = NULL, *buf2 = NULL;
1160 int pnum1, pnum2;
1161 int allocated1, allocated2;
1162 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1163 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001164 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001165 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001166 int64_t total_sectors;
1167 int64_t sector_num = 0;
1168 int64_t nb_sectors;
1169 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001170 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001171 bool image_opts = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001172
Max Reitz40055952014-07-22 22:58:42 +02001173 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001174 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001175 static const struct option long_options[] = {
1176 {"help", no_argument, 0, 'h'},
1177 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001178 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001179 {0, 0, 0, 0}
1180 };
1181 c = getopt_long(argc, argv, "hf:F:T:pqs",
1182 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001183 if (c == -1) {
1184 break;
1185 }
1186 switch (c) {
1187 case '?':
1188 case 'h':
1189 help();
1190 break;
1191 case 'f':
1192 fmt1 = optarg;
1193 break;
1194 case 'F':
1195 fmt2 = optarg;
1196 break;
Max Reitz40055952014-07-22 22:58:42 +02001197 case 'T':
1198 cache = optarg;
1199 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001200 case 'p':
1201 progress = true;
1202 break;
1203 case 'q':
1204 quiet = true;
1205 break;
1206 case 's':
1207 strict = true;
1208 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001209 case OPTION_OBJECT: {
1210 QemuOpts *opts;
1211 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1212 optarg, true);
1213 if (!opts) {
1214 ret = 2;
1215 goto out4;
1216 }
1217 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001218 case OPTION_IMAGE_OPTS:
1219 image_opts = true;
1220 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 }
1222 }
1223
1224 /* Progress is not shown in Quiet mode */
1225 if (quiet) {
1226 progress = false;
1227 }
1228
1229
Kevin Wolffc11eb22013-08-05 10:53:04 +02001230 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001231 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001232 }
1233 filename1 = argv[optind++];
1234 filename2 = argv[optind++];
1235
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001236 if (qemu_opts_foreach(&qemu_object_opts,
1237 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001238 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001239 ret = 2;
1240 goto out4;
1241 }
1242
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001243 /* Initialize before goto out */
1244 qemu_progress_init(progress, 2.0);
1245
Kevin Wolfce099542016-03-15 13:01:04 +01001246 flags = 0;
1247 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001248 if (ret < 0) {
1249 error_report("Invalid source cache option: %s", cache);
1250 ret = 2;
1251 goto out3;
1252 }
1253
Kevin Wolfce099542016-03-15 13:01:04 +01001254 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001255 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001256 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001257 goto out3;
1258 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001259
Kevin Wolfce099542016-03-15 13:01:04 +01001260 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001261 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001262 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001263 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001264 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001265 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001266 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001267
Max Reitzf1d3cd72015-02-05 13:58:18 -05001268 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1269 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1270 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001271 if (total_sectors1 < 0) {
1272 error_report("Can't get size of %s: %s",
1273 filename1, strerror(-total_sectors1));
1274 ret = 4;
1275 goto out;
1276 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001277 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001278 if (total_sectors2 < 0) {
1279 error_report("Can't get size of %s: %s",
1280 filename2, strerror(-total_sectors2));
1281 ret = 4;
1282 goto out;
1283 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001284 total_sectors = MIN(total_sectors1, total_sectors2);
1285 progress_base = MAX(total_sectors1, total_sectors2);
1286
1287 qemu_progress_print(0, 100);
1288
1289 if (strict && total_sectors1 != total_sectors2) {
1290 ret = 1;
1291 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1292 goto out;
1293 }
1294
1295 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001296 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001297 BlockDriverState *file;
1298
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299 nb_sectors = sectors_to_process(total_sectors, sector_num);
1300 if (nb_sectors <= 0) {
1301 break;
1302 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001303 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1304 total_sectors1 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001305 &pnum1, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001306 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001307 ret = 3;
1308 error_report("Sector allocation test failed for %s", filename1);
1309 goto out;
1310 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001311 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001312
Fam Zheng25ad8e62016-01-13 16:37:41 +08001313 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1314 total_sectors2 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001315 &pnum2, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001316 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001317 ret = 3;
1318 error_report("Sector allocation test failed for %s", filename2);
1319 goto out;
1320 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001321 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1322 if (pnum1) {
1323 nb_sectors = MIN(nb_sectors, pnum1);
1324 }
1325 if (pnum2) {
1326 nb_sectors = MIN(nb_sectors, pnum2);
1327 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001328
Fam Zheng25ad8e62016-01-13 16:37:41 +08001329 if (strict) {
1330 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1331 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1332 ret = 1;
1333 qprintf(quiet, "Strict mode: Offset %" PRId64
1334 " block status mismatch!\n",
1335 sectors_to_bytes(sector_num));
1336 goto out;
1337 }
1338 }
1339 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1340 nb_sectors = MIN(pnum1, pnum2);
1341 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001342 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001343 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1344 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 if (ret < 0) {
1346 error_report("Error while reading offset %" PRId64 " of %s:"
1347 " %s", sectors_to_bytes(sector_num), filename1,
1348 strerror(-ret));
1349 ret = 4;
1350 goto out;
1351 }
Eric Blake91669202016-05-06 10:26:43 -06001352 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1353 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001354 if (ret < 0) {
1355 error_report("Error while reading offset %" PRId64
1356 " of %s: %s", sectors_to_bytes(sector_num),
1357 filename2, strerror(-ret));
1358 ret = 4;
1359 goto out;
1360 }
1361 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1362 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001363 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1364 sectors_to_bytes(
1365 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001366 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001367 goto out;
1368 }
1369 }
1370 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001371
1372 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001373 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001374 filename1, buf1, quiet);
1375 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001376 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001377 filename2, buf1, quiet);
1378 }
1379 if (ret) {
1380 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381 error_report("Error while reading offset %" PRId64 ": %s",
1382 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001383 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001384 }
1385 goto out;
1386 }
1387 }
1388 sector_num += nb_sectors;
1389 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1390 }
1391
1392 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001393 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394 int64_t total_sectors_over;
1395 const char *filename_over;
1396
1397 qprintf(quiet, "Warning: Image size mismatch!\n");
1398 if (total_sectors1 > total_sectors2) {
1399 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001400 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001401 filename_over = filename1;
1402 } else {
1403 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001404 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001405 filename_over = filename2;
1406 }
1407
1408 for (;;) {
1409 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1410 if (nb_sectors <= 0) {
1411 break;
1412 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001413 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001414 nb_sectors, &pnum);
1415 if (ret < 0) {
1416 ret = 3;
1417 error_report("Sector allocation test failed for %s",
1418 filename_over);
1419 goto out;
1420
1421 }
1422 nb_sectors = pnum;
1423 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001424 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001425 filename_over, buf1, quiet);
1426 if (ret) {
1427 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 error_report("Error while reading offset %" PRId64
1429 " of %s: %s", sectors_to_bytes(sector_num),
1430 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001431 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001432 }
1433 goto out;
1434 }
1435 }
1436 sector_num += nb_sectors;
1437 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1438 }
1439 }
1440
1441 qprintf(quiet, "Images are identical.\n");
1442 ret = 0;
1443
1444out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001445 qemu_vfree(buf1);
1446 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001447 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001448out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001449 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001450out3:
1451 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001452out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001453 return ret;
1454}
1455
Kevin Wolf690c7302015-03-19 13:33:32 +01001456enum ImgConvertBlockStatus {
1457 BLK_DATA,
1458 BLK_ZERO,
1459 BLK_BACKING_FILE,
1460};
1461
1462typedef struct ImgConvertState {
1463 BlockBackend **src;
1464 int64_t *src_sectors;
1465 int src_cur, src_num;
1466 int64_t src_cur_offset;
1467 int64_t total_sectors;
1468 int64_t allocated_sectors;
1469 enum ImgConvertBlockStatus status;
1470 int64_t sector_next_status;
1471 BlockBackend *target;
1472 bool has_zero_init;
1473 bool compressed;
1474 bool target_has_backing;
1475 int min_sparse;
1476 size_t cluster_sectors;
1477 size_t buf_sectors;
1478} ImgConvertState;
1479
1480static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1481{
1482 assert(sector_num >= s->src_cur_offset);
1483 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1484 s->src_cur_offset += s->src_sectors[s->src_cur];
1485 s->src_cur++;
1486 assert(s->src_cur < s->src_num);
1487 }
1488}
1489
1490static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1491{
1492 int64_t ret;
1493 int n;
1494
1495 convert_select_part(s, sector_num);
1496
1497 assert(s->total_sectors > sector_num);
1498 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1499
1500 if (s->sector_next_status <= sector_num) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08001501 BlockDriverState *file;
Kevin Wolf690c7302015-03-19 13:33:32 +01001502 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1503 sector_num - s->src_cur_offset,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001504 n, &n, &file);
Kevin Wolf690c7302015-03-19 13:33:32 +01001505 if (ret < 0) {
1506 return ret;
1507 }
1508
1509 if (ret & BDRV_BLOCK_ZERO) {
1510 s->status = BLK_ZERO;
1511 } else if (ret & BDRV_BLOCK_DATA) {
1512 s->status = BLK_DATA;
1513 } else if (!s->target_has_backing) {
1514 /* Without a target backing file we must copy over the contents of
1515 * the backing file as well. */
Ren Kimura263a6f42016-04-28 01:04:58 +09001516 /* Check block status of the backing file chain to avoid
Kevin Wolf690c7302015-03-19 13:33:32 +01001517 * needlessly reading zeroes and limiting the iteration to the
1518 * buffer size */
Ren Kimura263a6f42016-04-28 01:04:58 +09001519 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1520 sector_num - s->src_cur_offset,
1521 n, &n, &file);
1522 if (ret < 0) {
1523 return ret;
1524 }
1525
1526 if (ret & BDRV_BLOCK_ZERO) {
1527 s->status = BLK_ZERO;
1528 } else {
1529 s->status = BLK_DATA;
1530 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001531 } else {
1532 s->status = BLK_BACKING_FILE;
1533 }
1534
1535 s->sector_next_status = sector_num + n;
1536 }
1537
1538 n = MIN(n, s->sector_next_status - sector_num);
1539 if (s->status == BLK_DATA) {
1540 n = MIN(n, s->buf_sectors);
1541 }
1542
1543 /* We need to write complete clusters for compressed images, so if an
1544 * unallocated area is shorter than that, we must consider the whole
1545 * cluster allocated. */
1546 if (s->compressed) {
1547 if (n < s->cluster_sectors) {
1548 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1549 s->status = BLK_DATA;
1550 } else {
1551 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1552 }
1553 }
1554
1555 return n;
1556}
1557
1558static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1559 uint8_t *buf)
1560{
1561 int n;
1562 int ret;
1563
Kevin Wolf690c7302015-03-19 13:33:32 +01001564 assert(nb_sectors <= s->buf_sectors);
1565 while (nb_sectors > 0) {
1566 BlockBackend *blk;
1567 int64_t bs_sectors;
1568
1569 /* In the case of compression with multiple source files, we can get a
1570 * nb_sectors that spreads into the next part. So we must be able to
1571 * read across multiple BDSes for one convert_read() call. */
1572 convert_select_part(s, sector_num);
1573 blk = s->src[s->src_cur];
1574 bs_sectors = s->src_sectors[s->src_cur];
1575
1576 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
Eric Blake91669202016-05-06 10:26:43 -06001577 ret = blk_pread(blk,
1578 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1579 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001580 if (ret < 0) {
1581 return ret;
1582 }
1583
1584 sector_num += n;
1585 nb_sectors -= n;
1586 buf += n * BDRV_SECTOR_SIZE;
1587 }
1588
1589 return 0;
1590}
1591
1592static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1593 const uint8_t *buf)
1594{
1595 int ret;
1596
1597 while (nb_sectors > 0) {
1598 int n = nb_sectors;
1599
1600 switch (s->status) {
1601 case BLK_BACKING_FILE:
1602 /* If we have a backing file, leave clusters unallocated that are
1603 * unallocated in the source image, so that the backing file is
1604 * visible at the respective offset. */
1605 assert(s->target_has_backing);
1606 break;
1607
1608 case BLK_DATA:
1609 /* We must always write compressed clusters as a whole, so don't
1610 * try to find zeroed parts in the buffer. We can only save the
1611 * write if the buffer is completely zeroed and we're allowed to
1612 * keep the target sparse. */
1613 if (s->compressed) {
1614 if (s->has_zero_init && s->min_sparse &&
1615 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1616 {
1617 assert(!s->target_has_backing);
1618 break;
1619 }
1620
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001621 ret = blk_pwrite_compressed(s->target,
1622 sector_num << BDRV_SECTOR_BITS,
1623 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001624 if (ret < 0) {
1625 return ret;
1626 }
1627 break;
1628 }
1629
1630 /* If there is real non-zero data or we're told to keep the target
1631 * fully allocated (-S 0), we must write it. Otherwise we can treat
1632 * it as zero sectors. */
1633 if (!s->min_sparse ||
1634 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1635 {
Eric Blake91669202016-05-06 10:26:43 -06001636 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1637 buf, n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001638 if (ret < 0) {
1639 return ret;
1640 }
1641 break;
1642 }
1643 /* fall-through */
1644
1645 case BLK_ZERO:
1646 if (s->has_zero_init) {
1647 break;
1648 }
Eric Blaked004bd52016-05-24 16:25:20 -06001649 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1650 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001651 if (ret < 0) {
1652 return ret;
1653 }
1654 break;
1655 }
1656
1657 sector_num += n;
1658 nb_sectors -= n;
1659 buf += n * BDRV_SECTOR_SIZE;
1660 }
1661
1662 return 0;
1663}
1664
1665static int convert_do_copy(ImgConvertState *s)
1666{
1667 uint8_t *buf = NULL;
1668 int64_t sector_num, allocated_done;
1669 int ret;
1670 int n;
1671
1672 /* Check whether we have zero initialisation or can get it efficiently */
1673 s->has_zero_init = s->min_sparse && !s->target_has_backing
1674 ? bdrv_has_zero_init(blk_bs(s->target))
1675 : false;
1676
1677 if (!s->has_zero_init && !s->target_has_backing &&
1678 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1679 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001680 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001681 if (ret == 0) {
1682 s->has_zero_init = true;
1683 }
1684 }
1685
1686 /* Allocate buffer for copied data. For compressed images, only one cluster
1687 * can be copied at a time. */
1688 if (s->compressed) {
1689 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1690 error_report("invalid cluster size");
1691 ret = -EINVAL;
1692 goto fail;
1693 }
1694 s->buf_sectors = s->cluster_sectors;
1695 }
1696 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1697
1698 /* Calculate allocated sectors for progress */
1699 s->allocated_sectors = 0;
1700 sector_num = 0;
1701 while (sector_num < s->total_sectors) {
1702 n = convert_iteration_sectors(s, sector_num);
1703 if (n < 0) {
1704 ret = n;
1705 goto fail;
1706 }
Max Reitzaad15de2016-03-24 23:33:57 +01001707 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1708 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001709 s->allocated_sectors += n;
1710 }
1711 sector_num += n;
1712 }
1713
1714 /* Do the copy */
1715 s->src_cur = 0;
1716 s->src_cur_offset = 0;
1717 s->sector_next_status = 0;
1718
1719 sector_num = 0;
1720 allocated_done = 0;
1721
1722 while (sector_num < s->total_sectors) {
1723 n = convert_iteration_sectors(s, sector_num);
1724 if (n < 0) {
1725 ret = n;
1726 goto fail;
1727 }
Max Reitzaad15de2016-03-24 23:33:57 +01001728 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1729 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001730 allocated_done += n;
1731 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1732 0);
1733 }
1734
Max Reitzaad15de2016-03-24 23:33:57 +01001735 if (s->status == BLK_DATA) {
1736 ret = convert_read(s, sector_num, n, buf);
1737 if (ret < 0) {
1738 error_report("error while reading sector %" PRId64
1739 ": %s", sector_num, strerror(-ret));
1740 goto fail;
1741 }
1742 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1743 n = MIN(n, s->buf_sectors);
1744 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1745 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001746 }
1747
1748 ret = convert_write(s, sector_num, n, buf);
1749 if (ret < 0) {
1750 error_report("error while writing sector %" PRId64
1751 ": %s", sector_num, strerror(-ret));
1752 goto fail;
1753 }
1754
1755 sector_num += n;
1756 }
1757
1758 if (s->compressed) {
1759 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001760 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001761 if (ret < 0) {
1762 goto fail;
1763 }
1764 }
1765
1766 ret = 0;
1767fail:
1768 qemu_vfree(buf);
1769 return ret;
1770}
1771
bellardea2384d2004-08-01 21:59:26 +00001772static int img_convert(int argc, char **argv)
1773{
Kevin Wolf690c7302015-03-19 13:33:32 +01001774 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001775 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001776 int progress = 0, flags, src_flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001777 bool writethrough, src_writethrough;
Max Reitz40055952014-07-22 22:58:42 +02001778 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001779 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001780 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001781 BlockDriverState **bs = NULL, *out_bs = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001782 int64_t total_sectors;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001783 int64_t *bs_sectors = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001784 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardfaea38e2006-08-05 21:31:00 +00001785 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001786 QemuOpts *opts = NULL;
1787 QemuOptsList *create_opts = NULL;
1788 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001789 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001790 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001791 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001792 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001793 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001794 QemuOpts *sn_opts = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001795 ImgConvertState state;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001796 bool image_opts = false;
bellardea2384d2004-08-01 21:59:26 +00001797
1798 fmt = NULL;
1799 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001800 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001801 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001802 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001803 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001804 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001805 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001806 static const struct option long_options[] = {
1807 {"help", no_argument, 0, 'h'},
1808 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001809 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001810 {0, 0, 0, 0}
1811 };
1812 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1813 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001814 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001815 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001816 }
bellardea2384d2004-08-01 21:59:26 +00001817 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001818 case '?':
bellardea2384d2004-08-01 21:59:26 +00001819 case 'h':
1820 help();
1821 break;
1822 case 'f':
1823 fmt = optarg;
1824 break;
1825 case 'O':
1826 out_fmt = optarg;
1827 break;
thsf58c7b32008-06-05 21:53:49 +00001828 case 'B':
1829 out_baseimg = optarg;
1830 break;
bellardea2384d2004-08-01 21:59:26 +00001831 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001832 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001833 break;
1834 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001835 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001836 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001837 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001838 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001839 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001840 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001841 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001842 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001843 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001844 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001845 if (!is_valid_option_list(optarg)) {
1846 error_report("Invalid option list: %s", optarg);
1847 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001848 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001849 }
1850 if (!options) {
1851 options = g_strdup(optarg);
1852 } else {
1853 char *old_options = options;
1854 options = g_strdup_printf("%s,%s", options, optarg);
1855 g_free(old_options);
1856 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001857 break;
edison51ef6722010-09-21 19:58:41 -07001858 case 's':
1859 snapshot_name = optarg;
1860 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001861 case 'l':
1862 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01001863 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1864 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08001865 if (!sn_opts) {
1866 error_report("Failed in parsing snapshot param '%s'",
1867 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001868 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001869 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001870 }
1871 } else {
1872 snapshot_name = optarg;
1873 }
1874 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001875 case 'S':
1876 {
1877 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01001878
1879 sval = cvtnum(optarg);
1880 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001881 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001882 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001883 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001884 }
1885
1886 min_sparse = sval / BDRV_SECTOR_SIZE;
1887 break;
1888 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001889 case 'p':
1890 progress = 1;
1891 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001892 case 't':
1893 cache = optarg;
1894 break;
Max Reitz40055952014-07-22 22:58:42 +02001895 case 'T':
1896 src_cache = optarg;
1897 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001898 case 'q':
1899 quiet = true;
1900 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001901 case 'n':
1902 skip_create = 1;
1903 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001904 case OPTION_OBJECT:
1905 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1906 optarg, true);
1907 if (!opts) {
1908 goto fail_getopt;
1909 }
1910 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001911 case OPTION_IMAGE_OPTS:
1912 image_opts = true;
1913 break;
bellardea2384d2004-08-01 21:59:26 +00001914 }
1915 }
ths3b46e622007-09-17 08:09:54 +00001916
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001917 if (qemu_opts_foreach(&qemu_object_opts,
1918 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001919 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001920 goto fail_getopt;
1921 }
1922
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001923 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001924 if (quiet) {
1925 progress = 0;
1926 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001927 qemu_progress_init(progress, 1.0);
1928
balrog926c2d22007-10-31 01:11:44 +00001929 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001930 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001931
Kevin Wolf2dc83282014-02-21 16:24:05 +01001932 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001933 ret = print_block_option_help(out_filename, out_fmt);
1934 goto out;
1935 }
1936
bellardea2384d2004-08-01 21:59:26 +00001937 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001938 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001939 }
bellardea2384d2004-08-01 21:59:26 +00001940
thsf58c7b32008-06-05 21:53:49 +00001941
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001942 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001943 error_report("-B makes no sense when concatenating multiple input "
1944 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001945 ret = -1;
1946 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001947 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001948
Kevin Wolfce099542016-03-15 13:01:04 +01001949 src_flags = 0;
1950 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001951 if (ret < 0) {
1952 error_report("Invalid source cache option: %s", src_cache);
1953 goto out;
1954 }
1955
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001956 qemu_progress_print(0, 100);
1957
Markus Armbruster26f54e92014-10-07 13:59:04 +02001958 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001959 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001960 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001961
1962 total_sectors = 0;
1963 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Max Reitzefaa7c42016-03-16 19:54:38 +01001964 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
Kevin Wolfce099542016-03-15 13:01:04 +01001965 fmt, src_flags, src_writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001966 if (!blk[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001967 ret = -1;
1968 goto out;
1969 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001970 bs[bs_i] = blk_bs(blk[bs_i]);
Max Reitzf1d3cd72015-02-05 13:58:18 -05001971 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001972 if (bs_sectors[bs_i] < 0) {
1973 error_report("Could not get size of %s: %s",
1974 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1975 ret = -1;
1976 goto out;
1977 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001978 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001979 }
bellardea2384d2004-08-01 21:59:26 +00001980
Wenchao Xiaef806542013-12-04 17:10:57 +08001981 if (sn_opts) {
Peter Maydell10d6eda2017-02-10 16:28:24 +00001982 bdrv_snapshot_load_tmp(bs[0],
1983 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1984 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1985 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001986 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001987 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001988 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001989 ret = -1;
1990 goto out;
1991 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001992
1993 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001994 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001995 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001996 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08001997 ret = -1;
1998 goto out;
edison51ef6722010-09-21 19:58:41 -07001999 }
2000
Kevin Wolfefa84d42009-05-18 16:42:12 +02002001 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00002002 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002003 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002004 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002005 ret = -1;
2006 goto out;
2007 }
balrog926c2d22007-10-31 01:11:44 +00002008
Max Reitzb65a5e12015-02-05 13:58:12 -05002009 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002010 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +01002011 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002012 ret = -1;
2013 goto out;
2014 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09002015
Max Reitz2e024cd2015-02-11 09:58:46 -05002016 if (!skip_create) {
2017 if (!drv->create_opts) {
2018 error_report("Format driver '%s' does not support image creation",
2019 drv->format_name);
2020 ret = -1;
2021 goto out;
2022 }
Max Reitzf75613c2014-12-02 18:32:46 +01002023
Max Reitz2e024cd2015-02-11 09:58:46 -05002024 if (!proto_drv->create_opts) {
2025 error_report("Protocol driver '%s' does not support image creation",
2026 proto_drv->format_name);
2027 ret = -1;
2028 goto out;
2029 }
Max Reitzf75613c2014-12-02 18:32:46 +01002030
Max Reitz2e024cd2015-02-11 09:58:46 -05002031 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2032 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002033
Max Reitz2e024cd2015-02-11 09:58:46 -05002034 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002035 if (options) {
2036 qemu_opts_do_parse(opts, options, NULL, &local_err);
2037 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002038 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002039 ret = -1;
2040 goto out;
2041 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002042 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002043
Markus Armbruster39101f22015-02-12 16:46:36 +01002044 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2045 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002046 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2047 if (ret < 0) {
2048 goto out;
2049 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002050 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002051
Kevin Wolfa18953f2010-10-14 15:46:04 +02002052 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002053 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002054 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002055 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002056 }
2057
Kevin Wolfefa84d42009-05-18 16:42:12 +02002058 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01002059 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002060 bool encryption =
2061 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2062 const char *preallocation =
2063 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002064
Pavel Butsykin35fadca2016-07-22 11:17:48 +03002065 if (!drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002066 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002067 ret = -1;
2068 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002069 }
2070
Chunyan Liu83d05212014-06-05 17:20:51 +08002071 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002072 error_report("Compression and encryption not supported at "
2073 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002074 ret = -1;
2075 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002076 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002077
Chunyan Liu83d05212014-06-05 17:20:51 +08002078 if (preallocation
2079 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002080 {
2081 error_report("Compression and preallocation not supported at "
2082 "the same time");
2083 ret = -1;
2084 goto out;
2085 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002086 }
2087
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002088 if (!skip_create) {
2089 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002090 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002091 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002092 error_reportf_err(local_err, "%s: error while converting %s: ",
2093 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002094 goto out;
bellardea2384d2004-08-01 21:59:26 +00002095 }
2096 }
ths3b46e622007-09-17 08:09:54 +00002097
Peter Lieven5a37b602013-10-24 12:07:06 +02002098 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002099 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002100 if (ret < 0) {
2101 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002102 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002103 }
2104
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002105 /* XXX we should allow --image-opts to trigger use of
2106 * img_open() here, but then we have trouble with
2107 * the bdrv_create() call which takes different params.
2108 * Not critical right now, so fix can wait...
2109 */
Kevin Wolfce099542016-03-15 13:01:04 +01002110 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002111 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002112 ret = -1;
2113 goto out;
2114 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002115 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00002116
Eric Blake5def6b82016-06-23 16:37:19 -06002117 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002118 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2119 * as maximum. */
2120 bufsectors = MIN(32768,
Eric Blake5def6b82016-06-23 16:37:19 -06002121 MAX(bufsectors,
2122 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
Eric Blakeb9f78552016-06-23 16:37:21 -06002123 out_bs->bl.pdiscard_alignment >>
2124 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002125
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002126 if (skip_create) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05002127 int64_t output_sectors = blk_nb_sectors(out_blk);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002128 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002129 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002130 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002131 ret = -1;
2132 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02002133 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002134 error_report("output file is smaller than input file");
2135 ret = -1;
2136 goto out;
2137 }
2138 }
2139
Peter Lieven24f833c2013-11-27 11:07:07 +01002140 cluster_sectors = 0;
2141 ret = bdrv_get_info(out_bs, &bdi);
2142 if (ret < 0) {
2143 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002144 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002145 goto out;
2146 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002147 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08002148 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01002149 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2150 }
2151
Kevin Wolf690c7302015-03-19 13:33:32 +01002152 state = (ImgConvertState) {
2153 .src = blk,
2154 .src_sectors = bs_sectors,
2155 .src_num = bs_n,
2156 .total_sectors = total_sectors,
2157 .target = out_blk,
2158 .compressed = compress,
2159 .target_has_backing = (bool) out_baseimg,
2160 .min_sparse = min_sparse,
2161 .cluster_sectors = cluster_sectors,
2162 .buf_sectors = bufsectors,
2163 };
2164 ret = convert_do_copy(&state);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002165
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002166out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002167 if (!ret) {
2168 qemu_progress_print(100, 0);
2169 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002170 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002171 qemu_opts_del(opts);
2172 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002173 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002174 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02002175 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002176 if (blk) {
2177 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2178 blk_unref(blk[bs_i]);
2179 }
2180 g_free(blk);
2181 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02002182 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002183fail_getopt:
2184 g_free(options);
2185
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002186 if (ret) {
2187 return 1;
2188 }
bellardea2384d2004-08-01 21:59:26 +00002189 return 0;
2190}
2191
bellard57d1a2b2004-08-03 21:15:11 +00002192
bellardfaea38e2006-08-05 21:31:00 +00002193static void dump_snapshots(BlockDriverState *bs)
2194{
2195 QEMUSnapshotInfo *sn_tab, *sn;
2196 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002197
2198 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2199 if (nb_sns <= 0)
2200 return;
2201 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002202 bdrv_snapshot_dump(fprintf, stdout, NULL);
2203 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002204 for(i = 0; i < nb_sns; i++) {
2205 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002206 bdrv_snapshot_dump(fprintf, stdout, sn);
2207 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002208 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002209 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002210}
2211
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002212static void dump_json_image_info_list(ImageInfoList *list)
2213{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002214 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002215 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002216 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002217
2218 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2219 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002220 str = qobject_to_json_pretty(obj);
2221 assert(str != NULL);
2222 printf("%s\n", qstring_get_str(str));
2223 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002224 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002225 QDECREF(str);
2226}
2227
Benoît Canetc054b3f2012-09-05 13:09:02 +02002228static void dump_json_image_info(ImageInfo *info)
2229{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002230 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002231 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002232 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002233
2234 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2235 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002236 str = qobject_to_json_pretty(obj);
2237 assert(str != NULL);
2238 printf("%s\n", qstring_get_str(str));
2239 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002240 visit_free(v);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002241 QDECREF(str);
2242}
2243
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002244static void dump_human_image_info_list(ImageInfoList *list)
2245{
2246 ImageInfoList *elem;
2247 bool delim = false;
2248
2249 for (elem = list; elem; elem = elem->next) {
2250 if (delim) {
2251 printf("\n");
2252 }
2253 delim = true;
2254
Wenchao Xia5b917042013-05-25 11:09:45 +08002255 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002256 }
2257}
2258
2259static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2260{
2261 return strcmp(a, b) == 0;
2262}
2263
2264/**
2265 * Open an image file chain and return an ImageInfoList
2266 *
2267 * @filename: topmost image filename
2268 * @fmt: topmost image format (may be NULL to autodetect)
2269 * @chain: true - enumerate entire backing file chain
2270 * false - only topmost image file
2271 *
2272 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2273 * image file. If there was an error a message will have been printed to
2274 * stderr.
2275 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002276static ImageInfoList *collect_image_info_list(bool image_opts,
2277 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002278 const char *fmt,
2279 bool chain)
2280{
2281 ImageInfoList *head = NULL;
2282 ImageInfoList **last = &head;
2283 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002284 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002285
2286 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2287
2288 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002289 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002290 BlockDriverState *bs;
2291 ImageInfo *info;
2292 ImageInfoList *elem;
2293
2294 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2295 error_report("Backing file '%s' creates an infinite loop.",
2296 filename);
2297 goto err;
2298 }
2299 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2300
Max Reitzefaa7c42016-03-16 19:54:38 +01002301 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01002302 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002303 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002304 goto err;
2305 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002306 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002307
Wenchao Xia43526ec2013-06-06 12:27:58 +08002308 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002309 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002310 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002311 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002312 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002313 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002314
2315 elem = g_new0(ImageInfoList, 1);
2316 elem->value = info;
2317 *last = elem;
2318 last = &elem->next;
2319
Markus Armbruster26f54e92014-10-07 13:59:04 +02002320 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002321
2322 filename = fmt = NULL;
2323 if (chain) {
2324 if (info->has_full_backing_filename) {
2325 filename = info->full_backing_filename;
2326 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002327 error_report("Could not determine absolute backing filename,"
2328 " but backing filename '%s' present",
2329 info->backing_filename);
2330 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002331 }
2332 if (info->has_backing_filename_format) {
2333 fmt = info->backing_filename_format;
2334 }
2335 }
2336 }
2337 g_hash_table_destroy(filenames);
2338 return head;
2339
2340err:
2341 qapi_free_ImageInfoList(head);
2342 g_hash_table_destroy(filenames);
2343 return NULL;
2344}
2345
Benoît Canetc054b3f2012-09-05 13:09:02 +02002346static int img_info(int argc, char **argv)
2347{
2348 int c;
2349 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002350 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002351 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002352 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002353 bool image_opts = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002354
bellardea2384d2004-08-01 21:59:26 +00002355 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002356 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002357 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002358 int option_index = 0;
2359 static const struct option long_options[] = {
2360 {"help", no_argument, 0, 'h'},
2361 {"format", required_argument, 0, 'f'},
2362 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002363 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002364 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002365 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002366 {0, 0, 0, 0}
2367 };
2368 c = getopt_long(argc, argv, "f:h",
2369 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002370 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002371 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002372 }
bellardea2384d2004-08-01 21:59:26 +00002373 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002374 case '?':
bellardea2384d2004-08-01 21:59:26 +00002375 case 'h':
2376 help();
2377 break;
2378 case 'f':
2379 fmt = optarg;
2380 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002381 case OPTION_OUTPUT:
2382 output = optarg;
2383 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002384 case OPTION_BACKING_CHAIN:
2385 chain = true;
2386 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002387 case OPTION_OBJECT: {
2388 QemuOpts *opts;
2389 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2390 optarg, true);
2391 if (!opts) {
2392 return 1;
2393 }
2394 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002395 case OPTION_IMAGE_OPTS:
2396 image_opts = true;
2397 break;
bellardea2384d2004-08-01 21:59:26 +00002398 }
2399 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002400 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002401 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002402 }
bellardea2384d2004-08-01 21:59:26 +00002403 filename = argv[optind++];
2404
Benoît Canetc054b3f2012-09-05 13:09:02 +02002405 if (output && !strcmp(output, "json")) {
2406 output_format = OFORMAT_JSON;
2407 } else if (output && !strcmp(output, "human")) {
2408 output_format = OFORMAT_HUMAN;
2409 } else if (output) {
2410 error_report("--output must be used with human or json as argument.");
2411 return 1;
2412 }
2413
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002414 if (qemu_opts_foreach(&qemu_object_opts,
2415 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002416 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002417 return 1;
2418 }
2419
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002420 list = collect_image_info_list(image_opts, filename, fmt, chain);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002421 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002422 return 1;
2423 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002424
Benoît Canetc054b3f2012-09-05 13:09:02 +02002425 switch (output_format) {
2426 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002427 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002428 break;
2429 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002430 if (chain) {
2431 dump_json_image_info_list(list);
2432 } else {
2433 dump_json_image_info(list->value);
2434 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002435 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002436 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002437
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002438 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002439 return 0;
2440}
2441
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002442static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2443 MapEntry *next)
2444{
2445 switch (output_format) {
2446 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002447 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002448 error_report("File contains external, encrypted or compressed clusters.");
2449 exit(1);
2450 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002451 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002452 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002453 e->start, e->length,
2454 e->has_offset ? e->offset : 0,
2455 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002456 }
2457 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2458 * Modify the flags here to allow more coalescing.
2459 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002460 if (next && (!next->data || next->zero)) {
2461 next->data = false;
2462 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002463 }
2464 break;
2465 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002466 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2467 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002468 (e->start == 0 ? "[" : ",\n"),
2469 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002470 e->zero ? "true" : "false",
2471 e->data ? "true" : "false");
2472 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002473 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002474 }
2475 putchar('}');
2476
2477 if (!next) {
2478 printf("]\n");
2479 }
2480 break;
2481 }
2482}
2483
2484static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2485 int nb_sectors, MapEntry *e)
2486{
2487 int64_t ret;
2488 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002489 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002490 bool has_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002491
2492 /* As an optimization, we could cache the current range of unallocated
2493 * clusters in each file of the chain, and avoid querying the same
2494 * range repeatedly.
2495 */
2496
2497 depth = 0;
2498 for (;;) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08002499 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2500 &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002501 if (ret < 0) {
2502 return ret;
2503 }
2504 assert(nb_sectors);
2505 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2506 break;
2507 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002508 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002509 if (bs == NULL) {
2510 ret = 0;
2511 break;
2512 }
2513
2514 depth++;
2515 }
2516
John Snow28756452016-02-05 13:12:33 -05002517 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2518
2519 *e = (MapEntry) {
2520 .start = sector_num * BDRV_SECTOR_SIZE,
2521 .length = nb_sectors * BDRV_SECTOR_SIZE,
2522 .data = !!(ret & BDRV_BLOCK_DATA),
2523 .zero = !!(ret & BDRV_BLOCK_ZERO),
2524 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2525 .has_offset = has_offset,
2526 .depth = depth,
2527 .has_filename = file && has_offset,
2528 .filename = file && has_offset ? file->filename : NULL,
2529 };
2530
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002531 return 0;
2532}
2533
Fam Zheng16b0d552016-01-26 11:59:02 +08002534static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2535{
2536 if (curr->length == 0) {
2537 return false;
2538 }
2539 if (curr->zero != next->zero ||
2540 curr->data != next->data ||
2541 curr->depth != next->depth ||
2542 curr->has_filename != next->has_filename ||
2543 curr->has_offset != next->has_offset) {
2544 return false;
2545 }
2546 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2547 return false;
2548 }
2549 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2550 return false;
2551 }
2552 return true;
2553}
2554
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002555static int img_map(int argc, char **argv)
2556{
2557 int c;
2558 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002559 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002560 BlockDriverState *bs;
2561 const char *filename, *fmt, *output;
2562 int64_t length;
2563 MapEntry curr = { .length = 0 }, next;
2564 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002565 bool image_opts = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002566
2567 fmt = NULL;
2568 output = NULL;
2569 for (;;) {
2570 int option_index = 0;
2571 static const struct option long_options[] = {
2572 {"help", no_argument, 0, 'h'},
2573 {"format", required_argument, 0, 'f'},
2574 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002575 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002576 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002577 {0, 0, 0, 0}
2578 };
2579 c = getopt_long(argc, argv, "f:h",
2580 long_options, &option_index);
2581 if (c == -1) {
2582 break;
2583 }
2584 switch (c) {
2585 case '?':
2586 case 'h':
2587 help();
2588 break;
2589 case 'f':
2590 fmt = optarg;
2591 break;
2592 case OPTION_OUTPUT:
2593 output = optarg;
2594 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002595 case OPTION_OBJECT: {
2596 QemuOpts *opts;
2597 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2598 optarg, true);
2599 if (!opts) {
2600 return 1;
2601 }
2602 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002603 case OPTION_IMAGE_OPTS:
2604 image_opts = true;
2605 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002606 }
2607 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002608 if (optind != argc - 1) {
2609 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002610 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002611 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002612
2613 if (output && !strcmp(output, "json")) {
2614 output_format = OFORMAT_JSON;
2615 } else if (output && !strcmp(output, "human")) {
2616 output_format = OFORMAT_HUMAN;
2617 } else if (output) {
2618 error_report("--output must be used with human or json as argument.");
2619 return 1;
2620 }
2621
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002622 if (qemu_opts_foreach(&qemu_object_opts,
2623 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002624 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002625 return 1;
2626 }
2627
Kevin Wolfce099542016-03-15 13:01:04 +01002628 blk = img_open(image_opts, filename, fmt, 0, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002629 if (!blk) {
2630 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002631 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002632 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002633
2634 if (output_format == OFORMAT_HUMAN) {
2635 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2636 }
2637
Max Reitzf1d3cd72015-02-05 13:58:18 -05002638 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002639 while (curr.start + curr.length < length) {
2640 int64_t nsectors_left;
2641 int64_t sector_num;
2642 int n;
2643
2644 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2645
2646 /* Probe up to 1 GiB at a time. */
2647 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2648 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2649 ret = get_block_status(bs, sector_num, n, &next);
2650
2651 if (ret < 0) {
2652 error_report("Could not read file metadata: %s", strerror(-ret));
2653 goto out;
2654 }
2655
Fam Zheng16b0d552016-01-26 11:59:02 +08002656 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002657 curr.length += next.length;
2658 continue;
2659 }
2660
2661 if (curr.length > 0) {
2662 dump_map_entry(output_format, &curr, &next);
2663 }
2664 curr = next;
2665 }
2666
2667 dump_map_entry(output_format, &curr, NULL);
2668
2669out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002670 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002671 return ret < 0;
2672}
2673
aliguorif7b4a942009-01-07 17:40:15 +00002674#define SNAPSHOT_LIST 1
2675#define SNAPSHOT_CREATE 2
2676#define SNAPSHOT_APPLY 3
2677#define SNAPSHOT_DELETE 4
2678
Stuart Brady153859b2009-06-07 00:42:17 +01002679static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002680{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002681 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002682 BlockDriverState *bs;
2683 QEMUSnapshotInfo sn;
2684 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002685 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002686 int action = 0;
2687 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002688 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002689 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002690 bool image_opts = false;
aliguorif7b4a942009-01-07 17:40:15 +00002691
Kevin Wolfce099542016-03-15 13:01:04 +01002692 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002693 /* Parse commandline parameters */
2694 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002695 static const struct option long_options[] = {
2696 {"help", no_argument, 0, 'h'},
2697 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002698 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002699 {0, 0, 0, 0}
2700 };
2701 c = getopt_long(argc, argv, "la:c:d:hq",
2702 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002703 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002704 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002705 }
aliguorif7b4a942009-01-07 17:40:15 +00002706 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002707 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002708 case 'h':
2709 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002710 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002711 case 'l':
2712 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002713 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002714 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002715 }
2716 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002717 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002718 break;
2719 case 'a':
2720 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002721 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002722 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002723 }
2724 action = SNAPSHOT_APPLY;
2725 snapshot_name = optarg;
2726 break;
2727 case 'c':
2728 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002729 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002730 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002731 }
2732 action = SNAPSHOT_CREATE;
2733 snapshot_name = optarg;
2734 break;
2735 case 'd':
2736 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002737 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002738 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002739 }
2740 action = SNAPSHOT_DELETE;
2741 snapshot_name = optarg;
2742 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002743 case 'q':
2744 quiet = true;
2745 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002746 case OPTION_OBJECT: {
2747 QemuOpts *opts;
2748 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2749 optarg, true);
2750 if (!opts) {
2751 return 1;
2752 }
2753 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002754 case OPTION_IMAGE_OPTS:
2755 image_opts = true;
2756 break;
aliguorif7b4a942009-01-07 17:40:15 +00002757 }
2758 }
2759
Kevin Wolffc11eb22013-08-05 10:53:04 +02002760 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002761 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002762 }
aliguorif7b4a942009-01-07 17:40:15 +00002763 filename = argv[optind++];
2764
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002765 if (qemu_opts_foreach(&qemu_object_opts,
2766 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002767 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002768 return 1;
2769 }
2770
aliguorif7b4a942009-01-07 17:40:15 +00002771 /* Open the image */
Kevin Wolfce099542016-03-15 13:01:04 +01002772 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002773 if (!blk) {
2774 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002775 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002776 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002777
2778 /* Perform the requested action */
2779 switch(action) {
2780 case SNAPSHOT_LIST:
2781 dump_snapshots(bs);
2782 break;
2783
2784 case SNAPSHOT_CREATE:
2785 memset(&sn, 0, sizeof(sn));
2786 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2787
2788 qemu_gettimeofday(&tv);
2789 sn.date_sec = tv.tv_sec;
2790 sn.date_nsec = tv.tv_usec * 1000;
2791
2792 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002793 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002794 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002795 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002796 }
aliguorif7b4a942009-01-07 17:40:15 +00002797 break;
2798
2799 case SNAPSHOT_APPLY:
2800 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002801 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002802 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002803 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002804 }
aliguorif7b4a942009-01-07 17:40:15 +00002805 break;
2806
2807 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002808 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002809 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002810 error_reportf_err(err, "Could not delete snapshot '%s': ",
2811 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002812 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002813 }
aliguorif7b4a942009-01-07 17:40:15 +00002814 break;
2815 }
2816
2817 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002818 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002819 if (ret) {
2820 return 1;
2821 }
Stuart Brady153859b2009-06-07 00:42:17 +01002822 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002823}
2824
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002825static int img_rebase(int argc, char **argv)
2826{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002827 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01002828 uint8_t *buf_old = NULL;
2829 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05002830 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002831 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002832 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2833 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01002834 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002835 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002836 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002837 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002838 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002839 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002840
2841 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002842 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002843 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002844 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002845 out_baseimg = NULL;
2846 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002847 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002848 static const struct option long_options[] = {
2849 {"help", no_argument, 0, 'h'},
2850 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002851 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002852 {0, 0, 0, 0}
2853 };
2854 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2855 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002856 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002857 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002858 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002859 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002860 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002861 case 'h':
2862 help();
2863 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002864 case 'f':
2865 fmt = optarg;
2866 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002867 case 'F':
2868 out_basefmt = optarg;
2869 break;
2870 case 'b':
2871 out_baseimg = optarg;
2872 break;
2873 case 'u':
2874 unsafe = 1;
2875 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002876 case 'p':
2877 progress = 1;
2878 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002879 case 't':
2880 cache = optarg;
2881 break;
Max Reitz40055952014-07-22 22:58:42 +02002882 case 'T':
2883 src_cache = optarg;
2884 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002885 case 'q':
2886 quiet = true;
2887 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002888 case OPTION_OBJECT: {
2889 QemuOpts *opts;
2890 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2891 optarg, true);
2892 if (!opts) {
2893 return 1;
2894 }
2895 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002896 case OPTION_IMAGE_OPTS:
2897 image_opts = true;
2898 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002899 }
2900 }
2901
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002902 if (quiet) {
2903 progress = 0;
2904 }
2905
Fam Zhengac1307a2014-04-22 13:36:11 +08002906 if (optind != argc - 1) {
2907 error_exit("Expecting one image file name");
2908 }
2909 if (!unsafe && !out_baseimg) {
2910 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002911 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002912 filename = argv[optind++];
2913
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002914 if (qemu_opts_foreach(&qemu_object_opts,
2915 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002916 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002917 return 1;
2918 }
2919
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002920 qemu_progress_init(progress, 2.0);
2921 qemu_progress_print(0, 100);
2922
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002923 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01002924 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002925 if (ret < 0) {
2926 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002927 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002928 }
2929
Kevin Wolfce099542016-03-15 13:01:04 +01002930 src_flags = 0;
2931 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02002932 if (ret < 0) {
2933 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002934 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002935 }
2936
Kevin Wolfce099542016-03-15 13:01:04 +01002937 /* The source files are opened read-only, don't care about WCE */
2938 assert((src_flags & BDRV_O_RDWR) == 0);
2939 (void) src_writethrough;
2940
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002941 /*
2942 * Open the images.
2943 *
2944 * Ignore the old backing file for unsafe rebase in case we want to correct
2945 * the reference to a renamed or moved backing file.
2946 */
Kevin Wolfce099542016-03-15 13:01:04 +01002947 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002948 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002949 ret = -1;
2950 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002951 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002952 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002953
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002954 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05002955 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002956 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002957 ret = -1;
2958 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002959 }
2960 }
2961
2962 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002963 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05002964 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05002965 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002966
Max Reitz644483d2015-02-05 13:58:17 -05002967 if (bs->backing_format[0] != '\0') {
2968 options = qdict_new();
2969 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2970 }
2971
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002972 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01002973 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002974 options, src_flags, &local_err);
2975 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002976 error_reportf_err(local_err,
2977 "Could not open old backing file '%s': ",
2978 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002979 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002980 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002981 }
Max Reitz644483d2015-02-05 13:58:17 -05002982
Alex Bligha6166732012-10-16 13:46:18 +01002983 if (out_baseimg[0]) {
Max Reitz644483d2015-02-05 13:58:17 -05002984 if (out_basefmt) {
2985 options = qdict_new();
2986 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2987 } else {
2988 options = NULL;
2989 }
2990
Max Reitzefaa7c42016-03-16 19:54:38 +01002991 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002992 options, src_flags, &local_err);
2993 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002994 error_reportf_err(local_err,
2995 "Could not open new backing file '%s': ",
2996 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002997 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01002998 goto out;
2999 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003000 }
3001 }
3002
3003 /*
3004 * Check each unallocated cluster in the COW file. If it is unallocated,
3005 * accesses go to the backing file. We must therefore compare this cluster
3006 * in the old and new backing file, and if they differ we need to copy it
3007 * from the old backing file into the COW file.
3008 *
3009 * If qemu-img crashes during this step, no harm is done. The content of
3010 * the image is the same as the original one at any time.
3011 */
3012 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003013 int64_t num_sectors;
3014 int64_t old_backing_num_sectors;
3015 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003016 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003017 int n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003018 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003019
Max Reitzf1d3cd72015-02-05 13:58:18 -05003020 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3021 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003022
Max Reitzf1d3cd72015-02-05 13:58:18 -05003023 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003024 if (num_sectors < 0) {
3025 error_report("Could not get size of '%s': %s",
3026 filename, strerror(-num_sectors));
3027 ret = -1;
3028 goto out;
3029 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003030 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003031 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003032 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003033
3034 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3035 error_report("Could not get size of '%s': %s",
3036 backing_name, strerror(-old_backing_num_sectors));
3037 ret = -1;
3038 goto out;
3039 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003040 if (blk_new_backing) {
3041 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003042 if (new_backing_num_sectors < 0) {
3043 error_report("Could not get size of '%s': %s",
3044 out_baseimg, strerror(-new_backing_num_sectors));
3045 ret = -1;
3046 goto out;
3047 }
Alex Bligha6166732012-10-16 13:46:18 +01003048 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003049
Kevin Wolf1f710492012-10-12 14:29:18 +02003050 if (num_sectors != 0) {
3051 local_progress = (float)100 /
3052 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3053 }
3054
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003055 for (sector = 0; sector < num_sectors; sector += n) {
3056
3057 /* How many sectors can we handle with the next read? */
3058 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3059 n = (IO_BUF_SIZE / 512);
3060 } else {
3061 n = num_sectors - sector;
3062 }
3063
3064 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02003065 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003066 if (ret < 0) {
3067 error_report("error while reading image metadata: %s",
3068 strerror(-ret));
3069 goto out;
3070 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003071 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003072 continue;
3073 }
3074
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003075 /*
3076 * Read old and new backing file and take into consideration that
3077 * backing files may be smaller than the COW image.
3078 */
3079 if (sector >= old_backing_num_sectors) {
3080 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3081 } else {
3082 if (sector + n > old_backing_num_sectors) {
3083 n = old_backing_num_sectors - sector;
3084 }
3085
Eric Blake91669202016-05-06 10:26:43 -06003086 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3087 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003088 if (ret < 0) {
3089 error_report("error while reading from old backing file");
3090 goto out;
3091 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003092 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003093
Max Reitzf1d3cd72015-02-05 13:58:18 -05003094 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003095 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3096 } else {
3097 if (sector + n > new_backing_num_sectors) {
3098 n = new_backing_num_sectors - sector;
3099 }
3100
Eric Blake91669202016-05-06 10:26:43 -06003101 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3102 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003103 if (ret < 0) {
3104 error_report("error while reading from new backing file");
3105 goto out;
3106 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003107 }
3108
3109 /* If they differ, we need to write to the COW file */
3110 uint64_t written = 0;
3111
3112 while (written < n) {
3113 int pnum;
3114
3115 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003116 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003117 {
Eric Blake91669202016-05-06 10:26:43 -06003118 ret = blk_pwrite(blk,
3119 (sector + written) << BDRV_SECTOR_BITS,
3120 buf_old + written * 512,
3121 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003122 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003123 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003124 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003125 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003126 }
3127 }
3128
3129 written += pnum;
3130 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003131 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003132 }
3133 }
3134
3135 /*
3136 * Change the backing file. All clusters that are different from the old
3137 * backing file are overwritten in the COW file now, so the visible content
3138 * doesn't change when we switch the backing file.
3139 */
Alex Bligha6166732012-10-16 13:46:18 +01003140 if (out_baseimg && *out_baseimg) {
3141 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3142 } else {
3143 ret = bdrv_change_backing_file(bs, NULL, NULL);
3144 }
3145
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003146 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003147 error_report("Could not change the backing file to '%s': No "
3148 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003149 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003150 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003151 out_baseimg, strerror(-ret));
3152 }
3153
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003154 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003155 /*
3156 * TODO At this point it is possible to check if any clusters that are
3157 * allocated in the COW file are the same in the backing file. If so, they
3158 * could be dropped from the COW file. Don't do this before switching the
3159 * backing file, in case of a crash this would lead to corruption.
3160 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003161out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003162 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163 /* Cleanup */
3164 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003165 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003166 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003167 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003168 qemu_vfree(buf_old);
3169 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003170
Markus Armbruster26f54e92014-10-07 13:59:04 +02003171 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003172 if (ret) {
3173 return 1;
3174 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003175 return 0;
3176}
3177
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003178static int img_resize(int argc, char **argv)
3179{
Markus Armbruster6750e792015-02-12 17:43:08 +01003180 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003181 int c, ret, relative;
3182 const char *filename, *fmt, *size;
3183 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003184 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003185 BlockBackend *blk = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003186 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003187
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003188 static QemuOptsList resize_options = {
3189 .name = "resize_options",
3190 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3191 .desc = {
3192 {
3193 .name = BLOCK_OPT_SIZE,
3194 .type = QEMU_OPT_SIZE,
3195 .help = "Virtual disk size"
3196 }, {
3197 /* end of list */
3198 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003199 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003200 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003201 bool image_opts = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003202
Kevin Wolfe80fec72011-04-29 10:58:12 +02003203 /* Remove size from argv manually so that negative numbers are not treated
3204 * as options by getopt. */
3205 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003206 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003207 return 1;
3208 }
3209
3210 size = argv[--argc];
3211
3212 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003213 fmt = NULL;
3214 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003215 static const struct option long_options[] = {
3216 {"help", no_argument, 0, 'h'},
3217 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003218 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003219 {0, 0, 0, 0}
3220 };
3221 c = getopt_long(argc, argv, "f:hq",
3222 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003223 if (c == -1) {
3224 break;
3225 }
3226 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01003227 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003228 case 'h':
3229 help();
3230 break;
3231 case 'f':
3232 fmt = optarg;
3233 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003234 case 'q':
3235 quiet = true;
3236 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003237 case OPTION_OBJECT: {
3238 QemuOpts *opts;
3239 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3240 optarg, true);
3241 if (!opts) {
3242 return 1;
3243 }
3244 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003245 case OPTION_IMAGE_OPTS:
3246 image_opts = true;
3247 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003248 }
3249 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003250 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003251 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003252 }
3253 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003254
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003255 if (qemu_opts_foreach(&qemu_object_opts,
3256 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003257 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003258 return 1;
3259 }
3260
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003261 /* Choose grow, shrink, or absolute resize mode */
3262 switch (size[0]) {
3263 case '+':
3264 relative = 1;
3265 size++;
3266 break;
3267 case '-':
3268 relative = -1;
3269 size++;
3270 break;
3271 default:
3272 relative = 0;
3273 break;
3274 }
3275
3276 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003277 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003278 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003279 if (err) {
3280 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003281 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003282 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003283 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003284 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003285 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3286 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003287
Max Reitzefaa7c42016-03-16 19:54:38 +01003288 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01003289 BDRV_O_RDWR, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003290 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003291 ret = -1;
3292 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003293 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003294
3295 if (relative) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05003296 total_size = blk_getlength(blk) + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003297 } else {
3298 total_size = n;
3299 }
3300 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003301 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003302 ret = -1;
3303 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003304 }
3305
Max Reitzf1d3cd72015-02-05 13:58:18 -05003306 ret = blk_truncate(blk, total_size);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003307 switch (ret) {
3308 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003309 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003310 break;
3311 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01003312 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003313 break;
3314 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01003315 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003316 break;
3317 default:
Max Reitzbcf23482016-06-15 17:36:29 +02003318 error_report("Error resizing image: %s", strerror(-ret));
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003319 break;
3320 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003321out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003322 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003323 if (ret) {
3324 return 1;
3325 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003326 return 0;
3327}
3328
Max Reitz76a3a342014-10-27 11:12:51 +01003329static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003330 int64_t offset, int64_t total_work_size,
3331 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003332{
3333 qemu_progress_print(100.f * offset / total_work_size, 0);
3334}
3335
Max Reitz6f176b42013-09-03 10:09:50 +02003336static int img_amend(int argc, char **argv)
3337{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003338 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003339 int c, ret = 0;
3340 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003341 QemuOptsList *create_opts = NULL;
3342 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003343 const char *fmt = NULL, *filename, *cache;
3344 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003345 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003346 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003347 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003348 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003349 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003350
Max Reitzbd39e6e2014-07-22 22:58:43 +02003351 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003352 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003353 static const struct option long_options[] = {
3354 {"help", no_argument, 0, 'h'},
3355 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003356 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003357 {0, 0, 0, 0}
3358 };
3359 c = getopt_long(argc, argv, "ho:f:t:pq",
3360 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003361 if (c == -1) {
3362 break;
3363 }
3364
3365 switch (c) {
3366 case 'h':
3367 case '?':
3368 help();
3369 break;
3370 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01003371 if (!is_valid_option_list(optarg)) {
3372 error_report("Invalid option list: %s", optarg);
3373 ret = -1;
Max Reitze814dff2015-08-20 16:00:38 -07003374 goto out_no_progress;
Kevin Wolf626f84f2014-02-21 16:24:06 +01003375 }
3376 if (!options) {
3377 options = g_strdup(optarg);
3378 } else {
3379 char *old_options = options;
3380 options = g_strdup_printf("%s,%s", options, optarg);
3381 g_free(old_options);
3382 }
Max Reitz6f176b42013-09-03 10:09:50 +02003383 break;
3384 case 'f':
3385 fmt = optarg;
3386 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003387 case 't':
3388 cache = optarg;
3389 break;
Max Reitz76a3a342014-10-27 11:12:51 +01003390 case 'p':
3391 progress = true;
3392 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003393 case 'q':
3394 quiet = true;
3395 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003396 case OPTION_OBJECT:
3397 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3398 optarg, true);
3399 if (!opts) {
3400 ret = -1;
3401 goto out_no_progress;
3402 }
3403 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003404 case OPTION_IMAGE_OPTS:
3405 image_opts = true;
3406 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003407 }
3408 }
3409
Max Reitz6f176b42013-09-03 10:09:50 +02003410 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003411 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003412 }
3413
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003414 if (qemu_opts_foreach(&qemu_object_opts,
3415 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003416 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003417 ret = -1;
3418 goto out_no_progress;
3419 }
3420
Max Reitz76a3a342014-10-27 11:12:51 +01003421 if (quiet) {
3422 progress = false;
3423 }
3424 qemu_progress_init(progress, 1.0);
3425
Kevin Wolfa283cb62014-02-21 16:24:07 +01003426 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3427 if (fmt && has_help_option(options)) {
3428 /* If a format is explicitly specified (and possibly no filename is
3429 * given), print option help here */
3430 ret = print_block_option_help(filename, fmt);
3431 goto out;
3432 }
3433
3434 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003435 error_report("Expecting one image file name");
3436 ret = -1;
3437 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003438 }
Max Reitz6f176b42013-09-03 10:09:50 +02003439
Kevin Wolfce099542016-03-15 13:01:04 +01003440 flags = BDRV_O_RDWR;
3441 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003442 if (ret < 0) {
3443 error_report("Invalid cache option: %s", cache);
3444 goto out;
3445 }
3446
Kevin Wolfce099542016-03-15 13:01:04 +01003447 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003448 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003449 ret = -1;
3450 goto out;
3451 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003452 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003453
3454 fmt = bs->drv->format_name;
3455
Kevin Wolf626f84f2014-02-21 16:24:06 +01003456 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003457 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003458 ret = print_block_option_help(filename, fmt);
3459 goto out;
3460 }
3461
Max Reitzb2439d22014-12-02 18:32:47 +01003462 if (!bs->drv->create_opts) {
3463 error_report("Format driver '%s' does not support any options to amend",
3464 fmt);
3465 ret = -1;
3466 goto out;
3467 }
3468
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003469 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003470 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003471 qemu_opts_do_parse(opts, options, NULL, &err);
3472 if (err) {
3473 error_report_err(err);
3474 ret = -1;
3475 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003476 }
3477
Max Reitz76a3a342014-10-27 11:12:51 +01003478 /* In case the driver does not call amend_status_cb() */
3479 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003480 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003481 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003482 if (ret < 0) {
3483 error_report("Error while amending options: %s", strerror(-ret));
3484 goto out;
3485 }
3486
3487out:
Max Reitz76a3a342014-10-27 11:12:51 +01003488 qemu_progress_end();
3489
Max Reitze814dff2015-08-20 16:00:38 -07003490out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003491 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003492 qemu_opts_del(opts);
3493 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003494 g_free(options);
3495
Max Reitz6f176b42013-09-03 10:09:50 +02003496 if (ret) {
3497 return 1;
3498 }
3499 return 0;
3500}
3501
Kevin Wolfb6133b82014-08-05 14:17:13 +02003502typedef struct BenchData {
3503 BlockBackend *blk;
3504 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003505 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003506 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003507 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003508 int nrreq;
3509 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003510 int flush_interval;
3511 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003512 uint8_t *buf;
3513 QEMUIOVector *qiov;
3514
3515 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003516 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003517 uint64_t offset;
3518} BenchData;
3519
Kevin Wolf55d539c2016-06-03 13:59:41 +02003520static void bench_undrained_flush_cb(void *opaque, int ret)
3521{
3522 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003523 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003524 exit(EXIT_FAILURE);
3525 }
3526}
3527
Kevin Wolfb6133b82014-08-05 14:17:13 +02003528static void bench_cb(void *opaque, int ret)
3529{
3530 BenchData *b = opaque;
3531 BlockAIOCB *acb;
3532
3533 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003534 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003535 exit(EXIT_FAILURE);
3536 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003537
3538 if (b->in_flush) {
3539 /* Just finished a flush with drained queue: Start next requests */
3540 assert(b->in_flight == 0);
3541 b->in_flush = false;
3542 } else if (b->in_flight > 0) {
3543 int remaining = b->n - b->in_flight;
3544
Kevin Wolfb6133b82014-08-05 14:17:13 +02003545 b->n--;
3546 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003547
3548 /* Time for flush? Drain queue if requested, then flush */
3549 if (b->flush_interval && remaining % b->flush_interval == 0) {
3550 if (!b->in_flight || !b->drain_on_flush) {
3551 BlockCompletionFunc *cb;
3552
3553 if (b->drain_on_flush) {
3554 b->in_flush = true;
3555 cb = bench_cb;
3556 } else {
3557 cb = bench_undrained_flush_cb;
3558 }
3559
3560 acb = blk_aio_flush(b->blk, cb, b);
3561 if (!acb) {
3562 error_report("Failed to issue flush request");
3563 exit(EXIT_FAILURE);
3564 }
3565 }
3566 if (b->drain_on_flush) {
3567 return;
3568 }
3569 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003570 }
3571
3572 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003573 int64_t offset = b->offset;
3574 /* blk_aio_* might look for completed I/Os and kick bench_cb
3575 * again, so make sure this operation is counted by in_flight
3576 * and b->offset is ready for the next submission.
3577 */
3578 b->in_flight++;
3579 b->offset += b->step;
3580 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003581 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003582 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003583 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003584 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003585 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003586 if (!acb) {
3587 error_report("Failed to issue request");
3588 exit(EXIT_FAILURE);
3589 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003590 }
3591}
3592
3593static int img_bench(int argc, char **argv)
3594{
3595 int c, ret = 0;
3596 const char *fmt = NULL, *filename;
3597 bool quiet = false;
3598 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003599 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003600 int count = 75000;
3601 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003602 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003603 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003604 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003605 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003606 int flush_interval = 0;
3607 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003608 int64_t image_size;
3609 BlockBackend *blk = NULL;
3610 BenchData data = {};
3611 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003612 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003613 struct timeval t1, t2;
3614 int i;
3615
3616 for (;;) {
3617 static const struct option long_options[] = {
3618 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003619 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003620 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003621 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003622 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003623 {0, 0, 0, 0}
3624 };
Kevin Wolf83de9be2015-07-13 13:13:17 +02003625 c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003626 if (c == -1) {
3627 break;
3628 }
3629
3630 switch (c) {
3631 case 'h':
3632 case '?':
3633 help();
3634 break;
3635 case 'c':
3636 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003637 unsigned long res;
3638
3639 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003640 error_report("Invalid request count specified");
3641 return 1;
3642 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003643 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003644 break;
3645 }
3646 case 'd':
3647 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003648 unsigned long res;
3649
3650 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003651 error_report("Invalid queue depth specified");
3652 return 1;
3653 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003654 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003655 break;
3656 }
3657 case 'f':
3658 fmt = optarg;
3659 break;
3660 case 'n':
3661 flags |= BDRV_O_NATIVE_AIO;
3662 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003663 case 'o':
3664 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003665 offset = cvtnum(optarg);
3666 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003667 error_report("Invalid offset specified");
3668 return 1;
3669 }
3670 break;
3671 }
3672 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003673 case 'q':
3674 quiet = true;
3675 break;
3676 case 's':
3677 {
3678 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003679
Markus Armbruster606caa02017-02-21 21:14:04 +01003680 sval = cvtnum(optarg);
3681 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003682 error_report("Invalid buffer size specified");
3683 return 1;
3684 }
3685
3686 bufsize = sval;
3687 break;
3688 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003689 case 'S':
3690 {
3691 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003692
Markus Armbruster606caa02017-02-21 21:14:04 +01003693 sval = cvtnum(optarg);
3694 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003695 error_report("Invalid step size specified");
3696 return 1;
3697 }
3698
3699 step = sval;
3700 break;
3701 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003702 case 't':
3703 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3704 if (ret < 0) {
3705 error_report("Invalid cache mode");
3706 ret = -1;
3707 goto out;
3708 }
3709 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003710 case 'w':
3711 flags |= BDRV_O_RDWR;
3712 is_write = true;
3713 break;
3714 case OPTION_PATTERN:
3715 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003716 unsigned long res;
3717
3718 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003719 error_report("Invalid pattern byte specified");
3720 return 1;
3721 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003722 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003723 break;
3724 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003725 case OPTION_FLUSH_INTERVAL:
3726 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003727 unsigned long res;
3728
3729 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003730 error_report("Invalid flush interval specified");
3731 return 1;
3732 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003733 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003734 break;
3735 }
3736 case OPTION_NO_DRAIN:
3737 drain_on_flush = false;
3738 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003739 case OPTION_IMAGE_OPTS:
3740 image_opts = true;
3741 break;
3742 }
3743 }
3744
3745 if (optind != argc - 1) {
3746 error_exit("Expecting one image file name");
3747 }
3748 filename = argv[argc - 1];
3749
Kevin Wolf55d539c2016-06-03 13:59:41 +02003750 if (!is_write && flush_interval) {
3751 error_report("--flush-interval is only available in write tests");
3752 ret = -1;
3753 goto out;
3754 }
3755 if (flush_interval && flush_interval < depth) {
3756 error_report("Flush interval can't be smaller than depth");
3757 ret = -1;
3758 goto out;
3759 }
3760
Kevin Wolfb6133b82014-08-05 14:17:13 +02003761 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3762 if (!blk) {
3763 ret = -1;
3764 goto out;
3765 }
3766
3767 image_size = blk_getlength(blk);
3768 if (image_size < 0) {
3769 ret = image_size;
3770 goto out;
3771 }
3772
3773 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003774 .blk = blk,
3775 .image_size = image_size,
3776 .bufsize = bufsize,
3777 .step = step ?: bufsize,
3778 .nrreq = depth,
3779 .n = count,
3780 .offset = offset,
3781 .write = is_write,
3782 .flush_interval = flush_interval,
3783 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02003784 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02003785 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02003786 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02003787 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02003788 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02003789 if (flush_interval) {
3790 printf("Sending flush every %d requests\n", flush_interval);
3791 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003792
3793 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003794 memset(data.buf, pattern, data.nrreq * data.bufsize);
3795
Kevin Wolfb6133b82014-08-05 14:17:13 +02003796 data.qiov = g_new(QEMUIOVector, data.nrreq);
3797 for (i = 0; i < data.nrreq; i++) {
3798 qemu_iovec_init(&data.qiov[i], 1);
3799 qemu_iovec_add(&data.qiov[i],
3800 data.buf + i * data.bufsize, data.bufsize);
3801 }
3802
3803 gettimeofday(&t1, NULL);
3804 bench_cb(&data, 0);
3805
3806 while (data.n > 0) {
3807 main_loop_wait(false);
3808 }
3809 gettimeofday(&t2, NULL);
3810
3811 printf("Run completed in %3.3f seconds.\n",
3812 (t2.tv_sec - t1.tv_sec)
3813 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3814
3815out:
3816 qemu_vfree(data.buf);
3817 blk_unref(blk);
3818
3819 if (ret) {
3820 return 1;
3821 }
3822 return 0;
3823}
3824
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003825#define C_BS 01
3826#define C_COUNT 02
3827#define C_IF 04
3828#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02003829#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003830
3831struct DdInfo {
3832 unsigned int flags;
3833 int64_t count;
3834};
3835
3836struct DdIo {
3837 int bsz; /* Block size */
3838 char *filename;
3839 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02003840 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003841};
3842
3843struct DdOpts {
3844 const char *name;
3845 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
3846 unsigned int flag;
3847};
3848
3849static int img_dd_bs(const char *arg,
3850 struct DdIo *in, struct DdIo *out,
3851 struct DdInfo *dd)
3852{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003853 int64_t res;
3854
Markus Armbruster606caa02017-02-21 21:14:04 +01003855 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003856
Markus Armbruster606caa02017-02-21 21:14:04 +01003857 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003858 error_report("invalid number: '%s'", arg);
3859 return 1;
3860 }
3861 in->bsz = out->bsz = res;
3862
3863 return 0;
3864}
3865
3866static int img_dd_count(const char *arg,
3867 struct DdIo *in, struct DdIo *out,
3868 struct DdInfo *dd)
3869{
Markus Armbruster606caa02017-02-21 21:14:04 +01003870 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003871
Markus Armbruster606caa02017-02-21 21:14:04 +01003872 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003873 error_report("invalid number: '%s'", arg);
3874 return 1;
3875 }
3876
3877 return 0;
3878}
3879
3880static int img_dd_if(const char *arg,
3881 struct DdIo *in, struct DdIo *out,
3882 struct DdInfo *dd)
3883{
3884 in->filename = g_strdup(arg);
3885
3886 return 0;
3887}
3888
3889static int img_dd_of(const char *arg,
3890 struct DdIo *in, struct DdIo *out,
3891 struct DdInfo *dd)
3892{
3893 out->filename = g_strdup(arg);
3894
3895 return 0;
3896}
3897
Reda Sallahif7c15532016-08-10 16:16:09 +02003898static int img_dd_skip(const char *arg,
3899 struct DdIo *in, struct DdIo *out,
3900 struct DdInfo *dd)
3901{
Markus Armbruster606caa02017-02-21 21:14:04 +01003902 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02003903
Markus Armbruster606caa02017-02-21 21:14:04 +01003904 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02003905 error_report("invalid number: '%s'", arg);
3906 return 1;
3907 }
3908
3909 return 0;
3910}
3911
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003912static int img_dd(int argc, char **argv)
3913{
3914 int ret = 0;
3915 char *arg = NULL;
3916 char *tmp;
3917 BlockDriver *drv = NULL, *proto_drv = NULL;
3918 BlockBackend *blk1 = NULL, *blk2 = NULL;
3919 QemuOpts *opts = NULL;
3920 QemuOptsList *create_opts = NULL;
3921 Error *local_err = NULL;
3922 bool image_opts = false;
3923 int c, i;
3924 const char *out_fmt = "raw";
3925 const char *fmt = NULL;
3926 int64_t size = 0;
3927 int64_t block_count = 0, out_pos, in_pos;
3928 struct DdInfo dd = {
3929 .flags = 0,
3930 .count = 0,
3931 };
3932 struct DdIo in = {
3933 .bsz = 512, /* Block size is by default 512 bytes */
3934 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003935 .buf = NULL,
3936 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003937 };
3938 struct DdIo out = {
3939 .bsz = 512,
3940 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003941 .buf = NULL,
3942 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003943 };
3944
3945 const struct DdOpts options[] = {
3946 { "bs", img_dd_bs, C_BS },
3947 { "count", img_dd_count, C_COUNT },
3948 { "if", img_dd_if, C_IF },
3949 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02003950 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003951 { NULL, NULL, 0 }
3952 };
3953 const struct option long_options[] = {
3954 { "help", no_argument, 0, 'h'},
3955 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3956 { 0, 0, 0, 0 }
3957 };
3958
3959 while ((c = getopt_long(argc, argv, "hf:O:", long_options, NULL))) {
3960 if (c == EOF) {
3961 break;
3962 }
3963 switch (c) {
3964 case 'O':
3965 out_fmt = optarg;
3966 break;
3967 case 'f':
3968 fmt = optarg;
3969 break;
3970 case '?':
3971 error_report("Try 'qemu-img --help' for more information.");
3972 ret = -1;
3973 goto out;
3974 case 'h':
3975 help();
3976 break;
3977 case OPTION_IMAGE_OPTS:
3978 image_opts = true;
3979 break;
3980 }
3981 }
3982
3983 for (i = optind; i < argc; i++) {
3984 int j;
3985 arg = g_strdup(argv[i]);
3986
3987 tmp = strchr(arg, '=');
3988 if (tmp == NULL) {
3989 error_report("unrecognized operand %s", arg);
3990 ret = -1;
3991 goto out;
3992 }
3993
3994 *tmp++ = '\0';
3995
3996 for (j = 0; options[j].name != NULL; j++) {
3997 if (!strcmp(arg, options[j].name)) {
3998 break;
3999 }
4000 }
4001 if (options[j].name == NULL) {
4002 error_report("unrecognized operand %s", arg);
4003 ret = -1;
4004 goto out;
4005 }
4006
4007 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4008 ret = -1;
4009 goto out;
4010 }
4011 dd.flags |= options[j].flag;
4012 g_free(arg);
4013 arg = NULL;
4014 }
4015
4016 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4017 error_report("Must specify both input and output files");
4018 ret = -1;
4019 goto out;
4020 }
4021 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false);
4022
4023 if (!blk1) {
4024 ret = -1;
4025 goto out;
4026 }
4027
4028 drv = bdrv_find_format(out_fmt);
4029 if (!drv) {
4030 error_report("Unknown file format");
4031 ret = -1;
4032 goto out;
4033 }
4034 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4035
4036 if (!proto_drv) {
4037 error_report_err(local_err);
4038 ret = -1;
4039 goto out;
4040 }
4041 if (!drv->create_opts) {
4042 error_report("Format driver '%s' does not support image creation",
4043 drv->format_name);
4044 ret = -1;
4045 goto out;
4046 }
4047 if (!proto_drv->create_opts) {
4048 error_report("Protocol driver '%s' does not support image creation",
4049 proto_drv->format_name);
4050 ret = -1;
4051 goto out;
4052 }
4053 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4054 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4055
4056 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4057
4058 size = blk_getlength(blk1);
4059 if (size < 0) {
4060 error_report("Failed to get size for '%s'", in.filename);
4061 ret = -1;
4062 goto out;
4063 }
4064
4065 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4066 dd.count * in.bsz < size) {
4067 size = dd.count * in.bsz;
4068 }
4069
Reda Sallahif7c15532016-08-10 16:16:09 +02004070 /* Overflow means the specified offset is beyond input image's size */
4071 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4072 size < in.bsz * in.offset)) {
4073 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4074 } else {
4075 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4076 size - in.bsz * in.offset, &error_abort);
4077 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004078
4079 ret = bdrv_create(drv, out.filename, opts, &local_err);
4080 if (ret < 0) {
4081 error_reportf_err(local_err,
4082 "%s: error while creating output image: ",
4083 out.filename);
4084 ret = -1;
4085 goto out;
4086 }
4087
4088 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4089 false, false);
4090
4091 if (!blk2) {
4092 ret = -1;
4093 goto out;
4094 }
4095
Reda Sallahif7c15532016-08-10 16:16:09 +02004096 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4097 size < in.offset * in.bsz)) {
4098 /* We give a warning if the skip option is bigger than the input
4099 * size and create an empty output disk image (i.e. like dd(1)).
4100 */
4101 error_report("%s: cannot skip to specified offset", in.filename);
4102 in_pos = size;
4103 } else {
4104 in_pos = in.offset * in.bsz;
4105 }
4106
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004107 in.buf = g_new(uint8_t, in.bsz);
4108
Reda Sallahif7c15532016-08-10 16:16:09 +02004109 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004110 int in_ret, out_ret;
4111
4112 if (in_pos + in.bsz > size) {
4113 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4114 } else {
4115 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4116 }
4117 if (in_ret < 0) {
4118 error_report("error while reading from input image file: %s",
4119 strerror(-in_ret));
4120 ret = -1;
4121 goto out;
4122 }
4123 in_pos += in_ret;
4124
4125 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4126
4127 if (out_ret < 0) {
4128 error_report("error while writing to output image file: %s",
4129 strerror(-out_ret));
4130 ret = -1;
4131 goto out;
4132 }
4133 out_pos += out_ret;
4134 }
4135
4136out:
4137 g_free(arg);
4138 qemu_opts_del(opts);
4139 qemu_opts_free(create_opts);
4140 blk_unref(blk1);
4141 blk_unref(blk2);
4142 g_free(in.filename);
4143 g_free(out.filename);
4144 g_free(in.buf);
4145 g_free(out.buf);
4146
4147 if (ret) {
4148 return 1;
4149 }
4150 return 0;
4151}
4152
Kevin Wolfb6133b82014-08-05 14:17:13 +02004153
Anthony Liguoric227f092009-10-01 16:12:16 -05004154static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004155#define DEF(option, callback, arg_string) \
4156 { option, callback },
4157#include "qemu-img-cmds.h"
4158#undef DEF
4159#undef GEN_DOCS
4160 { NULL, NULL, },
4161};
4162
bellardea2384d2004-08-01 21:59:26 +00004163int main(int argc, char **argv)
4164{
Anthony Liguoric227f092009-10-01 16:12:16 -05004165 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004166 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004167 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004168 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004169 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004170 static const struct option long_options[] = {
4171 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004172 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004173 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004174 {0, 0, 0, 0}
4175 };
bellardea2384d2004-08-01 21:59:26 +00004176
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004177#ifdef CONFIG_POSIX
4178 signal(SIGPIPE, SIG_IGN);
4179#endif
4180
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004181 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004182 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004183 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004184
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004185 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004186 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004187 exit(EXIT_FAILURE);
4188 }
4189
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004190 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004191
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004192 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004193 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004194 if (argc < 2) {
4195 error_exit("Not enough arguments");
4196 }
Stuart Brady153859b2009-06-07 00:42:17 +01004197
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004198 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004199 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004200 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004201
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004202 while ((c = getopt_long(argc, argv, "+hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004203 switch (c) {
4204 case 'h':
4205 help();
4206 return 0;
4207 case 'V':
4208 printf(QEMU_IMG_VERSION);
4209 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004210 case 'T':
4211 g_free(trace_file);
4212 trace_file = trace_opt_parse(optarg);
4213 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004214 }
bellardea2384d2004-08-01 21:59:26 +00004215 }
Stuart Brady153859b2009-06-07 00:42:17 +01004216
Denis V. Lunev10985132016-06-17 17:44:13 +03004217 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004218
Denis V. Lunev10985132016-06-17 17:44:13 +03004219 /* reset getopt_long scanning */
4220 argc -= optind;
4221 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004222 return 0;
4223 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004224 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004225 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004226
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004227 if (!trace_init_backends()) {
4228 exit(1);
4229 }
4230 trace_init_file(trace_file);
4231 qemu_set_log(LOG_TRACE);
4232
Denis V. Lunev10985132016-06-17 17:44:13 +03004233 /* find the command */
4234 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4235 if (!strcmp(cmdname, cmd->name)) {
4236 return cmd->handler(argc, argv);
4237 }
4238 }
Jeff Cody7db16892014-04-25 17:02:32 -04004239
Stuart Brady153859b2009-06-07 00:42:17 +01004240 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004241 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004242}