blob: 40629176033ef2f3b7a5c2f1bde85d633f32e2cb [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Peter Maydell80c71a22016-01-18 18:01:42 +000024#include "qemu/osdep.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080025#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010026#include "qapi/error.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020027#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010028#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010029#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010030#include "qapi/qmp/qjson.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020031#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000032#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010033#include "qemu/option.h"
34#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030035#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010037#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020038#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010039#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020040#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080041#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010042#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030043#include "trace/control.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020044#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000045
Don Slutz61979a62015-01-09 10:17:35 -050046#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020047 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040048
Anthony Liguoric227f092009-10-01 16:12:16 -050049typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010050 const char *name;
51 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050052} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010053
Federico Simoncelli8599ea42013-01-28 06:59:47 -050054enum {
55 OPTION_OUTPUT = 256,
56 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000057 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000058 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020059 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020060 OPTION_FLUSH_INTERVAL = 261,
61 OPTION_NO_DRAIN = 262,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050062};
63
64typedef enum OutputFormat {
65 OFORMAT_JSON,
66 OFORMAT_HUMAN,
67} OutputFormat;
68
Kevin Wolfe6996142016-03-15 13:03:11 +010069/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040070#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000071
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010072static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000073{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010074 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000075}
76
Fam Zhengac1307a2014-04-22 13:36:11 +080077static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
78{
79 va_list ap;
80
81 error_printf("qemu-img: ");
82
83 va_start(ap, fmt);
84 error_vprintf(fmt, ap);
85 va_end(ap);
86
87 error_printf("\nTry 'qemu-img --help' for more information\n");
88 exit(EXIT_FAILURE);
89}
90
blueswir1d2c639d2009-01-24 18:19:25 +000091/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080092static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000093{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010094 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040095 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +030096 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +030097 "QEMU disk image utility\n"
98 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +030099 " '-h', '--help' display this help and exit\n"
100 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300101 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
102 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300103 "\n"
malc3f020d72010-02-08 12:04:56 +0300104 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100105#define DEF(option, callback, arg_string) \
106 " " arg_string "\n"
107#include "qemu-img-cmds.h"
108#undef DEF
109#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300110 "\n"
111 "Command parameters:\n"
112 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000113 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
114 " manual page for a description of the object properties. The most common\n"
115 " object type is a 'secret', which is used to supply passwords and/or\n"
116 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300117 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400118 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800119 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
120 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100121 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
122 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300123 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200124 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
125 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
126 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300127 " 'output_filename' is the destination disk image filename\n"
128 " 'output_fmt' is the destination format\n"
129 " 'options' is a comma separated list of format specific options in a\n"
130 " name=value format. Use -o ? for an overview of the options supported by the\n"
131 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800132 " 'snapshot_param' is param used for internal snapshot, format\n"
133 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
134 " '[ID_OR_NAME]'\n"
135 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
136 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300137 " '-c' indicates that target image must be compressed (qcow format only)\n"
138 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
139 " match exactly. The image doesn't need a working backing file before\n"
140 " rebasing in this case (useful for renaming the backing file)\n"
141 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200142 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100143 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200144 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
145 " contain only zeros for qemu-img to create a sparse image during\n"
146 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
147 " unallocated or zero sectors, and the destination image will always be\n"
148 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200149 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100150 " '-n' skips the target volume creation (useful if the volume is created\n"
151 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300152 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200153 "Parameters to check subcommand:\n"
154 " '-r' tries to repair any inconsistencies that are found during the check.\n"
155 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
156 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200157 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200158 "\n"
malc3f020d72010-02-08 12:04:56 +0300159 "Parameters to snapshot subcommand:\n"
160 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
161 " '-a' applies a snapshot (revert disk to saved state)\n"
162 " '-c' creates a snapshot\n"
163 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100164 " '-l' lists all snapshots in the given image\n"
165 "\n"
166 "Parameters to compare subcommand:\n"
167 " '-f' first image format\n"
168 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200169 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
170 "\n"
171 "Parameters to dd subcommand:\n"
172 " 'bs=BYTES' read and write up to BYTES bytes at a time "
173 "(default: 512)\n"
174 " 'count=N' copy only N input blocks\n"
175 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200176 " 'of=FILE' write to FILE\n"
177 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100178
179 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100180 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000181 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800182 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000183}
184
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000185static QemuOptsList qemu_object_opts = {
186 .name = "object",
187 .implied_opt_name = "qom-type",
188 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
189 .desc = {
190 { }
191 },
192};
193
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000194static QemuOptsList qemu_source_opts = {
195 .name = "source",
196 .implied_opt_name = "file",
197 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
198 .desc = {
199 { }
200 },
201};
202
Stefan Weil7c30f652013-06-16 17:01:05 +0200203static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100204{
205 int ret = 0;
206 if (!quiet) {
207 va_list args;
208 va_start(args, fmt);
209 ret = vprintf(fmt, args);
210 va_end(args);
211 }
212 return ret;
213}
214
bellardea2384d2004-08-01 21:59:26 +0000215
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100216static int print_block_option_help(const char *filename, const char *fmt)
217{
218 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800219 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500220 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100221
222 /* Find driver and parse its options */
223 drv = bdrv_find_format(fmt);
224 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100225 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100226 return 1;
227 }
228
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800229 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100230 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500231 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100232 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100233 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800234 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100235 return 1;
236 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800237 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100238 }
239
Chunyan Liu83d05212014-06-05 17:20:51 +0800240 qemu_opts_print_help(create_opts);
241 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242 return 0;
243}
244
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000245
246static int img_open_password(BlockBackend *blk, const char *filename,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000247 int flags, bool quiet)
bellard75c23802004-08-27 21:28:58 +0000248{
249 BlockDriverState *bs;
bellard75c23802004-08-27 21:28:58 +0000250 char password[256];
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000251
252 bs = blk_bs(blk);
Daniel P. Berrange4ef130f2016-03-21 14:11:43 +0000253 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
254 !(flags & BDRV_O_NO_IO)) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000255 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
256 if (qemu_read_password(password, sizeof(password)) < 0) {
257 error_report("No password given");
258 return -1;
259 }
260 if (bdrv_set_key(bs, password) < 0) {
261 error_report("invalid password");
262 return -1;
263 }
264 }
265 return 0;
266}
267
268
Max Reitzefaa7c42016-03-16 19:54:38 +0100269static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100270 QemuOpts *opts, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000271 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000272{
273 QDict *options;
274 Error *local_err = NULL;
275 BlockBackend *blk;
276 options = qemu_opts_to_qdict(opts, NULL);
Max Reitzefaa7c42016-03-16 19:54:38 +0100277 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000278 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100279 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000280 return NULL;
281 }
Kevin Wolfce099542016-03-15 13:01:04 +0100282 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000283
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000284 if (img_open_password(blk, optstr, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000285 blk_unref(blk);
286 return NULL;
287 }
288 return blk;
289}
290
Max Reitzefaa7c42016-03-16 19:54:38 +0100291static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292 const char *fmt, int flags,
Kevin Wolfce099542016-03-15 13:01:04 +0100293 bool writethrough, bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000294{
295 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200296 Error *local_err = NULL;
Max Reitz5bd31322015-02-05 13:58:16 -0500297 QDict *options = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100298
bellard75c23802004-08-27 21:28:58 +0000299 if (fmt) {
Max Reitz5bd31322015-02-05 13:58:16 -0500300 options = qdict_new();
301 qdict_put(options, "driver", qstring_from_str(fmt));
bellard75c23802004-08-27 21:28:58 +0000302 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100303
Max Reitzefaa7c42016-03-16 19:54:38 +0100304 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500305 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100306 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 return NULL;
bellard75c23802004-08-27 21:28:58 +0000308 }
Kevin Wolfce099542016-03-15 13:01:04 +0100309 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100310
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000311 if (img_open_password(blk, filename, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312 blk_unref(blk);
313 return NULL;
bellard75c23802004-08-27 21:28:58 +0000314 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200315 return blk;
bellard75c23802004-08-27 21:28:58 +0000316}
317
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318
Max Reitzefaa7c42016-03-16 19:54:38 +0100319static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100321 const char *fmt, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000322 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000323{
324 BlockBackend *blk;
325 if (image_opts) {
326 QemuOpts *opts;
327 if (fmt) {
328 error_report("--image-opts and --format are mutually exclusive");
329 return NULL;
330 }
331 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
332 filename, true);
333 if (!opts) {
334 return NULL;
335 }
Kevin Wolfce099542016-03-15 13:01:04 +0100336 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000337 } else {
Kevin Wolfce099542016-03-15 13:01:04 +0100338 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000339 }
340 return blk;
341}
342
343
Chunyan Liu83d05212014-06-05 17:20:51 +0800344static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100345 const char *base_filename,
346 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200347{
Markus Armbruster6750e792015-02-12 17:43:08 +0100348 Error *err = NULL;
349
Kevin Wolfefa84d42009-05-18 16:42:12 +0200350 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100351 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100352 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100353 error_report("Backing file not supported for file format '%s'",
354 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100355 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900356 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200357 }
358 }
359 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100360 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100361 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100362 error_report("Backing file format not supported for file "
363 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100364 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900365 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200366 }
367 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900368 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200369}
370
Markus Armbruster606caa02017-02-21 21:14:04 +0100371static int64_t cvtnum(const char *s)
372{
373 char *end;
374 int64_t ret;
375
376 ret = qemu_strtosz(s, &end);
377 if (*end != '\0') {
378 /* Detritus at the end of the string */
379 return -EINVAL;
380 }
381 return ret;
382}
383
bellardea2384d2004-08-01 21:59:26 +0000384static int img_create(int argc, char **argv)
385{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200386 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100387 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000388 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000389 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000390 const char *filename;
391 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200392 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200393 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100394 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000395
bellardea2384d2004-08-01 21:59:26 +0000396 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000397 static const struct option long_options[] = {
398 {"help", no_argument, 0, 'h'},
399 {"object", required_argument, 0, OPTION_OBJECT},
400 {0, 0, 0, 0}
401 };
402 c = getopt_long(argc, argv, "F:b:f:he6o:q",
403 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100404 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000405 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100406 }
bellardea2384d2004-08-01 21:59:26 +0000407 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100408 case '?':
bellardea2384d2004-08-01 21:59:26 +0000409 case 'h':
410 help();
411 break;
aliguori9230eaf2009-03-28 17:55:19 +0000412 case 'F':
413 base_fmt = optarg;
414 break;
bellardea2384d2004-08-01 21:59:26 +0000415 case 'b':
416 base_filename = optarg;
417 break;
418 case 'f':
419 fmt = optarg;
420 break;
421 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200422 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100423 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100424 goto fail;
thsd8871c52007-10-24 16:11:42 +0000425 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200426 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100427 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100428 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200429 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100430 if (!is_valid_option_list(optarg)) {
431 error_report("Invalid option list: %s", optarg);
432 goto fail;
433 }
434 if (!options) {
435 options = g_strdup(optarg);
436 } else {
437 char *old_options = options;
438 options = g_strdup_printf("%s,%s", options, optarg);
439 g_free(old_options);
440 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200441 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100442 case 'q':
443 quiet = true;
444 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000445 case OPTION_OBJECT: {
446 QemuOpts *opts;
447 opts = qemu_opts_parse_noisily(&qemu_object_opts,
448 optarg, true);
449 if (!opts) {
450 goto fail;
451 }
452 } break;
bellardea2384d2004-08-01 21:59:26 +0000453 }
454 }
aliguori9230eaf2009-03-28 17:55:19 +0000455
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900456 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100457 filename = (optind < argc) ? argv[optind] : NULL;
458 if (options && has_help_option(options)) {
459 g_free(options);
460 return print_block_option_help(filename, fmt);
461 }
462
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100463 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800464 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100465 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100466 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900467
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000468 if (qemu_opts_foreach(&qemu_object_opts,
469 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200470 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000471 goto fail;
472 }
473
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100474 /* Get image size, if specified */
475 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100476 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100477
478 sval = cvtnum(argv[optind++]);
479 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800480 if (sval == -ERANGE) {
481 error_report("Image size must be less than 8 EiB!");
482 } else {
483 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200484 "G, T, P or E suffixes for ");
485 error_report("kilobytes, megabytes, gigabytes, terabytes, "
486 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800487 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100488 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100489 }
490 img_size = (uint64_t)sval;
491 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200492 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800493 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200494 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100495
Luiz Capitulino9b375252012-11-30 10:52:05 -0200496 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Kevin Wolf61de4c62016-03-18 17:46:45 +0100497 options, img_size, 0, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100498 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100499 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100500 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900501 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200502
Kevin Wolf77386bf2014-02-21 16:24:04 +0100503 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000504 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100505
506fail:
507 g_free(options);
508 return 1;
bellardea2384d2004-08-01 21:59:26 +0000509}
510
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100511static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500512{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500513 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500514 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100515 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600516
517 visit_type_ImageCheck(v, NULL, &check, &error_abort);
518 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500519 str = qobject_to_json_pretty(obj);
520 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100521 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500522 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600523 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500524 QDECREF(str);
525}
526
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100527static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500528{
529 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100530 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500531 } else {
532 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100533 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
534 "Data may be corrupted, or further writes to the image "
535 "may corrupt it.\n",
536 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500537 }
538
539 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100540 qprintf(quiet,
541 "\n%" PRId64 " leaked clusters were found on the image.\n"
542 "This means waste of disk space, but no harm to data.\n",
543 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500544 }
545
546 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100547 qprintf(quiet,
548 "\n%" PRId64
549 " internal errors have occurred during the check.\n",
550 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500551 }
552 }
553
554 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100555 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
556 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
557 check->allocated_clusters, check->total_clusters,
558 check->allocated_clusters * 100.0 / check->total_clusters,
559 check->fragmented_clusters * 100.0 / check->allocated_clusters,
560 check->compressed_clusters * 100.0 /
561 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562 }
563
564 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100565 qprintf(quiet,
566 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500567 }
568}
569
570static int collect_image_check(BlockDriverState *bs,
571 ImageCheck *check,
572 const char *filename,
573 const char *fmt,
574 int fix)
575{
576 int ret;
577 BdrvCheckResult result;
578
579 ret = bdrv_check(bs, &result, fix);
580 if (ret < 0) {
581 return ret;
582 }
583
584 check->filename = g_strdup(filename);
585 check->format = g_strdup(bdrv_get_format_name(bs));
586 check->check_errors = result.check_errors;
587 check->corruptions = result.corruptions;
588 check->has_corruptions = result.corruptions != 0;
589 check->leaks = result.leaks;
590 check->has_leaks = result.leaks != 0;
591 check->corruptions_fixed = result.corruptions_fixed;
592 check->has_corruptions_fixed = result.corruptions != 0;
593 check->leaks_fixed = result.leaks_fixed;
594 check->has_leaks_fixed = result.leaks != 0;
595 check->image_end_offset = result.image_end_offset;
596 check->has_image_end_offset = result.image_end_offset != 0;
597 check->total_clusters = result.bfi.total_clusters;
598 check->has_total_clusters = result.bfi.total_clusters != 0;
599 check->allocated_clusters = result.bfi.allocated_clusters;
600 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
601 check->fragmented_clusters = result.bfi.fragmented_clusters;
602 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100603 check->compressed_clusters = result.bfi.compressed_clusters;
604 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500605
606 return 0;
607}
608
Kevin Wolfe076f332010-06-29 11:43:13 +0200609/*
610 * Checks an image for consistency. Exit codes:
611 *
Max Reitzd6635c42014-06-02 22:15:21 +0200612 * 0 - Check completed, image is good
613 * 1 - Check not completed because of internal errors
614 * 2 - Check completed, image is corrupted
615 * 3 - Check completed, image has leaked clusters, but is good otherwise
616 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200617 */
aliguori15859692009-04-21 23:11:53 +0000618static int img_check(int argc, char **argv)
619{
620 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500621 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200622 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200623 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000624 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200625 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100626 int flags = BDRV_O_CHECK;
627 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200628 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000630 bool image_opts = false;
aliguori15859692009-04-21 23:11:53 +0000631
632 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500633 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200634 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100635
aliguori15859692009-04-21 23:11:53 +0000636 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500637 int option_index = 0;
638 static const struct option long_options[] = {
639 {"help", no_argument, 0, 'h'},
640 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530641 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500642 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000643 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000644 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645 {0, 0, 0, 0}
646 };
Max Reitz40055952014-07-22 22:58:42 +0200647 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500648 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100649 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000650 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100651 }
aliguori15859692009-04-21 23:11:53 +0000652 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100653 case '?':
aliguori15859692009-04-21 23:11:53 +0000654 case 'h':
655 help();
656 break;
657 case 'f':
658 fmt = optarg;
659 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200660 case 'r':
661 flags |= BDRV_O_RDWR;
662
663 if (!strcmp(optarg, "leaks")) {
664 fix = BDRV_FIX_LEAKS;
665 } else if (!strcmp(optarg, "all")) {
666 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
667 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800668 error_exit("Unknown option value for -r "
669 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200670 }
671 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500672 case OPTION_OUTPUT:
673 output = optarg;
674 break;
Max Reitz40055952014-07-22 22:58:42 +0200675 case 'T':
676 cache = optarg;
677 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100678 case 'q':
679 quiet = true;
680 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000681 case OPTION_OBJECT: {
682 QemuOpts *opts;
683 opts = qemu_opts_parse_noisily(&qemu_object_opts,
684 optarg, true);
685 if (!opts) {
686 return 1;
687 }
688 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000689 case OPTION_IMAGE_OPTS:
690 image_opts = true;
691 break;
aliguori15859692009-04-21 23:11:53 +0000692 }
693 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200694 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800695 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100696 }
aliguori15859692009-04-21 23:11:53 +0000697 filename = argv[optind++];
698
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500699 if (output && !strcmp(output, "json")) {
700 output_format = OFORMAT_JSON;
701 } else if (output && !strcmp(output, "human")) {
702 output_format = OFORMAT_HUMAN;
703 } else if (output) {
704 error_report("--output must be used with human or json as argument.");
705 return 1;
706 }
707
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000708 if (qemu_opts_foreach(&qemu_object_opts,
709 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200710 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000711 return 1;
712 }
713
Kevin Wolfce099542016-03-15 13:01:04 +0100714 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200715 if (ret < 0) {
716 error_report("Invalid source cache option: %s", cache);
717 return 1;
718 }
719
Kevin Wolfce099542016-03-15 13:01:04 +0100720 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200721 if (!blk) {
722 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900723 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200724 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500725
726 check = g_new0(ImageCheck, 1);
727 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200728
729 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200730 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200731 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500732 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200733 }
734
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500735 if (check->corruptions_fixed || check->leaks_fixed) {
736 int corruptions_fixed, leaks_fixed;
737
738 leaks_fixed = check->leaks_fixed;
739 corruptions_fixed = check->corruptions_fixed;
740
741 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100742 qprintf(quiet,
743 "The following inconsistencies were found and repaired:\n\n"
744 " %" PRId64 " leaked clusters\n"
745 " %" PRId64 " corruptions\n\n"
746 "Double checking the fixed image now...\n",
747 check->leaks_fixed,
748 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500749 }
750
751 ret = collect_image_check(bs, check, filename, fmt, 0);
752
753 check->leaks_fixed = leaks_fixed;
754 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200755 }
756
Max Reitz832390a2014-10-23 15:29:12 +0200757 if (!ret) {
758 switch (output_format) {
759 case OFORMAT_HUMAN:
760 dump_human_image_check(check, quiet);
761 break;
762 case OFORMAT_JSON:
763 dump_json_image_check(check, quiet);
764 break;
765 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500766 }
767
768 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200769 if (ret) {
770 error_report("Check failed: %s", strerror(-ret));
771 } else {
772 error_report("Check failed");
773 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500774 ret = 1;
775 goto fail;
776 }
777
778 if (check->corruptions) {
779 ret = 2;
780 } else if (check->leaks) {
781 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200782 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500783 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000784 }
785
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500786fail:
787 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200788 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500789 return ret;
aliguori15859692009-04-21 23:11:53 +0000790}
791
Max Reitzd4a32382014-10-24 15:57:37 +0200792typedef struct CommonBlockJobCBInfo {
793 BlockDriverState *bs;
794 Error **errp;
795} CommonBlockJobCBInfo;
796
797static void common_block_job_cb(void *opaque, int ret)
798{
799 CommonBlockJobCBInfo *cbi = opaque;
800
801 if (ret < 0) {
802 error_setg_errno(cbi->errp, -ret, "Block job failed");
803 }
Max Reitzd4a32382014-10-24 15:57:37 +0200804}
805
806static void run_block_job(BlockJob *job, Error **errp)
807{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200808 AioContext *aio_context = blk_get_aio_context(job->blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200809
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200810 aio_context_acquire(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200811 do {
812 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500813 qemu_progress_print(job->len ?
814 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200815 } while (!job->ready);
816
817 block_job_complete_sync(job, errp);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200818 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200819
820 /* A block job may finish instantaneously without publishing any progress,
821 * so just signal completion here */
822 qemu_progress_print(100.f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200823}
824
bellardea2384d2004-08-01 21:59:26 +0000825static int img_commit(int argc, char **argv)
826{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400827 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200828 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200829 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200830 BlockDriverState *bs, *base_bs;
Max Reitz687fa1d2014-10-24 15:57:39 +0200831 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100832 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200833 Error *local_err = NULL;
834 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000835 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200836 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000837
838 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400839 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200840 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000841 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000842 static const struct option long_options[] = {
843 {"help", no_argument, 0, 'h'},
844 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000845 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000846 {0, 0, 0, 0}
847 };
848 c = getopt_long(argc, argv, "f:ht:b:dpq",
849 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100850 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000851 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100852 }
bellardea2384d2004-08-01 21:59:26 +0000853 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100854 case '?':
bellardea2384d2004-08-01 21:59:26 +0000855 case 'h':
856 help();
857 break;
858 case 'f':
859 fmt = optarg;
860 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400861 case 't':
862 cache = optarg;
863 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200864 case 'b':
865 base = optarg;
866 /* -b implies -d */
867 drop = true;
868 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200869 case 'd':
870 drop = true;
871 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200872 case 'p':
873 progress = true;
874 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100875 case 'q':
876 quiet = true;
877 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000878 case OPTION_OBJECT: {
879 QemuOpts *opts;
880 opts = qemu_opts_parse_noisily(&qemu_object_opts,
881 optarg, true);
882 if (!opts) {
883 return 1;
884 }
885 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000886 case OPTION_IMAGE_OPTS:
887 image_opts = true;
888 break;
bellardea2384d2004-08-01 21:59:26 +0000889 }
890 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200891
892 /* Progress is not shown in Quiet mode */
893 if (quiet) {
894 progress = false;
895 }
896
Kevin Wolffc11eb22013-08-05 10:53:04 +0200897 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800898 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100899 }
bellardea2384d2004-08-01 21:59:26 +0000900 filename = argv[optind++];
901
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000902 if (qemu_opts_foreach(&qemu_object_opts,
903 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200904 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000905 return 1;
906 }
907
Max Reitz9a86fe42014-10-24 15:57:38 +0200908 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100909 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400910 if (ret < 0) {
911 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100912 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400913 }
914
Kevin Wolfce099542016-03-15 13:01:04 +0100915 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200916 if (!blk) {
917 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900918 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200919 bs = blk_bs(blk);
920
Max Reitz687fa1d2014-10-24 15:57:39 +0200921 qemu_progress_init(progress, 1.f);
922 qemu_progress_print(0.f, 100);
923
Max Reitz1b22bff2014-10-24 15:57:40 +0200924 if (base) {
925 base_bs = bdrv_find_backing_image(bs, base);
926 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100927 error_setg(&local_err,
928 "Did not find '%s' in the backing chain of '%s'",
929 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200930 goto done;
931 }
932 } else {
933 /* This is different from QMP, which by default uses the deepest file in
934 * the backing chain (i.e., the very base); however, the traditional
935 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +0200936 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +0200937 if (!base_bs) {
938 error_setg(&local_err, "Image does not have a backing file");
939 goto done;
940 }
bellardea2384d2004-08-01 21:59:26 +0000941 }
942
Max Reitzd4a32382014-10-24 15:57:37 +0200943 cbi = (CommonBlockJobCBInfo){
944 .errp = &local_err,
945 .bs = bs,
946 };
947
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200948 aio_context = bdrv_get_aio_context(bs);
949 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -0400950 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
951 BLOCKDEV_ON_ERROR_REPORT, common_block_job_cb, &cbi,
952 &local_err, false);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200953 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200954 if (local_err) {
955 goto done;
956 }
957
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200958 /* When the block job completes, the BlockBackend reference will point to
959 * the old backing file. In order to avoid that the top image is already
960 * deleted, so we can still empty it afterwards, increment the reference
961 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +0200962 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200963 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200964 }
965
Max Reitzd4a32382014-10-24 15:57:37 +0200966 run_block_job(bs->job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +0200967 if (local_err) {
968 goto unref_backing;
969 }
970
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200971 if (!drop && bs->drv->bdrv_make_empty) {
972 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200973 if (ret) {
974 error_setg_errno(&local_err, -ret, "Could not empty %s",
975 filename);
976 goto unref_backing;
977 }
978 }
979
980unref_backing:
981 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200982 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200983 }
Max Reitzd4a32382014-10-24 15:57:37 +0200984
985done:
Max Reitz687fa1d2014-10-24 15:57:39 +0200986 qemu_progress_end();
987
Markus Armbruster26f54e92014-10-07 13:59:04 +0200988 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200989
990 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +0100991 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900992 return 1;
993 }
Max Reitzd4a32382014-10-24 15:57:37 +0200994
995 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000996 return 0;
997}
998
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400999/*
thsf58c7b32008-06-05 21:53:49 +00001000 * Returns true iff the first sector pointed to by 'buf' contains at least
1001 * a non-NUL byte.
1002 *
1003 * 'pnum' is set to the number of sectors (including and immediately following
1004 * the first one) that are known to be in the same allocated/unallocated state.
1005 */
bellardea2384d2004-08-01 21:59:26 +00001006static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1007{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001008 bool is_zero;
1009 int i;
bellardea2384d2004-08-01 21:59:26 +00001010
1011 if (n <= 0) {
1012 *pnum = 0;
1013 return 0;
1014 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001015 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001016 for(i = 1; i < n; i++) {
1017 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001018 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001019 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001020 }
bellardea2384d2004-08-01 21:59:26 +00001021 }
1022 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001023 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001024}
1025
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001026/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001027 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1028 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1029 * breaking up write requests for only small sparse areas.
1030 */
1031static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1032 int min)
1033{
1034 int ret;
1035 int num_checked, num_used;
1036
1037 if (n < min) {
1038 min = n;
1039 }
1040
1041 ret = is_allocated_sectors(buf, n, pnum);
1042 if (!ret) {
1043 return ret;
1044 }
1045
1046 num_used = *pnum;
1047 buf += BDRV_SECTOR_SIZE * *pnum;
1048 n -= *pnum;
1049 num_checked = num_used;
1050
1051 while (n > 0) {
1052 ret = is_allocated_sectors(buf, n, pnum);
1053
1054 buf += BDRV_SECTOR_SIZE * *pnum;
1055 n -= *pnum;
1056 num_checked += *pnum;
1057 if (ret) {
1058 num_used = num_checked;
1059 } else if (*pnum >= min) {
1060 break;
1061 }
1062 }
1063
1064 *pnum = num_used;
1065 return 1;
1066}
1067
1068/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001069 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1070 * buffers matches, non-zero otherwise.
1071 *
1072 * pnum is set to the number of sectors (including and immediately following
1073 * the first one) that are known to have the same comparison result
1074 */
1075static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1076 int *pnum)
1077{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001078 bool res;
1079 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001080
1081 if (n <= 0) {
1082 *pnum = 0;
1083 return 0;
1084 }
1085
1086 res = !!memcmp(buf1, buf2, 512);
1087 for(i = 1; i < n; i++) {
1088 buf1 += 512;
1089 buf2 += 512;
1090
1091 if (!!memcmp(buf1, buf2, 512) != res) {
1092 break;
1093 }
1094 }
1095
1096 *pnum = i;
1097 return res;
1098}
1099
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001100#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001101
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001102static int64_t sectors_to_bytes(int64_t sectors)
1103{
1104 return sectors << BDRV_SECTOR_BITS;
1105}
1106
1107static int64_t sectors_to_process(int64_t total, int64_t from)
1108{
1109 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1110}
1111
1112/*
1113 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1114 *
1115 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1116 * data and negative value on error.
1117 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001118 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001119 * @param sect_num: Number of first sector to check
1120 * @param sect_count: Number of sectors to check
1121 * @param filename: Name of disk file we are checking (logging purpose)
1122 * @param buffer: Allocated buffer for storing read data
1123 * @param quiet: Flag for quiet mode
1124 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001125static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001126 int sect_count, const char *filename,
1127 uint8_t *buffer, bool quiet)
1128{
1129 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001130 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1131 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001132 if (ret < 0) {
1133 error_report("Error while reading offset %" PRId64 " of %s: %s",
1134 sectors_to_bytes(sect_num), filename, strerror(-ret));
1135 return ret;
1136 }
1137 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1138 if (ret || pnum != sect_count) {
1139 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1140 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1141 return 1;
1142 }
1143
1144 return 0;
1145}
1146
1147/*
1148 * Compares two images. Exit codes:
1149 *
1150 * 0 - Images are identical
1151 * 1 - Images differ
1152 * >1 - Error occurred
1153 */
1154static int img_compare(int argc, char **argv)
1155{
Max Reitz40055952014-07-22 22:58:42 +02001156 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001157 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001158 BlockDriverState *bs1, *bs2;
1159 int64_t total_sectors1, total_sectors2;
1160 uint8_t *buf1 = NULL, *buf2 = NULL;
1161 int pnum1, pnum2;
1162 int allocated1, allocated2;
1163 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1164 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001165 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001166 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001167 int64_t total_sectors;
1168 int64_t sector_num = 0;
1169 int64_t nb_sectors;
1170 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001171 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001172 bool image_opts = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001173
Max Reitz40055952014-07-22 22:58:42 +02001174 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001175 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001176 static const struct option long_options[] = {
1177 {"help", no_argument, 0, 'h'},
1178 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001179 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001180 {0, 0, 0, 0}
1181 };
1182 c = getopt_long(argc, argv, "hf:F:T:pqs",
1183 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001184 if (c == -1) {
1185 break;
1186 }
1187 switch (c) {
1188 case '?':
1189 case 'h':
1190 help();
1191 break;
1192 case 'f':
1193 fmt1 = optarg;
1194 break;
1195 case 'F':
1196 fmt2 = optarg;
1197 break;
Max Reitz40055952014-07-22 22:58:42 +02001198 case 'T':
1199 cache = optarg;
1200 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001201 case 'p':
1202 progress = true;
1203 break;
1204 case 'q':
1205 quiet = true;
1206 break;
1207 case 's':
1208 strict = true;
1209 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001210 case OPTION_OBJECT: {
1211 QemuOpts *opts;
1212 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1213 optarg, true);
1214 if (!opts) {
1215 ret = 2;
1216 goto out4;
1217 }
1218 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001219 case OPTION_IMAGE_OPTS:
1220 image_opts = true;
1221 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001222 }
1223 }
1224
1225 /* Progress is not shown in Quiet mode */
1226 if (quiet) {
1227 progress = false;
1228 }
1229
1230
Kevin Wolffc11eb22013-08-05 10:53:04 +02001231 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001232 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233 }
1234 filename1 = argv[optind++];
1235 filename2 = argv[optind++];
1236
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001237 if (qemu_opts_foreach(&qemu_object_opts,
1238 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001239 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001240 ret = 2;
1241 goto out4;
1242 }
1243
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001244 /* Initialize before goto out */
1245 qemu_progress_init(progress, 2.0);
1246
Kevin Wolfce099542016-03-15 13:01:04 +01001247 flags = 0;
1248 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001249 if (ret < 0) {
1250 error_report("Invalid source cache option: %s", cache);
1251 ret = 2;
1252 goto out3;
1253 }
1254
Kevin Wolfce099542016-03-15 13:01:04 +01001255 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001256 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001257 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001258 goto out3;
1259 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001260
Kevin Wolfce099542016-03-15 13:01:04 +01001261 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001262 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001263 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001264 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001265 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001266 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001267 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001268
Max Reitzf1d3cd72015-02-05 13:58:18 -05001269 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1270 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1271 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001272 if (total_sectors1 < 0) {
1273 error_report("Can't get size of %s: %s",
1274 filename1, strerror(-total_sectors1));
1275 ret = 4;
1276 goto out;
1277 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001278 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001279 if (total_sectors2 < 0) {
1280 error_report("Can't get size of %s: %s",
1281 filename2, strerror(-total_sectors2));
1282 ret = 4;
1283 goto out;
1284 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001285 total_sectors = MIN(total_sectors1, total_sectors2);
1286 progress_base = MAX(total_sectors1, total_sectors2);
1287
1288 qemu_progress_print(0, 100);
1289
1290 if (strict && total_sectors1 != total_sectors2) {
1291 ret = 1;
1292 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1293 goto out;
1294 }
1295
1296 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001297 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001298 BlockDriverState *file;
1299
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300 nb_sectors = sectors_to_process(total_sectors, sector_num);
1301 if (nb_sectors <= 0) {
1302 break;
1303 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001304 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1305 total_sectors1 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001306 &pnum1, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001307 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001308 ret = 3;
1309 error_report("Sector allocation test failed for %s", filename1);
1310 goto out;
1311 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001312 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001313
Fam Zheng25ad8e62016-01-13 16:37:41 +08001314 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1315 total_sectors2 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001316 &pnum2, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001317 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 ret = 3;
1319 error_report("Sector allocation test failed for %s", filename2);
1320 goto out;
1321 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001322 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1323 if (pnum1) {
1324 nb_sectors = MIN(nb_sectors, pnum1);
1325 }
1326 if (pnum2) {
1327 nb_sectors = MIN(nb_sectors, pnum2);
1328 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001329
Fam Zheng25ad8e62016-01-13 16:37:41 +08001330 if (strict) {
1331 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1332 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1333 ret = 1;
1334 qprintf(quiet, "Strict mode: Offset %" PRId64
1335 " block status mismatch!\n",
1336 sectors_to_bytes(sector_num));
1337 goto out;
1338 }
1339 }
1340 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1341 nb_sectors = MIN(pnum1, pnum2);
1342 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001343 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001344 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1345 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001346 if (ret < 0) {
1347 error_report("Error while reading offset %" PRId64 " of %s:"
1348 " %s", sectors_to_bytes(sector_num), filename1,
1349 strerror(-ret));
1350 ret = 4;
1351 goto out;
1352 }
Eric Blake91669202016-05-06 10:26:43 -06001353 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1354 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001355 if (ret < 0) {
1356 error_report("Error while reading offset %" PRId64
1357 " of %s: %s", sectors_to_bytes(sector_num),
1358 filename2, strerror(-ret));
1359 ret = 4;
1360 goto out;
1361 }
1362 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1363 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1365 sectors_to_bytes(
1366 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001367 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001368 goto out;
1369 }
1370 }
1371 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001372
1373 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001374 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001375 filename1, buf1, quiet);
1376 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001377 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 filename2, buf1, quiet);
1379 }
1380 if (ret) {
1381 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001382 error_report("Error while reading offset %" PRId64 ": %s",
1383 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001384 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001385 }
1386 goto out;
1387 }
1388 }
1389 sector_num += nb_sectors;
1390 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1391 }
1392
1393 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001394 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395 int64_t total_sectors_over;
1396 const char *filename_over;
1397
1398 qprintf(quiet, "Warning: Image size mismatch!\n");
1399 if (total_sectors1 > total_sectors2) {
1400 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001401 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001402 filename_over = filename1;
1403 } else {
1404 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001405 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001406 filename_over = filename2;
1407 }
1408
1409 for (;;) {
1410 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1411 if (nb_sectors <= 0) {
1412 break;
1413 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001414 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415 nb_sectors, &pnum);
1416 if (ret < 0) {
1417 ret = 3;
1418 error_report("Sector allocation test failed for %s",
1419 filename_over);
1420 goto out;
1421
1422 }
1423 nb_sectors = pnum;
1424 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001425 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001426 filename_over, buf1, quiet);
1427 if (ret) {
1428 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001429 error_report("Error while reading offset %" PRId64
1430 " of %s: %s", sectors_to_bytes(sector_num),
1431 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001432 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001433 }
1434 goto out;
1435 }
1436 }
1437 sector_num += nb_sectors;
1438 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1439 }
1440 }
1441
1442 qprintf(quiet, "Images are identical.\n");
1443 ret = 0;
1444
1445out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001446 qemu_vfree(buf1);
1447 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001448 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001450 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451out3:
1452 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001453out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001454 return ret;
1455}
1456
Kevin Wolf690c7302015-03-19 13:33:32 +01001457enum ImgConvertBlockStatus {
1458 BLK_DATA,
1459 BLK_ZERO,
1460 BLK_BACKING_FILE,
1461};
1462
1463typedef struct ImgConvertState {
1464 BlockBackend **src;
1465 int64_t *src_sectors;
1466 int src_cur, src_num;
1467 int64_t src_cur_offset;
1468 int64_t total_sectors;
1469 int64_t allocated_sectors;
1470 enum ImgConvertBlockStatus status;
1471 int64_t sector_next_status;
1472 BlockBackend *target;
1473 bool has_zero_init;
1474 bool compressed;
1475 bool target_has_backing;
1476 int min_sparse;
1477 size_t cluster_sectors;
1478 size_t buf_sectors;
1479} ImgConvertState;
1480
1481static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1482{
1483 assert(sector_num >= s->src_cur_offset);
1484 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1485 s->src_cur_offset += s->src_sectors[s->src_cur];
1486 s->src_cur++;
1487 assert(s->src_cur < s->src_num);
1488 }
1489}
1490
1491static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1492{
1493 int64_t ret;
1494 int n;
1495
1496 convert_select_part(s, sector_num);
1497
1498 assert(s->total_sectors > sector_num);
1499 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1500
1501 if (s->sector_next_status <= sector_num) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08001502 BlockDriverState *file;
Kevin Wolf690c7302015-03-19 13:33:32 +01001503 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1504 sector_num - s->src_cur_offset,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001505 n, &n, &file);
Kevin Wolf690c7302015-03-19 13:33:32 +01001506 if (ret < 0) {
1507 return ret;
1508 }
1509
1510 if (ret & BDRV_BLOCK_ZERO) {
1511 s->status = BLK_ZERO;
1512 } else if (ret & BDRV_BLOCK_DATA) {
1513 s->status = BLK_DATA;
1514 } else if (!s->target_has_backing) {
1515 /* Without a target backing file we must copy over the contents of
1516 * the backing file as well. */
Ren Kimura263a6f42016-04-28 01:04:58 +09001517 /* Check block status of the backing file chain to avoid
Kevin Wolf690c7302015-03-19 13:33:32 +01001518 * needlessly reading zeroes and limiting the iteration to the
1519 * buffer size */
Ren Kimura263a6f42016-04-28 01:04:58 +09001520 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1521 sector_num - s->src_cur_offset,
1522 n, &n, &file);
1523 if (ret < 0) {
1524 return ret;
1525 }
1526
1527 if (ret & BDRV_BLOCK_ZERO) {
1528 s->status = BLK_ZERO;
1529 } else {
1530 s->status = BLK_DATA;
1531 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001532 } else {
1533 s->status = BLK_BACKING_FILE;
1534 }
1535
1536 s->sector_next_status = sector_num + n;
1537 }
1538
1539 n = MIN(n, s->sector_next_status - sector_num);
1540 if (s->status == BLK_DATA) {
1541 n = MIN(n, s->buf_sectors);
1542 }
1543
1544 /* We need to write complete clusters for compressed images, so if an
1545 * unallocated area is shorter than that, we must consider the whole
1546 * cluster allocated. */
1547 if (s->compressed) {
1548 if (n < s->cluster_sectors) {
1549 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1550 s->status = BLK_DATA;
1551 } else {
1552 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1553 }
1554 }
1555
1556 return n;
1557}
1558
1559static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1560 uint8_t *buf)
1561{
1562 int n;
1563 int ret;
1564
Kevin Wolf690c7302015-03-19 13:33:32 +01001565 assert(nb_sectors <= s->buf_sectors);
1566 while (nb_sectors > 0) {
1567 BlockBackend *blk;
1568 int64_t bs_sectors;
1569
1570 /* In the case of compression with multiple source files, we can get a
1571 * nb_sectors that spreads into the next part. So we must be able to
1572 * read across multiple BDSes for one convert_read() call. */
1573 convert_select_part(s, sector_num);
1574 blk = s->src[s->src_cur];
1575 bs_sectors = s->src_sectors[s->src_cur];
1576
1577 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
Eric Blake91669202016-05-06 10:26:43 -06001578 ret = blk_pread(blk,
1579 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1580 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001581 if (ret < 0) {
1582 return ret;
1583 }
1584
1585 sector_num += n;
1586 nb_sectors -= n;
1587 buf += n * BDRV_SECTOR_SIZE;
1588 }
1589
1590 return 0;
1591}
1592
1593static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1594 const uint8_t *buf)
1595{
1596 int ret;
1597
1598 while (nb_sectors > 0) {
1599 int n = nb_sectors;
1600
1601 switch (s->status) {
1602 case BLK_BACKING_FILE:
1603 /* If we have a backing file, leave clusters unallocated that are
1604 * unallocated in the source image, so that the backing file is
1605 * visible at the respective offset. */
1606 assert(s->target_has_backing);
1607 break;
1608
1609 case BLK_DATA:
1610 /* We must always write compressed clusters as a whole, so don't
1611 * try to find zeroed parts in the buffer. We can only save the
1612 * write if the buffer is completely zeroed and we're allowed to
1613 * keep the target sparse. */
1614 if (s->compressed) {
1615 if (s->has_zero_init && s->min_sparse &&
1616 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1617 {
1618 assert(!s->target_has_backing);
1619 break;
1620 }
1621
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001622 ret = blk_pwrite_compressed(s->target,
1623 sector_num << BDRV_SECTOR_BITS,
1624 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001625 if (ret < 0) {
1626 return ret;
1627 }
1628 break;
1629 }
1630
1631 /* If there is real non-zero data or we're told to keep the target
1632 * fully allocated (-S 0), we must write it. Otherwise we can treat
1633 * it as zero sectors. */
1634 if (!s->min_sparse ||
1635 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1636 {
Eric Blake91669202016-05-06 10:26:43 -06001637 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1638 buf, n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001639 if (ret < 0) {
1640 return ret;
1641 }
1642 break;
1643 }
1644 /* fall-through */
1645
1646 case BLK_ZERO:
1647 if (s->has_zero_init) {
1648 break;
1649 }
Eric Blaked004bd52016-05-24 16:25:20 -06001650 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1651 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001652 if (ret < 0) {
1653 return ret;
1654 }
1655 break;
1656 }
1657
1658 sector_num += n;
1659 nb_sectors -= n;
1660 buf += n * BDRV_SECTOR_SIZE;
1661 }
1662
1663 return 0;
1664}
1665
1666static int convert_do_copy(ImgConvertState *s)
1667{
1668 uint8_t *buf = NULL;
1669 int64_t sector_num, allocated_done;
1670 int ret;
1671 int n;
1672
1673 /* Check whether we have zero initialisation or can get it efficiently */
1674 s->has_zero_init = s->min_sparse && !s->target_has_backing
1675 ? bdrv_has_zero_init(blk_bs(s->target))
1676 : false;
1677
1678 if (!s->has_zero_init && !s->target_has_backing &&
1679 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1680 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001681 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001682 if (ret == 0) {
1683 s->has_zero_init = true;
1684 }
1685 }
1686
1687 /* Allocate buffer for copied data. For compressed images, only one cluster
1688 * can be copied at a time. */
1689 if (s->compressed) {
1690 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1691 error_report("invalid cluster size");
1692 ret = -EINVAL;
1693 goto fail;
1694 }
1695 s->buf_sectors = s->cluster_sectors;
1696 }
1697 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1698
1699 /* Calculate allocated sectors for progress */
1700 s->allocated_sectors = 0;
1701 sector_num = 0;
1702 while (sector_num < s->total_sectors) {
1703 n = convert_iteration_sectors(s, sector_num);
1704 if (n < 0) {
1705 ret = n;
1706 goto fail;
1707 }
Max Reitzaad15de2016-03-24 23:33:57 +01001708 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1709 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001710 s->allocated_sectors += n;
1711 }
1712 sector_num += n;
1713 }
1714
1715 /* Do the copy */
1716 s->src_cur = 0;
1717 s->src_cur_offset = 0;
1718 s->sector_next_status = 0;
1719
1720 sector_num = 0;
1721 allocated_done = 0;
1722
1723 while (sector_num < s->total_sectors) {
1724 n = convert_iteration_sectors(s, sector_num);
1725 if (n < 0) {
1726 ret = n;
1727 goto fail;
1728 }
Max Reitzaad15de2016-03-24 23:33:57 +01001729 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1730 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001731 allocated_done += n;
1732 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1733 0);
1734 }
1735
Max Reitzaad15de2016-03-24 23:33:57 +01001736 if (s->status == BLK_DATA) {
1737 ret = convert_read(s, sector_num, n, buf);
1738 if (ret < 0) {
1739 error_report("error while reading sector %" PRId64
1740 ": %s", sector_num, strerror(-ret));
1741 goto fail;
1742 }
1743 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1744 n = MIN(n, s->buf_sectors);
1745 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1746 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 }
1748
1749 ret = convert_write(s, sector_num, n, buf);
1750 if (ret < 0) {
1751 error_report("error while writing sector %" PRId64
1752 ": %s", sector_num, strerror(-ret));
1753 goto fail;
1754 }
1755
1756 sector_num += n;
1757 }
1758
1759 if (s->compressed) {
1760 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001761 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 if (ret < 0) {
1763 goto fail;
1764 }
1765 }
1766
1767 ret = 0;
1768fail:
1769 qemu_vfree(buf);
1770 return ret;
1771}
1772
bellardea2384d2004-08-01 21:59:26 +00001773static int img_convert(int argc, char **argv)
1774{
Kevin Wolf690c7302015-03-19 13:33:32 +01001775 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001776 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001777 int progress = 0, flags, src_flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001778 bool writethrough, src_writethrough;
Max Reitz40055952014-07-22 22:58:42 +02001779 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001780 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001781 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001782 BlockDriverState **bs = NULL, *out_bs = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001783 int64_t total_sectors;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001784 int64_t *bs_sectors = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001785 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardfaea38e2006-08-05 21:31:00 +00001786 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001787 QemuOpts *opts = NULL;
1788 QemuOptsList *create_opts = NULL;
1789 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001790 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001791 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001792 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001793 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001794 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001795 QemuOpts *sn_opts = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001796 ImgConvertState state;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001797 bool image_opts = false;
bellardea2384d2004-08-01 21:59:26 +00001798
1799 fmt = NULL;
1800 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001801 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001802 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001803 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001804 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001805 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001806 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001807 static const struct option long_options[] = {
1808 {"help", no_argument, 0, 'h'},
1809 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001810 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001811 {0, 0, 0, 0}
1812 };
1813 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1814 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001815 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001816 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001817 }
bellardea2384d2004-08-01 21:59:26 +00001818 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001819 case '?':
bellardea2384d2004-08-01 21:59:26 +00001820 case 'h':
1821 help();
1822 break;
1823 case 'f':
1824 fmt = optarg;
1825 break;
1826 case 'O':
1827 out_fmt = optarg;
1828 break;
thsf58c7b32008-06-05 21:53:49 +00001829 case 'B':
1830 out_baseimg = optarg;
1831 break;
bellardea2384d2004-08-01 21:59:26 +00001832 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001833 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001834 break;
1835 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001836 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001837 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001838 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001839 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001840 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001841 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001842 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001843 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001844 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001845 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001846 if (!is_valid_option_list(optarg)) {
1847 error_report("Invalid option list: %s", optarg);
1848 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001849 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001850 }
1851 if (!options) {
1852 options = g_strdup(optarg);
1853 } else {
1854 char *old_options = options;
1855 options = g_strdup_printf("%s,%s", options, optarg);
1856 g_free(old_options);
1857 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001858 break;
edison51ef6722010-09-21 19:58:41 -07001859 case 's':
1860 snapshot_name = optarg;
1861 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001862 case 'l':
1863 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01001864 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1865 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08001866 if (!sn_opts) {
1867 error_report("Failed in parsing snapshot param '%s'",
1868 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001869 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001870 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001871 }
1872 } else {
1873 snapshot_name = optarg;
1874 }
1875 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001876 case 'S':
1877 {
1878 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01001879
1880 sval = cvtnum(optarg);
1881 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001882 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001883 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001884 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001885 }
1886
1887 min_sparse = sval / BDRV_SECTOR_SIZE;
1888 break;
1889 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001890 case 'p':
1891 progress = 1;
1892 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001893 case 't':
1894 cache = optarg;
1895 break;
Max Reitz40055952014-07-22 22:58:42 +02001896 case 'T':
1897 src_cache = optarg;
1898 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001899 case 'q':
1900 quiet = true;
1901 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001902 case 'n':
1903 skip_create = 1;
1904 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001905 case OPTION_OBJECT:
1906 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1907 optarg, true);
1908 if (!opts) {
1909 goto fail_getopt;
1910 }
1911 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001912 case OPTION_IMAGE_OPTS:
1913 image_opts = true;
1914 break;
bellardea2384d2004-08-01 21:59:26 +00001915 }
1916 }
ths3b46e622007-09-17 08:09:54 +00001917
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001918 if (qemu_opts_foreach(&qemu_object_opts,
1919 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001920 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001921 goto fail_getopt;
1922 }
1923
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001924 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001925 if (quiet) {
1926 progress = 0;
1927 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001928 qemu_progress_init(progress, 1.0);
1929
balrog926c2d22007-10-31 01:11:44 +00001930 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001931 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001932
Kevin Wolf2dc83282014-02-21 16:24:05 +01001933 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001934 ret = print_block_option_help(out_filename, out_fmt);
1935 goto out;
1936 }
1937
bellardea2384d2004-08-01 21:59:26 +00001938 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001939 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001940 }
bellardea2384d2004-08-01 21:59:26 +00001941
thsf58c7b32008-06-05 21:53:49 +00001942
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001943 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001944 error_report("-B makes no sense when concatenating multiple input "
1945 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001946 ret = -1;
1947 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001948 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001949
Kevin Wolfce099542016-03-15 13:01:04 +01001950 src_flags = 0;
1951 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001952 if (ret < 0) {
1953 error_report("Invalid source cache option: %s", src_cache);
1954 goto out;
1955 }
1956
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001957 qemu_progress_print(0, 100);
1958
Markus Armbruster26f54e92014-10-07 13:59:04 +02001959 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001960 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001961 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001962
1963 total_sectors = 0;
1964 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Max Reitzefaa7c42016-03-16 19:54:38 +01001965 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
Kevin Wolfce099542016-03-15 13:01:04 +01001966 fmt, src_flags, src_writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001967 if (!blk[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001968 ret = -1;
1969 goto out;
1970 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001971 bs[bs_i] = blk_bs(blk[bs_i]);
Max Reitzf1d3cd72015-02-05 13:58:18 -05001972 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001973 if (bs_sectors[bs_i] < 0) {
1974 error_report("Could not get size of %s: %s",
1975 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1976 ret = -1;
1977 goto out;
1978 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001979 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001980 }
bellardea2384d2004-08-01 21:59:26 +00001981
Wenchao Xiaef806542013-12-04 17:10:57 +08001982 if (sn_opts) {
Peter Maydell10d6eda2017-02-10 16:28:24 +00001983 bdrv_snapshot_load_tmp(bs[0],
1984 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1985 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1986 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001987 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001988 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001989 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001990 ret = -1;
1991 goto out;
1992 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001993
1994 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001995 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001996 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001997 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08001998 ret = -1;
1999 goto out;
edison51ef6722010-09-21 19:58:41 -07002000 }
2001
Kevin Wolfefa84d42009-05-18 16:42:12 +02002002 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00002003 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002004 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002005 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002006 ret = -1;
2007 goto out;
2008 }
balrog926c2d22007-10-31 01:11:44 +00002009
Max Reitzb65a5e12015-02-05 13:58:12 -05002010 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002011 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +01002012 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002013 ret = -1;
2014 goto out;
2015 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09002016
Max Reitz2e024cd2015-02-11 09:58:46 -05002017 if (!skip_create) {
2018 if (!drv->create_opts) {
2019 error_report("Format driver '%s' does not support image creation",
2020 drv->format_name);
2021 ret = -1;
2022 goto out;
2023 }
Max Reitzf75613c2014-12-02 18:32:46 +01002024
Max Reitz2e024cd2015-02-11 09:58:46 -05002025 if (!proto_drv->create_opts) {
2026 error_report("Protocol driver '%s' does not support image creation",
2027 proto_drv->format_name);
2028 ret = -1;
2029 goto out;
2030 }
Max Reitzf75613c2014-12-02 18:32:46 +01002031
Max Reitz2e024cd2015-02-11 09:58:46 -05002032 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2033 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002034
Max Reitz2e024cd2015-02-11 09:58:46 -05002035 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002036 if (options) {
2037 qemu_opts_do_parse(opts, options, NULL, &local_err);
2038 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002039 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002040 ret = -1;
2041 goto out;
2042 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002043 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002044
Markus Armbruster39101f22015-02-12 16:46:36 +01002045 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2046 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002047 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2048 if (ret < 0) {
2049 goto out;
2050 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002051 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002052
Kevin Wolfa18953f2010-10-14 15:46:04 +02002053 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002054 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002055 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002056 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002057 }
2058
Kevin Wolfefa84d42009-05-18 16:42:12 +02002059 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01002060 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002061 bool encryption =
2062 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2063 const char *preallocation =
2064 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002065
Pavel Butsykin35fadca2016-07-22 11:17:48 +03002066 if (!drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002067 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002068 ret = -1;
2069 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002070 }
2071
Chunyan Liu83d05212014-06-05 17:20:51 +08002072 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002073 error_report("Compression and encryption not supported at "
2074 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002075 ret = -1;
2076 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002077 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002078
Chunyan Liu83d05212014-06-05 17:20:51 +08002079 if (preallocation
2080 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002081 {
2082 error_report("Compression and preallocation not supported at "
2083 "the same time");
2084 ret = -1;
2085 goto out;
2086 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002087 }
2088
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002089 if (!skip_create) {
2090 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002091 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002092 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002093 error_reportf_err(local_err, "%s: error while converting %s: ",
2094 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002095 goto out;
bellardea2384d2004-08-01 21:59:26 +00002096 }
2097 }
ths3b46e622007-09-17 08:09:54 +00002098
Peter Lieven5a37b602013-10-24 12:07:06 +02002099 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002100 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002101 if (ret < 0) {
2102 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002103 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002104 }
2105
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002106 /* XXX we should allow --image-opts to trigger use of
2107 * img_open() here, but then we have trouble with
2108 * the bdrv_create() call which takes different params.
2109 * Not critical right now, so fix can wait...
2110 */
Kevin Wolfce099542016-03-15 13:01:04 +01002111 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002112 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002113 ret = -1;
2114 goto out;
2115 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002116 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00002117
Eric Blake5def6b82016-06-23 16:37:19 -06002118 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002119 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2120 * as maximum. */
2121 bufsectors = MIN(32768,
Eric Blake5def6b82016-06-23 16:37:19 -06002122 MAX(bufsectors,
2123 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
Eric Blakeb9f78552016-06-23 16:37:21 -06002124 out_bs->bl.pdiscard_alignment >>
2125 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002126
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002127 if (skip_create) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05002128 int64_t output_sectors = blk_nb_sectors(out_blk);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002129 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002130 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002131 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002132 ret = -1;
2133 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02002134 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002135 error_report("output file is smaller than input file");
2136 ret = -1;
2137 goto out;
2138 }
2139 }
2140
Peter Lieven24f833c2013-11-27 11:07:07 +01002141 cluster_sectors = 0;
2142 ret = bdrv_get_info(out_bs, &bdi);
2143 if (ret < 0) {
2144 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002145 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002146 goto out;
2147 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002148 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08002149 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01002150 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2151 }
2152
Kevin Wolf690c7302015-03-19 13:33:32 +01002153 state = (ImgConvertState) {
2154 .src = blk,
2155 .src_sectors = bs_sectors,
2156 .src_num = bs_n,
2157 .total_sectors = total_sectors,
2158 .target = out_blk,
2159 .compressed = compress,
2160 .target_has_backing = (bool) out_baseimg,
2161 .min_sparse = min_sparse,
2162 .cluster_sectors = cluster_sectors,
2163 .buf_sectors = bufsectors,
2164 };
2165 ret = convert_do_copy(&state);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002166
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002167out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002168 if (!ret) {
2169 qemu_progress_print(100, 0);
2170 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002171 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002172 qemu_opts_del(opts);
2173 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002174 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002175 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02002176 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002177 if (blk) {
2178 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2179 blk_unref(blk[bs_i]);
2180 }
2181 g_free(blk);
2182 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02002183 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002184fail_getopt:
2185 g_free(options);
2186
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002187 if (ret) {
2188 return 1;
2189 }
bellardea2384d2004-08-01 21:59:26 +00002190 return 0;
2191}
2192
bellard57d1a2b2004-08-03 21:15:11 +00002193
bellardfaea38e2006-08-05 21:31:00 +00002194static void dump_snapshots(BlockDriverState *bs)
2195{
2196 QEMUSnapshotInfo *sn_tab, *sn;
2197 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002198
2199 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2200 if (nb_sns <= 0)
2201 return;
2202 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002203 bdrv_snapshot_dump(fprintf, stdout, NULL);
2204 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002205 for(i = 0; i < nb_sns; i++) {
2206 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002207 bdrv_snapshot_dump(fprintf, stdout, sn);
2208 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002209 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002210 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002211}
2212
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002213static void dump_json_image_info_list(ImageInfoList *list)
2214{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002215 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002216 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002217 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002218
2219 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2220 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002221 str = qobject_to_json_pretty(obj);
2222 assert(str != NULL);
2223 printf("%s\n", qstring_get_str(str));
2224 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002225 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002226 QDECREF(str);
2227}
2228
Benoît Canetc054b3f2012-09-05 13:09:02 +02002229static void dump_json_image_info(ImageInfo *info)
2230{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002231 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002232 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002233 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002234
2235 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2236 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002237 str = qobject_to_json_pretty(obj);
2238 assert(str != NULL);
2239 printf("%s\n", qstring_get_str(str));
2240 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002241 visit_free(v);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002242 QDECREF(str);
2243}
2244
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002245static void dump_human_image_info_list(ImageInfoList *list)
2246{
2247 ImageInfoList *elem;
2248 bool delim = false;
2249
2250 for (elem = list; elem; elem = elem->next) {
2251 if (delim) {
2252 printf("\n");
2253 }
2254 delim = true;
2255
Wenchao Xia5b917042013-05-25 11:09:45 +08002256 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002257 }
2258}
2259
2260static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2261{
2262 return strcmp(a, b) == 0;
2263}
2264
2265/**
2266 * Open an image file chain and return an ImageInfoList
2267 *
2268 * @filename: topmost image filename
2269 * @fmt: topmost image format (may be NULL to autodetect)
2270 * @chain: true - enumerate entire backing file chain
2271 * false - only topmost image file
2272 *
2273 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2274 * image file. If there was an error a message will have been printed to
2275 * stderr.
2276 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002277static ImageInfoList *collect_image_info_list(bool image_opts,
2278 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002279 const char *fmt,
2280 bool chain)
2281{
2282 ImageInfoList *head = NULL;
2283 ImageInfoList **last = &head;
2284 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002285 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002286
2287 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2288
2289 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002290 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002291 BlockDriverState *bs;
2292 ImageInfo *info;
2293 ImageInfoList *elem;
2294
2295 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2296 error_report("Backing file '%s' creates an infinite loop.",
2297 filename);
2298 goto err;
2299 }
2300 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2301
Max Reitzefaa7c42016-03-16 19:54:38 +01002302 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01002303 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002304 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002305 goto err;
2306 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002307 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002308
Wenchao Xia43526ec2013-06-06 12:27:58 +08002309 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002310 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002311 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002312 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002313 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002314 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002315
2316 elem = g_new0(ImageInfoList, 1);
2317 elem->value = info;
2318 *last = elem;
2319 last = &elem->next;
2320
Markus Armbruster26f54e92014-10-07 13:59:04 +02002321 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002322
2323 filename = fmt = NULL;
2324 if (chain) {
2325 if (info->has_full_backing_filename) {
2326 filename = info->full_backing_filename;
2327 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002328 error_report("Could not determine absolute backing filename,"
2329 " but backing filename '%s' present",
2330 info->backing_filename);
2331 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002332 }
2333 if (info->has_backing_filename_format) {
2334 fmt = info->backing_filename_format;
2335 }
2336 }
2337 }
2338 g_hash_table_destroy(filenames);
2339 return head;
2340
2341err:
2342 qapi_free_ImageInfoList(head);
2343 g_hash_table_destroy(filenames);
2344 return NULL;
2345}
2346
Benoît Canetc054b3f2012-09-05 13:09:02 +02002347static int img_info(int argc, char **argv)
2348{
2349 int c;
2350 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002351 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002352 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002353 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002354 bool image_opts = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002355
bellardea2384d2004-08-01 21:59:26 +00002356 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002357 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002358 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002359 int option_index = 0;
2360 static const struct option long_options[] = {
2361 {"help", no_argument, 0, 'h'},
2362 {"format", required_argument, 0, 'f'},
2363 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002364 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002365 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002366 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002367 {0, 0, 0, 0}
2368 };
2369 c = getopt_long(argc, argv, "f:h",
2370 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002371 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002372 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002373 }
bellardea2384d2004-08-01 21:59:26 +00002374 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002375 case '?':
bellardea2384d2004-08-01 21:59:26 +00002376 case 'h':
2377 help();
2378 break;
2379 case 'f':
2380 fmt = optarg;
2381 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002382 case OPTION_OUTPUT:
2383 output = optarg;
2384 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002385 case OPTION_BACKING_CHAIN:
2386 chain = true;
2387 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002388 case OPTION_OBJECT: {
2389 QemuOpts *opts;
2390 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2391 optarg, true);
2392 if (!opts) {
2393 return 1;
2394 }
2395 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002396 case OPTION_IMAGE_OPTS:
2397 image_opts = true;
2398 break;
bellardea2384d2004-08-01 21:59:26 +00002399 }
2400 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002401 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002402 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002403 }
bellardea2384d2004-08-01 21:59:26 +00002404 filename = argv[optind++];
2405
Benoît Canetc054b3f2012-09-05 13:09:02 +02002406 if (output && !strcmp(output, "json")) {
2407 output_format = OFORMAT_JSON;
2408 } else if (output && !strcmp(output, "human")) {
2409 output_format = OFORMAT_HUMAN;
2410 } else if (output) {
2411 error_report("--output must be used with human or json as argument.");
2412 return 1;
2413 }
2414
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002415 if (qemu_opts_foreach(&qemu_object_opts,
2416 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002417 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002418 return 1;
2419 }
2420
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002421 list = collect_image_info_list(image_opts, filename, fmt, chain);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002422 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002423 return 1;
2424 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002425
Benoît Canetc054b3f2012-09-05 13:09:02 +02002426 switch (output_format) {
2427 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002428 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002429 break;
2430 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002431 if (chain) {
2432 dump_json_image_info_list(list);
2433 } else {
2434 dump_json_image_info(list->value);
2435 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002436 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002437 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002438
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002439 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002440 return 0;
2441}
2442
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002443static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2444 MapEntry *next)
2445{
2446 switch (output_format) {
2447 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002448 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002449 error_report("File contains external, encrypted or compressed clusters.");
2450 exit(1);
2451 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002452 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002453 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002454 e->start, e->length,
2455 e->has_offset ? e->offset : 0,
2456 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002457 }
2458 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2459 * Modify the flags here to allow more coalescing.
2460 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002461 if (next && (!next->data || next->zero)) {
2462 next->data = false;
2463 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002464 }
2465 break;
2466 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002467 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2468 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002469 (e->start == 0 ? "[" : ",\n"),
2470 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002471 e->zero ? "true" : "false",
2472 e->data ? "true" : "false");
2473 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002474 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002475 }
2476 putchar('}');
2477
2478 if (!next) {
2479 printf("]\n");
2480 }
2481 break;
2482 }
2483}
2484
2485static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2486 int nb_sectors, MapEntry *e)
2487{
2488 int64_t ret;
2489 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002490 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002491 bool has_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002492
2493 /* As an optimization, we could cache the current range of unallocated
2494 * clusters in each file of the chain, and avoid querying the same
2495 * range repeatedly.
2496 */
2497
2498 depth = 0;
2499 for (;;) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08002500 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2501 &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002502 if (ret < 0) {
2503 return ret;
2504 }
2505 assert(nb_sectors);
2506 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2507 break;
2508 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002509 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002510 if (bs == NULL) {
2511 ret = 0;
2512 break;
2513 }
2514
2515 depth++;
2516 }
2517
John Snow28756452016-02-05 13:12:33 -05002518 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2519
2520 *e = (MapEntry) {
2521 .start = sector_num * BDRV_SECTOR_SIZE,
2522 .length = nb_sectors * BDRV_SECTOR_SIZE,
2523 .data = !!(ret & BDRV_BLOCK_DATA),
2524 .zero = !!(ret & BDRV_BLOCK_ZERO),
2525 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2526 .has_offset = has_offset,
2527 .depth = depth,
2528 .has_filename = file && has_offset,
2529 .filename = file && has_offset ? file->filename : NULL,
2530 };
2531
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002532 return 0;
2533}
2534
Fam Zheng16b0d552016-01-26 11:59:02 +08002535static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2536{
2537 if (curr->length == 0) {
2538 return false;
2539 }
2540 if (curr->zero != next->zero ||
2541 curr->data != next->data ||
2542 curr->depth != next->depth ||
2543 curr->has_filename != next->has_filename ||
2544 curr->has_offset != next->has_offset) {
2545 return false;
2546 }
2547 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2548 return false;
2549 }
2550 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2551 return false;
2552 }
2553 return true;
2554}
2555
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002556static int img_map(int argc, char **argv)
2557{
2558 int c;
2559 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002560 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002561 BlockDriverState *bs;
2562 const char *filename, *fmt, *output;
2563 int64_t length;
2564 MapEntry curr = { .length = 0 }, next;
2565 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002566 bool image_opts = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002567
2568 fmt = NULL;
2569 output = NULL;
2570 for (;;) {
2571 int option_index = 0;
2572 static const struct option long_options[] = {
2573 {"help", no_argument, 0, 'h'},
2574 {"format", required_argument, 0, 'f'},
2575 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002576 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002577 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002578 {0, 0, 0, 0}
2579 };
2580 c = getopt_long(argc, argv, "f:h",
2581 long_options, &option_index);
2582 if (c == -1) {
2583 break;
2584 }
2585 switch (c) {
2586 case '?':
2587 case 'h':
2588 help();
2589 break;
2590 case 'f':
2591 fmt = optarg;
2592 break;
2593 case OPTION_OUTPUT:
2594 output = optarg;
2595 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002596 case OPTION_OBJECT: {
2597 QemuOpts *opts;
2598 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2599 optarg, true);
2600 if (!opts) {
2601 return 1;
2602 }
2603 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002604 case OPTION_IMAGE_OPTS:
2605 image_opts = true;
2606 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002607 }
2608 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002609 if (optind != argc - 1) {
2610 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002611 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002612 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002613
2614 if (output && !strcmp(output, "json")) {
2615 output_format = OFORMAT_JSON;
2616 } else if (output && !strcmp(output, "human")) {
2617 output_format = OFORMAT_HUMAN;
2618 } else if (output) {
2619 error_report("--output must be used with human or json as argument.");
2620 return 1;
2621 }
2622
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002623 if (qemu_opts_foreach(&qemu_object_opts,
2624 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002625 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002626 return 1;
2627 }
2628
Kevin Wolfce099542016-03-15 13:01:04 +01002629 blk = img_open(image_opts, filename, fmt, 0, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002630 if (!blk) {
2631 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002632 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002633 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002634
2635 if (output_format == OFORMAT_HUMAN) {
2636 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2637 }
2638
Max Reitzf1d3cd72015-02-05 13:58:18 -05002639 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002640 while (curr.start + curr.length < length) {
2641 int64_t nsectors_left;
2642 int64_t sector_num;
2643 int n;
2644
2645 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2646
2647 /* Probe up to 1 GiB at a time. */
2648 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2649 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2650 ret = get_block_status(bs, sector_num, n, &next);
2651
2652 if (ret < 0) {
2653 error_report("Could not read file metadata: %s", strerror(-ret));
2654 goto out;
2655 }
2656
Fam Zheng16b0d552016-01-26 11:59:02 +08002657 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002658 curr.length += next.length;
2659 continue;
2660 }
2661
2662 if (curr.length > 0) {
2663 dump_map_entry(output_format, &curr, &next);
2664 }
2665 curr = next;
2666 }
2667
2668 dump_map_entry(output_format, &curr, NULL);
2669
2670out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002671 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002672 return ret < 0;
2673}
2674
aliguorif7b4a942009-01-07 17:40:15 +00002675#define SNAPSHOT_LIST 1
2676#define SNAPSHOT_CREATE 2
2677#define SNAPSHOT_APPLY 3
2678#define SNAPSHOT_DELETE 4
2679
Stuart Brady153859b2009-06-07 00:42:17 +01002680static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002681{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002682 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002683 BlockDriverState *bs;
2684 QEMUSnapshotInfo sn;
2685 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002686 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002687 int action = 0;
2688 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002689 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002690 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002691 bool image_opts = false;
aliguorif7b4a942009-01-07 17:40:15 +00002692
Kevin Wolfce099542016-03-15 13:01:04 +01002693 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002694 /* Parse commandline parameters */
2695 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002696 static const struct option long_options[] = {
2697 {"help", no_argument, 0, 'h'},
2698 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002699 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002700 {0, 0, 0, 0}
2701 };
2702 c = getopt_long(argc, argv, "la:c:d:hq",
2703 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002704 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002705 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002706 }
aliguorif7b4a942009-01-07 17:40:15 +00002707 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002708 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002709 case 'h':
2710 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002711 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002712 case 'l':
2713 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002714 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002715 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002716 }
2717 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002718 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002719 break;
2720 case 'a':
2721 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002722 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002723 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002724 }
2725 action = SNAPSHOT_APPLY;
2726 snapshot_name = optarg;
2727 break;
2728 case 'c':
2729 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002730 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002731 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002732 }
2733 action = SNAPSHOT_CREATE;
2734 snapshot_name = optarg;
2735 break;
2736 case 'd':
2737 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002738 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002739 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002740 }
2741 action = SNAPSHOT_DELETE;
2742 snapshot_name = optarg;
2743 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002744 case 'q':
2745 quiet = true;
2746 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002747 case OPTION_OBJECT: {
2748 QemuOpts *opts;
2749 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2750 optarg, true);
2751 if (!opts) {
2752 return 1;
2753 }
2754 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002755 case OPTION_IMAGE_OPTS:
2756 image_opts = true;
2757 break;
aliguorif7b4a942009-01-07 17:40:15 +00002758 }
2759 }
2760
Kevin Wolffc11eb22013-08-05 10:53:04 +02002761 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002762 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002763 }
aliguorif7b4a942009-01-07 17:40:15 +00002764 filename = argv[optind++];
2765
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002766 if (qemu_opts_foreach(&qemu_object_opts,
2767 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002768 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002769 return 1;
2770 }
2771
aliguorif7b4a942009-01-07 17:40:15 +00002772 /* Open the image */
Kevin Wolfce099542016-03-15 13:01:04 +01002773 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002774 if (!blk) {
2775 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002776 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002777 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002778
2779 /* Perform the requested action */
2780 switch(action) {
2781 case SNAPSHOT_LIST:
2782 dump_snapshots(bs);
2783 break;
2784
2785 case SNAPSHOT_CREATE:
2786 memset(&sn, 0, sizeof(sn));
2787 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2788
2789 qemu_gettimeofday(&tv);
2790 sn.date_sec = tv.tv_sec;
2791 sn.date_nsec = tv.tv_usec * 1000;
2792
2793 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002794 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002795 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002796 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002797 }
aliguorif7b4a942009-01-07 17:40:15 +00002798 break;
2799
2800 case SNAPSHOT_APPLY:
2801 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002802 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002803 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002804 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002805 }
aliguorif7b4a942009-01-07 17:40:15 +00002806 break;
2807
2808 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002809 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002810 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002811 error_reportf_err(err, "Could not delete snapshot '%s': ",
2812 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002813 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002814 }
aliguorif7b4a942009-01-07 17:40:15 +00002815 break;
2816 }
2817
2818 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002819 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002820 if (ret) {
2821 return 1;
2822 }
Stuart Brady153859b2009-06-07 00:42:17 +01002823 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002824}
2825
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002826static int img_rebase(int argc, char **argv)
2827{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002828 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01002829 uint8_t *buf_old = NULL;
2830 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05002831 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002832 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002833 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2834 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01002835 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002836 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002837 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002838 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002839 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002840 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002841
2842 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002843 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002844 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002845 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002846 out_baseimg = NULL;
2847 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002848 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002849 static const struct option long_options[] = {
2850 {"help", no_argument, 0, 'h'},
2851 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002852 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002853 {0, 0, 0, 0}
2854 };
2855 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2856 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002857 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002858 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002859 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002860 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002861 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002862 case 'h':
2863 help();
2864 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002865 case 'f':
2866 fmt = optarg;
2867 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002868 case 'F':
2869 out_basefmt = optarg;
2870 break;
2871 case 'b':
2872 out_baseimg = optarg;
2873 break;
2874 case 'u':
2875 unsafe = 1;
2876 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002877 case 'p':
2878 progress = 1;
2879 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002880 case 't':
2881 cache = optarg;
2882 break;
Max Reitz40055952014-07-22 22:58:42 +02002883 case 'T':
2884 src_cache = optarg;
2885 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002886 case 'q':
2887 quiet = true;
2888 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002889 case OPTION_OBJECT: {
2890 QemuOpts *opts;
2891 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2892 optarg, true);
2893 if (!opts) {
2894 return 1;
2895 }
2896 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002897 case OPTION_IMAGE_OPTS:
2898 image_opts = true;
2899 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002900 }
2901 }
2902
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002903 if (quiet) {
2904 progress = 0;
2905 }
2906
Fam Zhengac1307a2014-04-22 13:36:11 +08002907 if (optind != argc - 1) {
2908 error_exit("Expecting one image file name");
2909 }
2910 if (!unsafe && !out_baseimg) {
2911 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002912 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002913 filename = argv[optind++];
2914
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002915 if (qemu_opts_foreach(&qemu_object_opts,
2916 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002917 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002918 return 1;
2919 }
2920
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002921 qemu_progress_init(progress, 2.0);
2922 qemu_progress_print(0, 100);
2923
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002924 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01002925 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002926 if (ret < 0) {
2927 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002928 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002929 }
2930
Kevin Wolfce099542016-03-15 13:01:04 +01002931 src_flags = 0;
2932 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02002933 if (ret < 0) {
2934 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002935 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002936 }
2937
Kevin Wolfce099542016-03-15 13:01:04 +01002938 /* The source files are opened read-only, don't care about WCE */
2939 assert((src_flags & BDRV_O_RDWR) == 0);
2940 (void) src_writethrough;
2941
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002942 /*
2943 * Open the images.
2944 *
2945 * Ignore the old backing file for unsafe rebase in case we want to correct
2946 * the reference to a renamed or moved backing file.
2947 */
Kevin Wolfce099542016-03-15 13:01:04 +01002948 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002949 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002950 ret = -1;
2951 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002952 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002953 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002954
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002955 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05002956 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002957 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002958 ret = -1;
2959 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002960 }
2961 }
2962
2963 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002964 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05002965 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05002966 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002967
Max Reitz644483d2015-02-05 13:58:17 -05002968 if (bs->backing_format[0] != '\0') {
2969 options = qdict_new();
2970 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2971 }
2972
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002973 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01002974 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002975 options, src_flags, &local_err);
2976 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002977 error_reportf_err(local_err,
2978 "Could not open old backing file '%s': ",
2979 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002980 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002981 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002982 }
Max Reitz644483d2015-02-05 13:58:17 -05002983
Alex Bligha6166732012-10-16 13:46:18 +01002984 if (out_baseimg[0]) {
Max Reitz644483d2015-02-05 13:58:17 -05002985 if (out_basefmt) {
2986 options = qdict_new();
2987 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2988 } else {
2989 options = NULL;
2990 }
2991
Max Reitzefaa7c42016-03-16 19:54:38 +01002992 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002993 options, src_flags, &local_err);
2994 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002995 error_reportf_err(local_err,
2996 "Could not open new backing file '%s': ",
2997 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002998 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01002999 goto out;
3000 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003001 }
3002 }
3003
3004 /*
3005 * Check each unallocated cluster in the COW file. If it is unallocated,
3006 * accesses go to the backing file. We must therefore compare this cluster
3007 * in the old and new backing file, and if they differ we need to copy it
3008 * from the old backing file into the COW file.
3009 *
3010 * If qemu-img crashes during this step, no harm is done. The content of
3011 * the image is the same as the original one at any time.
3012 */
3013 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003014 int64_t num_sectors;
3015 int64_t old_backing_num_sectors;
3016 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003017 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003018 int n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003019 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003020
Max Reitzf1d3cd72015-02-05 13:58:18 -05003021 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3022 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003023
Max Reitzf1d3cd72015-02-05 13:58:18 -05003024 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003025 if (num_sectors < 0) {
3026 error_report("Could not get size of '%s': %s",
3027 filename, strerror(-num_sectors));
3028 ret = -1;
3029 goto out;
3030 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003031 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003032 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003033 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003034
3035 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3036 error_report("Could not get size of '%s': %s",
3037 backing_name, strerror(-old_backing_num_sectors));
3038 ret = -1;
3039 goto out;
3040 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003041 if (blk_new_backing) {
3042 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003043 if (new_backing_num_sectors < 0) {
3044 error_report("Could not get size of '%s': %s",
3045 out_baseimg, strerror(-new_backing_num_sectors));
3046 ret = -1;
3047 goto out;
3048 }
Alex Bligha6166732012-10-16 13:46:18 +01003049 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003050
Kevin Wolf1f710492012-10-12 14:29:18 +02003051 if (num_sectors != 0) {
3052 local_progress = (float)100 /
3053 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3054 }
3055
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003056 for (sector = 0; sector < num_sectors; sector += n) {
3057
3058 /* How many sectors can we handle with the next read? */
3059 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3060 n = (IO_BUF_SIZE / 512);
3061 } else {
3062 n = num_sectors - sector;
3063 }
3064
3065 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02003066 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003067 if (ret < 0) {
3068 error_report("error while reading image metadata: %s",
3069 strerror(-ret));
3070 goto out;
3071 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003072 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003073 continue;
3074 }
3075
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003076 /*
3077 * Read old and new backing file and take into consideration that
3078 * backing files may be smaller than the COW image.
3079 */
3080 if (sector >= old_backing_num_sectors) {
3081 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3082 } else {
3083 if (sector + n > old_backing_num_sectors) {
3084 n = old_backing_num_sectors - sector;
3085 }
3086
Eric Blake91669202016-05-06 10:26:43 -06003087 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3088 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003089 if (ret < 0) {
3090 error_report("error while reading from old backing file");
3091 goto out;
3092 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003093 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003094
Max Reitzf1d3cd72015-02-05 13:58:18 -05003095 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003096 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3097 } else {
3098 if (sector + n > new_backing_num_sectors) {
3099 n = new_backing_num_sectors - sector;
3100 }
3101
Eric Blake91669202016-05-06 10:26:43 -06003102 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3103 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003104 if (ret < 0) {
3105 error_report("error while reading from new backing file");
3106 goto out;
3107 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003108 }
3109
3110 /* If they differ, we need to write to the COW file */
3111 uint64_t written = 0;
3112
3113 while (written < n) {
3114 int pnum;
3115
3116 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003117 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003118 {
Eric Blake91669202016-05-06 10:26:43 -06003119 ret = blk_pwrite(blk,
3120 (sector + written) << BDRV_SECTOR_BITS,
3121 buf_old + written * 512,
3122 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003123 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003124 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003125 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003126 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003127 }
3128 }
3129
3130 written += pnum;
3131 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003132 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003133 }
3134 }
3135
3136 /*
3137 * Change the backing file. All clusters that are different from the old
3138 * backing file are overwritten in the COW file now, so the visible content
3139 * doesn't change when we switch the backing file.
3140 */
Alex Bligha6166732012-10-16 13:46:18 +01003141 if (out_baseimg && *out_baseimg) {
3142 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3143 } else {
3144 ret = bdrv_change_backing_file(bs, NULL, NULL);
3145 }
3146
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003147 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003148 error_report("Could not change the backing file to '%s': No "
3149 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003150 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003151 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003152 out_baseimg, strerror(-ret));
3153 }
3154
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003155 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003156 /*
3157 * TODO At this point it is possible to check if any clusters that are
3158 * allocated in the COW file are the same in the backing file. If so, they
3159 * could be dropped from the COW file. Don't do this before switching the
3160 * backing file, in case of a crash this would lead to corruption.
3161 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003162out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003163 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003164 /* Cleanup */
3165 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003166 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003167 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003168 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003169 qemu_vfree(buf_old);
3170 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003171
Markus Armbruster26f54e92014-10-07 13:59:04 +02003172 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003173 if (ret) {
3174 return 1;
3175 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003176 return 0;
3177}
3178
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003179static int img_resize(int argc, char **argv)
3180{
Markus Armbruster6750e792015-02-12 17:43:08 +01003181 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003182 int c, ret, relative;
3183 const char *filename, *fmt, *size;
3184 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003185 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003186 BlockBackend *blk = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003187 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003188
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003189 static QemuOptsList resize_options = {
3190 .name = "resize_options",
3191 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3192 .desc = {
3193 {
3194 .name = BLOCK_OPT_SIZE,
3195 .type = QEMU_OPT_SIZE,
3196 .help = "Virtual disk size"
3197 }, {
3198 /* end of list */
3199 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003200 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003201 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003202 bool image_opts = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003203
Kevin Wolfe80fec72011-04-29 10:58:12 +02003204 /* Remove size from argv manually so that negative numbers are not treated
3205 * as options by getopt. */
3206 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003207 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003208 return 1;
3209 }
3210
3211 size = argv[--argc];
3212
3213 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003214 fmt = NULL;
3215 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003216 static const struct option long_options[] = {
3217 {"help", no_argument, 0, 'h'},
3218 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003219 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003220 {0, 0, 0, 0}
3221 };
3222 c = getopt_long(argc, argv, "f:hq",
3223 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003224 if (c == -1) {
3225 break;
3226 }
3227 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01003228 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003229 case 'h':
3230 help();
3231 break;
3232 case 'f':
3233 fmt = optarg;
3234 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003235 case 'q':
3236 quiet = true;
3237 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003238 case OPTION_OBJECT: {
3239 QemuOpts *opts;
3240 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3241 optarg, true);
3242 if (!opts) {
3243 return 1;
3244 }
3245 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003246 case OPTION_IMAGE_OPTS:
3247 image_opts = true;
3248 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003249 }
3250 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003251 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003252 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003253 }
3254 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003255
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003256 if (qemu_opts_foreach(&qemu_object_opts,
3257 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003258 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003259 return 1;
3260 }
3261
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003262 /* Choose grow, shrink, or absolute resize mode */
3263 switch (size[0]) {
3264 case '+':
3265 relative = 1;
3266 size++;
3267 break;
3268 case '-':
3269 relative = -1;
3270 size++;
3271 break;
3272 default:
3273 relative = 0;
3274 break;
3275 }
3276
3277 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003278 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003279 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003280 if (err) {
3281 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003282 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003283 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003284 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003285 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003286 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3287 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003288
Max Reitzefaa7c42016-03-16 19:54:38 +01003289 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01003290 BDRV_O_RDWR, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003291 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003292 ret = -1;
3293 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003294 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003295
3296 if (relative) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05003297 total_size = blk_getlength(blk) + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003298 } else {
3299 total_size = n;
3300 }
3301 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003302 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003303 ret = -1;
3304 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003305 }
3306
Max Reitzf1d3cd72015-02-05 13:58:18 -05003307 ret = blk_truncate(blk, total_size);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003308 switch (ret) {
3309 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003310 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003311 break;
3312 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01003313 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003314 break;
3315 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01003316 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003317 break;
3318 default:
Max Reitzbcf23482016-06-15 17:36:29 +02003319 error_report("Error resizing image: %s", strerror(-ret));
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003320 break;
3321 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003322out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003323 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003324 if (ret) {
3325 return 1;
3326 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003327 return 0;
3328}
3329
Max Reitz76a3a342014-10-27 11:12:51 +01003330static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003331 int64_t offset, int64_t total_work_size,
3332 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003333{
3334 qemu_progress_print(100.f * offset / total_work_size, 0);
3335}
3336
Max Reitz6f176b42013-09-03 10:09:50 +02003337static int img_amend(int argc, char **argv)
3338{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003339 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003340 int c, ret = 0;
3341 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003342 QemuOptsList *create_opts = NULL;
3343 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003344 const char *fmt = NULL, *filename, *cache;
3345 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003346 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003347 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003348 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003349 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003350 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003351
Max Reitzbd39e6e2014-07-22 22:58:43 +02003352 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003353 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003354 static const struct option long_options[] = {
3355 {"help", no_argument, 0, 'h'},
3356 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003357 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003358 {0, 0, 0, 0}
3359 };
3360 c = getopt_long(argc, argv, "ho:f:t:pq",
3361 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003362 if (c == -1) {
3363 break;
3364 }
3365
3366 switch (c) {
3367 case 'h':
3368 case '?':
3369 help();
3370 break;
3371 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01003372 if (!is_valid_option_list(optarg)) {
3373 error_report("Invalid option list: %s", optarg);
3374 ret = -1;
Max Reitze814dff2015-08-20 16:00:38 -07003375 goto out_no_progress;
Kevin Wolf626f84f2014-02-21 16:24:06 +01003376 }
3377 if (!options) {
3378 options = g_strdup(optarg);
3379 } else {
3380 char *old_options = options;
3381 options = g_strdup_printf("%s,%s", options, optarg);
3382 g_free(old_options);
3383 }
Max Reitz6f176b42013-09-03 10:09:50 +02003384 break;
3385 case 'f':
3386 fmt = optarg;
3387 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003388 case 't':
3389 cache = optarg;
3390 break;
Max Reitz76a3a342014-10-27 11:12:51 +01003391 case 'p':
3392 progress = true;
3393 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003394 case 'q':
3395 quiet = true;
3396 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003397 case OPTION_OBJECT:
3398 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3399 optarg, true);
3400 if (!opts) {
3401 ret = -1;
3402 goto out_no_progress;
3403 }
3404 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003405 case OPTION_IMAGE_OPTS:
3406 image_opts = true;
3407 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003408 }
3409 }
3410
Max Reitz6f176b42013-09-03 10:09:50 +02003411 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003412 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003413 }
3414
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003415 if (qemu_opts_foreach(&qemu_object_opts,
3416 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003417 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003418 ret = -1;
3419 goto out_no_progress;
3420 }
3421
Max Reitz76a3a342014-10-27 11:12:51 +01003422 if (quiet) {
3423 progress = false;
3424 }
3425 qemu_progress_init(progress, 1.0);
3426
Kevin Wolfa283cb62014-02-21 16:24:07 +01003427 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3428 if (fmt && has_help_option(options)) {
3429 /* If a format is explicitly specified (and possibly no filename is
3430 * given), print option help here */
3431 ret = print_block_option_help(filename, fmt);
3432 goto out;
3433 }
3434
3435 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003436 error_report("Expecting one image file name");
3437 ret = -1;
3438 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003439 }
Max Reitz6f176b42013-09-03 10:09:50 +02003440
Kevin Wolfce099542016-03-15 13:01:04 +01003441 flags = BDRV_O_RDWR;
3442 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003443 if (ret < 0) {
3444 error_report("Invalid cache option: %s", cache);
3445 goto out;
3446 }
3447
Kevin Wolfce099542016-03-15 13:01:04 +01003448 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003449 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003450 ret = -1;
3451 goto out;
3452 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003453 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003454
3455 fmt = bs->drv->format_name;
3456
Kevin Wolf626f84f2014-02-21 16:24:06 +01003457 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003458 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003459 ret = print_block_option_help(filename, fmt);
3460 goto out;
3461 }
3462
Max Reitzb2439d22014-12-02 18:32:47 +01003463 if (!bs->drv->create_opts) {
3464 error_report("Format driver '%s' does not support any options to amend",
3465 fmt);
3466 ret = -1;
3467 goto out;
3468 }
3469
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003470 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003471 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003472 qemu_opts_do_parse(opts, options, NULL, &err);
3473 if (err) {
3474 error_report_err(err);
3475 ret = -1;
3476 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003477 }
3478
Max Reitz76a3a342014-10-27 11:12:51 +01003479 /* In case the driver does not call amend_status_cb() */
3480 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003481 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003482 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003483 if (ret < 0) {
3484 error_report("Error while amending options: %s", strerror(-ret));
3485 goto out;
3486 }
3487
3488out:
Max Reitz76a3a342014-10-27 11:12:51 +01003489 qemu_progress_end();
3490
Max Reitze814dff2015-08-20 16:00:38 -07003491out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003492 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003493 qemu_opts_del(opts);
3494 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003495 g_free(options);
3496
Max Reitz6f176b42013-09-03 10:09:50 +02003497 if (ret) {
3498 return 1;
3499 }
3500 return 0;
3501}
3502
Kevin Wolfb6133b82014-08-05 14:17:13 +02003503typedef struct BenchData {
3504 BlockBackend *blk;
3505 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003506 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003507 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003508 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003509 int nrreq;
3510 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003511 int flush_interval;
3512 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003513 uint8_t *buf;
3514 QEMUIOVector *qiov;
3515
3516 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003517 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003518 uint64_t offset;
3519} BenchData;
3520
Kevin Wolf55d539c2016-06-03 13:59:41 +02003521static void bench_undrained_flush_cb(void *opaque, int ret)
3522{
3523 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003524 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003525 exit(EXIT_FAILURE);
3526 }
3527}
3528
Kevin Wolfb6133b82014-08-05 14:17:13 +02003529static void bench_cb(void *opaque, int ret)
3530{
3531 BenchData *b = opaque;
3532 BlockAIOCB *acb;
3533
3534 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003535 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003536 exit(EXIT_FAILURE);
3537 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003538
3539 if (b->in_flush) {
3540 /* Just finished a flush with drained queue: Start next requests */
3541 assert(b->in_flight == 0);
3542 b->in_flush = false;
3543 } else if (b->in_flight > 0) {
3544 int remaining = b->n - b->in_flight;
3545
Kevin Wolfb6133b82014-08-05 14:17:13 +02003546 b->n--;
3547 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003548
3549 /* Time for flush? Drain queue if requested, then flush */
3550 if (b->flush_interval && remaining % b->flush_interval == 0) {
3551 if (!b->in_flight || !b->drain_on_flush) {
3552 BlockCompletionFunc *cb;
3553
3554 if (b->drain_on_flush) {
3555 b->in_flush = true;
3556 cb = bench_cb;
3557 } else {
3558 cb = bench_undrained_flush_cb;
3559 }
3560
3561 acb = blk_aio_flush(b->blk, cb, b);
3562 if (!acb) {
3563 error_report("Failed to issue flush request");
3564 exit(EXIT_FAILURE);
3565 }
3566 }
3567 if (b->drain_on_flush) {
3568 return;
3569 }
3570 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003571 }
3572
3573 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003574 int64_t offset = b->offset;
3575 /* blk_aio_* might look for completed I/Os and kick bench_cb
3576 * again, so make sure this operation is counted by in_flight
3577 * and b->offset is ready for the next submission.
3578 */
3579 b->in_flight++;
3580 b->offset += b->step;
3581 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003582 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003583 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003584 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003585 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003586 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003587 if (!acb) {
3588 error_report("Failed to issue request");
3589 exit(EXIT_FAILURE);
3590 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003591 }
3592}
3593
3594static int img_bench(int argc, char **argv)
3595{
3596 int c, ret = 0;
3597 const char *fmt = NULL, *filename;
3598 bool quiet = false;
3599 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003600 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003601 int count = 75000;
3602 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003603 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003604 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003605 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003606 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003607 int flush_interval = 0;
3608 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003609 int64_t image_size;
3610 BlockBackend *blk = NULL;
3611 BenchData data = {};
3612 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003613 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003614 struct timeval t1, t2;
3615 int i;
3616
3617 for (;;) {
3618 static const struct option long_options[] = {
3619 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003620 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003621 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003622 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003623 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003624 {0, 0, 0, 0}
3625 };
Kevin Wolf83de9be2015-07-13 13:13:17 +02003626 c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003627 if (c == -1) {
3628 break;
3629 }
3630
3631 switch (c) {
3632 case 'h':
3633 case '?':
3634 help();
3635 break;
3636 case 'c':
3637 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003638 unsigned long res;
3639
3640 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003641 error_report("Invalid request count specified");
3642 return 1;
3643 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003644 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003645 break;
3646 }
3647 case 'd':
3648 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003649 unsigned long res;
3650
3651 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003652 error_report("Invalid queue depth specified");
3653 return 1;
3654 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003655 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003656 break;
3657 }
3658 case 'f':
3659 fmt = optarg;
3660 break;
3661 case 'n':
3662 flags |= BDRV_O_NATIVE_AIO;
3663 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003664 case 'o':
3665 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003666 offset = cvtnum(optarg);
3667 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003668 error_report("Invalid offset specified");
3669 return 1;
3670 }
3671 break;
3672 }
3673 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003674 case 'q':
3675 quiet = true;
3676 break;
3677 case 's':
3678 {
3679 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003680
Markus Armbruster606caa02017-02-21 21:14:04 +01003681 sval = cvtnum(optarg);
3682 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003683 error_report("Invalid buffer size specified");
3684 return 1;
3685 }
3686
3687 bufsize = sval;
3688 break;
3689 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003690 case 'S':
3691 {
3692 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003693
Markus Armbruster606caa02017-02-21 21:14:04 +01003694 sval = cvtnum(optarg);
3695 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003696 error_report("Invalid step size specified");
3697 return 1;
3698 }
3699
3700 step = sval;
3701 break;
3702 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003703 case 't':
3704 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3705 if (ret < 0) {
3706 error_report("Invalid cache mode");
3707 ret = -1;
3708 goto out;
3709 }
3710 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003711 case 'w':
3712 flags |= BDRV_O_RDWR;
3713 is_write = true;
3714 break;
3715 case OPTION_PATTERN:
3716 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003717 unsigned long res;
3718
3719 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003720 error_report("Invalid pattern byte specified");
3721 return 1;
3722 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003723 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003724 break;
3725 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003726 case OPTION_FLUSH_INTERVAL:
3727 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003728 unsigned long res;
3729
3730 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003731 error_report("Invalid flush interval specified");
3732 return 1;
3733 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003734 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003735 break;
3736 }
3737 case OPTION_NO_DRAIN:
3738 drain_on_flush = false;
3739 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003740 case OPTION_IMAGE_OPTS:
3741 image_opts = true;
3742 break;
3743 }
3744 }
3745
3746 if (optind != argc - 1) {
3747 error_exit("Expecting one image file name");
3748 }
3749 filename = argv[argc - 1];
3750
Kevin Wolf55d539c2016-06-03 13:59:41 +02003751 if (!is_write && flush_interval) {
3752 error_report("--flush-interval is only available in write tests");
3753 ret = -1;
3754 goto out;
3755 }
3756 if (flush_interval && flush_interval < depth) {
3757 error_report("Flush interval can't be smaller than depth");
3758 ret = -1;
3759 goto out;
3760 }
3761
Kevin Wolfb6133b82014-08-05 14:17:13 +02003762 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3763 if (!blk) {
3764 ret = -1;
3765 goto out;
3766 }
3767
3768 image_size = blk_getlength(blk);
3769 if (image_size < 0) {
3770 ret = image_size;
3771 goto out;
3772 }
3773
3774 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003775 .blk = blk,
3776 .image_size = image_size,
3777 .bufsize = bufsize,
3778 .step = step ?: bufsize,
3779 .nrreq = depth,
3780 .n = count,
3781 .offset = offset,
3782 .write = is_write,
3783 .flush_interval = flush_interval,
3784 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02003785 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02003786 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02003787 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02003788 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02003789 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02003790 if (flush_interval) {
3791 printf("Sending flush every %d requests\n", flush_interval);
3792 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003793
3794 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003795 memset(data.buf, pattern, data.nrreq * data.bufsize);
3796
Kevin Wolfb6133b82014-08-05 14:17:13 +02003797 data.qiov = g_new(QEMUIOVector, data.nrreq);
3798 for (i = 0; i < data.nrreq; i++) {
3799 qemu_iovec_init(&data.qiov[i], 1);
3800 qemu_iovec_add(&data.qiov[i],
3801 data.buf + i * data.bufsize, data.bufsize);
3802 }
3803
3804 gettimeofday(&t1, NULL);
3805 bench_cb(&data, 0);
3806
3807 while (data.n > 0) {
3808 main_loop_wait(false);
3809 }
3810 gettimeofday(&t2, NULL);
3811
3812 printf("Run completed in %3.3f seconds.\n",
3813 (t2.tv_sec - t1.tv_sec)
3814 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3815
3816out:
3817 qemu_vfree(data.buf);
3818 blk_unref(blk);
3819
3820 if (ret) {
3821 return 1;
3822 }
3823 return 0;
3824}
3825
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003826#define C_BS 01
3827#define C_COUNT 02
3828#define C_IF 04
3829#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02003830#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003831
3832struct DdInfo {
3833 unsigned int flags;
3834 int64_t count;
3835};
3836
3837struct DdIo {
3838 int bsz; /* Block size */
3839 char *filename;
3840 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02003841 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003842};
3843
3844struct DdOpts {
3845 const char *name;
3846 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
3847 unsigned int flag;
3848};
3849
3850static int img_dd_bs(const char *arg,
3851 struct DdIo *in, struct DdIo *out,
3852 struct DdInfo *dd)
3853{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003854 int64_t res;
3855
Markus Armbruster606caa02017-02-21 21:14:04 +01003856 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003857
Markus Armbruster606caa02017-02-21 21:14:04 +01003858 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003859 error_report("invalid number: '%s'", arg);
3860 return 1;
3861 }
3862 in->bsz = out->bsz = res;
3863
3864 return 0;
3865}
3866
3867static int img_dd_count(const char *arg,
3868 struct DdIo *in, struct DdIo *out,
3869 struct DdInfo *dd)
3870{
Markus Armbruster606caa02017-02-21 21:14:04 +01003871 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003872
Markus Armbruster606caa02017-02-21 21:14:04 +01003873 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003874 error_report("invalid number: '%s'", arg);
3875 return 1;
3876 }
3877
3878 return 0;
3879}
3880
3881static int img_dd_if(const char *arg,
3882 struct DdIo *in, struct DdIo *out,
3883 struct DdInfo *dd)
3884{
3885 in->filename = g_strdup(arg);
3886
3887 return 0;
3888}
3889
3890static int img_dd_of(const char *arg,
3891 struct DdIo *in, struct DdIo *out,
3892 struct DdInfo *dd)
3893{
3894 out->filename = g_strdup(arg);
3895
3896 return 0;
3897}
3898
Reda Sallahif7c15532016-08-10 16:16:09 +02003899static int img_dd_skip(const char *arg,
3900 struct DdIo *in, struct DdIo *out,
3901 struct DdInfo *dd)
3902{
Markus Armbruster606caa02017-02-21 21:14:04 +01003903 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02003904
Markus Armbruster606caa02017-02-21 21:14:04 +01003905 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02003906 error_report("invalid number: '%s'", arg);
3907 return 1;
3908 }
3909
3910 return 0;
3911}
3912
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003913static int img_dd(int argc, char **argv)
3914{
3915 int ret = 0;
3916 char *arg = NULL;
3917 char *tmp;
3918 BlockDriver *drv = NULL, *proto_drv = NULL;
3919 BlockBackend *blk1 = NULL, *blk2 = NULL;
3920 QemuOpts *opts = NULL;
3921 QemuOptsList *create_opts = NULL;
3922 Error *local_err = NULL;
3923 bool image_opts = false;
3924 int c, i;
3925 const char *out_fmt = "raw";
3926 const char *fmt = NULL;
3927 int64_t size = 0;
3928 int64_t block_count = 0, out_pos, in_pos;
3929 struct DdInfo dd = {
3930 .flags = 0,
3931 .count = 0,
3932 };
3933 struct DdIo in = {
3934 .bsz = 512, /* Block size is by default 512 bytes */
3935 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003936 .buf = NULL,
3937 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003938 };
3939 struct DdIo out = {
3940 .bsz = 512,
3941 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003942 .buf = NULL,
3943 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003944 };
3945
3946 const struct DdOpts options[] = {
3947 { "bs", img_dd_bs, C_BS },
3948 { "count", img_dd_count, C_COUNT },
3949 { "if", img_dd_if, C_IF },
3950 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02003951 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003952 { NULL, NULL, 0 }
3953 };
3954 const struct option long_options[] = {
3955 { "help", no_argument, 0, 'h'},
3956 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3957 { 0, 0, 0, 0 }
3958 };
3959
3960 while ((c = getopt_long(argc, argv, "hf:O:", long_options, NULL))) {
3961 if (c == EOF) {
3962 break;
3963 }
3964 switch (c) {
3965 case 'O':
3966 out_fmt = optarg;
3967 break;
3968 case 'f':
3969 fmt = optarg;
3970 break;
3971 case '?':
3972 error_report("Try 'qemu-img --help' for more information.");
3973 ret = -1;
3974 goto out;
3975 case 'h':
3976 help();
3977 break;
3978 case OPTION_IMAGE_OPTS:
3979 image_opts = true;
3980 break;
3981 }
3982 }
3983
3984 for (i = optind; i < argc; i++) {
3985 int j;
3986 arg = g_strdup(argv[i]);
3987
3988 tmp = strchr(arg, '=');
3989 if (tmp == NULL) {
3990 error_report("unrecognized operand %s", arg);
3991 ret = -1;
3992 goto out;
3993 }
3994
3995 *tmp++ = '\0';
3996
3997 for (j = 0; options[j].name != NULL; j++) {
3998 if (!strcmp(arg, options[j].name)) {
3999 break;
4000 }
4001 }
4002 if (options[j].name == NULL) {
4003 error_report("unrecognized operand %s", arg);
4004 ret = -1;
4005 goto out;
4006 }
4007
4008 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4009 ret = -1;
4010 goto out;
4011 }
4012 dd.flags |= options[j].flag;
4013 g_free(arg);
4014 arg = NULL;
4015 }
4016
4017 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4018 error_report("Must specify both input and output files");
4019 ret = -1;
4020 goto out;
4021 }
4022 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false);
4023
4024 if (!blk1) {
4025 ret = -1;
4026 goto out;
4027 }
4028
4029 drv = bdrv_find_format(out_fmt);
4030 if (!drv) {
4031 error_report("Unknown file format");
4032 ret = -1;
4033 goto out;
4034 }
4035 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4036
4037 if (!proto_drv) {
4038 error_report_err(local_err);
4039 ret = -1;
4040 goto out;
4041 }
4042 if (!drv->create_opts) {
4043 error_report("Format driver '%s' does not support image creation",
4044 drv->format_name);
4045 ret = -1;
4046 goto out;
4047 }
4048 if (!proto_drv->create_opts) {
4049 error_report("Protocol driver '%s' does not support image creation",
4050 proto_drv->format_name);
4051 ret = -1;
4052 goto out;
4053 }
4054 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4055 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4056
4057 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4058
4059 size = blk_getlength(blk1);
4060 if (size < 0) {
4061 error_report("Failed to get size for '%s'", in.filename);
4062 ret = -1;
4063 goto out;
4064 }
4065
4066 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4067 dd.count * in.bsz < size) {
4068 size = dd.count * in.bsz;
4069 }
4070
Reda Sallahif7c15532016-08-10 16:16:09 +02004071 /* Overflow means the specified offset is beyond input image's size */
4072 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4073 size < in.bsz * in.offset)) {
4074 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4075 } else {
4076 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4077 size - in.bsz * in.offset, &error_abort);
4078 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004079
4080 ret = bdrv_create(drv, out.filename, opts, &local_err);
4081 if (ret < 0) {
4082 error_reportf_err(local_err,
4083 "%s: error while creating output image: ",
4084 out.filename);
4085 ret = -1;
4086 goto out;
4087 }
4088
4089 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4090 false, false);
4091
4092 if (!blk2) {
4093 ret = -1;
4094 goto out;
4095 }
4096
Reda Sallahif7c15532016-08-10 16:16:09 +02004097 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4098 size < in.offset * in.bsz)) {
4099 /* We give a warning if the skip option is bigger than the input
4100 * size and create an empty output disk image (i.e. like dd(1)).
4101 */
4102 error_report("%s: cannot skip to specified offset", in.filename);
4103 in_pos = size;
4104 } else {
4105 in_pos = in.offset * in.bsz;
4106 }
4107
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004108 in.buf = g_new(uint8_t, in.bsz);
4109
Reda Sallahif7c15532016-08-10 16:16:09 +02004110 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004111 int in_ret, out_ret;
4112
4113 if (in_pos + in.bsz > size) {
4114 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4115 } else {
4116 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4117 }
4118 if (in_ret < 0) {
4119 error_report("error while reading from input image file: %s",
4120 strerror(-in_ret));
4121 ret = -1;
4122 goto out;
4123 }
4124 in_pos += in_ret;
4125
4126 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4127
4128 if (out_ret < 0) {
4129 error_report("error while writing to output image file: %s",
4130 strerror(-out_ret));
4131 ret = -1;
4132 goto out;
4133 }
4134 out_pos += out_ret;
4135 }
4136
4137out:
4138 g_free(arg);
4139 qemu_opts_del(opts);
4140 qemu_opts_free(create_opts);
4141 blk_unref(blk1);
4142 blk_unref(blk2);
4143 g_free(in.filename);
4144 g_free(out.filename);
4145 g_free(in.buf);
4146 g_free(out.buf);
4147
4148 if (ret) {
4149 return 1;
4150 }
4151 return 0;
4152}
4153
Kevin Wolfb6133b82014-08-05 14:17:13 +02004154
Anthony Liguoric227f092009-10-01 16:12:16 -05004155static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004156#define DEF(option, callback, arg_string) \
4157 { option, callback },
4158#include "qemu-img-cmds.h"
4159#undef DEF
4160#undef GEN_DOCS
4161 { NULL, NULL, },
4162};
4163
bellardea2384d2004-08-01 21:59:26 +00004164int main(int argc, char **argv)
4165{
Anthony Liguoric227f092009-10-01 16:12:16 -05004166 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004167 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004168 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004169 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004170 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004171 static const struct option long_options[] = {
4172 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004173 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004174 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004175 {0, 0, 0, 0}
4176 };
bellardea2384d2004-08-01 21:59:26 +00004177
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004178#ifdef CONFIG_POSIX
4179 signal(SIGPIPE, SIG_IGN);
4180#endif
4181
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004182 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004183 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004184 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004185
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004186 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004187 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004188 exit(EXIT_FAILURE);
4189 }
4190
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004191 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004192
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004193 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004194 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004195 if (argc < 2) {
4196 error_exit("Not enough arguments");
4197 }
Stuart Brady153859b2009-06-07 00:42:17 +01004198
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004199 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004200 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004201 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004202
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004203 while ((c = getopt_long(argc, argv, "+hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004204 switch (c) {
4205 case 'h':
4206 help();
4207 return 0;
4208 case 'V':
4209 printf(QEMU_IMG_VERSION);
4210 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004211 case 'T':
4212 g_free(trace_file);
4213 trace_file = trace_opt_parse(optarg);
4214 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004215 }
bellardea2384d2004-08-01 21:59:26 +00004216 }
Stuart Brady153859b2009-06-07 00:42:17 +01004217
Denis V. Lunev10985132016-06-17 17:44:13 +03004218 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004219
Denis V. Lunev10985132016-06-17 17:44:13 +03004220 /* reset getopt_long scanning */
4221 argc -= optind;
4222 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004223 return 0;
4224 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004225 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004226 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004227
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004228 if (!trace_init_backends()) {
4229 exit(1);
4230 }
4231 trace_init_file(trace_file);
4232 qemu_set_log(LOG_TRACE);
4233
Denis V. Lunev10985132016-06-17 17:44:13 +03004234 /* find the command */
4235 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4236 if (!strcmp(cmdname, cmd->name)) {
4237 return cmd->handler(argc, argv);
4238 }
4239 }
Jeff Cody7db16892014-04-25 17:02:32 -04004240
Stuart Brady153859b2009-06-07 00:42:17 +01004241 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004242 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004243}