blob: 5df66fe6614cdcc9a6b9cd3ab852509cc356c0ee [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
bellardea2384d2004-08-01 21:59:26 +0000371static int img_create(int argc, char **argv)
372{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200373 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100374 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000375 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000376 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000377 const char *filename;
378 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200379 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200380 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100381 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000382
bellardea2384d2004-08-01 21:59:26 +0000383 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000384 static const struct option long_options[] = {
385 {"help", no_argument, 0, 'h'},
386 {"object", required_argument, 0, OPTION_OBJECT},
387 {0, 0, 0, 0}
388 };
389 c = getopt_long(argc, argv, "F:b:f:he6o:q",
390 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100391 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000392 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100393 }
bellardea2384d2004-08-01 21:59:26 +0000394 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100395 case '?':
bellardea2384d2004-08-01 21:59:26 +0000396 case 'h':
397 help();
398 break;
aliguori9230eaf2009-03-28 17:55:19 +0000399 case 'F':
400 base_fmt = optarg;
401 break;
bellardea2384d2004-08-01 21:59:26 +0000402 case 'b':
403 base_filename = optarg;
404 break;
405 case 'f':
406 fmt = optarg;
407 break;
408 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200409 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100410 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100411 goto fail;
thsd8871c52007-10-24 16:11:42 +0000412 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200413 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100414 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100415 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200416 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100417 if (!is_valid_option_list(optarg)) {
418 error_report("Invalid option list: %s", optarg);
419 goto fail;
420 }
421 if (!options) {
422 options = g_strdup(optarg);
423 } else {
424 char *old_options = options;
425 options = g_strdup_printf("%s,%s", options, optarg);
426 g_free(old_options);
427 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200428 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100429 case 'q':
430 quiet = true;
431 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000432 case OPTION_OBJECT: {
433 QemuOpts *opts;
434 opts = qemu_opts_parse_noisily(&qemu_object_opts,
435 optarg, true);
436 if (!opts) {
437 goto fail;
438 }
439 } break;
bellardea2384d2004-08-01 21:59:26 +0000440 }
441 }
aliguori9230eaf2009-03-28 17:55:19 +0000442
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900443 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100444 filename = (optind < argc) ? argv[optind] : NULL;
445 if (options && has_help_option(options)) {
446 g_free(options);
447 return print_block_option_help(filename, fmt);
448 }
449
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100450 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800451 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100452 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100453 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900454
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000455 if (qemu_opts_foreach(&qemu_object_opts,
456 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200457 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000458 goto fail;
459 }
460
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100461 /* Get image size, if specified */
462 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100463 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100464 char *end;
Marc-André Lureau4677bb42015-09-16 18:02:56 +0200465 sval = qemu_strtosz_suffix(argv[optind++], &end,
466 QEMU_STRTOSZ_DEFSUFFIX_B);
Markus Armbrustere36b3692011-11-22 09:46:05 +0100467 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800468 if (sval == -ERANGE) {
469 error_report("Image size must be less than 8 EiB!");
470 } else {
471 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200472 "G, T, P or E suffixes for ");
473 error_report("kilobytes, megabytes, gigabytes, terabytes, "
474 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800475 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100476 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100477 }
478 img_size = (uint64_t)sval;
479 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200480 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800481 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200482 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100483
Luiz Capitulino9b375252012-11-30 10:52:05 -0200484 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Kevin Wolf61de4c62016-03-18 17:46:45 +0100485 options, img_size, 0, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100486 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100487 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100488 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900489 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200490
Kevin Wolf77386bf2014-02-21 16:24:04 +0100491 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000492 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100493
494fail:
495 g_free(options);
496 return 1;
bellardea2384d2004-08-01 21:59:26 +0000497}
498
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100499static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500500{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500501 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500502 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100503 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600504
505 visit_type_ImageCheck(v, NULL, &check, &error_abort);
506 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500507 str = qobject_to_json_pretty(obj);
508 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100509 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500510 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600511 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500512 QDECREF(str);
513}
514
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100515static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500516{
517 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100518 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500519 } else {
520 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100521 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
522 "Data may be corrupted, or further writes to the image "
523 "may corrupt it.\n",
524 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500525 }
526
527 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100528 qprintf(quiet,
529 "\n%" PRId64 " leaked clusters were found on the image.\n"
530 "This means waste of disk space, but no harm to data.\n",
531 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500532 }
533
534 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100535 qprintf(quiet,
536 "\n%" PRId64
537 " internal errors have occurred during the check.\n",
538 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500539 }
540 }
541
542 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100543 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
544 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
545 check->allocated_clusters, check->total_clusters,
546 check->allocated_clusters * 100.0 / check->total_clusters,
547 check->fragmented_clusters * 100.0 / check->allocated_clusters,
548 check->compressed_clusters * 100.0 /
549 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500550 }
551
552 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100553 qprintf(quiet,
554 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500555 }
556}
557
558static int collect_image_check(BlockDriverState *bs,
559 ImageCheck *check,
560 const char *filename,
561 const char *fmt,
562 int fix)
563{
564 int ret;
565 BdrvCheckResult result;
566
567 ret = bdrv_check(bs, &result, fix);
568 if (ret < 0) {
569 return ret;
570 }
571
572 check->filename = g_strdup(filename);
573 check->format = g_strdup(bdrv_get_format_name(bs));
574 check->check_errors = result.check_errors;
575 check->corruptions = result.corruptions;
576 check->has_corruptions = result.corruptions != 0;
577 check->leaks = result.leaks;
578 check->has_leaks = result.leaks != 0;
579 check->corruptions_fixed = result.corruptions_fixed;
580 check->has_corruptions_fixed = result.corruptions != 0;
581 check->leaks_fixed = result.leaks_fixed;
582 check->has_leaks_fixed = result.leaks != 0;
583 check->image_end_offset = result.image_end_offset;
584 check->has_image_end_offset = result.image_end_offset != 0;
585 check->total_clusters = result.bfi.total_clusters;
586 check->has_total_clusters = result.bfi.total_clusters != 0;
587 check->allocated_clusters = result.bfi.allocated_clusters;
588 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
589 check->fragmented_clusters = result.bfi.fragmented_clusters;
590 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100591 check->compressed_clusters = result.bfi.compressed_clusters;
592 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500593
594 return 0;
595}
596
Kevin Wolfe076f332010-06-29 11:43:13 +0200597/*
598 * Checks an image for consistency. Exit codes:
599 *
Max Reitzd6635c42014-06-02 22:15:21 +0200600 * 0 - Check completed, image is good
601 * 1 - Check not completed because of internal errors
602 * 2 - Check completed, image is corrupted
603 * 3 - Check completed, image has leaked clusters, but is good otherwise
604 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200605 */
aliguori15859692009-04-21 23:11:53 +0000606static int img_check(int argc, char **argv)
607{
608 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500609 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200610 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200611 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000612 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200613 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100614 int flags = BDRV_O_CHECK;
615 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200616 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100617 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000618 bool image_opts = false;
aliguori15859692009-04-21 23:11:53 +0000619
620 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500621 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200622 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100623
aliguori15859692009-04-21 23:11:53 +0000624 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500625 int option_index = 0;
626 static const struct option long_options[] = {
627 {"help", no_argument, 0, 'h'},
628 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530629 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500630 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000631 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000632 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500633 {0, 0, 0, 0}
634 };
Max Reitz40055952014-07-22 22:58:42 +0200635 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500636 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100637 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000638 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100639 }
aliguori15859692009-04-21 23:11:53 +0000640 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100641 case '?':
aliguori15859692009-04-21 23:11:53 +0000642 case 'h':
643 help();
644 break;
645 case 'f':
646 fmt = optarg;
647 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200648 case 'r':
649 flags |= BDRV_O_RDWR;
650
651 if (!strcmp(optarg, "leaks")) {
652 fix = BDRV_FIX_LEAKS;
653 } else if (!strcmp(optarg, "all")) {
654 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
655 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800656 error_exit("Unknown option value for -r "
657 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200658 }
659 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500660 case OPTION_OUTPUT:
661 output = optarg;
662 break;
Max Reitz40055952014-07-22 22:58:42 +0200663 case 'T':
664 cache = optarg;
665 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100666 case 'q':
667 quiet = true;
668 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000669 case OPTION_OBJECT: {
670 QemuOpts *opts;
671 opts = qemu_opts_parse_noisily(&qemu_object_opts,
672 optarg, true);
673 if (!opts) {
674 return 1;
675 }
676 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000677 case OPTION_IMAGE_OPTS:
678 image_opts = true;
679 break;
aliguori15859692009-04-21 23:11:53 +0000680 }
681 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200682 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800683 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100684 }
aliguori15859692009-04-21 23:11:53 +0000685 filename = argv[optind++];
686
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500687 if (output && !strcmp(output, "json")) {
688 output_format = OFORMAT_JSON;
689 } else if (output && !strcmp(output, "human")) {
690 output_format = OFORMAT_HUMAN;
691 } else if (output) {
692 error_report("--output must be used with human or json as argument.");
693 return 1;
694 }
695
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000696 if (qemu_opts_foreach(&qemu_object_opts,
697 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200698 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000699 return 1;
700 }
701
Kevin Wolfce099542016-03-15 13:01:04 +0100702 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200703 if (ret < 0) {
704 error_report("Invalid source cache option: %s", cache);
705 return 1;
706 }
707
Kevin Wolfce099542016-03-15 13:01:04 +0100708 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200709 if (!blk) {
710 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900711 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200712 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500713
714 check = g_new0(ImageCheck, 1);
715 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200716
717 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200718 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200719 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500720 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200721 }
722
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500723 if (check->corruptions_fixed || check->leaks_fixed) {
724 int corruptions_fixed, leaks_fixed;
725
726 leaks_fixed = check->leaks_fixed;
727 corruptions_fixed = check->corruptions_fixed;
728
729 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100730 qprintf(quiet,
731 "The following inconsistencies were found and repaired:\n\n"
732 " %" PRId64 " leaked clusters\n"
733 " %" PRId64 " corruptions\n\n"
734 "Double checking the fixed image now...\n",
735 check->leaks_fixed,
736 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500737 }
738
739 ret = collect_image_check(bs, check, filename, fmt, 0);
740
741 check->leaks_fixed = leaks_fixed;
742 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200743 }
744
Max Reitz832390a2014-10-23 15:29:12 +0200745 if (!ret) {
746 switch (output_format) {
747 case OFORMAT_HUMAN:
748 dump_human_image_check(check, quiet);
749 break;
750 case OFORMAT_JSON:
751 dump_json_image_check(check, quiet);
752 break;
753 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500754 }
755
756 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200757 if (ret) {
758 error_report("Check failed: %s", strerror(-ret));
759 } else {
760 error_report("Check failed");
761 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500762 ret = 1;
763 goto fail;
764 }
765
766 if (check->corruptions) {
767 ret = 2;
768 } else if (check->leaks) {
769 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200770 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500771 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000772 }
773
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500774fail:
775 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200776 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500777 return ret;
aliguori15859692009-04-21 23:11:53 +0000778}
779
Max Reitzd4a32382014-10-24 15:57:37 +0200780typedef struct CommonBlockJobCBInfo {
781 BlockDriverState *bs;
782 Error **errp;
783} CommonBlockJobCBInfo;
784
785static void common_block_job_cb(void *opaque, int ret)
786{
787 CommonBlockJobCBInfo *cbi = opaque;
788
789 if (ret < 0) {
790 error_setg_errno(cbi->errp, -ret, "Block job failed");
791 }
Max Reitzd4a32382014-10-24 15:57:37 +0200792}
793
794static void run_block_job(BlockJob *job, Error **errp)
795{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200796 AioContext *aio_context = blk_get_aio_context(job->blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200797
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200798 aio_context_acquire(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200799 do {
800 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500801 qemu_progress_print(job->len ?
802 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200803 } while (!job->ready);
804
805 block_job_complete_sync(job, errp);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200806 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200807
808 /* A block job may finish instantaneously without publishing any progress,
809 * so just signal completion here */
810 qemu_progress_print(100.f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200811}
812
bellardea2384d2004-08-01 21:59:26 +0000813static int img_commit(int argc, char **argv)
814{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400815 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200816 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200817 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200818 BlockDriverState *bs, *base_bs;
Max Reitz687fa1d2014-10-24 15:57:39 +0200819 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100820 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200821 Error *local_err = NULL;
822 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000823 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200824 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000825
826 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400827 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200828 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000829 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000830 static const struct option long_options[] = {
831 {"help", no_argument, 0, 'h'},
832 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000833 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000834 {0, 0, 0, 0}
835 };
836 c = getopt_long(argc, argv, "f:ht:b:dpq",
837 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100838 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000839 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100840 }
bellardea2384d2004-08-01 21:59:26 +0000841 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100842 case '?':
bellardea2384d2004-08-01 21:59:26 +0000843 case 'h':
844 help();
845 break;
846 case 'f':
847 fmt = optarg;
848 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400849 case 't':
850 cache = optarg;
851 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200852 case 'b':
853 base = optarg;
854 /* -b implies -d */
855 drop = true;
856 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200857 case 'd':
858 drop = true;
859 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200860 case 'p':
861 progress = true;
862 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100863 case 'q':
864 quiet = true;
865 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000866 case OPTION_OBJECT: {
867 QemuOpts *opts;
868 opts = qemu_opts_parse_noisily(&qemu_object_opts,
869 optarg, true);
870 if (!opts) {
871 return 1;
872 }
873 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000874 case OPTION_IMAGE_OPTS:
875 image_opts = true;
876 break;
bellardea2384d2004-08-01 21:59:26 +0000877 }
878 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200879
880 /* Progress is not shown in Quiet mode */
881 if (quiet) {
882 progress = false;
883 }
884
Kevin Wolffc11eb22013-08-05 10:53:04 +0200885 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800886 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100887 }
bellardea2384d2004-08-01 21:59:26 +0000888 filename = argv[optind++];
889
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000890 if (qemu_opts_foreach(&qemu_object_opts,
891 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200892 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000893 return 1;
894 }
895
Max Reitz9a86fe42014-10-24 15:57:38 +0200896 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100897 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400898 if (ret < 0) {
899 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100900 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400901 }
902
Kevin Wolfce099542016-03-15 13:01:04 +0100903 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200904 if (!blk) {
905 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900906 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200907 bs = blk_bs(blk);
908
Max Reitz687fa1d2014-10-24 15:57:39 +0200909 qemu_progress_init(progress, 1.f);
910 qemu_progress_print(0.f, 100);
911
Max Reitz1b22bff2014-10-24 15:57:40 +0200912 if (base) {
913 base_bs = bdrv_find_backing_image(bs, base);
914 if (!base_bs) {
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +0100915 error_setg(&local_err, QERR_BASE_NOT_FOUND, base);
Max Reitz1b22bff2014-10-24 15:57:40 +0200916 goto done;
917 }
918 } else {
919 /* This is different from QMP, which by default uses the deepest file in
920 * the backing chain (i.e., the very base); however, the traditional
921 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +0200922 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +0200923 if (!base_bs) {
924 error_setg(&local_err, "Image does not have a backing file");
925 goto done;
926 }
bellardea2384d2004-08-01 21:59:26 +0000927 }
928
Max Reitzd4a32382014-10-24 15:57:37 +0200929 cbi = (CommonBlockJobCBInfo){
930 .errp = &local_err,
931 .bs = bs,
932 };
933
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200934 aio_context = bdrv_get_aio_context(bs);
935 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -0400936 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
937 BLOCKDEV_ON_ERROR_REPORT, common_block_job_cb, &cbi,
938 &local_err, false);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200939 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200940 if (local_err) {
941 goto done;
942 }
943
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200944 /* When the block job completes, the BlockBackend reference will point to
945 * the old backing file. In order to avoid that the top image is already
946 * deleted, so we can still empty it afterwards, increment the reference
947 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +0200948 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200949 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200950 }
951
Max Reitzd4a32382014-10-24 15:57:37 +0200952 run_block_job(bs->job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +0200953 if (local_err) {
954 goto unref_backing;
955 }
956
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200957 if (!drop && bs->drv->bdrv_make_empty) {
958 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200959 if (ret) {
960 error_setg_errno(&local_err, -ret, "Could not empty %s",
961 filename);
962 goto unref_backing;
963 }
964 }
965
966unref_backing:
967 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200968 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200969 }
Max Reitzd4a32382014-10-24 15:57:37 +0200970
971done:
Max Reitz687fa1d2014-10-24 15:57:39 +0200972 qemu_progress_end();
973
Markus Armbruster26f54e92014-10-07 13:59:04 +0200974 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200975
976 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +0100977 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900978 return 1;
979 }
Max Reitzd4a32382014-10-24 15:57:37 +0200980
981 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000982 return 0;
983}
984
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400985/*
thsf58c7b32008-06-05 21:53:49 +0000986 * Returns true iff the first sector pointed to by 'buf' contains at least
987 * a non-NUL byte.
988 *
989 * 'pnum' is set to the number of sectors (including and immediately following
990 * the first one) that are known to be in the same allocated/unallocated state.
991 */
bellardea2384d2004-08-01 21:59:26 +0000992static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
993{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000994 bool is_zero;
995 int i;
bellardea2384d2004-08-01 21:59:26 +0000996
997 if (n <= 0) {
998 *pnum = 0;
999 return 0;
1000 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001001 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001002 for(i = 1; i < n; i++) {
1003 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001004 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001005 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001006 }
bellardea2384d2004-08-01 21:59:26 +00001007 }
1008 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001009 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001010}
1011
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001012/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001013 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1014 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1015 * breaking up write requests for only small sparse areas.
1016 */
1017static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1018 int min)
1019{
1020 int ret;
1021 int num_checked, num_used;
1022
1023 if (n < min) {
1024 min = n;
1025 }
1026
1027 ret = is_allocated_sectors(buf, n, pnum);
1028 if (!ret) {
1029 return ret;
1030 }
1031
1032 num_used = *pnum;
1033 buf += BDRV_SECTOR_SIZE * *pnum;
1034 n -= *pnum;
1035 num_checked = num_used;
1036
1037 while (n > 0) {
1038 ret = is_allocated_sectors(buf, n, pnum);
1039
1040 buf += BDRV_SECTOR_SIZE * *pnum;
1041 n -= *pnum;
1042 num_checked += *pnum;
1043 if (ret) {
1044 num_used = num_checked;
1045 } else if (*pnum >= min) {
1046 break;
1047 }
1048 }
1049
1050 *pnum = num_used;
1051 return 1;
1052}
1053
1054/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001055 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1056 * buffers matches, non-zero otherwise.
1057 *
1058 * pnum is set to the number of sectors (including and immediately following
1059 * the first one) that are known to have the same comparison result
1060 */
1061static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1062 int *pnum)
1063{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001064 bool res;
1065 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001066
1067 if (n <= 0) {
1068 *pnum = 0;
1069 return 0;
1070 }
1071
1072 res = !!memcmp(buf1, buf2, 512);
1073 for(i = 1; i < n; i++) {
1074 buf1 += 512;
1075 buf2 += 512;
1076
1077 if (!!memcmp(buf1, buf2, 512) != res) {
1078 break;
1079 }
1080 }
1081
1082 *pnum = i;
1083 return res;
1084}
1085
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001086#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001087
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001088static int64_t sectors_to_bytes(int64_t sectors)
1089{
1090 return sectors << BDRV_SECTOR_BITS;
1091}
1092
1093static int64_t sectors_to_process(int64_t total, int64_t from)
1094{
1095 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1096}
1097
1098/*
1099 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1100 *
1101 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1102 * data and negative value on error.
1103 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001104 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001105 * @param sect_num: Number of first sector to check
1106 * @param sect_count: Number of sectors to check
1107 * @param filename: Name of disk file we are checking (logging purpose)
1108 * @param buffer: Allocated buffer for storing read data
1109 * @param quiet: Flag for quiet mode
1110 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001111static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001112 int sect_count, const char *filename,
1113 uint8_t *buffer, bool quiet)
1114{
1115 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001116 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1117 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001118 if (ret < 0) {
1119 error_report("Error while reading offset %" PRId64 " of %s: %s",
1120 sectors_to_bytes(sect_num), filename, strerror(-ret));
1121 return ret;
1122 }
1123 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1124 if (ret || pnum != sect_count) {
1125 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1126 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1127 return 1;
1128 }
1129
1130 return 0;
1131}
1132
1133/*
1134 * Compares two images. Exit codes:
1135 *
1136 * 0 - Images are identical
1137 * 1 - Images differ
1138 * >1 - Error occurred
1139 */
1140static int img_compare(int argc, char **argv)
1141{
Max Reitz40055952014-07-22 22:58:42 +02001142 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001143 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001144 BlockDriverState *bs1, *bs2;
1145 int64_t total_sectors1, total_sectors2;
1146 uint8_t *buf1 = NULL, *buf2 = NULL;
1147 int pnum1, pnum2;
1148 int allocated1, allocated2;
1149 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1150 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001151 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001152 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001153 int64_t total_sectors;
1154 int64_t sector_num = 0;
1155 int64_t nb_sectors;
1156 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001157 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001158 bool image_opts = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001159
Max Reitz40055952014-07-22 22:58:42 +02001160 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001161 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001162 static const struct option long_options[] = {
1163 {"help", no_argument, 0, 'h'},
1164 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001165 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001166 {0, 0, 0, 0}
1167 };
1168 c = getopt_long(argc, argv, "hf:F:T:pqs",
1169 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001170 if (c == -1) {
1171 break;
1172 }
1173 switch (c) {
1174 case '?':
1175 case 'h':
1176 help();
1177 break;
1178 case 'f':
1179 fmt1 = optarg;
1180 break;
1181 case 'F':
1182 fmt2 = optarg;
1183 break;
Max Reitz40055952014-07-22 22:58:42 +02001184 case 'T':
1185 cache = optarg;
1186 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001187 case 'p':
1188 progress = true;
1189 break;
1190 case 'q':
1191 quiet = true;
1192 break;
1193 case 's':
1194 strict = true;
1195 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001196 case OPTION_OBJECT: {
1197 QemuOpts *opts;
1198 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1199 optarg, true);
1200 if (!opts) {
1201 ret = 2;
1202 goto out4;
1203 }
1204 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001205 case OPTION_IMAGE_OPTS:
1206 image_opts = true;
1207 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001208 }
1209 }
1210
1211 /* Progress is not shown in Quiet mode */
1212 if (quiet) {
1213 progress = false;
1214 }
1215
1216
Kevin Wolffc11eb22013-08-05 10:53:04 +02001217 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001218 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001219 }
1220 filename1 = argv[optind++];
1221 filename2 = argv[optind++];
1222
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001223 if (qemu_opts_foreach(&qemu_object_opts,
1224 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001225 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001226 ret = 2;
1227 goto out4;
1228 }
1229
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001230 /* Initialize before goto out */
1231 qemu_progress_init(progress, 2.0);
1232
Kevin Wolfce099542016-03-15 13:01:04 +01001233 flags = 0;
1234 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001235 if (ret < 0) {
1236 error_report("Invalid source cache option: %s", cache);
1237 ret = 2;
1238 goto out3;
1239 }
1240
Kevin Wolfce099542016-03-15 13:01:04 +01001241 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001242 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001243 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001244 goto out3;
1245 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001246
Kevin Wolfce099542016-03-15 13:01:04 +01001247 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001248 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001249 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001250 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001251 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001252 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001253 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254
Max Reitzf1d3cd72015-02-05 13:58:18 -05001255 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1256 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1257 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001258 if (total_sectors1 < 0) {
1259 error_report("Can't get size of %s: %s",
1260 filename1, strerror(-total_sectors1));
1261 ret = 4;
1262 goto out;
1263 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001264 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001265 if (total_sectors2 < 0) {
1266 error_report("Can't get size of %s: %s",
1267 filename2, strerror(-total_sectors2));
1268 ret = 4;
1269 goto out;
1270 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001271 total_sectors = MIN(total_sectors1, total_sectors2);
1272 progress_base = MAX(total_sectors1, total_sectors2);
1273
1274 qemu_progress_print(0, 100);
1275
1276 if (strict && total_sectors1 != total_sectors2) {
1277 ret = 1;
1278 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1279 goto out;
1280 }
1281
1282 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001283 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001284 BlockDriverState *file;
1285
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001286 nb_sectors = sectors_to_process(total_sectors, sector_num);
1287 if (nb_sectors <= 0) {
1288 break;
1289 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001290 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1291 total_sectors1 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001292 &pnum1, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001293 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001294 ret = 3;
1295 error_report("Sector allocation test failed for %s", filename1);
1296 goto out;
1297 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001298 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299
Fam Zheng25ad8e62016-01-13 16:37:41 +08001300 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1301 total_sectors2 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001302 &pnum2, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001303 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001304 ret = 3;
1305 error_report("Sector allocation test failed for %s", filename2);
1306 goto out;
1307 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001308 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1309 if (pnum1) {
1310 nb_sectors = MIN(nb_sectors, pnum1);
1311 }
1312 if (pnum2) {
1313 nb_sectors = MIN(nb_sectors, pnum2);
1314 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001315
Fam Zheng25ad8e62016-01-13 16:37:41 +08001316 if (strict) {
1317 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1318 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1319 ret = 1;
1320 qprintf(quiet, "Strict mode: Offset %" PRId64
1321 " block status mismatch!\n",
1322 sectors_to_bytes(sector_num));
1323 goto out;
1324 }
1325 }
1326 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1327 nb_sectors = MIN(pnum1, pnum2);
1328 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001329 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001330 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1331 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001332 if (ret < 0) {
1333 error_report("Error while reading offset %" PRId64 " of %s:"
1334 " %s", sectors_to_bytes(sector_num), filename1,
1335 strerror(-ret));
1336 ret = 4;
1337 goto out;
1338 }
Eric Blake91669202016-05-06 10:26:43 -06001339 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1340 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001341 if (ret < 0) {
1342 error_report("Error while reading offset %" PRId64
1343 " of %s: %s", sectors_to_bytes(sector_num),
1344 filename2, strerror(-ret));
1345 ret = 4;
1346 goto out;
1347 }
1348 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1349 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001350 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1351 sectors_to_bytes(
1352 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001353 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001354 goto out;
1355 }
1356 }
1357 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001358
1359 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001360 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001361 filename1, buf1, quiet);
1362 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001363 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 filename2, buf1, quiet);
1365 }
1366 if (ret) {
1367 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001368 error_report("Error while reading offset %" PRId64 ": %s",
1369 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001370 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001371 }
1372 goto out;
1373 }
1374 }
1375 sector_num += nb_sectors;
1376 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1377 }
1378
1379 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001380 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381 int64_t total_sectors_over;
1382 const char *filename_over;
1383
1384 qprintf(quiet, "Warning: Image size mismatch!\n");
1385 if (total_sectors1 > total_sectors2) {
1386 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001387 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001388 filename_over = filename1;
1389 } else {
1390 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001391 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 filename_over = filename2;
1393 }
1394
1395 for (;;) {
1396 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1397 if (nb_sectors <= 0) {
1398 break;
1399 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001400 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001401 nb_sectors, &pnum);
1402 if (ret < 0) {
1403 ret = 3;
1404 error_report("Sector allocation test failed for %s",
1405 filename_over);
1406 goto out;
1407
1408 }
1409 nb_sectors = pnum;
1410 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001411 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001412 filename_over, buf1, quiet);
1413 if (ret) {
1414 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415 error_report("Error while reading offset %" PRId64
1416 " of %s: %s", sectors_to_bytes(sector_num),
1417 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001418 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001419 }
1420 goto out;
1421 }
1422 }
1423 sector_num += nb_sectors;
1424 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1425 }
1426 }
1427
1428 qprintf(quiet, "Images are identical.\n");
1429 ret = 0;
1430
1431out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001432 qemu_vfree(buf1);
1433 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001434 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001435out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001436 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001437out3:
1438 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001439out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001440 return ret;
1441}
1442
Kevin Wolf690c7302015-03-19 13:33:32 +01001443enum ImgConvertBlockStatus {
1444 BLK_DATA,
1445 BLK_ZERO,
1446 BLK_BACKING_FILE,
1447};
1448
1449typedef struct ImgConvertState {
1450 BlockBackend **src;
1451 int64_t *src_sectors;
1452 int src_cur, src_num;
1453 int64_t src_cur_offset;
1454 int64_t total_sectors;
1455 int64_t allocated_sectors;
1456 enum ImgConvertBlockStatus status;
1457 int64_t sector_next_status;
1458 BlockBackend *target;
1459 bool has_zero_init;
1460 bool compressed;
1461 bool target_has_backing;
1462 int min_sparse;
1463 size_t cluster_sectors;
1464 size_t buf_sectors;
1465} ImgConvertState;
1466
1467static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1468{
1469 assert(sector_num >= s->src_cur_offset);
1470 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1471 s->src_cur_offset += s->src_sectors[s->src_cur];
1472 s->src_cur++;
1473 assert(s->src_cur < s->src_num);
1474 }
1475}
1476
1477static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1478{
1479 int64_t ret;
1480 int n;
1481
1482 convert_select_part(s, sector_num);
1483
1484 assert(s->total_sectors > sector_num);
1485 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1486
1487 if (s->sector_next_status <= sector_num) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08001488 BlockDriverState *file;
Kevin Wolf690c7302015-03-19 13:33:32 +01001489 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1490 sector_num - s->src_cur_offset,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001491 n, &n, &file);
Kevin Wolf690c7302015-03-19 13:33:32 +01001492 if (ret < 0) {
1493 return ret;
1494 }
1495
1496 if (ret & BDRV_BLOCK_ZERO) {
1497 s->status = BLK_ZERO;
1498 } else if (ret & BDRV_BLOCK_DATA) {
1499 s->status = BLK_DATA;
1500 } else if (!s->target_has_backing) {
1501 /* Without a target backing file we must copy over the contents of
1502 * the backing file as well. */
Ren Kimura263a6f42016-04-28 01:04:58 +09001503 /* Check block status of the backing file chain to avoid
Kevin Wolf690c7302015-03-19 13:33:32 +01001504 * needlessly reading zeroes and limiting the iteration to the
1505 * buffer size */
Ren Kimura263a6f42016-04-28 01:04:58 +09001506 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1507 sector_num - s->src_cur_offset,
1508 n, &n, &file);
1509 if (ret < 0) {
1510 return ret;
1511 }
1512
1513 if (ret & BDRV_BLOCK_ZERO) {
1514 s->status = BLK_ZERO;
1515 } else {
1516 s->status = BLK_DATA;
1517 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001518 } else {
1519 s->status = BLK_BACKING_FILE;
1520 }
1521
1522 s->sector_next_status = sector_num + n;
1523 }
1524
1525 n = MIN(n, s->sector_next_status - sector_num);
1526 if (s->status == BLK_DATA) {
1527 n = MIN(n, s->buf_sectors);
1528 }
1529
1530 /* We need to write complete clusters for compressed images, so if an
1531 * unallocated area is shorter than that, we must consider the whole
1532 * cluster allocated. */
1533 if (s->compressed) {
1534 if (n < s->cluster_sectors) {
1535 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1536 s->status = BLK_DATA;
1537 } else {
1538 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1539 }
1540 }
1541
1542 return n;
1543}
1544
1545static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1546 uint8_t *buf)
1547{
1548 int n;
1549 int ret;
1550
Kevin Wolf690c7302015-03-19 13:33:32 +01001551 assert(nb_sectors <= s->buf_sectors);
1552 while (nb_sectors > 0) {
1553 BlockBackend *blk;
1554 int64_t bs_sectors;
1555
1556 /* In the case of compression with multiple source files, we can get a
1557 * nb_sectors that spreads into the next part. So we must be able to
1558 * read across multiple BDSes for one convert_read() call. */
1559 convert_select_part(s, sector_num);
1560 blk = s->src[s->src_cur];
1561 bs_sectors = s->src_sectors[s->src_cur];
1562
1563 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
Eric Blake91669202016-05-06 10:26:43 -06001564 ret = blk_pread(blk,
1565 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1566 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 if (ret < 0) {
1568 return ret;
1569 }
1570
1571 sector_num += n;
1572 nb_sectors -= n;
1573 buf += n * BDRV_SECTOR_SIZE;
1574 }
1575
1576 return 0;
1577}
1578
1579static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1580 const uint8_t *buf)
1581{
1582 int ret;
1583
1584 while (nb_sectors > 0) {
1585 int n = nb_sectors;
1586
1587 switch (s->status) {
1588 case BLK_BACKING_FILE:
1589 /* If we have a backing file, leave clusters unallocated that are
1590 * unallocated in the source image, so that the backing file is
1591 * visible at the respective offset. */
1592 assert(s->target_has_backing);
1593 break;
1594
1595 case BLK_DATA:
1596 /* We must always write compressed clusters as a whole, so don't
1597 * try to find zeroed parts in the buffer. We can only save the
1598 * write if the buffer is completely zeroed and we're allowed to
1599 * keep the target sparse. */
1600 if (s->compressed) {
1601 if (s->has_zero_init && s->min_sparse &&
1602 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1603 {
1604 assert(!s->target_has_backing);
1605 break;
1606 }
1607
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001608 ret = blk_pwrite_compressed(s->target,
1609 sector_num << BDRV_SECTOR_BITS,
1610 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001611 if (ret < 0) {
1612 return ret;
1613 }
1614 break;
1615 }
1616
1617 /* If there is real non-zero data or we're told to keep the target
1618 * fully allocated (-S 0), we must write it. Otherwise we can treat
1619 * it as zero sectors. */
1620 if (!s->min_sparse ||
1621 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1622 {
Eric Blake91669202016-05-06 10:26:43 -06001623 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1624 buf, n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001625 if (ret < 0) {
1626 return ret;
1627 }
1628 break;
1629 }
1630 /* fall-through */
1631
1632 case BLK_ZERO:
1633 if (s->has_zero_init) {
1634 break;
1635 }
Eric Blaked004bd52016-05-24 16:25:20 -06001636 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1637 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001638 if (ret < 0) {
1639 return ret;
1640 }
1641 break;
1642 }
1643
1644 sector_num += n;
1645 nb_sectors -= n;
1646 buf += n * BDRV_SECTOR_SIZE;
1647 }
1648
1649 return 0;
1650}
1651
1652static int convert_do_copy(ImgConvertState *s)
1653{
1654 uint8_t *buf = NULL;
1655 int64_t sector_num, allocated_done;
1656 int ret;
1657 int n;
1658
1659 /* Check whether we have zero initialisation or can get it efficiently */
1660 s->has_zero_init = s->min_sparse && !s->target_has_backing
1661 ? bdrv_has_zero_init(blk_bs(s->target))
1662 : false;
1663
1664 if (!s->has_zero_init && !s->target_has_backing &&
1665 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1666 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001667 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001668 if (ret == 0) {
1669 s->has_zero_init = true;
1670 }
1671 }
1672
1673 /* Allocate buffer for copied data. For compressed images, only one cluster
1674 * can be copied at a time. */
1675 if (s->compressed) {
1676 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1677 error_report("invalid cluster size");
1678 ret = -EINVAL;
1679 goto fail;
1680 }
1681 s->buf_sectors = s->cluster_sectors;
1682 }
1683 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1684
1685 /* Calculate allocated sectors for progress */
1686 s->allocated_sectors = 0;
1687 sector_num = 0;
1688 while (sector_num < s->total_sectors) {
1689 n = convert_iteration_sectors(s, sector_num);
1690 if (n < 0) {
1691 ret = n;
1692 goto fail;
1693 }
Max Reitzaad15de2016-03-24 23:33:57 +01001694 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1695 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001696 s->allocated_sectors += n;
1697 }
1698 sector_num += n;
1699 }
1700
1701 /* Do the copy */
1702 s->src_cur = 0;
1703 s->src_cur_offset = 0;
1704 s->sector_next_status = 0;
1705
1706 sector_num = 0;
1707 allocated_done = 0;
1708
1709 while (sector_num < s->total_sectors) {
1710 n = convert_iteration_sectors(s, sector_num);
1711 if (n < 0) {
1712 ret = n;
1713 goto fail;
1714 }
Max Reitzaad15de2016-03-24 23:33:57 +01001715 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1716 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001717 allocated_done += n;
1718 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1719 0);
1720 }
1721
Max Reitzaad15de2016-03-24 23:33:57 +01001722 if (s->status == BLK_DATA) {
1723 ret = convert_read(s, sector_num, n, buf);
1724 if (ret < 0) {
1725 error_report("error while reading sector %" PRId64
1726 ": %s", sector_num, strerror(-ret));
1727 goto fail;
1728 }
1729 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1730 n = MIN(n, s->buf_sectors);
1731 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1732 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001733 }
1734
1735 ret = convert_write(s, sector_num, n, buf);
1736 if (ret < 0) {
1737 error_report("error while writing sector %" PRId64
1738 ": %s", sector_num, strerror(-ret));
1739 goto fail;
1740 }
1741
1742 sector_num += n;
1743 }
1744
1745 if (s->compressed) {
1746 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001747 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001748 if (ret < 0) {
1749 goto fail;
1750 }
1751 }
1752
1753 ret = 0;
1754fail:
1755 qemu_vfree(buf);
1756 return ret;
1757}
1758
bellardea2384d2004-08-01 21:59:26 +00001759static int img_convert(int argc, char **argv)
1760{
Kevin Wolf690c7302015-03-19 13:33:32 +01001761 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001762 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001763 int progress = 0, flags, src_flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001764 bool writethrough, src_writethrough;
Max Reitz40055952014-07-22 22:58:42 +02001765 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001766 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001767 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001768 BlockDriverState **bs = NULL, *out_bs = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001769 int64_t total_sectors;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001770 int64_t *bs_sectors = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001771 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardfaea38e2006-08-05 21:31:00 +00001772 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001773 QemuOpts *opts = NULL;
1774 QemuOptsList *create_opts = NULL;
1775 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001776 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001777 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001778 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001779 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001780 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001781 QemuOpts *sn_opts = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001782 ImgConvertState state;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001783 bool image_opts = false;
bellardea2384d2004-08-01 21:59:26 +00001784
1785 fmt = NULL;
1786 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001787 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001788 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001789 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001790 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001791 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001792 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001793 static const struct option long_options[] = {
1794 {"help", no_argument, 0, 'h'},
1795 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001796 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001797 {0, 0, 0, 0}
1798 };
1799 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1800 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001801 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001802 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001803 }
bellardea2384d2004-08-01 21:59:26 +00001804 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001805 case '?':
bellardea2384d2004-08-01 21:59:26 +00001806 case 'h':
1807 help();
1808 break;
1809 case 'f':
1810 fmt = optarg;
1811 break;
1812 case 'O':
1813 out_fmt = optarg;
1814 break;
thsf58c7b32008-06-05 21:53:49 +00001815 case 'B':
1816 out_baseimg = optarg;
1817 break;
bellardea2384d2004-08-01 21:59:26 +00001818 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001819 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001820 break;
1821 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001822 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001823 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001824 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001825 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001826 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001827 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001828 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001829 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001830 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001831 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001832 if (!is_valid_option_list(optarg)) {
1833 error_report("Invalid option list: %s", optarg);
1834 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001835 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001836 }
1837 if (!options) {
1838 options = g_strdup(optarg);
1839 } else {
1840 char *old_options = options;
1841 options = g_strdup_printf("%s,%s", options, optarg);
1842 g_free(old_options);
1843 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001844 break;
edison51ef6722010-09-21 19:58:41 -07001845 case 's':
1846 snapshot_name = optarg;
1847 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001848 case 'l':
1849 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01001850 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1851 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08001852 if (!sn_opts) {
1853 error_report("Failed in parsing snapshot param '%s'",
1854 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001855 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001856 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001857 }
1858 } else {
1859 snapshot_name = optarg;
1860 }
1861 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001862 case 'S':
1863 {
1864 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001865 char *end;
Marc-André Lureau4677bb42015-09-16 18:02:56 +02001866 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
Markus Armbrustere36b3692011-11-22 09:46:05 +01001867 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001868 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001869 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001870 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001871 }
1872
1873 min_sparse = sval / BDRV_SECTOR_SIZE;
1874 break;
1875 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001876 case 'p':
1877 progress = 1;
1878 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001879 case 't':
1880 cache = optarg;
1881 break;
Max Reitz40055952014-07-22 22:58:42 +02001882 case 'T':
1883 src_cache = optarg;
1884 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001885 case 'q':
1886 quiet = true;
1887 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001888 case 'n':
1889 skip_create = 1;
1890 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001891 case OPTION_OBJECT:
1892 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1893 optarg, true);
1894 if (!opts) {
1895 goto fail_getopt;
1896 }
1897 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001898 case OPTION_IMAGE_OPTS:
1899 image_opts = true;
1900 break;
bellardea2384d2004-08-01 21:59:26 +00001901 }
1902 }
ths3b46e622007-09-17 08:09:54 +00001903
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001904 if (qemu_opts_foreach(&qemu_object_opts,
1905 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001906 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001907 goto fail_getopt;
1908 }
1909
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001910 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001911 if (quiet) {
1912 progress = 0;
1913 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001914 qemu_progress_init(progress, 1.0);
1915
balrog926c2d22007-10-31 01:11:44 +00001916 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001917 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001918
Kevin Wolf2dc83282014-02-21 16:24:05 +01001919 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001920 ret = print_block_option_help(out_filename, out_fmt);
1921 goto out;
1922 }
1923
bellardea2384d2004-08-01 21:59:26 +00001924 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001925 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001926 }
bellardea2384d2004-08-01 21:59:26 +00001927
thsf58c7b32008-06-05 21:53:49 +00001928
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001929 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001930 error_report("-B makes no sense when concatenating multiple input "
1931 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001932 ret = -1;
1933 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001934 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001935
Kevin Wolfce099542016-03-15 13:01:04 +01001936 src_flags = 0;
1937 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001938 if (ret < 0) {
1939 error_report("Invalid source cache option: %s", src_cache);
1940 goto out;
1941 }
1942
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001943 qemu_progress_print(0, 100);
1944
Markus Armbruster26f54e92014-10-07 13:59:04 +02001945 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001946 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001947 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001948
1949 total_sectors = 0;
1950 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Max Reitzefaa7c42016-03-16 19:54:38 +01001951 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
Kevin Wolfce099542016-03-15 13:01:04 +01001952 fmt, src_flags, src_writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001953 if (!blk[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001954 ret = -1;
1955 goto out;
1956 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001957 bs[bs_i] = blk_bs(blk[bs_i]);
Max Reitzf1d3cd72015-02-05 13:58:18 -05001958 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001959 if (bs_sectors[bs_i] < 0) {
1960 error_report("Could not get size of %s: %s",
1961 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1962 ret = -1;
1963 goto out;
1964 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001965 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001966 }
bellardea2384d2004-08-01 21:59:26 +00001967
Wenchao Xiaef806542013-12-04 17:10:57 +08001968 if (sn_opts) {
1969 ret = bdrv_snapshot_load_tmp(bs[0],
1970 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1971 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1972 &local_err);
1973 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001974 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001975 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001976 ret = -1;
1977 goto out;
1978 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001979
1980 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001981 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001982 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001983 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08001984 ret = -1;
1985 goto out;
edison51ef6722010-09-21 19:58:41 -07001986 }
1987
Kevin Wolfefa84d42009-05-18 16:42:12 +02001988 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001989 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001990 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001991 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001992 ret = -1;
1993 goto out;
1994 }
balrog926c2d22007-10-31 01:11:44 +00001995
Max Reitzb65a5e12015-02-05 13:58:12 -05001996 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001997 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +01001998 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001999 ret = -1;
2000 goto out;
2001 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09002002
Max Reitz2e024cd2015-02-11 09:58:46 -05002003 if (!skip_create) {
2004 if (!drv->create_opts) {
2005 error_report("Format driver '%s' does not support image creation",
2006 drv->format_name);
2007 ret = -1;
2008 goto out;
2009 }
Max Reitzf75613c2014-12-02 18:32:46 +01002010
Max Reitz2e024cd2015-02-11 09:58:46 -05002011 if (!proto_drv->create_opts) {
2012 error_report("Protocol driver '%s' does not support image creation",
2013 proto_drv->format_name);
2014 ret = -1;
2015 goto out;
2016 }
Max Reitzf75613c2014-12-02 18:32:46 +01002017
Max Reitz2e024cd2015-02-11 09:58:46 -05002018 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2019 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002020
Max Reitz2e024cd2015-02-11 09:58:46 -05002021 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002022 if (options) {
2023 qemu_opts_do_parse(opts, options, NULL, &local_err);
2024 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002025 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002026 ret = -1;
2027 goto out;
2028 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002029 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002030
Markus Armbruster39101f22015-02-12 16:46:36 +01002031 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2032 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002033 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2034 if (ret < 0) {
2035 goto out;
2036 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002037 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002038
Kevin Wolfa18953f2010-10-14 15:46:04 +02002039 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002040 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002041 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002042 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002043 }
2044
Kevin Wolfefa84d42009-05-18 16:42:12 +02002045 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01002046 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002047 bool encryption =
2048 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2049 const char *preallocation =
2050 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002051
Pavel Butsykin35fadca2016-07-22 11:17:48 +03002052 if (!drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002053 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002054 ret = -1;
2055 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002056 }
2057
Chunyan Liu83d05212014-06-05 17:20:51 +08002058 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002059 error_report("Compression and encryption not supported at "
2060 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002061 ret = -1;
2062 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002063 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002064
Chunyan Liu83d05212014-06-05 17:20:51 +08002065 if (preallocation
2066 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002067 {
2068 error_report("Compression and preallocation not supported at "
2069 "the same time");
2070 ret = -1;
2071 goto out;
2072 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002073 }
2074
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002075 if (!skip_create) {
2076 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002077 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002078 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002079 error_reportf_err(local_err, "%s: error while converting %s: ",
2080 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002081 goto out;
bellardea2384d2004-08-01 21:59:26 +00002082 }
2083 }
ths3b46e622007-09-17 08:09:54 +00002084
Peter Lieven5a37b602013-10-24 12:07:06 +02002085 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002086 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002087 if (ret < 0) {
2088 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002089 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002090 }
2091
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002092 /* XXX we should allow --image-opts to trigger use of
2093 * img_open() here, but then we have trouble with
2094 * the bdrv_create() call which takes different params.
2095 * Not critical right now, so fix can wait...
2096 */
Kevin Wolfce099542016-03-15 13:01:04 +01002097 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002098 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002099 ret = -1;
2100 goto out;
2101 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002102 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00002103
Eric Blake5def6b82016-06-23 16:37:19 -06002104 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002105 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2106 * as maximum. */
2107 bufsectors = MIN(32768,
Eric Blake5def6b82016-06-23 16:37:19 -06002108 MAX(bufsectors,
2109 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
Eric Blakeb9f78552016-06-23 16:37:21 -06002110 out_bs->bl.pdiscard_alignment >>
2111 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002112
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002113 if (skip_create) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05002114 int64_t output_sectors = blk_nb_sectors(out_blk);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002115 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002116 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002117 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002118 ret = -1;
2119 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02002120 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002121 error_report("output file is smaller than input file");
2122 ret = -1;
2123 goto out;
2124 }
2125 }
2126
Peter Lieven24f833c2013-11-27 11:07:07 +01002127 cluster_sectors = 0;
2128 ret = bdrv_get_info(out_bs, &bdi);
2129 if (ret < 0) {
2130 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002131 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002132 goto out;
2133 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002134 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08002135 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01002136 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2137 }
2138
Kevin Wolf690c7302015-03-19 13:33:32 +01002139 state = (ImgConvertState) {
2140 .src = blk,
2141 .src_sectors = bs_sectors,
2142 .src_num = bs_n,
2143 .total_sectors = total_sectors,
2144 .target = out_blk,
2145 .compressed = compress,
2146 .target_has_backing = (bool) out_baseimg,
2147 .min_sparse = min_sparse,
2148 .cluster_sectors = cluster_sectors,
2149 .buf_sectors = bufsectors,
2150 };
2151 ret = convert_do_copy(&state);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002152
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002153out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002154 if (!ret) {
2155 qemu_progress_print(100, 0);
2156 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002157 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002158 qemu_opts_del(opts);
2159 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002160 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002161 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02002162 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002163 if (blk) {
2164 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2165 blk_unref(blk[bs_i]);
2166 }
2167 g_free(blk);
2168 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02002169 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002170fail_getopt:
2171 g_free(options);
2172
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002173 if (ret) {
2174 return 1;
2175 }
bellardea2384d2004-08-01 21:59:26 +00002176 return 0;
2177}
2178
bellard57d1a2b2004-08-03 21:15:11 +00002179
bellardfaea38e2006-08-05 21:31:00 +00002180static void dump_snapshots(BlockDriverState *bs)
2181{
2182 QEMUSnapshotInfo *sn_tab, *sn;
2183 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002184
2185 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2186 if (nb_sns <= 0)
2187 return;
2188 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002189 bdrv_snapshot_dump(fprintf, stdout, NULL);
2190 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002191 for(i = 0; i < nb_sns; i++) {
2192 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002193 bdrv_snapshot_dump(fprintf, stdout, sn);
2194 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002195 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002196 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002197}
2198
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002199static void dump_json_image_info_list(ImageInfoList *list)
2200{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002201 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002202 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002203 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002204
2205 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2206 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002207 str = qobject_to_json_pretty(obj);
2208 assert(str != NULL);
2209 printf("%s\n", qstring_get_str(str));
2210 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002211 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002212 QDECREF(str);
2213}
2214
Benoît Canetc054b3f2012-09-05 13:09:02 +02002215static void dump_json_image_info(ImageInfo *info)
2216{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002217 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002218 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002219 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002220
2221 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2222 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002223 str = qobject_to_json_pretty(obj);
2224 assert(str != NULL);
2225 printf("%s\n", qstring_get_str(str));
2226 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002227 visit_free(v);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002228 QDECREF(str);
2229}
2230
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002231static void dump_human_image_info_list(ImageInfoList *list)
2232{
2233 ImageInfoList *elem;
2234 bool delim = false;
2235
2236 for (elem = list; elem; elem = elem->next) {
2237 if (delim) {
2238 printf("\n");
2239 }
2240 delim = true;
2241
Wenchao Xia5b917042013-05-25 11:09:45 +08002242 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002243 }
2244}
2245
2246static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2247{
2248 return strcmp(a, b) == 0;
2249}
2250
2251/**
2252 * Open an image file chain and return an ImageInfoList
2253 *
2254 * @filename: topmost image filename
2255 * @fmt: topmost image format (may be NULL to autodetect)
2256 * @chain: true - enumerate entire backing file chain
2257 * false - only topmost image file
2258 *
2259 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2260 * image file. If there was an error a message will have been printed to
2261 * stderr.
2262 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002263static ImageInfoList *collect_image_info_list(bool image_opts,
2264 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002265 const char *fmt,
2266 bool chain)
2267{
2268 ImageInfoList *head = NULL;
2269 ImageInfoList **last = &head;
2270 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002271 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002272
2273 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2274
2275 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002276 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002277 BlockDriverState *bs;
2278 ImageInfo *info;
2279 ImageInfoList *elem;
2280
2281 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2282 error_report("Backing file '%s' creates an infinite loop.",
2283 filename);
2284 goto err;
2285 }
2286 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2287
Max Reitzefaa7c42016-03-16 19:54:38 +01002288 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01002289 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002290 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002291 goto err;
2292 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002293 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002294
Wenchao Xia43526ec2013-06-06 12:27:58 +08002295 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002296 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002297 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002298 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002299 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002300 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002301
2302 elem = g_new0(ImageInfoList, 1);
2303 elem->value = info;
2304 *last = elem;
2305 last = &elem->next;
2306
Markus Armbruster26f54e92014-10-07 13:59:04 +02002307 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002308
2309 filename = fmt = NULL;
2310 if (chain) {
2311 if (info->has_full_backing_filename) {
2312 filename = info->full_backing_filename;
2313 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002314 error_report("Could not determine absolute backing filename,"
2315 " but backing filename '%s' present",
2316 info->backing_filename);
2317 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002318 }
2319 if (info->has_backing_filename_format) {
2320 fmt = info->backing_filename_format;
2321 }
2322 }
2323 }
2324 g_hash_table_destroy(filenames);
2325 return head;
2326
2327err:
2328 qapi_free_ImageInfoList(head);
2329 g_hash_table_destroy(filenames);
2330 return NULL;
2331}
2332
Benoît Canetc054b3f2012-09-05 13:09:02 +02002333static int img_info(int argc, char **argv)
2334{
2335 int c;
2336 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002337 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002338 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002339 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002340 bool image_opts = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002341
bellardea2384d2004-08-01 21:59:26 +00002342 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002343 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002344 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002345 int option_index = 0;
2346 static const struct option long_options[] = {
2347 {"help", no_argument, 0, 'h'},
2348 {"format", required_argument, 0, 'f'},
2349 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002350 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002351 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002352 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002353 {0, 0, 0, 0}
2354 };
2355 c = getopt_long(argc, argv, "f:h",
2356 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002357 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002358 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002359 }
bellardea2384d2004-08-01 21:59:26 +00002360 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002361 case '?':
bellardea2384d2004-08-01 21:59:26 +00002362 case 'h':
2363 help();
2364 break;
2365 case 'f':
2366 fmt = optarg;
2367 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002368 case OPTION_OUTPUT:
2369 output = optarg;
2370 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002371 case OPTION_BACKING_CHAIN:
2372 chain = true;
2373 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002374 case OPTION_OBJECT: {
2375 QemuOpts *opts;
2376 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2377 optarg, true);
2378 if (!opts) {
2379 return 1;
2380 }
2381 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002382 case OPTION_IMAGE_OPTS:
2383 image_opts = true;
2384 break;
bellardea2384d2004-08-01 21:59:26 +00002385 }
2386 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002387 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002388 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002389 }
bellardea2384d2004-08-01 21:59:26 +00002390 filename = argv[optind++];
2391
Benoît Canetc054b3f2012-09-05 13:09:02 +02002392 if (output && !strcmp(output, "json")) {
2393 output_format = OFORMAT_JSON;
2394 } else if (output && !strcmp(output, "human")) {
2395 output_format = OFORMAT_HUMAN;
2396 } else if (output) {
2397 error_report("--output must be used with human or json as argument.");
2398 return 1;
2399 }
2400
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002401 if (qemu_opts_foreach(&qemu_object_opts,
2402 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002403 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002404 return 1;
2405 }
2406
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002407 list = collect_image_info_list(image_opts, filename, fmt, chain);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002408 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002409 return 1;
2410 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002411
Benoît Canetc054b3f2012-09-05 13:09:02 +02002412 switch (output_format) {
2413 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002414 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002415 break;
2416 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002417 if (chain) {
2418 dump_json_image_info_list(list);
2419 } else {
2420 dump_json_image_info(list->value);
2421 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002422 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002423 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002424
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002425 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002426 return 0;
2427}
2428
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002429static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2430 MapEntry *next)
2431{
2432 switch (output_format) {
2433 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002434 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002435 error_report("File contains external, encrypted or compressed clusters.");
2436 exit(1);
2437 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002438 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002439 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002440 e->start, e->length,
2441 e->has_offset ? e->offset : 0,
2442 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002443 }
2444 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2445 * Modify the flags here to allow more coalescing.
2446 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002447 if (next && (!next->data || next->zero)) {
2448 next->data = false;
2449 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002450 }
2451 break;
2452 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002453 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2454 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002455 (e->start == 0 ? "[" : ",\n"),
2456 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002457 e->zero ? "true" : "false",
2458 e->data ? "true" : "false");
2459 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002460 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002461 }
2462 putchar('}');
2463
2464 if (!next) {
2465 printf("]\n");
2466 }
2467 break;
2468 }
2469}
2470
2471static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2472 int nb_sectors, MapEntry *e)
2473{
2474 int64_t ret;
2475 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002476 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002477 bool has_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002478
2479 /* As an optimization, we could cache the current range of unallocated
2480 * clusters in each file of the chain, and avoid querying the same
2481 * range repeatedly.
2482 */
2483
2484 depth = 0;
2485 for (;;) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08002486 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2487 &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002488 if (ret < 0) {
2489 return ret;
2490 }
2491 assert(nb_sectors);
2492 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2493 break;
2494 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002495 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002496 if (bs == NULL) {
2497 ret = 0;
2498 break;
2499 }
2500
2501 depth++;
2502 }
2503
John Snow28756452016-02-05 13:12:33 -05002504 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2505
2506 *e = (MapEntry) {
2507 .start = sector_num * BDRV_SECTOR_SIZE,
2508 .length = nb_sectors * BDRV_SECTOR_SIZE,
2509 .data = !!(ret & BDRV_BLOCK_DATA),
2510 .zero = !!(ret & BDRV_BLOCK_ZERO),
2511 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2512 .has_offset = has_offset,
2513 .depth = depth,
2514 .has_filename = file && has_offset,
2515 .filename = file && has_offset ? file->filename : NULL,
2516 };
2517
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002518 return 0;
2519}
2520
Fam Zheng16b0d552016-01-26 11:59:02 +08002521static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2522{
2523 if (curr->length == 0) {
2524 return false;
2525 }
2526 if (curr->zero != next->zero ||
2527 curr->data != next->data ||
2528 curr->depth != next->depth ||
2529 curr->has_filename != next->has_filename ||
2530 curr->has_offset != next->has_offset) {
2531 return false;
2532 }
2533 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2534 return false;
2535 }
2536 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2537 return false;
2538 }
2539 return true;
2540}
2541
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002542static int img_map(int argc, char **argv)
2543{
2544 int c;
2545 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002546 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002547 BlockDriverState *bs;
2548 const char *filename, *fmt, *output;
2549 int64_t length;
2550 MapEntry curr = { .length = 0 }, next;
2551 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002552 bool image_opts = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002553
2554 fmt = NULL;
2555 output = NULL;
2556 for (;;) {
2557 int option_index = 0;
2558 static const struct option long_options[] = {
2559 {"help", no_argument, 0, 'h'},
2560 {"format", required_argument, 0, 'f'},
2561 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002562 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002563 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002564 {0, 0, 0, 0}
2565 };
2566 c = getopt_long(argc, argv, "f:h",
2567 long_options, &option_index);
2568 if (c == -1) {
2569 break;
2570 }
2571 switch (c) {
2572 case '?':
2573 case 'h':
2574 help();
2575 break;
2576 case 'f':
2577 fmt = optarg;
2578 break;
2579 case OPTION_OUTPUT:
2580 output = optarg;
2581 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002582 case OPTION_OBJECT: {
2583 QemuOpts *opts;
2584 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2585 optarg, true);
2586 if (!opts) {
2587 return 1;
2588 }
2589 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002590 case OPTION_IMAGE_OPTS:
2591 image_opts = true;
2592 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002593 }
2594 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002595 if (optind != argc - 1) {
2596 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002597 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002598 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002599
2600 if (output && !strcmp(output, "json")) {
2601 output_format = OFORMAT_JSON;
2602 } else if (output && !strcmp(output, "human")) {
2603 output_format = OFORMAT_HUMAN;
2604 } else if (output) {
2605 error_report("--output must be used with human or json as argument.");
2606 return 1;
2607 }
2608
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002609 if (qemu_opts_foreach(&qemu_object_opts,
2610 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002611 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002612 return 1;
2613 }
2614
Kevin Wolfce099542016-03-15 13:01:04 +01002615 blk = img_open(image_opts, filename, fmt, 0, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002616 if (!blk) {
2617 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002618 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002619 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002620
2621 if (output_format == OFORMAT_HUMAN) {
2622 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2623 }
2624
Max Reitzf1d3cd72015-02-05 13:58:18 -05002625 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002626 while (curr.start + curr.length < length) {
2627 int64_t nsectors_left;
2628 int64_t sector_num;
2629 int n;
2630
2631 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2632
2633 /* Probe up to 1 GiB at a time. */
2634 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2635 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2636 ret = get_block_status(bs, sector_num, n, &next);
2637
2638 if (ret < 0) {
2639 error_report("Could not read file metadata: %s", strerror(-ret));
2640 goto out;
2641 }
2642
Fam Zheng16b0d552016-01-26 11:59:02 +08002643 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002644 curr.length += next.length;
2645 continue;
2646 }
2647
2648 if (curr.length > 0) {
2649 dump_map_entry(output_format, &curr, &next);
2650 }
2651 curr = next;
2652 }
2653
2654 dump_map_entry(output_format, &curr, NULL);
2655
2656out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002657 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002658 return ret < 0;
2659}
2660
aliguorif7b4a942009-01-07 17:40:15 +00002661#define SNAPSHOT_LIST 1
2662#define SNAPSHOT_CREATE 2
2663#define SNAPSHOT_APPLY 3
2664#define SNAPSHOT_DELETE 4
2665
Stuart Brady153859b2009-06-07 00:42:17 +01002666static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002667{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002668 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002669 BlockDriverState *bs;
2670 QEMUSnapshotInfo sn;
2671 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002672 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002673 int action = 0;
2674 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002675 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002676 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002677 bool image_opts = false;
aliguorif7b4a942009-01-07 17:40:15 +00002678
Kevin Wolfce099542016-03-15 13:01:04 +01002679 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002680 /* Parse commandline parameters */
2681 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002682 static const struct option long_options[] = {
2683 {"help", no_argument, 0, 'h'},
2684 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002685 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002686 {0, 0, 0, 0}
2687 };
2688 c = getopt_long(argc, argv, "la:c:d:hq",
2689 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002690 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002691 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002692 }
aliguorif7b4a942009-01-07 17:40:15 +00002693 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002694 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002695 case 'h':
2696 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002697 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002698 case 'l':
2699 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002700 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002701 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002702 }
2703 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002704 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002705 break;
2706 case 'a':
2707 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002708 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002709 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002710 }
2711 action = SNAPSHOT_APPLY;
2712 snapshot_name = optarg;
2713 break;
2714 case 'c':
2715 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002716 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002717 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002718 }
2719 action = SNAPSHOT_CREATE;
2720 snapshot_name = optarg;
2721 break;
2722 case 'd':
2723 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002724 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002725 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002726 }
2727 action = SNAPSHOT_DELETE;
2728 snapshot_name = optarg;
2729 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002730 case 'q':
2731 quiet = true;
2732 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002733 case OPTION_OBJECT: {
2734 QemuOpts *opts;
2735 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2736 optarg, true);
2737 if (!opts) {
2738 return 1;
2739 }
2740 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002741 case OPTION_IMAGE_OPTS:
2742 image_opts = true;
2743 break;
aliguorif7b4a942009-01-07 17:40:15 +00002744 }
2745 }
2746
Kevin Wolffc11eb22013-08-05 10:53:04 +02002747 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002748 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002749 }
aliguorif7b4a942009-01-07 17:40:15 +00002750 filename = argv[optind++];
2751
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002752 if (qemu_opts_foreach(&qemu_object_opts,
2753 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002754 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002755 return 1;
2756 }
2757
aliguorif7b4a942009-01-07 17:40:15 +00002758 /* Open the image */
Kevin Wolfce099542016-03-15 13:01:04 +01002759 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002760 if (!blk) {
2761 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002762 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002763 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002764
2765 /* Perform the requested action */
2766 switch(action) {
2767 case SNAPSHOT_LIST:
2768 dump_snapshots(bs);
2769 break;
2770
2771 case SNAPSHOT_CREATE:
2772 memset(&sn, 0, sizeof(sn));
2773 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2774
2775 qemu_gettimeofday(&tv);
2776 sn.date_sec = tv.tv_sec;
2777 sn.date_nsec = tv.tv_usec * 1000;
2778
2779 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002780 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002781 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002782 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002783 }
aliguorif7b4a942009-01-07 17:40:15 +00002784 break;
2785
2786 case SNAPSHOT_APPLY:
2787 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002788 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002789 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002790 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002791 }
aliguorif7b4a942009-01-07 17:40:15 +00002792 break;
2793
2794 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002795 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002796 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002797 error_reportf_err(err, "Could not delete snapshot '%s': ",
2798 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002799 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002800 }
aliguorif7b4a942009-01-07 17:40:15 +00002801 break;
2802 }
2803
2804 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002805 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002806 if (ret) {
2807 return 1;
2808 }
Stuart Brady153859b2009-06-07 00:42:17 +01002809 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002810}
2811
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002812static int img_rebase(int argc, char **argv)
2813{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002814 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01002815 uint8_t *buf_old = NULL;
2816 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05002817 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002818 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002819 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2820 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01002821 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002822 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002823 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002824 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002825 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002826 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002827
2828 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002829 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002830 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002831 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002832 out_baseimg = NULL;
2833 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002834 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002835 static const struct option long_options[] = {
2836 {"help", no_argument, 0, 'h'},
2837 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002838 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002839 {0, 0, 0, 0}
2840 };
2841 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2842 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002843 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002844 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002845 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002846 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002847 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002848 case 'h':
2849 help();
2850 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002851 case 'f':
2852 fmt = optarg;
2853 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002854 case 'F':
2855 out_basefmt = optarg;
2856 break;
2857 case 'b':
2858 out_baseimg = optarg;
2859 break;
2860 case 'u':
2861 unsafe = 1;
2862 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002863 case 'p':
2864 progress = 1;
2865 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002866 case 't':
2867 cache = optarg;
2868 break;
Max Reitz40055952014-07-22 22:58:42 +02002869 case 'T':
2870 src_cache = optarg;
2871 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002872 case 'q':
2873 quiet = true;
2874 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002875 case OPTION_OBJECT: {
2876 QemuOpts *opts;
2877 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2878 optarg, true);
2879 if (!opts) {
2880 return 1;
2881 }
2882 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002883 case OPTION_IMAGE_OPTS:
2884 image_opts = true;
2885 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002886 }
2887 }
2888
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002889 if (quiet) {
2890 progress = 0;
2891 }
2892
Fam Zhengac1307a2014-04-22 13:36:11 +08002893 if (optind != argc - 1) {
2894 error_exit("Expecting one image file name");
2895 }
2896 if (!unsafe && !out_baseimg) {
2897 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002898 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002899 filename = argv[optind++];
2900
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002901 if (qemu_opts_foreach(&qemu_object_opts,
2902 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002903 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002904 return 1;
2905 }
2906
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002907 qemu_progress_init(progress, 2.0);
2908 qemu_progress_print(0, 100);
2909
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002910 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01002911 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002912 if (ret < 0) {
2913 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002914 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002915 }
2916
Kevin Wolfce099542016-03-15 13:01:04 +01002917 src_flags = 0;
2918 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02002919 if (ret < 0) {
2920 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002921 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002922 }
2923
Kevin Wolfce099542016-03-15 13:01:04 +01002924 /* The source files are opened read-only, don't care about WCE */
2925 assert((src_flags & BDRV_O_RDWR) == 0);
2926 (void) src_writethrough;
2927
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002928 /*
2929 * Open the images.
2930 *
2931 * Ignore the old backing file for unsafe rebase in case we want to correct
2932 * the reference to a renamed or moved backing file.
2933 */
Kevin Wolfce099542016-03-15 13:01:04 +01002934 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002935 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002936 ret = -1;
2937 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002938 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002939 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002940
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002941 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05002942 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002943 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002944 ret = -1;
2945 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002946 }
2947 }
2948
2949 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002950 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05002951 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05002952 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002953
Max Reitz644483d2015-02-05 13:58:17 -05002954 if (bs->backing_format[0] != '\0') {
2955 options = qdict_new();
2956 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2957 }
2958
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002959 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01002960 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002961 options, src_flags, &local_err);
2962 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002963 error_reportf_err(local_err,
2964 "Could not open old backing file '%s': ",
2965 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002966 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002967 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002968 }
Max Reitz644483d2015-02-05 13:58:17 -05002969
Alex Bligha6166732012-10-16 13:46:18 +01002970 if (out_baseimg[0]) {
Max Reitz644483d2015-02-05 13:58:17 -05002971 if (out_basefmt) {
2972 options = qdict_new();
2973 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2974 } else {
2975 options = NULL;
2976 }
2977
Max Reitzefaa7c42016-03-16 19:54:38 +01002978 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002979 options, src_flags, &local_err);
2980 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002981 error_reportf_err(local_err,
2982 "Could not open new backing file '%s': ",
2983 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002984 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01002985 goto out;
2986 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002987 }
2988 }
2989
2990 /*
2991 * Check each unallocated cluster in the COW file. If it is unallocated,
2992 * accesses go to the backing file. We must therefore compare this cluster
2993 * in the old and new backing file, and if they differ we need to copy it
2994 * from the old backing file into the COW file.
2995 *
2996 * If qemu-img crashes during this step, no harm is done. The content of
2997 * the image is the same as the original one at any time.
2998 */
2999 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003000 int64_t num_sectors;
3001 int64_t old_backing_num_sectors;
3002 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003003 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003004 int n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003005 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003006
Max Reitzf1d3cd72015-02-05 13:58:18 -05003007 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3008 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003009
Max Reitzf1d3cd72015-02-05 13:58:18 -05003010 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003011 if (num_sectors < 0) {
3012 error_report("Could not get size of '%s': %s",
3013 filename, strerror(-num_sectors));
3014 ret = -1;
3015 goto out;
3016 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003017 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003018 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003019 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003020
3021 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3022 error_report("Could not get size of '%s': %s",
3023 backing_name, strerror(-old_backing_num_sectors));
3024 ret = -1;
3025 goto out;
3026 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003027 if (blk_new_backing) {
3028 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003029 if (new_backing_num_sectors < 0) {
3030 error_report("Could not get size of '%s': %s",
3031 out_baseimg, strerror(-new_backing_num_sectors));
3032 ret = -1;
3033 goto out;
3034 }
Alex Bligha6166732012-10-16 13:46:18 +01003035 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003036
Kevin Wolf1f710492012-10-12 14:29:18 +02003037 if (num_sectors != 0) {
3038 local_progress = (float)100 /
3039 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3040 }
3041
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003042 for (sector = 0; sector < num_sectors; sector += n) {
3043
3044 /* How many sectors can we handle with the next read? */
3045 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3046 n = (IO_BUF_SIZE / 512);
3047 } else {
3048 n = num_sectors - sector;
3049 }
3050
3051 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02003052 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003053 if (ret < 0) {
3054 error_report("error while reading image metadata: %s",
3055 strerror(-ret));
3056 goto out;
3057 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003058 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003059 continue;
3060 }
3061
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003062 /*
3063 * Read old and new backing file and take into consideration that
3064 * backing files may be smaller than the COW image.
3065 */
3066 if (sector >= old_backing_num_sectors) {
3067 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3068 } else {
3069 if (sector + n > old_backing_num_sectors) {
3070 n = old_backing_num_sectors - sector;
3071 }
3072
Eric Blake91669202016-05-06 10:26:43 -06003073 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3074 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003075 if (ret < 0) {
3076 error_report("error while reading from old backing file");
3077 goto out;
3078 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003079 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003080
Max Reitzf1d3cd72015-02-05 13:58:18 -05003081 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003082 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3083 } else {
3084 if (sector + n > new_backing_num_sectors) {
3085 n = new_backing_num_sectors - sector;
3086 }
3087
Eric Blake91669202016-05-06 10:26:43 -06003088 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3089 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003090 if (ret < 0) {
3091 error_report("error while reading from new backing file");
3092 goto out;
3093 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003094 }
3095
3096 /* If they differ, we need to write to the COW file */
3097 uint64_t written = 0;
3098
3099 while (written < n) {
3100 int pnum;
3101
3102 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003103 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003104 {
Eric Blake91669202016-05-06 10:26:43 -06003105 ret = blk_pwrite(blk,
3106 (sector + written) << BDRV_SECTOR_BITS,
3107 buf_old + written * 512,
3108 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003109 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003110 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003111 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003112 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003113 }
3114 }
3115
3116 written += pnum;
3117 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003118 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003119 }
3120 }
3121
3122 /*
3123 * Change the backing file. All clusters that are different from the old
3124 * backing file are overwritten in the COW file now, so the visible content
3125 * doesn't change when we switch the backing file.
3126 */
Alex Bligha6166732012-10-16 13:46:18 +01003127 if (out_baseimg && *out_baseimg) {
3128 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3129 } else {
3130 ret = bdrv_change_backing_file(bs, NULL, NULL);
3131 }
3132
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003133 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003134 error_report("Could not change the backing file to '%s': No "
3135 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003136 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003137 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003138 out_baseimg, strerror(-ret));
3139 }
3140
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003141 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003142 /*
3143 * TODO At this point it is possible to check if any clusters that are
3144 * allocated in the COW file are the same in the backing file. If so, they
3145 * could be dropped from the COW file. Don't do this before switching the
3146 * backing file, in case of a crash this would lead to corruption.
3147 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003148out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003149 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003150 /* Cleanup */
3151 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003152 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003153 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003154 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003155 qemu_vfree(buf_old);
3156 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003157
Markus Armbruster26f54e92014-10-07 13:59:04 +02003158 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003159 if (ret) {
3160 return 1;
3161 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162 return 0;
3163}
3164
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003165static int img_resize(int argc, char **argv)
3166{
Markus Armbruster6750e792015-02-12 17:43:08 +01003167 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003168 int c, ret, relative;
3169 const char *filename, *fmt, *size;
3170 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003171 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003172 BlockBackend *blk = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003173 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003174
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003175 static QemuOptsList resize_options = {
3176 .name = "resize_options",
3177 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3178 .desc = {
3179 {
3180 .name = BLOCK_OPT_SIZE,
3181 .type = QEMU_OPT_SIZE,
3182 .help = "Virtual disk size"
3183 }, {
3184 /* end of list */
3185 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003186 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003187 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003188 bool image_opts = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003189
Kevin Wolfe80fec72011-04-29 10:58:12 +02003190 /* Remove size from argv manually so that negative numbers are not treated
3191 * as options by getopt. */
3192 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003193 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003194 return 1;
3195 }
3196
3197 size = argv[--argc];
3198
3199 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003200 fmt = NULL;
3201 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003202 static const struct option long_options[] = {
3203 {"help", no_argument, 0, 'h'},
3204 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003205 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003206 {0, 0, 0, 0}
3207 };
3208 c = getopt_long(argc, argv, "f:hq",
3209 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003210 if (c == -1) {
3211 break;
3212 }
3213 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01003214 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003215 case 'h':
3216 help();
3217 break;
3218 case 'f':
3219 fmt = optarg;
3220 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003221 case 'q':
3222 quiet = true;
3223 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003224 case OPTION_OBJECT: {
3225 QemuOpts *opts;
3226 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3227 optarg, true);
3228 if (!opts) {
3229 return 1;
3230 }
3231 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003232 case OPTION_IMAGE_OPTS:
3233 image_opts = true;
3234 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003235 }
3236 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003237 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003238 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003239 }
3240 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003241
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003242 if (qemu_opts_foreach(&qemu_object_opts,
3243 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003244 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003245 return 1;
3246 }
3247
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003248 /* Choose grow, shrink, or absolute resize mode */
3249 switch (size[0]) {
3250 case '+':
3251 relative = 1;
3252 size++;
3253 break;
3254 case '-':
3255 relative = -1;
3256 size++;
3257 break;
3258 default:
3259 relative = 0;
3260 break;
3261 }
3262
3263 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003264 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003265 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003266 if (err) {
3267 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003268 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003269 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003270 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003271 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003272 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3273 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003274
Max Reitzefaa7c42016-03-16 19:54:38 +01003275 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01003276 BDRV_O_RDWR, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003277 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003278 ret = -1;
3279 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003280 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003281
3282 if (relative) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05003283 total_size = blk_getlength(blk) + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003284 } else {
3285 total_size = n;
3286 }
3287 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003288 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003289 ret = -1;
3290 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003291 }
3292
Max Reitzf1d3cd72015-02-05 13:58:18 -05003293 ret = blk_truncate(blk, total_size);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003294 switch (ret) {
3295 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003296 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003297 break;
3298 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01003299 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003300 break;
3301 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01003302 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003303 break;
3304 default:
Max Reitzbcf23482016-06-15 17:36:29 +02003305 error_report("Error resizing image: %s", strerror(-ret));
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003306 break;
3307 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003308out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003309 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003310 if (ret) {
3311 return 1;
3312 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003313 return 0;
3314}
3315
Max Reitz76a3a342014-10-27 11:12:51 +01003316static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003317 int64_t offset, int64_t total_work_size,
3318 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003319{
3320 qemu_progress_print(100.f * offset / total_work_size, 0);
3321}
3322
Max Reitz6f176b42013-09-03 10:09:50 +02003323static int img_amend(int argc, char **argv)
3324{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003325 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003326 int c, ret = 0;
3327 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003328 QemuOptsList *create_opts = NULL;
3329 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003330 const char *fmt = NULL, *filename, *cache;
3331 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003332 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003333 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003334 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003335 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003336 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003337
Max Reitzbd39e6e2014-07-22 22:58:43 +02003338 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003339 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003340 static const struct option long_options[] = {
3341 {"help", no_argument, 0, 'h'},
3342 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003343 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003344 {0, 0, 0, 0}
3345 };
3346 c = getopt_long(argc, argv, "ho:f:t:pq",
3347 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003348 if (c == -1) {
3349 break;
3350 }
3351
3352 switch (c) {
3353 case 'h':
3354 case '?':
3355 help();
3356 break;
3357 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01003358 if (!is_valid_option_list(optarg)) {
3359 error_report("Invalid option list: %s", optarg);
3360 ret = -1;
Max Reitze814dff2015-08-20 16:00:38 -07003361 goto out_no_progress;
Kevin Wolf626f84f2014-02-21 16:24:06 +01003362 }
3363 if (!options) {
3364 options = g_strdup(optarg);
3365 } else {
3366 char *old_options = options;
3367 options = g_strdup_printf("%s,%s", options, optarg);
3368 g_free(old_options);
3369 }
Max Reitz6f176b42013-09-03 10:09:50 +02003370 break;
3371 case 'f':
3372 fmt = optarg;
3373 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003374 case 't':
3375 cache = optarg;
3376 break;
Max Reitz76a3a342014-10-27 11:12:51 +01003377 case 'p':
3378 progress = true;
3379 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003380 case 'q':
3381 quiet = true;
3382 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003383 case OPTION_OBJECT:
3384 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3385 optarg, true);
3386 if (!opts) {
3387 ret = -1;
3388 goto out_no_progress;
3389 }
3390 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003391 case OPTION_IMAGE_OPTS:
3392 image_opts = true;
3393 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003394 }
3395 }
3396
Max Reitz6f176b42013-09-03 10:09:50 +02003397 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003398 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003399 }
3400
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003401 if (qemu_opts_foreach(&qemu_object_opts,
3402 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003403 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003404 ret = -1;
3405 goto out_no_progress;
3406 }
3407
Max Reitz76a3a342014-10-27 11:12:51 +01003408 if (quiet) {
3409 progress = false;
3410 }
3411 qemu_progress_init(progress, 1.0);
3412
Kevin Wolfa283cb62014-02-21 16:24:07 +01003413 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3414 if (fmt && has_help_option(options)) {
3415 /* If a format is explicitly specified (and possibly no filename is
3416 * given), print option help here */
3417 ret = print_block_option_help(filename, fmt);
3418 goto out;
3419 }
3420
3421 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003422 error_report("Expecting one image file name");
3423 ret = -1;
3424 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003425 }
Max Reitz6f176b42013-09-03 10:09:50 +02003426
Kevin Wolfce099542016-03-15 13:01:04 +01003427 flags = BDRV_O_RDWR;
3428 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003429 if (ret < 0) {
3430 error_report("Invalid cache option: %s", cache);
3431 goto out;
3432 }
3433
Kevin Wolfce099542016-03-15 13:01:04 +01003434 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003435 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003436 ret = -1;
3437 goto out;
3438 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003439 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003440
3441 fmt = bs->drv->format_name;
3442
Kevin Wolf626f84f2014-02-21 16:24:06 +01003443 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003444 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003445 ret = print_block_option_help(filename, fmt);
3446 goto out;
3447 }
3448
Max Reitzb2439d22014-12-02 18:32:47 +01003449 if (!bs->drv->create_opts) {
3450 error_report("Format driver '%s' does not support any options to amend",
3451 fmt);
3452 ret = -1;
3453 goto out;
3454 }
3455
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003456 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003457 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003458 if (options) {
3459 qemu_opts_do_parse(opts, options, NULL, &err);
3460 if (err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01003461 error_report_err(err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003462 ret = -1;
3463 goto out;
3464 }
Max Reitz6f176b42013-09-03 10:09:50 +02003465 }
3466
Max Reitz76a3a342014-10-27 11:12:51 +01003467 /* In case the driver does not call amend_status_cb() */
3468 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003469 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003470 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003471 if (ret < 0) {
3472 error_report("Error while amending options: %s", strerror(-ret));
3473 goto out;
3474 }
3475
3476out:
Max Reitz76a3a342014-10-27 11:12:51 +01003477 qemu_progress_end();
3478
Max Reitze814dff2015-08-20 16:00:38 -07003479out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003480 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003481 qemu_opts_del(opts);
3482 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003483 g_free(options);
3484
Max Reitz6f176b42013-09-03 10:09:50 +02003485 if (ret) {
3486 return 1;
3487 }
3488 return 0;
3489}
3490
Kevin Wolfb6133b82014-08-05 14:17:13 +02003491typedef struct BenchData {
3492 BlockBackend *blk;
3493 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003494 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003495 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003496 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003497 int nrreq;
3498 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003499 int flush_interval;
3500 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003501 uint8_t *buf;
3502 QEMUIOVector *qiov;
3503
3504 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003505 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003506 uint64_t offset;
3507} BenchData;
3508
Kevin Wolf55d539c2016-06-03 13:59:41 +02003509static void bench_undrained_flush_cb(void *opaque, int ret)
3510{
3511 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003512 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003513 exit(EXIT_FAILURE);
3514 }
3515}
3516
Kevin Wolfb6133b82014-08-05 14:17:13 +02003517static void bench_cb(void *opaque, int ret)
3518{
3519 BenchData *b = opaque;
3520 BlockAIOCB *acb;
3521
3522 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003523 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003524 exit(EXIT_FAILURE);
3525 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003526
3527 if (b->in_flush) {
3528 /* Just finished a flush with drained queue: Start next requests */
3529 assert(b->in_flight == 0);
3530 b->in_flush = false;
3531 } else if (b->in_flight > 0) {
3532 int remaining = b->n - b->in_flight;
3533
Kevin Wolfb6133b82014-08-05 14:17:13 +02003534 b->n--;
3535 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003536
3537 /* Time for flush? Drain queue if requested, then flush */
3538 if (b->flush_interval && remaining % b->flush_interval == 0) {
3539 if (!b->in_flight || !b->drain_on_flush) {
3540 BlockCompletionFunc *cb;
3541
3542 if (b->drain_on_flush) {
3543 b->in_flush = true;
3544 cb = bench_cb;
3545 } else {
3546 cb = bench_undrained_flush_cb;
3547 }
3548
3549 acb = blk_aio_flush(b->blk, cb, b);
3550 if (!acb) {
3551 error_report("Failed to issue flush request");
3552 exit(EXIT_FAILURE);
3553 }
3554 }
3555 if (b->drain_on_flush) {
3556 return;
3557 }
3558 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003559 }
3560
3561 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003562 int64_t offset = b->offset;
3563 /* blk_aio_* might look for completed I/Os and kick bench_cb
3564 * again, so make sure this operation is counted by in_flight
3565 * and b->offset is ready for the next submission.
3566 */
3567 b->in_flight++;
3568 b->offset += b->step;
3569 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003570 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003571 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003572 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003573 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003574 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003575 if (!acb) {
3576 error_report("Failed to issue request");
3577 exit(EXIT_FAILURE);
3578 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003579 }
3580}
3581
3582static int img_bench(int argc, char **argv)
3583{
3584 int c, ret = 0;
3585 const char *fmt = NULL, *filename;
3586 bool quiet = false;
3587 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003588 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003589 int count = 75000;
3590 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003591 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003592 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003593 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003594 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003595 int flush_interval = 0;
3596 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003597 int64_t image_size;
3598 BlockBackend *blk = NULL;
3599 BenchData data = {};
3600 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003601 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003602 struct timeval t1, t2;
3603 int i;
3604
3605 for (;;) {
3606 static const struct option long_options[] = {
3607 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003608 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003609 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003610 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003611 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003612 {0, 0, 0, 0}
3613 };
Kevin Wolf83de9be2015-07-13 13:13:17 +02003614 c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003615 if (c == -1) {
3616 break;
3617 }
3618
3619 switch (c) {
3620 case 'h':
3621 case '?':
3622 help();
3623 break;
3624 case 'c':
3625 {
3626 char *end;
3627 errno = 0;
3628 count = strtoul(optarg, &end, 0);
3629 if (errno || *end || count > INT_MAX) {
3630 error_report("Invalid request count specified");
3631 return 1;
3632 }
3633 break;
3634 }
3635 case 'd':
3636 {
3637 char *end;
3638 errno = 0;
3639 depth = strtoul(optarg, &end, 0);
3640 if (errno || *end || depth > INT_MAX) {
3641 error_report("Invalid queue depth specified");
3642 return 1;
3643 }
3644 break;
3645 }
3646 case 'f':
3647 fmt = optarg;
3648 break;
3649 case 'n':
3650 flags |= BDRV_O_NATIVE_AIO;
3651 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003652 case 'o':
3653 {
3654 char *end;
3655 errno = 0;
3656 offset = qemu_strtosz_suffix(optarg, &end,
3657 QEMU_STRTOSZ_DEFSUFFIX_B);
3658 if (offset < 0|| *end) {
3659 error_report("Invalid offset specified");
3660 return 1;
3661 }
3662 break;
3663 }
3664 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003665 case 'q':
3666 quiet = true;
3667 break;
3668 case 's':
3669 {
3670 int64_t sval;
3671 char *end;
3672
3673 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3674 if (sval < 0 || sval > INT_MAX || *end) {
3675 error_report("Invalid buffer size specified");
3676 return 1;
3677 }
3678
3679 bufsize = sval;
3680 break;
3681 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003682 case 'S':
3683 {
3684 int64_t sval;
3685 char *end;
3686
3687 sval = qemu_strtosz_suffix(optarg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3688 if (sval < 0 || sval > INT_MAX || *end) {
3689 error_report("Invalid step size specified");
3690 return 1;
3691 }
3692
3693 step = sval;
3694 break;
3695 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003696 case 't':
3697 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3698 if (ret < 0) {
3699 error_report("Invalid cache mode");
3700 ret = -1;
3701 goto out;
3702 }
3703 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003704 case 'w':
3705 flags |= BDRV_O_RDWR;
3706 is_write = true;
3707 break;
3708 case OPTION_PATTERN:
3709 {
3710 char *end;
3711 errno = 0;
3712 pattern = strtoul(optarg, &end, 0);
3713 if (errno || *end || pattern > 0xff) {
3714 error_report("Invalid pattern byte specified");
3715 return 1;
3716 }
3717 break;
3718 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003719 case OPTION_FLUSH_INTERVAL:
3720 {
3721 char *end;
3722 errno = 0;
3723 flush_interval = strtoul(optarg, &end, 0);
3724 if (errno || *end || flush_interval > INT_MAX) {
3725 error_report("Invalid flush interval specified");
3726 return 1;
3727 }
3728 break;
3729 }
3730 case OPTION_NO_DRAIN:
3731 drain_on_flush = false;
3732 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003733 case OPTION_IMAGE_OPTS:
3734 image_opts = true;
3735 break;
3736 }
3737 }
3738
3739 if (optind != argc - 1) {
3740 error_exit("Expecting one image file name");
3741 }
3742 filename = argv[argc - 1];
3743
Kevin Wolf55d539c2016-06-03 13:59:41 +02003744 if (!is_write && flush_interval) {
3745 error_report("--flush-interval is only available in write tests");
3746 ret = -1;
3747 goto out;
3748 }
3749 if (flush_interval && flush_interval < depth) {
3750 error_report("Flush interval can't be smaller than depth");
3751 ret = -1;
3752 goto out;
3753 }
3754
Kevin Wolfb6133b82014-08-05 14:17:13 +02003755 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3756 if (!blk) {
3757 ret = -1;
3758 goto out;
3759 }
3760
3761 image_size = blk_getlength(blk);
3762 if (image_size < 0) {
3763 ret = image_size;
3764 goto out;
3765 }
3766
3767 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003768 .blk = blk,
3769 .image_size = image_size,
3770 .bufsize = bufsize,
3771 .step = step ?: bufsize,
3772 .nrreq = depth,
3773 .n = count,
3774 .offset = offset,
3775 .write = is_write,
3776 .flush_interval = flush_interval,
3777 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02003778 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02003779 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02003780 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02003781 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02003782 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02003783 if (flush_interval) {
3784 printf("Sending flush every %d requests\n", flush_interval);
3785 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003786
3787 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003788 memset(data.buf, pattern, data.nrreq * data.bufsize);
3789
Kevin Wolfb6133b82014-08-05 14:17:13 +02003790 data.qiov = g_new(QEMUIOVector, data.nrreq);
3791 for (i = 0; i < data.nrreq; i++) {
3792 qemu_iovec_init(&data.qiov[i], 1);
3793 qemu_iovec_add(&data.qiov[i],
3794 data.buf + i * data.bufsize, data.bufsize);
3795 }
3796
3797 gettimeofday(&t1, NULL);
3798 bench_cb(&data, 0);
3799
3800 while (data.n > 0) {
3801 main_loop_wait(false);
3802 }
3803 gettimeofday(&t2, NULL);
3804
3805 printf("Run completed in %3.3f seconds.\n",
3806 (t2.tv_sec - t1.tv_sec)
3807 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3808
3809out:
3810 qemu_vfree(data.buf);
3811 blk_unref(blk);
3812
3813 if (ret) {
3814 return 1;
3815 }
3816 return 0;
3817}
3818
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003819#define C_BS 01
3820#define C_COUNT 02
3821#define C_IF 04
3822#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02003823#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003824
3825struct DdInfo {
3826 unsigned int flags;
3827 int64_t count;
3828};
3829
3830struct DdIo {
3831 int bsz; /* Block size */
3832 char *filename;
3833 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02003834 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003835};
3836
3837struct DdOpts {
3838 const char *name;
3839 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
3840 unsigned int flag;
3841};
3842
3843static int img_dd_bs(const char *arg,
3844 struct DdIo *in, struct DdIo *out,
3845 struct DdInfo *dd)
3846{
3847 char *end;
3848 int64_t res;
3849
3850 res = qemu_strtosz_suffix(arg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3851
3852 if (res <= 0 || res > INT_MAX || *end) {
3853 error_report("invalid number: '%s'", arg);
3854 return 1;
3855 }
3856 in->bsz = out->bsz = res;
3857
3858 return 0;
3859}
3860
3861static int img_dd_count(const char *arg,
3862 struct DdIo *in, struct DdIo *out,
3863 struct DdInfo *dd)
3864{
3865 char *end;
3866
3867 dd->count = qemu_strtosz_suffix(arg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3868
3869 if (dd->count < 0 || *end) {
3870 error_report("invalid number: '%s'", arg);
3871 return 1;
3872 }
3873
3874 return 0;
3875}
3876
3877static int img_dd_if(const char *arg,
3878 struct DdIo *in, struct DdIo *out,
3879 struct DdInfo *dd)
3880{
3881 in->filename = g_strdup(arg);
3882
3883 return 0;
3884}
3885
3886static int img_dd_of(const char *arg,
3887 struct DdIo *in, struct DdIo *out,
3888 struct DdInfo *dd)
3889{
3890 out->filename = g_strdup(arg);
3891
3892 return 0;
3893}
3894
Reda Sallahif7c15532016-08-10 16:16:09 +02003895static int img_dd_skip(const char *arg,
3896 struct DdIo *in, struct DdIo *out,
3897 struct DdInfo *dd)
3898{
3899 char *end;
3900
3901 in->offset = qemu_strtosz_suffix(arg, &end, QEMU_STRTOSZ_DEFSUFFIX_B);
3902
3903 if (in->offset < 0 || *end) {
3904 error_report("invalid number: '%s'", arg);
3905 return 1;
3906 }
3907
3908 return 0;
3909}
3910
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003911static int img_dd(int argc, char **argv)
3912{
3913 int ret = 0;
3914 char *arg = NULL;
3915 char *tmp;
3916 BlockDriver *drv = NULL, *proto_drv = NULL;
3917 BlockBackend *blk1 = NULL, *blk2 = NULL;
3918 QemuOpts *opts = NULL;
3919 QemuOptsList *create_opts = NULL;
3920 Error *local_err = NULL;
3921 bool image_opts = false;
3922 int c, i;
3923 const char *out_fmt = "raw";
3924 const char *fmt = NULL;
3925 int64_t size = 0;
3926 int64_t block_count = 0, out_pos, in_pos;
3927 struct DdInfo dd = {
3928 .flags = 0,
3929 .count = 0,
3930 };
3931 struct DdIo in = {
3932 .bsz = 512, /* Block size is by default 512 bytes */
3933 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003934 .buf = NULL,
3935 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003936 };
3937 struct DdIo out = {
3938 .bsz = 512,
3939 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003940 .buf = NULL,
3941 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003942 };
3943
3944 const struct DdOpts options[] = {
3945 { "bs", img_dd_bs, C_BS },
3946 { "count", img_dd_count, C_COUNT },
3947 { "if", img_dd_if, C_IF },
3948 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02003949 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003950 { NULL, NULL, 0 }
3951 };
3952 const struct option long_options[] = {
3953 { "help", no_argument, 0, 'h'},
3954 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3955 { 0, 0, 0, 0 }
3956 };
3957
3958 while ((c = getopt_long(argc, argv, "hf:O:", long_options, NULL))) {
3959 if (c == EOF) {
3960 break;
3961 }
3962 switch (c) {
3963 case 'O':
3964 out_fmt = optarg;
3965 break;
3966 case 'f':
3967 fmt = optarg;
3968 break;
3969 case '?':
3970 error_report("Try 'qemu-img --help' for more information.");
3971 ret = -1;
3972 goto out;
3973 case 'h':
3974 help();
3975 break;
3976 case OPTION_IMAGE_OPTS:
3977 image_opts = true;
3978 break;
3979 }
3980 }
3981
3982 for (i = optind; i < argc; i++) {
3983 int j;
3984 arg = g_strdup(argv[i]);
3985
3986 tmp = strchr(arg, '=');
3987 if (tmp == NULL) {
3988 error_report("unrecognized operand %s", arg);
3989 ret = -1;
3990 goto out;
3991 }
3992
3993 *tmp++ = '\0';
3994
3995 for (j = 0; options[j].name != NULL; j++) {
3996 if (!strcmp(arg, options[j].name)) {
3997 break;
3998 }
3999 }
4000 if (options[j].name == NULL) {
4001 error_report("unrecognized operand %s", arg);
4002 ret = -1;
4003 goto out;
4004 }
4005
4006 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4007 ret = -1;
4008 goto out;
4009 }
4010 dd.flags |= options[j].flag;
4011 g_free(arg);
4012 arg = NULL;
4013 }
4014
4015 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4016 error_report("Must specify both input and output files");
4017 ret = -1;
4018 goto out;
4019 }
4020 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false);
4021
4022 if (!blk1) {
4023 ret = -1;
4024 goto out;
4025 }
4026
4027 drv = bdrv_find_format(out_fmt);
4028 if (!drv) {
4029 error_report("Unknown file format");
4030 ret = -1;
4031 goto out;
4032 }
4033 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4034
4035 if (!proto_drv) {
4036 error_report_err(local_err);
4037 ret = -1;
4038 goto out;
4039 }
4040 if (!drv->create_opts) {
4041 error_report("Format driver '%s' does not support image creation",
4042 drv->format_name);
4043 ret = -1;
4044 goto out;
4045 }
4046 if (!proto_drv->create_opts) {
4047 error_report("Protocol driver '%s' does not support image creation",
4048 proto_drv->format_name);
4049 ret = -1;
4050 goto out;
4051 }
4052 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4053 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4054
4055 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4056
4057 size = blk_getlength(blk1);
4058 if (size < 0) {
4059 error_report("Failed to get size for '%s'", in.filename);
4060 ret = -1;
4061 goto out;
4062 }
4063
4064 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4065 dd.count * in.bsz < size) {
4066 size = dd.count * in.bsz;
4067 }
4068
Reda Sallahif7c15532016-08-10 16:16:09 +02004069 /* Overflow means the specified offset is beyond input image's size */
4070 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4071 size < in.bsz * in.offset)) {
4072 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4073 } else {
4074 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4075 size - in.bsz * in.offset, &error_abort);
4076 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004077
4078 ret = bdrv_create(drv, out.filename, opts, &local_err);
4079 if (ret < 0) {
4080 error_reportf_err(local_err,
4081 "%s: error while creating output image: ",
4082 out.filename);
4083 ret = -1;
4084 goto out;
4085 }
4086
4087 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4088 false, false);
4089
4090 if (!blk2) {
4091 ret = -1;
4092 goto out;
4093 }
4094
Reda Sallahif7c15532016-08-10 16:16:09 +02004095 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4096 size < in.offset * in.bsz)) {
4097 /* We give a warning if the skip option is bigger than the input
4098 * size and create an empty output disk image (i.e. like dd(1)).
4099 */
4100 error_report("%s: cannot skip to specified offset", in.filename);
4101 in_pos = size;
4102 } else {
4103 in_pos = in.offset * in.bsz;
4104 }
4105
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004106 in.buf = g_new(uint8_t, in.bsz);
4107
Reda Sallahif7c15532016-08-10 16:16:09 +02004108 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004109 int in_ret, out_ret;
4110
4111 if (in_pos + in.bsz > size) {
4112 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4113 } else {
4114 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4115 }
4116 if (in_ret < 0) {
4117 error_report("error while reading from input image file: %s",
4118 strerror(-in_ret));
4119 ret = -1;
4120 goto out;
4121 }
4122 in_pos += in_ret;
4123
4124 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4125
4126 if (out_ret < 0) {
4127 error_report("error while writing to output image file: %s",
4128 strerror(-out_ret));
4129 ret = -1;
4130 goto out;
4131 }
4132 out_pos += out_ret;
4133 }
4134
4135out:
4136 g_free(arg);
4137 qemu_opts_del(opts);
4138 qemu_opts_free(create_opts);
4139 blk_unref(blk1);
4140 blk_unref(blk2);
4141 g_free(in.filename);
4142 g_free(out.filename);
4143 g_free(in.buf);
4144 g_free(out.buf);
4145
4146 if (ret) {
4147 return 1;
4148 }
4149 return 0;
4150}
4151
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152
Anthony Liguoric227f092009-10-01 16:12:16 -05004153static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004154#define DEF(option, callback, arg_string) \
4155 { option, callback },
4156#include "qemu-img-cmds.h"
4157#undef DEF
4158#undef GEN_DOCS
4159 { NULL, NULL, },
4160};
4161
bellardea2384d2004-08-01 21:59:26 +00004162int main(int argc, char **argv)
4163{
Anthony Liguoric227f092009-10-01 16:12:16 -05004164 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004165 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004166 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004167 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004168 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004169 static const struct option long_options[] = {
4170 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004171 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004172 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004173 {0, 0, 0, 0}
4174 };
bellardea2384d2004-08-01 21:59:26 +00004175
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004176#ifdef CONFIG_POSIX
4177 signal(SIGPIPE, SIG_IGN);
4178#endif
4179
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004180 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004181 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004182 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004183
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004184 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004185 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004186 exit(EXIT_FAILURE);
4187 }
4188
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004189 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004190
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004191 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004192 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004193 if (argc < 2) {
4194 error_exit("Not enough arguments");
4195 }
Stuart Brady153859b2009-06-07 00:42:17 +01004196
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004197 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004198 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004199 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004200
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004201 while ((c = getopt_long(argc, argv, "+hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004202 switch (c) {
4203 case 'h':
4204 help();
4205 return 0;
4206 case 'V':
4207 printf(QEMU_IMG_VERSION);
4208 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004209 case 'T':
4210 g_free(trace_file);
4211 trace_file = trace_opt_parse(optarg);
4212 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004213 }
bellardea2384d2004-08-01 21:59:26 +00004214 }
Stuart Brady153859b2009-06-07 00:42:17 +01004215
Denis V. Lunev10985132016-06-17 17:44:13 +03004216 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004217
Denis V. Lunev10985132016-06-17 17:44:13 +03004218 /* reset getopt_long scanning */
4219 argc -= optind;
4220 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004221 return 0;
4222 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004223 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004224 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004225
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004226 if (!trace_init_backends()) {
4227 exit(1);
4228 }
4229 trace_init_file(trace_file);
4230 qemu_set_log(LOG_TRACE);
4231
Denis V. Lunev10985132016-06-17 17:44:13 +03004232 /* find the command */
4233 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4234 if (!strcmp(cmdname, cmd->name)) {
4235 return cmd->handler(argc, argv);
4236 }
4237 }
Jeff Cody7db16892014-04-25 17:02:32 -04004238
Stuart Brady153859b2009-06-07 00:42:17 +01004239 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004240 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004241}