blob: f1c641c0a1d8c4b66987272f58cbcc8a7e9ed8c2 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Peter Maydell80c71a22016-01-18 18:01:42 +000024#include "qemu/osdep.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080025#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010026#include "qapi/error.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020027#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010028#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010029#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010030#include "qapi/qmp/qjson.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020031#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000032#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010033#include "qemu/option.h"
34#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030035#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010037#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020038#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010039#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020040#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080041#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010042#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030043#include "trace/control.h"
Benoît Canetc054b3f2012-09-05 13:09:02 +020044#include <getopt.h>
bellarde8445332006-06-14 15:32:10 +000045
Don Slutz61979a62015-01-09 10:17:35 -050046#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020047 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040048
Anthony Liguoric227f092009-10-01 16:12:16 -050049typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010050 const char *name;
51 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050052} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010053
Federico Simoncelli8599ea42013-01-28 06:59:47 -050054enum {
55 OPTION_OUTPUT = 256,
56 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000057 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000058 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020059 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020060 OPTION_FLUSH_INTERVAL = 261,
61 OPTION_NO_DRAIN = 262,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050062};
63
64typedef enum OutputFormat {
65 OFORMAT_JSON,
66 OFORMAT_HUMAN,
67} OutputFormat;
68
Kevin Wolfe6996142016-03-15 13:03:11 +010069/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040070#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000071
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010072static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000073{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010074 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000075}
76
Fam Zhengac1307a2014-04-22 13:36:11 +080077static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
78{
79 va_list ap;
80
81 error_printf("qemu-img: ");
82
83 va_start(ap, fmt);
84 error_vprintf(fmt, ap);
85 va_end(ap);
86
87 error_printf("\nTry 'qemu-img --help' for more information\n");
88 exit(EXIT_FAILURE);
89}
90
blueswir1d2c639d2009-01-24 18:19:25 +000091/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +080092static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +000093{
Paolo Bonzinie00291c2010-02-04 16:49:56 +010094 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -040095 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +030096 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +030097 "QEMU disk image utility\n"
98 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +030099 " '-h', '--help' display this help and exit\n"
100 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300101 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
102 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300103 "\n"
malc3f020d72010-02-08 12:04:56 +0300104 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100105#define DEF(option, callback, arg_string) \
106 " " arg_string "\n"
107#include "qemu-img-cmds.h"
108#undef DEF
109#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300110 "\n"
111 "Command parameters:\n"
112 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000113 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
114 " manual page for a description of the object properties. The most common\n"
115 " object type is a 'secret', which is used to supply passwords and/or\n"
116 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300117 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400118 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800119 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
120 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100121 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
122 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300123 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200124 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
125 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
126 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300127 " 'output_filename' is the destination disk image filename\n"
128 " 'output_fmt' is the destination format\n"
129 " 'options' is a comma separated list of format specific options in a\n"
130 " name=value format. Use -o ? for an overview of the options supported by the\n"
131 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800132 " 'snapshot_param' is param used for internal snapshot, format\n"
133 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
134 " '[ID_OR_NAME]'\n"
135 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
136 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300137 " '-c' indicates that target image must be compressed (qcow format only)\n"
138 " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
139 " match exactly. The image doesn't need a working backing file before\n"
140 " rebasing in this case (useful for renaming the backing file)\n"
141 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200142 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100143 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200144 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
145 " contain only zeros for qemu-img to create a sparse image during\n"
146 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
147 " unallocated or zero sectors, and the destination image will always be\n"
148 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200149 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100150 " '-n' skips the target volume creation (useful if the volume is created\n"
151 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300152 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200153 "Parameters to check subcommand:\n"
154 " '-r' tries to repair any inconsistencies that are found during the check.\n"
155 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
156 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200157 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200158 "\n"
malc3f020d72010-02-08 12:04:56 +0300159 "Parameters to snapshot subcommand:\n"
160 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
161 " '-a' applies a snapshot (revert disk to saved state)\n"
162 " '-c' creates a snapshot\n"
163 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100164 " '-l' lists all snapshots in the given image\n"
165 "\n"
166 "Parameters to compare subcommand:\n"
167 " '-f' first image format\n"
168 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200169 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
170 "\n"
171 "Parameters to dd subcommand:\n"
172 " 'bs=BYTES' read and write up to BYTES bytes at a time "
173 "(default: 512)\n"
174 " 'count=N' copy only N input blocks\n"
175 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200176 " 'of=FILE' write to FILE\n"
177 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100178
179 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100180 bdrv_iterate_format(format_print, NULL);
bellardea2384d2004-08-01 21:59:26 +0000181 printf("\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800182 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000183}
184
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000185static QemuOptsList qemu_object_opts = {
186 .name = "object",
187 .implied_opt_name = "qom-type",
188 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
189 .desc = {
190 { }
191 },
192};
193
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000194static QemuOptsList qemu_source_opts = {
195 .name = "source",
196 .implied_opt_name = "file",
197 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
198 .desc = {
199 { }
200 },
201};
202
Stefan Weil7c30f652013-06-16 17:01:05 +0200203static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100204{
205 int ret = 0;
206 if (!quiet) {
207 va_list args;
208 va_start(args, fmt);
209 ret = vprintf(fmt, args);
210 va_end(args);
211 }
212 return ret;
213}
214
bellardea2384d2004-08-01 21:59:26 +0000215
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100216static int print_block_option_help(const char *filename, const char *fmt)
217{
218 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800219 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500220 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100221
222 /* Find driver and parse its options */
223 drv = bdrv_find_format(fmt);
224 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100225 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100226 return 1;
227 }
228
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800229 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100230 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500231 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100232 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100233 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800234 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100235 return 1;
236 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800237 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100238 }
239
Chunyan Liu83d05212014-06-05 17:20:51 +0800240 qemu_opts_print_help(create_opts);
241 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100242 return 0;
243}
244
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000245
246static int img_open_password(BlockBackend *blk, const char *filename,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000247 int flags, bool quiet)
bellard75c23802004-08-27 21:28:58 +0000248{
249 BlockDriverState *bs;
bellard75c23802004-08-27 21:28:58 +0000250 char password[256];
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000251
252 bs = blk_bs(blk);
Daniel P. Berrange4ef130f2016-03-21 14:11:43 +0000253 if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
254 !(flags & BDRV_O_NO_IO)) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000255 qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
256 if (qemu_read_password(password, sizeof(password)) < 0) {
257 error_report("No password given");
258 return -1;
259 }
260 if (bdrv_set_key(bs, password) < 0) {
261 error_report("invalid password");
262 return -1;
263 }
264 }
265 return 0;
266}
267
268
Max Reitzefaa7c42016-03-16 19:54:38 +0100269static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100270 QemuOpts *opts, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000271 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000272{
273 QDict *options;
274 Error *local_err = NULL;
275 BlockBackend *blk;
276 options = qemu_opts_to_qdict(opts, NULL);
Max Reitzefaa7c42016-03-16 19:54:38 +0100277 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000278 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100279 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000280 return NULL;
281 }
Kevin Wolfce099542016-03-15 13:01:04 +0100282 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000283
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000284 if (img_open_password(blk, optstr, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000285 blk_unref(blk);
286 return NULL;
287 }
288 return blk;
289}
290
Max Reitzefaa7c42016-03-16 19:54:38 +0100291static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292 const char *fmt, int flags,
Kevin Wolfce099542016-03-15 13:01:04 +0100293 bool writethrough, bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000294{
295 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200296 Error *local_err = NULL;
Max Reitz5bd31322015-02-05 13:58:16 -0500297 QDict *options = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100298
bellard75c23802004-08-27 21:28:58 +0000299 if (fmt) {
Max Reitz5bd31322015-02-05 13:58:16 -0500300 options = qdict_new();
301 qdict_put(options, "driver", qstring_from_str(fmt));
bellard75c23802004-08-27 21:28:58 +0000302 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100303
Max Reitzefaa7c42016-03-16 19:54:38 +0100304 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500305 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100306 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000307 return NULL;
bellard75c23802004-08-27 21:28:58 +0000308 }
Kevin Wolfce099542016-03-15 13:01:04 +0100309 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100310
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000311 if (img_open_password(blk, filename, flags, quiet) < 0) {
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312 blk_unref(blk);
313 return NULL;
bellard75c23802004-08-27 21:28:58 +0000314 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200315 return blk;
bellard75c23802004-08-27 21:28:58 +0000316}
317
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318
Max Reitzefaa7c42016-03-16 19:54:38 +0100319static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100321 const char *fmt, int flags, bool writethrough,
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000322 bool quiet)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000323{
324 BlockBackend *blk;
325 if (image_opts) {
326 QemuOpts *opts;
327 if (fmt) {
328 error_report("--image-opts and --format are mutually exclusive");
329 return NULL;
330 }
331 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
332 filename, true);
333 if (!opts) {
334 return NULL;
335 }
Kevin Wolfce099542016-03-15 13:01:04 +0100336 blk = img_open_opts(filename, opts, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000337 } else {
Kevin Wolfce099542016-03-15 13:01:04 +0100338 blk = img_open_file(filename, fmt, flags, writethrough, quiet);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000339 }
340 return blk;
341}
342
343
Chunyan Liu83d05212014-06-05 17:20:51 +0800344static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100345 const char *base_filename,
346 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200347{
Markus Armbruster6750e792015-02-12 17:43:08 +0100348 Error *err = NULL;
349
Kevin Wolfefa84d42009-05-18 16:42:12 +0200350 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100351 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100352 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100353 error_report("Backing file not supported for file format '%s'",
354 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100355 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900356 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200357 }
358 }
359 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100360 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100361 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100362 error_report("Backing file format not supported for file "
363 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100364 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900365 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200366 }
367 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900368 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200369}
370
bellardea2384d2004-08-01 21:59:26 +0000371static int img_create(int argc, char **argv)
372{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200373 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100374 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000375 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000376 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000377 const char *filename;
378 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200379 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200380 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100381 bool quiet = false;
ths3b46e622007-09-17 08:09:54 +0000382
bellardea2384d2004-08-01 21:59:26 +0000383 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000384 static const struct option long_options[] = {
385 {"help", no_argument, 0, 'h'},
386 {"object", required_argument, 0, OPTION_OBJECT},
387 {0, 0, 0, 0}
388 };
389 c = getopt_long(argc, argv, "F:b:f:he6o:q",
390 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100391 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000392 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100393 }
bellardea2384d2004-08-01 21:59:26 +0000394 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100395 case '?':
bellardea2384d2004-08-01 21:59:26 +0000396 case 'h':
397 help();
398 break;
aliguori9230eaf2009-03-28 17:55:19 +0000399 case 'F':
400 base_fmt = optarg;
401 break;
bellardea2384d2004-08-01 21:59:26 +0000402 case 'b':
403 base_filename = optarg;
404 break;
405 case 'f':
406 fmt = optarg;
407 break;
408 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200409 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100410 "encryption\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100411 goto fail;
thsd8871c52007-10-24 16:11:42 +0000412 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +0200413 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +0100414 "compat6\' instead!");
Kevin Wolf77386bf2014-02-21 16:24:04 +0100415 goto fail;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200416 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100417 if (!is_valid_option_list(optarg)) {
418 error_report("Invalid option list: %s", optarg);
419 goto fail;
420 }
421 if (!options) {
422 options = g_strdup(optarg);
423 } else {
424 char *old_options = options;
425 options = g_strdup_printf("%s,%s", options, optarg);
426 g_free(old_options);
427 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200428 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100429 case 'q':
430 quiet = true;
431 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000432 case OPTION_OBJECT: {
433 QemuOpts *opts;
434 opts = qemu_opts_parse_noisily(&qemu_object_opts,
435 optarg, true);
436 if (!opts) {
437 goto fail;
438 }
439 } break;
bellardea2384d2004-08-01 21:59:26 +0000440 }
441 }
aliguori9230eaf2009-03-28 17:55:19 +0000442
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900443 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100444 filename = (optind < argc) ? argv[optind] : NULL;
445 if (options && has_help_option(options)) {
446 g_free(options);
447 return print_block_option_help(filename, fmt);
448 }
449
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100450 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800451 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100452 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100453 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900454
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000455 if (qemu_opts_foreach(&qemu_object_opts,
456 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200457 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000458 goto fail;
459 }
460
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100461 /* Get image size, if specified */
462 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100463 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +0100464 char *end;
Markus Armbruster466dea12017-02-21 21:14:00 +0100465 sval = qemu_strtosz(argv[optind++], &end);
Markus Armbrustere36b3692011-11-22 09:46:05 +0100466 if (sval < 0 || *end) {
liguang79443392012-12-17 09:49:23 +0800467 if (sval == -ERANGE) {
468 error_report("Image size must be less than 8 EiB!");
469 } else {
470 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200471 "G, T, P or E suffixes for ");
472 error_report("kilobytes, megabytes, gigabytes, terabytes, "
473 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800474 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100475 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100476 }
477 img_size = (uint64_t)sval;
478 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200479 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800480 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200481 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100482
Luiz Capitulino9b375252012-11-30 10:52:05 -0200483 bdrv_img_create(filename, fmt, base_filename, base_fmt,
Kevin Wolf61de4c62016-03-18 17:46:45 +0100484 options, img_size, 0, &local_err, quiet);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100485 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100486 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100487 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900488 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200489
Kevin Wolf77386bf2014-02-21 16:24:04 +0100490 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000491 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100492
493fail:
494 g_free(options);
495 return 1;
bellardea2384d2004-08-01 21:59:26 +0000496}
497
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100498static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500499{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500500 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500501 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100502 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600503
504 visit_type_ImageCheck(v, NULL, &check, &error_abort);
505 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500506 str = qobject_to_json_pretty(obj);
507 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100508 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500509 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600510 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500511 QDECREF(str);
512}
513
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100514static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500515{
516 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100517 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500518 } else {
519 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100520 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
521 "Data may be corrupted, or further writes to the image "
522 "may corrupt it.\n",
523 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500524 }
525
526 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100527 qprintf(quiet,
528 "\n%" PRId64 " leaked clusters were found on the image.\n"
529 "This means waste of disk space, but no harm to data.\n",
530 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500531 }
532
533 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100534 qprintf(quiet,
535 "\n%" PRId64
536 " internal errors have occurred during the check.\n",
537 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500538 }
539 }
540
541 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100542 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
543 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
544 check->allocated_clusters, check->total_clusters,
545 check->allocated_clusters * 100.0 / check->total_clusters,
546 check->fragmented_clusters * 100.0 / check->allocated_clusters,
547 check->compressed_clusters * 100.0 /
548 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500549 }
550
551 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100552 qprintf(quiet,
553 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 }
555}
556
557static int collect_image_check(BlockDriverState *bs,
558 ImageCheck *check,
559 const char *filename,
560 const char *fmt,
561 int fix)
562{
563 int ret;
564 BdrvCheckResult result;
565
566 ret = bdrv_check(bs, &result, fix);
567 if (ret < 0) {
568 return ret;
569 }
570
571 check->filename = g_strdup(filename);
572 check->format = g_strdup(bdrv_get_format_name(bs));
573 check->check_errors = result.check_errors;
574 check->corruptions = result.corruptions;
575 check->has_corruptions = result.corruptions != 0;
576 check->leaks = result.leaks;
577 check->has_leaks = result.leaks != 0;
578 check->corruptions_fixed = result.corruptions_fixed;
579 check->has_corruptions_fixed = result.corruptions != 0;
580 check->leaks_fixed = result.leaks_fixed;
581 check->has_leaks_fixed = result.leaks != 0;
582 check->image_end_offset = result.image_end_offset;
583 check->has_image_end_offset = result.image_end_offset != 0;
584 check->total_clusters = result.bfi.total_clusters;
585 check->has_total_clusters = result.bfi.total_clusters != 0;
586 check->allocated_clusters = result.bfi.allocated_clusters;
587 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
588 check->fragmented_clusters = result.bfi.fragmented_clusters;
589 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100590 check->compressed_clusters = result.bfi.compressed_clusters;
591 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500592
593 return 0;
594}
595
Kevin Wolfe076f332010-06-29 11:43:13 +0200596/*
597 * Checks an image for consistency. Exit codes:
598 *
Max Reitzd6635c42014-06-02 22:15:21 +0200599 * 0 - Check completed, image is good
600 * 1 - Check not completed because of internal errors
601 * 2 - Check completed, image is corrupted
602 * 3 - Check completed, image has leaked clusters, but is good otherwise
603 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200604 */
aliguori15859692009-04-21 23:11:53 +0000605static int img_check(int argc, char **argv)
606{
607 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200609 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200610 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000611 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200612 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100613 int flags = BDRV_O_CHECK;
614 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200615 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100616 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000617 bool image_opts = false;
aliguori15859692009-04-21 23:11:53 +0000618
619 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200621 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100622
aliguori15859692009-04-21 23:11:53 +0000623 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500624 int option_index = 0;
625 static const struct option long_options[] = {
626 {"help", no_argument, 0, 'h'},
627 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530628 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500629 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000630 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000631 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 {0, 0, 0, 0}
633 };
Max Reitz40055952014-07-22 22:58:42 +0200634 c = getopt_long(argc, argv, "hf:r:T:q",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500635 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100636 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000637 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100638 }
aliguori15859692009-04-21 23:11:53 +0000639 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100640 case '?':
aliguori15859692009-04-21 23:11:53 +0000641 case 'h':
642 help();
643 break;
644 case 'f':
645 fmt = optarg;
646 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200647 case 'r':
648 flags |= BDRV_O_RDWR;
649
650 if (!strcmp(optarg, "leaks")) {
651 fix = BDRV_FIX_LEAKS;
652 } else if (!strcmp(optarg, "all")) {
653 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
654 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800655 error_exit("Unknown option value for -r "
656 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200657 }
658 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500659 case OPTION_OUTPUT:
660 output = optarg;
661 break;
Max Reitz40055952014-07-22 22:58:42 +0200662 case 'T':
663 cache = optarg;
664 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100665 case 'q':
666 quiet = true;
667 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000668 case OPTION_OBJECT: {
669 QemuOpts *opts;
670 opts = qemu_opts_parse_noisily(&qemu_object_opts,
671 optarg, true);
672 if (!opts) {
673 return 1;
674 }
675 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000676 case OPTION_IMAGE_OPTS:
677 image_opts = true;
678 break;
aliguori15859692009-04-21 23:11:53 +0000679 }
680 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200681 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800682 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100683 }
aliguori15859692009-04-21 23:11:53 +0000684 filename = argv[optind++];
685
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 if (output && !strcmp(output, "json")) {
687 output_format = OFORMAT_JSON;
688 } else if (output && !strcmp(output, "human")) {
689 output_format = OFORMAT_HUMAN;
690 } else if (output) {
691 error_report("--output must be used with human or json as argument.");
692 return 1;
693 }
694
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000695 if (qemu_opts_foreach(&qemu_object_opts,
696 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200697 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000698 return 1;
699 }
700
Kevin Wolfce099542016-03-15 13:01:04 +0100701 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200702 if (ret < 0) {
703 error_report("Invalid source cache option: %s", cache);
704 return 1;
705 }
706
Kevin Wolfce099542016-03-15 13:01:04 +0100707 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200708 if (!blk) {
709 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900710 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200711 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712
713 check = g_new0(ImageCheck, 1);
714 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200715
716 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200717 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200718 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500719 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200720 }
721
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500722 if (check->corruptions_fixed || check->leaks_fixed) {
723 int corruptions_fixed, leaks_fixed;
724
725 leaks_fixed = check->leaks_fixed;
726 corruptions_fixed = check->corruptions_fixed;
727
728 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100729 qprintf(quiet,
730 "The following inconsistencies were found and repaired:\n\n"
731 " %" PRId64 " leaked clusters\n"
732 " %" PRId64 " corruptions\n\n"
733 "Double checking the fixed image now...\n",
734 check->leaks_fixed,
735 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500736 }
737
738 ret = collect_image_check(bs, check, filename, fmt, 0);
739
740 check->leaks_fixed = leaks_fixed;
741 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200742 }
743
Max Reitz832390a2014-10-23 15:29:12 +0200744 if (!ret) {
745 switch (output_format) {
746 case OFORMAT_HUMAN:
747 dump_human_image_check(check, quiet);
748 break;
749 case OFORMAT_JSON:
750 dump_json_image_check(check, quiet);
751 break;
752 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500753 }
754
755 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200756 if (ret) {
757 error_report("Check failed: %s", strerror(-ret));
758 } else {
759 error_report("Check failed");
760 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500761 ret = 1;
762 goto fail;
763 }
764
765 if (check->corruptions) {
766 ret = 2;
767 } else if (check->leaks) {
768 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200769 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500770 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000771 }
772
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500773fail:
774 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200775 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500776 return ret;
aliguori15859692009-04-21 23:11:53 +0000777}
778
Max Reitzd4a32382014-10-24 15:57:37 +0200779typedef struct CommonBlockJobCBInfo {
780 BlockDriverState *bs;
781 Error **errp;
782} CommonBlockJobCBInfo;
783
784static void common_block_job_cb(void *opaque, int ret)
785{
786 CommonBlockJobCBInfo *cbi = opaque;
787
788 if (ret < 0) {
789 error_setg_errno(cbi->errp, -ret, "Block job failed");
790 }
Max Reitzd4a32382014-10-24 15:57:37 +0200791}
792
793static void run_block_job(BlockJob *job, Error **errp)
794{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200795 AioContext *aio_context = blk_get_aio_context(job->blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200796
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200797 aio_context_acquire(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200798 do {
799 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500800 qemu_progress_print(job->len ?
801 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200802 } while (!job->ready);
803
804 block_job_complete_sync(job, errp);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200805 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200806
807 /* A block job may finish instantaneously without publishing any progress,
808 * so just signal completion here */
809 qemu_progress_print(100.f, 0);
Max Reitzd4a32382014-10-24 15:57:37 +0200810}
811
bellardea2384d2004-08-01 21:59:26 +0000812static int img_commit(int argc, char **argv)
813{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400814 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200815 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200816 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200817 BlockDriverState *bs, *base_bs;
Max Reitz687fa1d2014-10-24 15:57:39 +0200818 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100819 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200820 Error *local_err = NULL;
821 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000822 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200823 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000824
825 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400826 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200827 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000828 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000829 static const struct option long_options[] = {
830 {"help", no_argument, 0, 'h'},
831 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000832 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000833 {0, 0, 0, 0}
834 };
835 c = getopt_long(argc, argv, "f:ht:b:dpq",
836 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100837 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000838 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100839 }
bellardea2384d2004-08-01 21:59:26 +0000840 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +0100841 case '?':
bellardea2384d2004-08-01 21:59:26 +0000842 case 'h':
843 help();
844 break;
845 case 'f':
846 fmt = optarg;
847 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400848 case 't':
849 cache = optarg;
850 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200851 case 'b':
852 base = optarg;
853 /* -b implies -d */
854 drop = true;
855 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200856 case 'd':
857 drop = true;
858 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200859 case 'p':
860 progress = true;
861 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100862 case 'q':
863 quiet = true;
864 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000865 case OPTION_OBJECT: {
866 QemuOpts *opts;
867 opts = qemu_opts_parse_noisily(&qemu_object_opts,
868 optarg, true);
869 if (!opts) {
870 return 1;
871 }
872 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000873 case OPTION_IMAGE_OPTS:
874 image_opts = true;
875 break;
bellardea2384d2004-08-01 21:59:26 +0000876 }
877 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200878
879 /* Progress is not shown in Quiet mode */
880 if (quiet) {
881 progress = false;
882 }
883
Kevin Wolffc11eb22013-08-05 10:53:04 +0200884 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800885 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100886 }
bellardea2384d2004-08-01 21:59:26 +0000887 filename = argv[optind++];
888
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000889 if (qemu_opts_foreach(&qemu_object_opts,
890 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200891 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000892 return 1;
893 }
894
Max Reitz9a86fe42014-10-24 15:57:38 +0200895 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100896 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400897 if (ret < 0) {
898 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100899 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400900 }
901
Kevin Wolfce099542016-03-15 13:01:04 +0100902 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200903 if (!blk) {
904 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900905 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200906 bs = blk_bs(blk);
907
Max Reitz687fa1d2014-10-24 15:57:39 +0200908 qemu_progress_init(progress, 1.f);
909 qemu_progress_print(0.f, 100);
910
Max Reitz1b22bff2014-10-24 15:57:40 +0200911 if (base) {
912 base_bs = bdrv_find_backing_image(bs, base);
913 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100914 error_setg(&local_err,
915 "Did not find '%s' in the backing chain of '%s'",
916 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200917 goto done;
918 }
919 } else {
920 /* This is different from QMP, which by default uses the deepest file in
921 * the backing chain (i.e., the very base); however, the traditional
922 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +0200923 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +0200924 if (!base_bs) {
925 error_setg(&local_err, "Image does not have a backing file");
926 goto done;
927 }
bellardea2384d2004-08-01 21:59:26 +0000928 }
929
Max Reitzd4a32382014-10-24 15:57:37 +0200930 cbi = (CommonBlockJobCBInfo){
931 .errp = &local_err,
932 .bs = bs,
933 };
934
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200935 aio_context = bdrv_get_aio_context(bs);
936 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -0400937 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
938 BLOCKDEV_ON_ERROR_REPORT, common_block_job_cb, &cbi,
939 &local_err, false);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200940 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +0200941 if (local_err) {
942 goto done;
943 }
944
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200945 /* When the block job completes, the BlockBackend reference will point to
946 * the old backing file. In order to avoid that the top image is already
947 * deleted, so we can still empty it afterwards, increment the reference
948 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +0200949 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200950 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200951 }
952
Max Reitzd4a32382014-10-24 15:57:37 +0200953 run_block_job(bs->job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +0200954 if (local_err) {
955 goto unref_backing;
956 }
957
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200958 if (!drop && bs->drv->bdrv_make_empty) {
959 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200960 if (ret) {
961 error_setg_errno(&local_err, -ret, "Could not empty %s",
962 filename);
963 goto unref_backing;
964 }
965 }
966
967unref_backing:
968 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +0200969 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +0200970 }
Max Reitzd4a32382014-10-24 15:57:37 +0200971
972done:
Max Reitz687fa1d2014-10-24 15:57:39 +0200973 qemu_progress_end();
974
Markus Armbruster26f54e92014-10-07 13:59:04 +0200975 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +0200976
977 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +0100978 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900979 return 1;
980 }
Max Reitzd4a32382014-10-24 15:57:37 +0200981
982 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +0000983 return 0;
984}
985
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +0400986/*
thsf58c7b32008-06-05 21:53:49 +0000987 * Returns true iff the first sector pointed to by 'buf' contains at least
988 * a non-NUL byte.
989 *
990 * 'pnum' is set to the number of sectors (including and immediately following
991 * the first one) that are known to be in the same allocated/unallocated state.
992 */
bellardea2384d2004-08-01 21:59:26 +0000993static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
994{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +0000995 bool is_zero;
996 int i;
bellardea2384d2004-08-01 21:59:26 +0000997
998 if (n <= 0) {
999 *pnum = 0;
1000 return 0;
1001 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001002 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001003 for(i = 1; i < n; i++) {
1004 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001005 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001006 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001007 }
bellardea2384d2004-08-01 21:59:26 +00001008 }
1009 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001010 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001011}
1012
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001013/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001014 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1015 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1016 * breaking up write requests for only small sparse areas.
1017 */
1018static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1019 int min)
1020{
1021 int ret;
1022 int num_checked, num_used;
1023
1024 if (n < min) {
1025 min = n;
1026 }
1027
1028 ret = is_allocated_sectors(buf, n, pnum);
1029 if (!ret) {
1030 return ret;
1031 }
1032
1033 num_used = *pnum;
1034 buf += BDRV_SECTOR_SIZE * *pnum;
1035 n -= *pnum;
1036 num_checked = num_used;
1037
1038 while (n > 0) {
1039 ret = is_allocated_sectors(buf, n, pnum);
1040
1041 buf += BDRV_SECTOR_SIZE * *pnum;
1042 n -= *pnum;
1043 num_checked += *pnum;
1044 if (ret) {
1045 num_used = num_checked;
1046 } else if (*pnum >= min) {
1047 break;
1048 }
1049 }
1050
1051 *pnum = num_used;
1052 return 1;
1053}
1054
1055/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001056 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1057 * buffers matches, non-zero otherwise.
1058 *
1059 * pnum is set to the number of sectors (including and immediately following
1060 * the first one) that are known to have the same comparison result
1061 */
1062static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1063 int *pnum)
1064{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001065 bool res;
1066 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001067
1068 if (n <= 0) {
1069 *pnum = 0;
1070 return 0;
1071 }
1072
1073 res = !!memcmp(buf1, buf2, 512);
1074 for(i = 1; i < n; i++) {
1075 buf1 += 512;
1076 buf2 += 512;
1077
1078 if (!!memcmp(buf1, buf2, 512) != res) {
1079 break;
1080 }
1081 }
1082
1083 *pnum = i;
1084 return res;
1085}
1086
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001087#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001088
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001089static int64_t sectors_to_bytes(int64_t sectors)
1090{
1091 return sectors << BDRV_SECTOR_BITS;
1092}
1093
1094static int64_t sectors_to_process(int64_t total, int64_t from)
1095{
1096 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1097}
1098
1099/*
1100 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1101 *
1102 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1103 * data and negative value on error.
1104 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001105 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001106 * @param sect_num: Number of first sector to check
1107 * @param sect_count: Number of sectors to check
1108 * @param filename: Name of disk file we are checking (logging purpose)
1109 * @param buffer: Allocated buffer for storing read data
1110 * @param quiet: Flag for quiet mode
1111 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001112static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001113 int sect_count, const char *filename,
1114 uint8_t *buffer, bool quiet)
1115{
1116 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001117 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1118 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001119 if (ret < 0) {
1120 error_report("Error while reading offset %" PRId64 " of %s: %s",
1121 sectors_to_bytes(sect_num), filename, strerror(-ret));
1122 return ret;
1123 }
1124 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1125 if (ret || pnum != sect_count) {
1126 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1127 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1128 return 1;
1129 }
1130
1131 return 0;
1132}
1133
1134/*
1135 * Compares two images. Exit codes:
1136 *
1137 * 0 - Images are identical
1138 * 1 - Images differ
1139 * >1 - Error occurred
1140 */
1141static int img_compare(int argc, char **argv)
1142{
Max Reitz40055952014-07-22 22:58:42 +02001143 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001144 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001145 BlockDriverState *bs1, *bs2;
1146 int64_t total_sectors1, total_sectors2;
1147 uint8_t *buf1 = NULL, *buf2 = NULL;
1148 int pnum1, pnum2;
1149 int allocated1, allocated2;
1150 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1151 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001152 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001153 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001154 int64_t total_sectors;
1155 int64_t sector_num = 0;
1156 int64_t nb_sectors;
1157 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001158 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001159 bool image_opts = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001160
Max Reitz40055952014-07-22 22:58:42 +02001161 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001162 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001163 static const struct option long_options[] = {
1164 {"help", no_argument, 0, 'h'},
1165 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001166 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001167 {0, 0, 0, 0}
1168 };
1169 c = getopt_long(argc, argv, "hf:F:T:pqs",
1170 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001171 if (c == -1) {
1172 break;
1173 }
1174 switch (c) {
1175 case '?':
1176 case 'h':
1177 help();
1178 break;
1179 case 'f':
1180 fmt1 = optarg;
1181 break;
1182 case 'F':
1183 fmt2 = optarg;
1184 break;
Max Reitz40055952014-07-22 22:58:42 +02001185 case 'T':
1186 cache = optarg;
1187 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001188 case 'p':
1189 progress = true;
1190 break;
1191 case 'q':
1192 quiet = true;
1193 break;
1194 case 's':
1195 strict = true;
1196 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001197 case OPTION_OBJECT: {
1198 QemuOpts *opts;
1199 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1200 optarg, true);
1201 if (!opts) {
1202 ret = 2;
1203 goto out4;
1204 }
1205 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001206 case OPTION_IMAGE_OPTS:
1207 image_opts = true;
1208 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001209 }
1210 }
1211
1212 /* Progress is not shown in Quiet mode */
1213 if (quiet) {
1214 progress = false;
1215 }
1216
1217
Kevin Wolffc11eb22013-08-05 10:53:04 +02001218 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001219 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001220 }
1221 filename1 = argv[optind++];
1222 filename2 = argv[optind++];
1223
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001224 if (qemu_opts_foreach(&qemu_object_opts,
1225 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001226 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001227 ret = 2;
1228 goto out4;
1229 }
1230
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001231 /* Initialize before goto out */
1232 qemu_progress_init(progress, 2.0);
1233
Kevin Wolfce099542016-03-15 13:01:04 +01001234 flags = 0;
1235 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001236 if (ret < 0) {
1237 error_report("Invalid source cache option: %s", cache);
1238 ret = 2;
1239 goto out3;
1240 }
1241
Kevin Wolfce099542016-03-15 13:01:04 +01001242 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001243 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001245 goto out3;
1246 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001247
Kevin Wolfce099542016-03-15 13:01:04 +01001248 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001249 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001250 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001251 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001252 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001253 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001254 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001255
Max Reitzf1d3cd72015-02-05 13:58:18 -05001256 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1257 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1258 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001259 if (total_sectors1 < 0) {
1260 error_report("Can't get size of %s: %s",
1261 filename1, strerror(-total_sectors1));
1262 ret = 4;
1263 goto out;
1264 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001265 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001266 if (total_sectors2 < 0) {
1267 error_report("Can't get size of %s: %s",
1268 filename2, strerror(-total_sectors2));
1269 ret = 4;
1270 goto out;
1271 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 total_sectors = MIN(total_sectors1, total_sectors2);
1273 progress_base = MAX(total_sectors1, total_sectors2);
1274
1275 qemu_progress_print(0, 100);
1276
1277 if (strict && total_sectors1 != total_sectors2) {
1278 ret = 1;
1279 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1280 goto out;
1281 }
1282
1283 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001284 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001285 BlockDriverState *file;
1286
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 nb_sectors = sectors_to_process(total_sectors, sector_num);
1288 if (nb_sectors <= 0) {
1289 break;
1290 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001291 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1292 total_sectors1 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001293 &pnum1, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001294 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 ret = 3;
1296 error_report("Sector allocation test failed for %s", filename1);
1297 goto out;
1298 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001299 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300
Fam Zheng25ad8e62016-01-13 16:37:41 +08001301 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1302 total_sectors2 - sector_num,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001303 &pnum2, &file);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001304 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001305 ret = 3;
1306 error_report("Sector allocation test failed for %s", filename2);
1307 goto out;
1308 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001309 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1310 if (pnum1) {
1311 nb_sectors = MIN(nb_sectors, pnum1);
1312 }
1313 if (pnum2) {
1314 nb_sectors = MIN(nb_sectors, pnum2);
1315 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001316
Fam Zheng25ad8e62016-01-13 16:37:41 +08001317 if (strict) {
1318 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1319 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1320 ret = 1;
1321 qprintf(quiet, "Strict mode: Offset %" PRId64
1322 " block status mismatch!\n",
1323 sectors_to_bytes(sector_num));
1324 goto out;
1325 }
1326 }
1327 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1328 nb_sectors = MIN(pnum1, pnum2);
1329 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001330 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001331 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1332 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 if (ret < 0) {
1334 error_report("Error while reading offset %" PRId64 " of %s:"
1335 " %s", sectors_to_bytes(sector_num), filename1,
1336 strerror(-ret));
1337 ret = 4;
1338 goto out;
1339 }
Eric Blake91669202016-05-06 10:26:43 -06001340 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1341 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001342 if (ret < 0) {
1343 error_report("Error while reading offset %" PRId64
1344 " of %s: %s", sectors_to_bytes(sector_num),
1345 filename2, strerror(-ret));
1346 ret = 4;
1347 goto out;
1348 }
1349 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1350 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001351 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1352 sectors_to_bytes(
1353 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001354 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001355 goto out;
1356 }
1357 }
1358 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359
1360 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001361 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001362 filename1, buf1, quiet);
1363 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001364 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001365 filename2, buf1, quiet);
1366 }
1367 if (ret) {
1368 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001369 error_report("Error while reading offset %" PRId64 ": %s",
1370 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001371 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001372 }
1373 goto out;
1374 }
1375 }
1376 sector_num += nb_sectors;
1377 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1378 }
1379
1380 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001381 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001382 int64_t total_sectors_over;
1383 const char *filename_over;
1384
1385 qprintf(quiet, "Warning: Image size mismatch!\n");
1386 if (total_sectors1 > total_sectors2) {
1387 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001388 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001389 filename_over = filename1;
1390 } else {
1391 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001392 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 filename_over = filename2;
1394 }
1395
1396 for (;;) {
1397 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1398 if (nb_sectors <= 0) {
1399 break;
1400 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001401 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001402 nb_sectors, &pnum);
1403 if (ret < 0) {
1404 ret = 3;
1405 error_report("Sector allocation test failed for %s",
1406 filename_over);
1407 goto out;
1408
1409 }
1410 nb_sectors = pnum;
1411 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001412 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001413 filename_over, buf1, quiet);
1414 if (ret) {
1415 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 error_report("Error while reading offset %" PRId64
1417 " of %s: %s", sectors_to_bytes(sector_num),
1418 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001419 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001420 }
1421 goto out;
1422 }
1423 }
1424 sector_num += nb_sectors;
1425 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1426 }
1427 }
1428
1429 qprintf(quiet, "Images are identical.\n");
1430 ret = 0;
1431
1432out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001433 qemu_vfree(buf1);
1434 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001435 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001436out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001437 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001438out3:
1439 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001440out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001441 return ret;
1442}
1443
Kevin Wolf690c7302015-03-19 13:33:32 +01001444enum ImgConvertBlockStatus {
1445 BLK_DATA,
1446 BLK_ZERO,
1447 BLK_BACKING_FILE,
1448};
1449
1450typedef struct ImgConvertState {
1451 BlockBackend **src;
1452 int64_t *src_sectors;
1453 int src_cur, src_num;
1454 int64_t src_cur_offset;
1455 int64_t total_sectors;
1456 int64_t allocated_sectors;
1457 enum ImgConvertBlockStatus status;
1458 int64_t sector_next_status;
1459 BlockBackend *target;
1460 bool has_zero_init;
1461 bool compressed;
1462 bool target_has_backing;
1463 int min_sparse;
1464 size_t cluster_sectors;
1465 size_t buf_sectors;
1466} ImgConvertState;
1467
1468static void convert_select_part(ImgConvertState *s, int64_t sector_num)
1469{
1470 assert(sector_num >= s->src_cur_offset);
1471 while (sector_num - s->src_cur_offset >= s->src_sectors[s->src_cur]) {
1472 s->src_cur_offset += s->src_sectors[s->src_cur];
1473 s->src_cur++;
1474 assert(s->src_cur < s->src_num);
1475 }
1476}
1477
1478static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1479{
1480 int64_t ret;
1481 int n;
1482
1483 convert_select_part(s, sector_num);
1484
1485 assert(s->total_sectors > sector_num);
1486 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1487
1488 if (s->sector_next_status <= sector_num) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08001489 BlockDriverState *file;
Kevin Wolf690c7302015-03-19 13:33:32 +01001490 ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),
1491 sector_num - s->src_cur_offset,
Fam Zheng67a0fd22016-01-26 11:58:48 +08001492 n, &n, &file);
Kevin Wolf690c7302015-03-19 13:33:32 +01001493 if (ret < 0) {
1494 return ret;
1495 }
1496
1497 if (ret & BDRV_BLOCK_ZERO) {
1498 s->status = BLK_ZERO;
1499 } else if (ret & BDRV_BLOCK_DATA) {
1500 s->status = BLK_DATA;
1501 } else if (!s->target_has_backing) {
1502 /* Without a target backing file we must copy over the contents of
1503 * the backing file as well. */
Ren Kimura263a6f42016-04-28 01:04:58 +09001504 /* Check block status of the backing file chain to avoid
Kevin Wolf690c7302015-03-19 13:33:32 +01001505 * needlessly reading zeroes and limiting the iteration to the
1506 * buffer size */
Ren Kimura263a6f42016-04-28 01:04:58 +09001507 ret = bdrv_get_block_status_above(blk_bs(s->src[s->src_cur]), NULL,
1508 sector_num - s->src_cur_offset,
1509 n, &n, &file);
1510 if (ret < 0) {
1511 return ret;
1512 }
1513
1514 if (ret & BDRV_BLOCK_ZERO) {
1515 s->status = BLK_ZERO;
1516 } else {
1517 s->status = BLK_DATA;
1518 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001519 } else {
1520 s->status = BLK_BACKING_FILE;
1521 }
1522
1523 s->sector_next_status = sector_num + n;
1524 }
1525
1526 n = MIN(n, s->sector_next_status - sector_num);
1527 if (s->status == BLK_DATA) {
1528 n = MIN(n, s->buf_sectors);
1529 }
1530
1531 /* We need to write complete clusters for compressed images, so if an
1532 * unallocated area is shorter than that, we must consider the whole
1533 * cluster allocated. */
1534 if (s->compressed) {
1535 if (n < s->cluster_sectors) {
1536 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1537 s->status = BLK_DATA;
1538 } else {
1539 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1540 }
1541 }
1542
1543 return n;
1544}
1545
1546static int convert_read(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1547 uint8_t *buf)
1548{
1549 int n;
1550 int ret;
1551
Kevin Wolf690c7302015-03-19 13:33:32 +01001552 assert(nb_sectors <= s->buf_sectors);
1553 while (nb_sectors > 0) {
1554 BlockBackend *blk;
1555 int64_t bs_sectors;
1556
1557 /* In the case of compression with multiple source files, we can get a
1558 * nb_sectors that spreads into the next part. So we must be able to
1559 * read across multiple BDSes for one convert_read() call. */
1560 convert_select_part(s, sector_num);
1561 blk = s->src[s->src_cur];
1562 bs_sectors = s->src_sectors[s->src_cur];
1563
1564 n = MIN(nb_sectors, bs_sectors - (sector_num - s->src_cur_offset));
Eric Blake91669202016-05-06 10:26:43 -06001565 ret = blk_pread(blk,
1566 (sector_num - s->src_cur_offset) << BDRV_SECTOR_BITS,
1567 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001568 if (ret < 0) {
1569 return ret;
1570 }
1571
1572 sector_num += n;
1573 nb_sectors -= n;
1574 buf += n * BDRV_SECTOR_SIZE;
1575 }
1576
1577 return 0;
1578}
1579
1580static int convert_write(ImgConvertState *s, int64_t sector_num, int nb_sectors,
1581 const uint8_t *buf)
1582{
1583 int ret;
1584
1585 while (nb_sectors > 0) {
1586 int n = nb_sectors;
1587
1588 switch (s->status) {
1589 case BLK_BACKING_FILE:
1590 /* If we have a backing file, leave clusters unallocated that are
1591 * unallocated in the source image, so that the backing file is
1592 * visible at the respective offset. */
1593 assert(s->target_has_backing);
1594 break;
1595
1596 case BLK_DATA:
1597 /* We must always write compressed clusters as a whole, so don't
1598 * try to find zeroed parts in the buffer. We can only save the
1599 * write if the buffer is completely zeroed and we're allowed to
1600 * keep the target sparse. */
1601 if (s->compressed) {
1602 if (s->has_zero_init && s->min_sparse &&
1603 buffer_is_zero(buf, n * BDRV_SECTOR_SIZE))
1604 {
1605 assert(!s->target_has_backing);
1606 break;
1607 }
1608
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001609 ret = blk_pwrite_compressed(s->target,
1610 sector_num << BDRV_SECTOR_BITS,
1611 buf, n << BDRV_SECTOR_BITS);
Kevin Wolf690c7302015-03-19 13:33:32 +01001612 if (ret < 0) {
1613 return ret;
1614 }
1615 break;
1616 }
1617
1618 /* If there is real non-zero data or we're told to keep the target
1619 * fully allocated (-S 0), we must write it. Otherwise we can treat
1620 * it as zero sectors. */
1621 if (!s->min_sparse ||
1622 is_allocated_sectors_min(buf, n, &n, s->min_sparse))
1623 {
Eric Blake91669202016-05-06 10:26:43 -06001624 ret = blk_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1625 buf, n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001626 if (ret < 0) {
1627 return ret;
1628 }
1629 break;
1630 }
1631 /* fall-through */
1632
1633 case BLK_ZERO:
1634 if (s->has_zero_init) {
1635 break;
1636 }
Eric Blaked004bd52016-05-24 16:25:20 -06001637 ret = blk_pwrite_zeroes(s->target, sector_num << BDRV_SECTOR_BITS,
1638 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001639 if (ret < 0) {
1640 return ret;
1641 }
1642 break;
1643 }
1644
1645 sector_num += n;
1646 nb_sectors -= n;
1647 buf += n * BDRV_SECTOR_SIZE;
1648 }
1649
1650 return 0;
1651}
1652
1653static int convert_do_copy(ImgConvertState *s)
1654{
1655 uint8_t *buf = NULL;
1656 int64_t sector_num, allocated_done;
1657 int ret;
1658 int n;
1659
1660 /* Check whether we have zero initialisation or can get it efficiently */
1661 s->has_zero_init = s->min_sparse && !s->target_has_backing
1662 ? bdrv_has_zero_init(blk_bs(s->target))
1663 : false;
1664
1665 if (!s->has_zero_init && !s->target_has_backing &&
1666 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1667 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001668 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001669 if (ret == 0) {
1670 s->has_zero_init = true;
1671 }
1672 }
1673
1674 /* Allocate buffer for copied data. For compressed images, only one cluster
1675 * can be copied at a time. */
1676 if (s->compressed) {
1677 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1678 error_report("invalid cluster size");
1679 ret = -EINVAL;
1680 goto fail;
1681 }
1682 s->buf_sectors = s->cluster_sectors;
1683 }
1684 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1685
1686 /* Calculate allocated sectors for progress */
1687 s->allocated_sectors = 0;
1688 sector_num = 0;
1689 while (sector_num < s->total_sectors) {
1690 n = convert_iteration_sectors(s, sector_num);
1691 if (n < 0) {
1692 ret = n;
1693 goto fail;
1694 }
Max Reitzaad15de2016-03-24 23:33:57 +01001695 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1696 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001697 s->allocated_sectors += n;
1698 }
1699 sector_num += n;
1700 }
1701
1702 /* Do the copy */
1703 s->src_cur = 0;
1704 s->src_cur_offset = 0;
1705 s->sector_next_status = 0;
1706
1707 sector_num = 0;
1708 allocated_done = 0;
1709
1710 while (sector_num < s->total_sectors) {
1711 n = convert_iteration_sectors(s, sector_num);
1712 if (n < 0) {
1713 ret = n;
1714 goto fail;
1715 }
Max Reitzaad15de2016-03-24 23:33:57 +01001716 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1717 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001718 allocated_done += n;
1719 qemu_progress_print(100.0 * allocated_done / s->allocated_sectors,
1720 0);
1721 }
1722
Max Reitzaad15de2016-03-24 23:33:57 +01001723 if (s->status == BLK_DATA) {
1724 ret = convert_read(s, sector_num, n, buf);
1725 if (ret < 0) {
1726 error_report("error while reading sector %" PRId64
1727 ": %s", sector_num, strerror(-ret));
1728 goto fail;
1729 }
1730 } else if (!s->min_sparse && s->status == BLK_ZERO) {
1731 n = MIN(n, s->buf_sectors);
1732 memset(buf, 0, n * BDRV_SECTOR_SIZE);
1733 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001734 }
1735
1736 ret = convert_write(s, sector_num, n, buf);
1737 if (ret < 0) {
1738 error_report("error while writing sector %" PRId64
1739 ": %s", sector_num, strerror(-ret));
1740 goto fail;
1741 }
1742
1743 sector_num += n;
1744 }
1745
1746 if (s->compressed) {
1747 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001748 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 if (ret < 0) {
1750 goto fail;
1751 }
1752 }
1753
1754 ret = 0;
1755fail:
1756 qemu_vfree(buf);
1757 return ret;
1758}
1759
bellardea2384d2004-08-01 21:59:26 +00001760static int img_convert(int argc, char **argv)
1761{
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 int c, bs_n, bs_i, compress, cluster_sectors, skip_create;
Peter Lieven13c28af2013-11-27 11:07:01 +01001763 int64_t ret = 0;
Max Reitz40055952014-07-22 22:58:42 +02001764 int progress = 0, flags, src_flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001765 bool writethrough, src_writethrough;
Max Reitz40055952014-07-22 22:58:42 +02001766 const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09001767 BlockDriver *drv, *proto_drv;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001768 BlockBackend **blk = NULL, *out_blk = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001769 BlockDriverState **bs = NULL, *out_bs = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001770 int64_t total_sectors;
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001771 int64_t *bs_sectors = NULL;
Peter Lievenf2521c92013-11-27 11:07:06 +01001772 size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
bellardfaea38e2006-08-05 21:31:00 +00001773 BlockDriverInfo bdi;
Chunyan Liu83d05212014-06-05 17:20:51 +08001774 QemuOpts *opts = NULL;
1775 QemuOptsList *create_opts = NULL;
1776 const char *out_baseimg_param;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001777 char *options = NULL;
edison51ef6722010-09-21 19:58:41 -07001778 const char *snapshot_name = NULL;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001779 int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001780 bool quiet = false;
Max Reitzcc84d902013-09-06 17:14:26 +02001781 Error *local_err = NULL;
Wenchao Xiaef806542013-12-04 17:10:57 +08001782 QemuOpts *sn_opts = NULL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001783 ImgConvertState state;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001784 bool image_opts = false;
bellardea2384d2004-08-01 21:59:26 +00001785
1786 fmt = NULL;
1787 out_fmt = "raw";
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001788 cache = "unsafe";
Max Reitz40055952014-07-22 22:58:42 +02001789 src_cache = BDRV_DEFAULT_CACHE;
thsf58c7b32008-06-05 21:53:49 +00001790 out_baseimg = NULL;
Jes Sorenseneec77d92010-12-07 17:44:34 +01001791 compress = 0;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001792 skip_create = 0;
bellardea2384d2004-08-01 21:59:26 +00001793 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001794 static const struct option long_options[] = {
1795 {"help", no_argument, 0, 'h'},
1796 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001797 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001798 {0, 0, 0, 0}
1799 };
1800 c = getopt_long(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn",
1801 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001802 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001803 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001804 }
bellardea2384d2004-08-01 21:59:26 +00001805 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01001806 case '?':
bellardea2384d2004-08-01 21:59:26 +00001807 case 'h':
1808 help();
1809 break;
1810 case 'f':
1811 fmt = optarg;
1812 break;
1813 case 'O':
1814 out_fmt = optarg;
1815 break;
thsf58c7b32008-06-05 21:53:49 +00001816 case 'B':
1817 out_baseimg = optarg;
1818 break;
bellardea2384d2004-08-01 21:59:26 +00001819 case 'c':
Jes Sorenseneec77d92010-12-07 17:44:34 +01001820 compress = 1;
bellardea2384d2004-08-01 21:59:26 +00001821 break;
1822 case 'e':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001823 error_report("option -e is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001824 "encryption\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001825 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001826 goto fail_getopt;
thsec36ba12007-09-16 21:59:02 +00001827 case '6':
Markus Armbruster9d42e152011-06-22 14:03:55 +02001828 error_report("option -6 is deprecated, please use \'-o "
Jes Sorenseneec77d92010-12-07 17:44:34 +01001829 "compat6\' instead!");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001830 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001831 goto fail_getopt;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001832 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001833 if (!is_valid_option_list(optarg)) {
1834 error_report("Invalid option list: %s", optarg);
1835 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001836 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001837 }
1838 if (!options) {
1839 options = g_strdup(optarg);
1840 } else {
1841 char *old_options = options;
1842 options = g_strdup_printf("%s,%s", options, optarg);
1843 g_free(old_options);
1844 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001845 break;
edison51ef6722010-09-21 19:58:41 -07001846 case 's':
1847 snapshot_name = optarg;
1848 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001849 case 'l':
1850 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01001851 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1852 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08001853 if (!sn_opts) {
1854 error_report("Failed in parsing snapshot param '%s'",
1855 optarg);
Kevin Wolf2dc83282014-02-21 16:24:05 +01001856 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001857 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08001858 }
1859 } else {
1860 snapshot_name = optarg;
1861 }
1862 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001863 case 'S':
1864 {
1865 int64_t sval;
Markus Armbrustere36b3692011-11-22 09:46:05 +01001866 char *end;
Markus Armbruster466dea12017-02-21 21:14:00 +01001867 sval = qemu_strtosz(optarg, &end);
Markus Armbrustere36b3692011-11-22 09:46:05 +01001868 if (sval < 0 || *end) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02001869 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf2dc83282014-02-21 16:24:05 +01001870 ret = -1;
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001871 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001872 }
1873
1874 min_sparse = sval / BDRV_SECTOR_SIZE;
1875 break;
1876 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001877 case 'p':
1878 progress = 1;
1879 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001880 case 't':
1881 cache = optarg;
1882 break;
Max Reitz40055952014-07-22 22:58:42 +02001883 case 'T':
1884 src_cache = optarg;
1885 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001886 case 'q':
1887 quiet = true;
1888 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01001889 case 'n':
1890 skip_create = 1;
1891 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001892 case OPTION_OBJECT:
1893 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1894 optarg, true);
1895 if (!opts) {
1896 goto fail_getopt;
1897 }
1898 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001899 case OPTION_IMAGE_OPTS:
1900 image_opts = true;
1901 break;
bellardea2384d2004-08-01 21:59:26 +00001902 }
1903 }
ths3b46e622007-09-17 08:09:54 +00001904
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001905 if (qemu_opts_foreach(&qemu_object_opts,
1906 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001907 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001908 goto fail_getopt;
1909 }
1910
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001911 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001912 if (quiet) {
1913 progress = 0;
1914 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001915 qemu_progress_init(progress, 1.0);
1916
balrog926c2d22007-10-31 01:11:44 +00001917 bs_n = argc - optind - 1;
Kevin Wolfa283cb62014-02-21 16:24:07 +01001918 out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
thsf58c7b32008-06-05 21:53:49 +00001919
Kevin Wolf2dc83282014-02-21 16:24:05 +01001920 if (options && has_help_option(options)) {
Jes Sorensen4ac8aac2010-12-06 15:25:38 +01001921 ret = print_block_option_help(out_filename, out_fmt);
1922 goto out;
1923 }
1924
bellardea2384d2004-08-01 21:59:26 +00001925 if (bs_n < 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001926 error_exit("Must specify image file name");
ths5fafdf22007-09-16 21:08:06 +00001927 }
bellardea2384d2004-08-01 21:59:26 +00001928
thsf58c7b32008-06-05 21:53:49 +00001929
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001930 if (bs_n > 1 && out_baseimg) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001931 error_report("-B makes no sense when concatenating multiple input "
1932 "images");
Jes Sorensen31ca34b2010-12-06 15:25:36 +01001933 ret = -1;
1934 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001935 }
Dong Xu Wangf8111c22012-03-15 20:13:31 +08001936
Kevin Wolfce099542016-03-15 13:01:04 +01001937 src_flags = 0;
1938 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001939 if (ret < 0) {
1940 error_report("Invalid source cache option: %s", src_cache);
1941 goto out;
1942 }
1943
Jes Sorensen6b837bc2011-03-30 14:16:25 +02001944 qemu_progress_print(0, 100);
1945
Markus Armbruster26f54e92014-10-07 13:59:04 +02001946 blk = g_new0(BlockBackend *, bs_n);
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001947 bs = g_new0(BlockDriverState *, bs_n);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001948 bs_sectors = g_new(int64_t, bs_n);
balrog926c2d22007-10-31 01:11:44 +00001949
1950 total_sectors = 0;
1951 for (bs_i = 0; bs_i < bs_n; bs_i++) {
Max Reitzefaa7c42016-03-16 19:54:38 +01001952 blk[bs_i] = img_open(image_opts, argv[optind + bs_i],
Kevin Wolfce099542016-03-15 13:01:04 +01001953 fmt, src_flags, src_writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001954 if (!blk[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001955 ret = -1;
1956 goto out;
1957 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001958 bs[bs_i] = blk_bs(blk[bs_i]);
Max Reitzf1d3cd72015-02-05 13:58:18 -05001959 bs_sectors[bs_i] = blk_nb_sectors(blk[bs_i]);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001960 if (bs_sectors[bs_i] < 0) {
1961 error_report("Could not get size of %s: %s",
1962 argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
1963 ret = -1;
1964 goto out;
1965 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02001966 total_sectors += bs_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00001967 }
bellardea2384d2004-08-01 21:59:26 +00001968
Wenchao Xiaef806542013-12-04 17:10:57 +08001969 if (sn_opts) {
Peter Maydell10d6eda2017-02-10 16:28:24 +00001970 bdrv_snapshot_load_tmp(bs[0],
1971 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1972 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1973 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001974 } else if (snapshot_name != NULL) {
edison51ef6722010-09-21 19:58:41 -07001975 if (bs_n > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02001976 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07001977 ret = -1;
1978 goto out;
1979 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08001980
1981 bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08001982 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01001983 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01001984 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08001985 ret = -1;
1986 goto out;
edison51ef6722010-09-21 19:58:41 -07001987 }
1988
Kevin Wolfefa84d42009-05-18 16:42:12 +02001989 /* Find driver and parse its options */
bellardea2384d2004-08-01 21:59:26 +00001990 drv = bdrv_find_format(out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001991 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +01001992 error_report("Unknown file format '%s'", out_fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001993 ret = -1;
1994 goto out;
1995 }
balrog926c2d22007-10-31 01:11:44 +00001996
Max Reitzb65a5e12015-02-05 13:58:12 -05001997 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001998 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +01001999 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002000 ret = -1;
2001 goto out;
2002 }
MORITA Kazutakab50cbab2010-05-26 11:35:36 +09002003
Max Reitz2e024cd2015-02-11 09:58:46 -05002004 if (!skip_create) {
2005 if (!drv->create_opts) {
2006 error_report("Format driver '%s' does not support image creation",
2007 drv->format_name);
2008 ret = -1;
2009 goto out;
2010 }
Max Reitzf75613c2014-12-02 18:32:46 +01002011
Max Reitz2e024cd2015-02-11 09:58:46 -05002012 if (!proto_drv->create_opts) {
2013 error_report("Protocol driver '%s' does not support image creation",
2014 proto_drv->format_name);
2015 ret = -1;
2016 goto out;
2017 }
Max Reitzf75613c2014-12-02 18:32:46 +01002018
Max Reitz2e024cd2015-02-11 09:58:46 -05002019 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2020 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002021
Max Reitz2e024cd2015-02-11 09:58:46 -05002022 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002023 if (options) {
2024 qemu_opts_do_parse(opts, options, NULL, &local_err);
2025 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002026 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002027 ret = -1;
2028 goto out;
2029 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002030 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002031
Markus Armbruster39101f22015-02-12 16:46:36 +01002032 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512,
2033 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002034 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2035 if (ret < 0) {
2036 goto out;
2037 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002038 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002039
Kevin Wolfa18953f2010-10-14 15:46:04 +02002040 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002041 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002042 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002043 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002044 }
2045
Kevin Wolfefa84d42009-05-18 16:42:12 +02002046 /* Check if compression is supported */
Jes Sorenseneec77d92010-12-07 17:44:34 +01002047 if (compress) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002048 bool encryption =
2049 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
2050 const char *preallocation =
2051 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002052
Pavel Butsykin35fadca2016-07-22 11:17:48 +03002053 if (!drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002054 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002055 ret = -1;
2056 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002057 }
2058
Chunyan Liu83d05212014-06-05 17:20:51 +08002059 if (encryption) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002060 error_report("Compression and encryption not supported at "
2061 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002062 ret = -1;
2063 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002064 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002065
Chunyan Liu83d05212014-06-05 17:20:51 +08002066 if (preallocation
2067 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002068 {
2069 error_report("Compression and preallocation not supported at "
2070 "the same time");
2071 ret = -1;
2072 goto out;
2073 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002074 }
2075
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002076 if (!skip_create) {
2077 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002078 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002079 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002080 error_reportf_err(local_err, "%s: error while converting %s: ",
2081 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002082 goto out;
bellardea2384d2004-08-01 21:59:26 +00002083 }
2084 }
ths3b46e622007-09-17 08:09:54 +00002085
Peter Lieven5a37b602013-10-24 12:07:06 +02002086 flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002087 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002088 if (ret < 0) {
2089 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002090 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002091 }
2092
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002093 /* XXX we should allow --image-opts to trigger use of
2094 * img_open() here, but then we have trouble with
2095 * the bdrv_create() call which takes different params.
2096 * Not critical right now, so fix can wait...
2097 */
Kevin Wolfce099542016-03-15 13:01:04 +01002098 out_blk = img_open_file(out_filename, out_fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002099 if (!out_blk) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002100 ret = -1;
2101 goto out;
2102 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002103 out_bs = blk_bs(out_blk);
bellardea2384d2004-08-01 21:59:26 +00002104
Eric Blake5def6b82016-06-23 16:37:19 -06002105 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002106 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2107 * as maximum. */
2108 bufsectors = MIN(32768,
Eric Blake5def6b82016-06-23 16:37:19 -06002109 MAX(bufsectors,
2110 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
Eric Blakeb9f78552016-06-23 16:37:21 -06002111 out_bs->bl.pdiscard_alignment >>
2112 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002113
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002114 if (skip_create) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05002115 int64_t output_sectors = blk_nb_sectors(out_blk);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002116 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002117 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002118 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002119 ret = -1;
2120 goto out;
Markus Armbruster43716fa2014-06-26 13:23:21 +02002121 } else if (output_sectors < total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002122 error_report("output file is smaller than input file");
2123 ret = -1;
2124 goto out;
2125 }
2126 }
2127
Peter Lieven24f833c2013-11-27 11:07:07 +01002128 cluster_sectors = 0;
2129 ret = bdrv_get_info(out_bs, &bdi);
2130 if (ret < 0) {
2131 if (compress) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002132 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002133 goto out;
2134 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002135 } else {
Fam Zheng85f49ca2014-05-06 21:08:43 +08002136 compress = compress || bdi.needs_compressed_writes;
Peter Lieven24f833c2013-11-27 11:07:07 +01002137 cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
2138 }
2139
Kevin Wolf690c7302015-03-19 13:33:32 +01002140 state = (ImgConvertState) {
2141 .src = blk,
2142 .src_sectors = bs_sectors,
2143 .src_num = bs_n,
2144 .total_sectors = total_sectors,
2145 .target = out_blk,
2146 .compressed = compress,
2147 .target_has_backing = (bool) out_baseimg,
2148 .min_sparse = min_sparse,
2149 .cluster_sectors = cluster_sectors,
2150 .buf_sectors = bufsectors,
2151 };
2152 ret = convert_do_copy(&state);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002153
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002154out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002155 if (!ret) {
2156 qemu_progress_print(100, 0);
2157 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002158 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002159 qemu_opts_del(opts);
2160 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002161 qemu_opts_del(sn_opts);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002162 blk_unref(out_blk);
Markus Armbruster9ba10c92014-10-07 13:59:08 +02002163 g_free(bs);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002164 if (blk) {
2165 for (bs_i = 0; bs_i < bs_n; bs_i++) {
2166 blk_unref(blk[bs_i]);
2167 }
2168 g_free(blk);
2169 }
Markus Armbrusterd739f1c2014-06-26 13:23:24 +02002170 g_free(bs_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002171fail_getopt:
2172 g_free(options);
2173
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002174 if (ret) {
2175 return 1;
2176 }
bellardea2384d2004-08-01 21:59:26 +00002177 return 0;
2178}
2179
bellard57d1a2b2004-08-03 21:15:11 +00002180
bellardfaea38e2006-08-05 21:31:00 +00002181static void dump_snapshots(BlockDriverState *bs)
2182{
2183 QEMUSnapshotInfo *sn_tab, *sn;
2184 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002185
2186 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2187 if (nb_sns <= 0)
2188 return;
2189 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002190 bdrv_snapshot_dump(fprintf, stdout, NULL);
2191 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002192 for(i = 0; i < nb_sns; i++) {
2193 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002194 bdrv_snapshot_dump(fprintf, stdout, sn);
2195 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002196 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002197 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002198}
2199
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002200static void dump_json_image_info_list(ImageInfoList *list)
2201{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002202 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002203 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002204 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002205
2206 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2207 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002208 str = qobject_to_json_pretty(obj);
2209 assert(str != NULL);
2210 printf("%s\n", qstring_get_str(str));
2211 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002212 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002213 QDECREF(str);
2214}
2215
Benoît Canetc054b3f2012-09-05 13:09:02 +02002216static void dump_json_image_info(ImageInfo *info)
2217{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002218 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002219 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002220 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002221
2222 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2223 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002224 str = qobject_to_json_pretty(obj);
2225 assert(str != NULL);
2226 printf("%s\n", qstring_get_str(str));
2227 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002228 visit_free(v);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002229 QDECREF(str);
2230}
2231
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002232static void dump_human_image_info_list(ImageInfoList *list)
2233{
2234 ImageInfoList *elem;
2235 bool delim = false;
2236
2237 for (elem = list; elem; elem = elem->next) {
2238 if (delim) {
2239 printf("\n");
2240 }
2241 delim = true;
2242
Wenchao Xia5b917042013-05-25 11:09:45 +08002243 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002244 }
2245}
2246
2247static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2248{
2249 return strcmp(a, b) == 0;
2250}
2251
2252/**
2253 * Open an image file chain and return an ImageInfoList
2254 *
2255 * @filename: topmost image filename
2256 * @fmt: topmost image format (may be NULL to autodetect)
2257 * @chain: true - enumerate entire backing file chain
2258 * false - only topmost image file
2259 *
2260 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2261 * image file. If there was an error a message will have been printed to
2262 * stderr.
2263 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002264static ImageInfoList *collect_image_info_list(bool image_opts,
2265 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002266 const char *fmt,
2267 bool chain)
2268{
2269 ImageInfoList *head = NULL;
2270 ImageInfoList **last = &head;
2271 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002272 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002273
2274 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2275
2276 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002277 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002278 BlockDriverState *bs;
2279 ImageInfo *info;
2280 ImageInfoList *elem;
2281
2282 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2283 error_report("Backing file '%s' creates an infinite loop.",
2284 filename);
2285 goto err;
2286 }
2287 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2288
Max Reitzefaa7c42016-03-16 19:54:38 +01002289 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01002290 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002291 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002292 goto err;
2293 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002294 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002295
Wenchao Xia43526ec2013-06-06 12:27:58 +08002296 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002297 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002298 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002299 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002300 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002301 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002302
2303 elem = g_new0(ImageInfoList, 1);
2304 elem->value = info;
2305 *last = elem;
2306 last = &elem->next;
2307
Markus Armbruster26f54e92014-10-07 13:59:04 +02002308 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002309
2310 filename = fmt = NULL;
2311 if (chain) {
2312 if (info->has_full_backing_filename) {
2313 filename = info->full_backing_filename;
2314 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002315 error_report("Could not determine absolute backing filename,"
2316 " but backing filename '%s' present",
2317 info->backing_filename);
2318 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002319 }
2320 if (info->has_backing_filename_format) {
2321 fmt = info->backing_filename_format;
2322 }
2323 }
2324 }
2325 g_hash_table_destroy(filenames);
2326 return head;
2327
2328err:
2329 qapi_free_ImageInfoList(head);
2330 g_hash_table_destroy(filenames);
2331 return NULL;
2332}
2333
Benoît Canetc054b3f2012-09-05 13:09:02 +02002334static int img_info(int argc, char **argv)
2335{
2336 int c;
2337 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002338 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002339 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002340 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002341 bool image_opts = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002342
bellardea2384d2004-08-01 21:59:26 +00002343 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002344 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002345 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002346 int option_index = 0;
2347 static const struct option long_options[] = {
2348 {"help", no_argument, 0, 'h'},
2349 {"format", required_argument, 0, 'f'},
2350 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002351 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002352 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002353 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002354 {0, 0, 0, 0}
2355 };
2356 c = getopt_long(argc, argv, "f:h",
2357 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002358 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002359 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002360 }
bellardea2384d2004-08-01 21:59:26 +00002361 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002362 case '?':
bellardea2384d2004-08-01 21:59:26 +00002363 case 'h':
2364 help();
2365 break;
2366 case 'f':
2367 fmt = optarg;
2368 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002369 case OPTION_OUTPUT:
2370 output = optarg;
2371 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002372 case OPTION_BACKING_CHAIN:
2373 chain = true;
2374 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002375 case OPTION_OBJECT: {
2376 QemuOpts *opts;
2377 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2378 optarg, true);
2379 if (!opts) {
2380 return 1;
2381 }
2382 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002383 case OPTION_IMAGE_OPTS:
2384 image_opts = true;
2385 break;
bellardea2384d2004-08-01 21:59:26 +00002386 }
2387 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002388 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002389 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002390 }
bellardea2384d2004-08-01 21:59:26 +00002391 filename = argv[optind++];
2392
Benoît Canetc054b3f2012-09-05 13:09:02 +02002393 if (output && !strcmp(output, "json")) {
2394 output_format = OFORMAT_JSON;
2395 } else if (output && !strcmp(output, "human")) {
2396 output_format = OFORMAT_HUMAN;
2397 } else if (output) {
2398 error_report("--output must be used with human or json as argument.");
2399 return 1;
2400 }
2401
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002402 if (qemu_opts_foreach(&qemu_object_opts,
2403 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002404 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002405 return 1;
2406 }
2407
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002408 list = collect_image_info_list(image_opts, filename, fmt, chain);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002409 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002410 return 1;
2411 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002412
Benoît Canetc054b3f2012-09-05 13:09:02 +02002413 switch (output_format) {
2414 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002415 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002416 break;
2417 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002418 if (chain) {
2419 dump_json_image_info_list(list);
2420 } else {
2421 dump_json_image_info(list->value);
2422 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002423 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002424 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002425
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002426 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002427 return 0;
2428}
2429
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002430static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2431 MapEntry *next)
2432{
2433 switch (output_format) {
2434 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002435 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002436 error_report("File contains external, encrypted or compressed clusters.");
2437 exit(1);
2438 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002439 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002440 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002441 e->start, e->length,
2442 e->has_offset ? e->offset : 0,
2443 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002444 }
2445 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2446 * Modify the flags here to allow more coalescing.
2447 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002448 if (next && (!next->data || next->zero)) {
2449 next->data = false;
2450 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002451 }
2452 break;
2453 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002454 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2455 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002456 (e->start == 0 ? "[" : ",\n"),
2457 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002458 e->zero ? "true" : "false",
2459 e->data ? "true" : "false");
2460 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002461 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002462 }
2463 putchar('}');
2464
2465 if (!next) {
2466 printf("]\n");
2467 }
2468 break;
2469 }
2470}
2471
2472static int get_block_status(BlockDriverState *bs, int64_t sector_num,
2473 int nb_sectors, MapEntry *e)
2474{
2475 int64_t ret;
2476 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002477 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002478 bool has_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002479
2480 /* As an optimization, we could cache the current range of unallocated
2481 * clusters in each file of the chain, and avoid querying the same
2482 * range repeatedly.
2483 */
2484
2485 depth = 0;
2486 for (;;) {
Fam Zheng67a0fd22016-01-26 11:58:48 +08002487 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors,
2488 &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002489 if (ret < 0) {
2490 return ret;
2491 }
2492 assert(nb_sectors);
2493 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2494 break;
2495 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002496 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002497 if (bs == NULL) {
2498 ret = 0;
2499 break;
2500 }
2501
2502 depth++;
2503 }
2504
John Snow28756452016-02-05 13:12:33 -05002505 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2506
2507 *e = (MapEntry) {
2508 .start = sector_num * BDRV_SECTOR_SIZE,
2509 .length = nb_sectors * BDRV_SECTOR_SIZE,
2510 .data = !!(ret & BDRV_BLOCK_DATA),
2511 .zero = !!(ret & BDRV_BLOCK_ZERO),
2512 .offset = ret & BDRV_BLOCK_OFFSET_MASK,
2513 .has_offset = has_offset,
2514 .depth = depth,
2515 .has_filename = file && has_offset,
2516 .filename = file && has_offset ? file->filename : NULL,
2517 };
2518
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002519 return 0;
2520}
2521
Fam Zheng16b0d552016-01-26 11:59:02 +08002522static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2523{
2524 if (curr->length == 0) {
2525 return false;
2526 }
2527 if (curr->zero != next->zero ||
2528 curr->data != next->data ||
2529 curr->depth != next->depth ||
2530 curr->has_filename != next->has_filename ||
2531 curr->has_offset != next->has_offset) {
2532 return false;
2533 }
2534 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2535 return false;
2536 }
2537 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2538 return false;
2539 }
2540 return true;
2541}
2542
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002543static int img_map(int argc, char **argv)
2544{
2545 int c;
2546 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002547 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002548 BlockDriverState *bs;
2549 const char *filename, *fmt, *output;
2550 int64_t length;
2551 MapEntry curr = { .length = 0 }, next;
2552 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002553 bool image_opts = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002554
2555 fmt = NULL;
2556 output = NULL;
2557 for (;;) {
2558 int option_index = 0;
2559 static const struct option long_options[] = {
2560 {"help", no_argument, 0, 'h'},
2561 {"format", required_argument, 0, 'f'},
2562 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002563 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002564 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002565 {0, 0, 0, 0}
2566 };
2567 c = getopt_long(argc, argv, "f:h",
2568 long_options, &option_index);
2569 if (c == -1) {
2570 break;
2571 }
2572 switch (c) {
2573 case '?':
2574 case 'h':
2575 help();
2576 break;
2577 case 'f':
2578 fmt = optarg;
2579 break;
2580 case OPTION_OUTPUT:
2581 output = optarg;
2582 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002583 case OPTION_OBJECT: {
2584 QemuOpts *opts;
2585 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2586 optarg, true);
2587 if (!opts) {
2588 return 1;
2589 }
2590 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002591 case OPTION_IMAGE_OPTS:
2592 image_opts = true;
2593 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002594 }
2595 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002596 if (optind != argc - 1) {
2597 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002598 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002599 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002600
2601 if (output && !strcmp(output, "json")) {
2602 output_format = OFORMAT_JSON;
2603 } else if (output && !strcmp(output, "human")) {
2604 output_format = OFORMAT_HUMAN;
2605 } else if (output) {
2606 error_report("--output must be used with human or json as argument.");
2607 return 1;
2608 }
2609
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002610 if (qemu_opts_foreach(&qemu_object_opts,
2611 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002612 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002613 return 1;
2614 }
2615
Kevin Wolfce099542016-03-15 13:01:04 +01002616 blk = img_open(image_opts, filename, fmt, 0, false, false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002617 if (!blk) {
2618 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002619 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002620 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002621
2622 if (output_format == OFORMAT_HUMAN) {
2623 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2624 }
2625
Max Reitzf1d3cd72015-02-05 13:58:18 -05002626 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002627 while (curr.start + curr.length < length) {
2628 int64_t nsectors_left;
2629 int64_t sector_num;
2630 int n;
2631
2632 sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
2633
2634 /* Probe up to 1 GiB at a time. */
2635 nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
2636 n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
2637 ret = get_block_status(bs, sector_num, n, &next);
2638
2639 if (ret < 0) {
2640 error_report("Could not read file metadata: %s", strerror(-ret));
2641 goto out;
2642 }
2643
Fam Zheng16b0d552016-01-26 11:59:02 +08002644 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002645 curr.length += next.length;
2646 continue;
2647 }
2648
2649 if (curr.length > 0) {
2650 dump_map_entry(output_format, &curr, &next);
2651 }
2652 curr = next;
2653 }
2654
2655 dump_map_entry(output_format, &curr, NULL);
2656
2657out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002658 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002659 return ret < 0;
2660}
2661
aliguorif7b4a942009-01-07 17:40:15 +00002662#define SNAPSHOT_LIST 1
2663#define SNAPSHOT_CREATE 2
2664#define SNAPSHOT_APPLY 3
2665#define SNAPSHOT_DELETE 4
2666
Stuart Brady153859b2009-06-07 00:42:17 +01002667static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002668{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002669 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002670 BlockDriverState *bs;
2671 QEMUSnapshotInfo sn;
2672 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002673 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002674 int action = 0;
2675 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002676 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002677 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002678 bool image_opts = false;
aliguorif7b4a942009-01-07 17:40:15 +00002679
Kevin Wolfce099542016-03-15 13:01:04 +01002680 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002681 /* Parse commandline parameters */
2682 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002683 static const struct option long_options[] = {
2684 {"help", no_argument, 0, 'h'},
2685 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002686 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002687 {0, 0, 0, 0}
2688 };
2689 c = getopt_long(argc, argv, "la:c:d:hq",
2690 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002691 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002692 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002693 }
aliguorif7b4a942009-01-07 17:40:15 +00002694 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002695 case '?':
aliguorif7b4a942009-01-07 17:40:15 +00002696 case 'h':
2697 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002698 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002699 case 'l':
2700 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002701 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002702 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002703 }
2704 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002705 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002706 break;
2707 case 'a':
2708 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002709 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002710 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002711 }
2712 action = SNAPSHOT_APPLY;
2713 snapshot_name = optarg;
2714 break;
2715 case 'c':
2716 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002717 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002718 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002719 }
2720 action = SNAPSHOT_CREATE;
2721 snapshot_name = optarg;
2722 break;
2723 case 'd':
2724 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002725 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002726 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002727 }
2728 action = SNAPSHOT_DELETE;
2729 snapshot_name = optarg;
2730 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002731 case 'q':
2732 quiet = true;
2733 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002734 case OPTION_OBJECT: {
2735 QemuOpts *opts;
2736 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2737 optarg, true);
2738 if (!opts) {
2739 return 1;
2740 }
2741 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002742 case OPTION_IMAGE_OPTS:
2743 image_opts = true;
2744 break;
aliguorif7b4a942009-01-07 17:40:15 +00002745 }
2746 }
2747
Kevin Wolffc11eb22013-08-05 10:53:04 +02002748 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002749 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002750 }
aliguorif7b4a942009-01-07 17:40:15 +00002751 filename = argv[optind++];
2752
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002753 if (qemu_opts_foreach(&qemu_object_opts,
2754 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002755 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002756 return 1;
2757 }
2758
aliguorif7b4a942009-01-07 17:40:15 +00002759 /* Open the image */
Kevin Wolfce099542016-03-15 13:01:04 +01002760 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002761 if (!blk) {
2762 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002763 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002764 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002765
2766 /* Perform the requested action */
2767 switch(action) {
2768 case SNAPSHOT_LIST:
2769 dump_snapshots(bs);
2770 break;
2771
2772 case SNAPSHOT_CREATE:
2773 memset(&sn, 0, sizeof(sn));
2774 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2775
2776 qemu_gettimeofday(&tv);
2777 sn.date_sec = tv.tv_sec;
2778 sn.date_nsec = tv.tv_usec * 1000;
2779
2780 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002781 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002782 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002783 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002784 }
aliguorif7b4a942009-01-07 17:40:15 +00002785 break;
2786
2787 case SNAPSHOT_APPLY:
2788 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002789 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002790 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002791 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002792 }
aliguorif7b4a942009-01-07 17:40:15 +00002793 break;
2794
2795 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002796 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002797 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002798 error_reportf_err(err, "Could not delete snapshot '%s': ",
2799 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002800 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002801 }
aliguorif7b4a942009-01-07 17:40:15 +00002802 break;
2803 }
2804
2805 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02002806 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002807 if (ret) {
2808 return 1;
2809 }
Stuart Brady153859b2009-06-07 00:42:17 +01002810 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002811}
2812
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002813static int img_rebase(int argc, char **argv)
2814{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002815 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01002816 uint8_t *buf_old = NULL;
2817 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05002818 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002819 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02002820 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
2821 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01002822 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002823 int unsafe = 0;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002824 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002825 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002826 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002827 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002828
2829 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002830 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002831 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02002832 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002833 out_baseimg = NULL;
2834 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002835 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002836 static const struct option long_options[] = {
2837 {"help", no_argument, 0, 'h'},
2838 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002839 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002840 {0, 0, 0, 0}
2841 };
2842 c = getopt_long(argc, argv, "hf:F:b:upt:T:q",
2843 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002844 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002845 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002846 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002847 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01002848 case '?':
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002849 case 'h':
2850 help();
2851 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01002852 case 'f':
2853 fmt = optarg;
2854 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002855 case 'F':
2856 out_basefmt = optarg;
2857 break;
2858 case 'b':
2859 out_baseimg = optarg;
2860 break;
2861 case 'u':
2862 unsafe = 1;
2863 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002864 case 'p':
2865 progress = 1;
2866 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002867 case 't':
2868 cache = optarg;
2869 break;
Max Reitz40055952014-07-22 22:58:42 +02002870 case 'T':
2871 src_cache = optarg;
2872 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002873 case 'q':
2874 quiet = true;
2875 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002876 case OPTION_OBJECT: {
2877 QemuOpts *opts;
2878 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2879 optarg, true);
2880 if (!opts) {
2881 return 1;
2882 }
2883 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002884 case OPTION_IMAGE_OPTS:
2885 image_opts = true;
2886 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002887 }
2888 }
2889
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002890 if (quiet) {
2891 progress = 0;
2892 }
2893
Fam Zhengac1307a2014-04-22 13:36:11 +08002894 if (optind != argc - 1) {
2895 error_exit("Expecting one image file name");
2896 }
2897 if (!unsafe && !out_baseimg) {
2898 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002899 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002900 filename = argv[optind++];
2901
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002902 if (qemu_opts_foreach(&qemu_object_opts,
2903 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002904 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002905 return 1;
2906 }
2907
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002908 qemu_progress_init(progress, 2.0);
2909 qemu_progress_print(0, 100);
2910
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002911 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01002912 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002913 if (ret < 0) {
2914 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002915 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002916 }
2917
Kevin Wolfce099542016-03-15 13:01:04 +01002918 src_flags = 0;
2919 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02002920 if (ret < 0) {
2921 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002922 goto out;
Max Reitz40055952014-07-22 22:58:42 +02002923 }
2924
Kevin Wolfce099542016-03-15 13:01:04 +01002925 /* The source files are opened read-only, don't care about WCE */
2926 assert((src_flags & BDRV_O_RDWR) == 0);
2927 (void) src_writethrough;
2928
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002929 /*
2930 * Open the images.
2931 *
2932 * Ignore the old backing file for unsafe rebase in case we want to correct
2933 * the reference to a renamed or moved backing file.
2934 */
Kevin Wolfce099542016-03-15 13:01:04 +01002935 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002936 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002937 ret = -1;
2938 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002939 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002940 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002941
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002942 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05002943 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002944 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002945 ret = -1;
2946 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002947 }
2948 }
2949
2950 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01002951 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05002952 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05002953 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002954
Max Reitz644483d2015-02-05 13:58:17 -05002955 if (bs->backing_format[0] != '\0') {
2956 options = qdict_new();
2957 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2958 }
2959
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002960 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01002961 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002962 options, src_flags, &local_err);
2963 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002964 error_reportf_err(local_err,
2965 "Could not open old backing file '%s': ",
2966 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002967 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002968 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002969 }
Max Reitz644483d2015-02-05 13:58:17 -05002970
Alex Bligha6166732012-10-16 13:46:18 +01002971 if (out_baseimg[0]) {
Max Reitz644483d2015-02-05 13:58:17 -05002972 if (out_basefmt) {
2973 options = qdict_new();
2974 qdict_put(options, "driver", qstring_from_str(out_basefmt));
2975 } else {
2976 options = NULL;
2977 }
2978
Max Reitzefaa7c42016-03-16 19:54:38 +01002979 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05002980 options, src_flags, &local_err);
2981 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002982 error_reportf_err(local_err,
2983 "Could not open new backing file '%s': ",
2984 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08002985 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01002986 goto out;
2987 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01002988 }
2989 }
2990
2991 /*
2992 * Check each unallocated cluster in the COW file. If it is unallocated,
2993 * accesses go to the backing file. We must therefore compare this cluster
2994 * in the old and new backing file, and if they differ we need to copy it
2995 * from the old backing file into the COW file.
2996 *
2997 * If qemu-img crashes during this step, no harm is done. The content of
2998 * the image is the same as the original one at any time.
2999 */
3000 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003001 int64_t num_sectors;
3002 int64_t old_backing_num_sectors;
3003 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003004 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003005 int n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003006 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003007
Max Reitzf1d3cd72015-02-05 13:58:18 -05003008 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3009 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003010
Max Reitzf1d3cd72015-02-05 13:58:18 -05003011 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003012 if (num_sectors < 0) {
3013 error_report("Could not get size of '%s': %s",
3014 filename, strerror(-num_sectors));
3015 ret = -1;
3016 goto out;
3017 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003018 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003019 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003020 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003021
3022 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3023 error_report("Could not get size of '%s': %s",
3024 backing_name, strerror(-old_backing_num_sectors));
3025 ret = -1;
3026 goto out;
3027 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003028 if (blk_new_backing) {
3029 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003030 if (new_backing_num_sectors < 0) {
3031 error_report("Could not get size of '%s': %s",
3032 out_baseimg, strerror(-new_backing_num_sectors));
3033 ret = -1;
3034 goto out;
3035 }
Alex Bligha6166732012-10-16 13:46:18 +01003036 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003037
Kevin Wolf1f710492012-10-12 14:29:18 +02003038 if (num_sectors != 0) {
3039 local_progress = (float)100 /
3040 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3041 }
3042
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003043 for (sector = 0; sector < num_sectors; sector += n) {
3044
3045 /* How many sectors can we handle with the next read? */
3046 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3047 n = (IO_BUF_SIZE / 512);
3048 } else {
3049 n = num_sectors - sector;
3050 }
3051
3052 /* If the cluster is allocated, we don't need to take action */
Kevin Wolfcc60e322010-04-29 14:47:48 +02003053 ret = bdrv_is_allocated(bs, sector, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003054 if (ret < 0) {
3055 error_report("error while reading image metadata: %s",
3056 strerror(-ret));
3057 goto out;
3058 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003059 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003060 continue;
3061 }
3062
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003063 /*
3064 * Read old and new backing file and take into consideration that
3065 * backing files may be smaller than the COW image.
3066 */
3067 if (sector >= old_backing_num_sectors) {
3068 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3069 } else {
3070 if (sector + n > old_backing_num_sectors) {
3071 n = old_backing_num_sectors - sector;
3072 }
3073
Eric Blake91669202016-05-06 10:26:43 -06003074 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3075 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003076 if (ret < 0) {
3077 error_report("error while reading from old backing file");
3078 goto out;
3079 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003080 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003081
Max Reitzf1d3cd72015-02-05 13:58:18 -05003082 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003083 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3084 } else {
3085 if (sector + n > new_backing_num_sectors) {
3086 n = new_backing_num_sectors - sector;
3087 }
3088
Eric Blake91669202016-05-06 10:26:43 -06003089 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3090 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003091 if (ret < 0) {
3092 error_report("error while reading from new backing file");
3093 goto out;
3094 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003095 }
3096
3097 /* If they differ, we need to write to the COW file */
3098 uint64_t written = 0;
3099
3100 while (written < n) {
3101 int pnum;
3102
3103 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003104 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003105 {
Eric Blake91669202016-05-06 10:26:43 -06003106 ret = blk_pwrite(blk,
3107 (sector + written) << BDRV_SECTOR_BITS,
3108 buf_old + written * 512,
3109 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003110 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003111 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003112 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003113 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003114 }
3115 }
3116
3117 written += pnum;
3118 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003119 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003120 }
3121 }
3122
3123 /*
3124 * Change the backing file. All clusters that are different from the old
3125 * backing file are overwritten in the COW file now, so the visible content
3126 * doesn't change when we switch the backing file.
3127 */
Alex Bligha6166732012-10-16 13:46:18 +01003128 if (out_baseimg && *out_baseimg) {
3129 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3130 } else {
3131 ret = bdrv_change_backing_file(bs, NULL, NULL);
3132 }
3133
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003134 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003135 error_report("Could not change the backing file to '%s': No "
3136 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003137 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003138 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003139 out_baseimg, strerror(-ret));
3140 }
3141
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003142 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003143 /*
3144 * TODO At this point it is possible to check if any clusters that are
3145 * allocated in the COW file are the same in the backing file. If so, they
3146 * could be dropped from the COW file. Don't do this before switching the
3147 * backing file, in case of a crash this would lead to corruption.
3148 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003149out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003150 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003151 /* Cleanup */
3152 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003153 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003154 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003155 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003156 qemu_vfree(buf_old);
3157 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003158
Markus Armbruster26f54e92014-10-07 13:59:04 +02003159 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003160 if (ret) {
3161 return 1;
3162 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163 return 0;
3164}
3165
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003166static int img_resize(int argc, char **argv)
3167{
Markus Armbruster6750e792015-02-12 17:43:08 +01003168 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003169 int c, ret, relative;
3170 const char *filename, *fmt, *size;
3171 int64_t n, total_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003172 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003173 BlockBackend *blk = NULL;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003174 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003175
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003176 static QemuOptsList resize_options = {
3177 .name = "resize_options",
3178 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3179 .desc = {
3180 {
3181 .name = BLOCK_OPT_SIZE,
3182 .type = QEMU_OPT_SIZE,
3183 .help = "Virtual disk size"
3184 }, {
3185 /* end of list */
3186 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003187 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003188 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003189 bool image_opts = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003190
Kevin Wolfe80fec72011-04-29 10:58:12 +02003191 /* Remove size from argv manually so that negative numbers are not treated
3192 * as options by getopt. */
3193 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003194 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003195 return 1;
3196 }
3197
3198 size = argv[--argc];
3199
3200 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003201 fmt = NULL;
3202 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003203 static const struct option long_options[] = {
3204 {"help", no_argument, 0, 'h'},
3205 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003206 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003207 {0, 0, 0, 0}
3208 };
3209 c = getopt_long(argc, argv, "f:hq",
3210 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003211 if (c == -1) {
3212 break;
3213 }
3214 switch(c) {
Jes Sorensenef873942010-12-06 15:25:40 +01003215 case '?':
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003216 case 'h':
3217 help();
3218 break;
3219 case 'f':
3220 fmt = optarg;
3221 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003222 case 'q':
3223 quiet = true;
3224 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003225 case OPTION_OBJECT: {
3226 QemuOpts *opts;
3227 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3228 optarg, true);
3229 if (!opts) {
3230 return 1;
3231 }
3232 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003233 case OPTION_IMAGE_OPTS:
3234 image_opts = true;
3235 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003236 }
3237 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003238 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003239 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003240 }
3241 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003242
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003243 if (qemu_opts_foreach(&qemu_object_opts,
3244 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003245 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003246 return 1;
3247 }
3248
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003249 /* Choose grow, shrink, or absolute resize mode */
3250 switch (size[0]) {
3251 case '+':
3252 relative = 1;
3253 size++;
3254 break;
3255 case '-':
3256 relative = -1;
3257 size++;
3258 break;
3259 default:
3260 relative = 0;
3261 break;
3262 }
3263
3264 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003265 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003266 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003267 if (err) {
3268 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003269 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003270 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003271 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003272 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003273 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3274 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003275
Max Reitzefaa7c42016-03-16 19:54:38 +01003276 blk = img_open(image_opts, filename, fmt,
Kevin Wolfce099542016-03-15 13:01:04 +01003277 BDRV_O_RDWR, false, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003278 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003279 ret = -1;
3280 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003281 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003282
3283 if (relative) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05003284 total_size = blk_getlength(blk) + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003285 } else {
3286 total_size = n;
3287 }
3288 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003289 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003290 ret = -1;
3291 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003292 }
3293
Max Reitzf1d3cd72015-02-05 13:58:18 -05003294 ret = blk_truncate(blk, total_size);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003295 switch (ret) {
3296 case 0:
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003297 qprintf(quiet, "Image resized.\n");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003298 break;
3299 case -ENOTSUP:
Kevin Wolf259b2172012-03-06 12:44:45 +01003300 error_report("This image does not support resize");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003301 break;
3302 case -EACCES:
Jes Sorensen15654a62010-12-16 14:31:53 +01003303 error_report("Image is read-only");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003304 break;
3305 default:
Max Reitzbcf23482016-06-15 17:36:29 +02003306 error_report("Error resizing image: %s", strerror(-ret));
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003307 break;
3308 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003309out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003310 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003311 if (ret) {
3312 return 1;
3313 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003314 return 0;
3315}
3316
Max Reitz76a3a342014-10-27 11:12:51 +01003317static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003318 int64_t offset, int64_t total_work_size,
3319 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003320{
3321 qemu_progress_print(100.f * offset / total_work_size, 0);
3322}
3323
Max Reitz6f176b42013-09-03 10:09:50 +02003324static int img_amend(int argc, char **argv)
3325{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003326 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003327 int c, ret = 0;
3328 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003329 QemuOptsList *create_opts = NULL;
3330 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003331 const char *fmt = NULL, *filename, *cache;
3332 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003333 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003334 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003335 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003336 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003337 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003338
Max Reitzbd39e6e2014-07-22 22:58:43 +02003339 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003340 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003341 static const struct option long_options[] = {
3342 {"help", no_argument, 0, 'h'},
3343 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003344 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003345 {0, 0, 0, 0}
3346 };
3347 c = getopt_long(argc, argv, "ho:f:t:pq",
3348 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003349 if (c == -1) {
3350 break;
3351 }
3352
3353 switch (c) {
3354 case 'h':
3355 case '?':
3356 help();
3357 break;
3358 case 'o':
Kevin Wolf626f84f2014-02-21 16:24:06 +01003359 if (!is_valid_option_list(optarg)) {
3360 error_report("Invalid option list: %s", optarg);
3361 ret = -1;
Max Reitze814dff2015-08-20 16:00:38 -07003362 goto out_no_progress;
Kevin Wolf626f84f2014-02-21 16:24:06 +01003363 }
3364 if (!options) {
3365 options = g_strdup(optarg);
3366 } else {
3367 char *old_options = options;
3368 options = g_strdup_printf("%s,%s", options, optarg);
3369 g_free(old_options);
3370 }
Max Reitz6f176b42013-09-03 10:09:50 +02003371 break;
3372 case 'f':
3373 fmt = optarg;
3374 break;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003375 case 't':
3376 cache = optarg;
3377 break;
Max Reitz76a3a342014-10-27 11:12:51 +01003378 case 'p':
3379 progress = true;
3380 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003381 case 'q':
3382 quiet = true;
3383 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003384 case OPTION_OBJECT:
3385 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3386 optarg, true);
3387 if (!opts) {
3388 ret = -1;
3389 goto out_no_progress;
3390 }
3391 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003392 case OPTION_IMAGE_OPTS:
3393 image_opts = true;
3394 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003395 }
3396 }
3397
Max Reitz6f176b42013-09-03 10:09:50 +02003398 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003399 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003400 }
3401
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003402 if (qemu_opts_foreach(&qemu_object_opts,
3403 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003404 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003405 ret = -1;
3406 goto out_no_progress;
3407 }
3408
Max Reitz76a3a342014-10-27 11:12:51 +01003409 if (quiet) {
3410 progress = false;
3411 }
3412 qemu_progress_init(progress, 1.0);
3413
Kevin Wolfa283cb62014-02-21 16:24:07 +01003414 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3415 if (fmt && has_help_option(options)) {
3416 /* If a format is explicitly specified (and possibly no filename is
3417 * given), print option help here */
3418 ret = print_block_option_help(filename, fmt);
3419 goto out;
3420 }
3421
3422 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003423 error_report("Expecting one image file name");
3424 ret = -1;
3425 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003426 }
Max Reitz6f176b42013-09-03 10:09:50 +02003427
Kevin Wolfce099542016-03-15 13:01:04 +01003428 flags = BDRV_O_RDWR;
3429 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003430 if (ret < 0) {
3431 error_report("Invalid cache option: %s", cache);
3432 goto out;
3433 }
3434
Kevin Wolfce099542016-03-15 13:01:04 +01003435 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003436 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003437 ret = -1;
3438 goto out;
3439 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003440 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003441
3442 fmt = bs->drv->format_name;
3443
Kevin Wolf626f84f2014-02-21 16:24:06 +01003444 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003445 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003446 ret = print_block_option_help(filename, fmt);
3447 goto out;
3448 }
3449
Max Reitzb2439d22014-12-02 18:32:47 +01003450 if (!bs->drv->create_opts) {
3451 error_report("Format driver '%s' does not support any options to amend",
3452 fmt);
3453 ret = -1;
3454 goto out;
3455 }
3456
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003457 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003458 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003459 qemu_opts_do_parse(opts, options, NULL, &err);
3460 if (err) {
3461 error_report_err(err);
3462 ret = -1;
3463 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003464 }
3465
Max Reitz76a3a342014-10-27 11:12:51 +01003466 /* In case the driver does not call amend_status_cb() */
3467 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003468 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003469 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003470 if (ret < 0) {
3471 error_report("Error while amending options: %s", strerror(-ret));
3472 goto out;
3473 }
3474
3475out:
Max Reitz76a3a342014-10-27 11:12:51 +01003476 qemu_progress_end();
3477
Max Reitze814dff2015-08-20 16:00:38 -07003478out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003479 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003480 qemu_opts_del(opts);
3481 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003482 g_free(options);
3483
Max Reitz6f176b42013-09-03 10:09:50 +02003484 if (ret) {
3485 return 1;
3486 }
3487 return 0;
3488}
3489
Kevin Wolfb6133b82014-08-05 14:17:13 +02003490typedef struct BenchData {
3491 BlockBackend *blk;
3492 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003493 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003494 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003495 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003496 int nrreq;
3497 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003498 int flush_interval;
3499 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003500 uint8_t *buf;
3501 QEMUIOVector *qiov;
3502
3503 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003504 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003505 uint64_t offset;
3506} BenchData;
3507
Kevin Wolf55d539c2016-06-03 13:59:41 +02003508static void bench_undrained_flush_cb(void *opaque, int ret)
3509{
3510 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003511 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003512 exit(EXIT_FAILURE);
3513 }
3514}
3515
Kevin Wolfb6133b82014-08-05 14:17:13 +02003516static void bench_cb(void *opaque, int ret)
3517{
3518 BenchData *b = opaque;
3519 BlockAIOCB *acb;
3520
3521 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003522 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003523 exit(EXIT_FAILURE);
3524 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003525
3526 if (b->in_flush) {
3527 /* Just finished a flush with drained queue: Start next requests */
3528 assert(b->in_flight == 0);
3529 b->in_flush = false;
3530 } else if (b->in_flight > 0) {
3531 int remaining = b->n - b->in_flight;
3532
Kevin Wolfb6133b82014-08-05 14:17:13 +02003533 b->n--;
3534 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003535
3536 /* Time for flush? Drain queue if requested, then flush */
3537 if (b->flush_interval && remaining % b->flush_interval == 0) {
3538 if (!b->in_flight || !b->drain_on_flush) {
3539 BlockCompletionFunc *cb;
3540
3541 if (b->drain_on_flush) {
3542 b->in_flush = true;
3543 cb = bench_cb;
3544 } else {
3545 cb = bench_undrained_flush_cb;
3546 }
3547
3548 acb = blk_aio_flush(b->blk, cb, b);
3549 if (!acb) {
3550 error_report("Failed to issue flush request");
3551 exit(EXIT_FAILURE);
3552 }
3553 }
3554 if (b->drain_on_flush) {
3555 return;
3556 }
3557 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003558 }
3559
3560 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003561 int64_t offset = b->offset;
3562 /* blk_aio_* might look for completed I/Os and kick bench_cb
3563 * again, so make sure this operation is counted by in_flight
3564 * and b->offset is ready for the next submission.
3565 */
3566 b->in_flight++;
3567 b->offset += b->step;
3568 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003569 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003570 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003571 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003572 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003573 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003574 if (!acb) {
3575 error_report("Failed to issue request");
3576 exit(EXIT_FAILURE);
3577 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003578 }
3579}
3580
3581static int img_bench(int argc, char **argv)
3582{
3583 int c, ret = 0;
3584 const char *fmt = NULL, *filename;
3585 bool quiet = false;
3586 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003587 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003588 int count = 75000;
3589 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003590 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003591 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003592 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003593 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003594 int flush_interval = 0;
3595 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003596 int64_t image_size;
3597 BlockBackend *blk = NULL;
3598 BenchData data = {};
3599 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003600 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003601 struct timeval t1, t2;
3602 int i;
3603
3604 for (;;) {
3605 static const struct option long_options[] = {
3606 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003607 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003608 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003609 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003610 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003611 {0, 0, 0, 0}
3612 };
Kevin Wolf83de9be2015-07-13 13:13:17 +02003613 c = getopt_long(argc, argv, "hc:d:f:no:qs:S:t:w", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003614 if (c == -1) {
3615 break;
3616 }
3617
3618 switch (c) {
3619 case 'h':
3620 case '?':
3621 help();
3622 break;
3623 case 'c':
3624 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003625 unsigned long res;
3626
3627 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003628 error_report("Invalid request count specified");
3629 return 1;
3630 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003631 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003632 break;
3633 }
3634 case 'd':
3635 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003636 unsigned long res;
3637
3638 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003639 error_report("Invalid queue depth specified");
3640 return 1;
3641 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003642 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003643 break;
3644 }
3645 case 'f':
3646 fmt = optarg;
3647 break;
3648 case 'n':
3649 flags |= BDRV_O_NATIVE_AIO;
3650 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003651 case 'o':
3652 {
3653 char *end;
3654 errno = 0;
Markus Armbruster466dea12017-02-21 21:14:00 +01003655 offset = qemu_strtosz(optarg, &end);
Kevin Wolfd3199a32015-07-10 18:09:18 +02003656 if (offset < 0|| *end) {
3657 error_report("Invalid offset specified");
3658 return 1;
3659 }
3660 break;
3661 }
3662 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003663 case 'q':
3664 quiet = true;
3665 break;
3666 case 's':
3667 {
3668 int64_t sval;
3669 char *end;
3670
Markus Armbruster466dea12017-02-21 21:14:00 +01003671 sval = qemu_strtosz(optarg, &end);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003672 if (sval < 0 || sval > INT_MAX || *end) {
3673 error_report("Invalid buffer size specified");
3674 return 1;
3675 }
3676
3677 bufsize = sval;
3678 break;
3679 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003680 case 'S':
3681 {
3682 int64_t sval;
3683 char *end;
3684
Markus Armbruster466dea12017-02-21 21:14:00 +01003685 sval = qemu_strtosz(optarg, &end);
Kevin Wolf83de9be2015-07-13 13:13:17 +02003686 if (sval < 0 || sval > INT_MAX || *end) {
3687 error_report("Invalid step size specified");
3688 return 1;
3689 }
3690
3691 step = sval;
3692 break;
3693 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003694 case 't':
3695 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3696 if (ret < 0) {
3697 error_report("Invalid cache mode");
3698 ret = -1;
3699 goto out;
3700 }
3701 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003702 case 'w':
3703 flags |= BDRV_O_RDWR;
3704 is_write = true;
3705 break;
3706 case OPTION_PATTERN:
3707 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003708 unsigned long res;
3709
3710 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003711 error_report("Invalid pattern byte specified");
3712 return 1;
3713 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003714 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003715 break;
3716 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003717 case OPTION_FLUSH_INTERVAL:
3718 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003719 unsigned long res;
3720
3721 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003722 error_report("Invalid flush interval specified");
3723 return 1;
3724 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003725 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003726 break;
3727 }
3728 case OPTION_NO_DRAIN:
3729 drain_on_flush = false;
3730 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003731 case OPTION_IMAGE_OPTS:
3732 image_opts = true;
3733 break;
3734 }
3735 }
3736
3737 if (optind != argc - 1) {
3738 error_exit("Expecting one image file name");
3739 }
3740 filename = argv[argc - 1];
3741
Kevin Wolf55d539c2016-06-03 13:59:41 +02003742 if (!is_write && flush_interval) {
3743 error_report("--flush-interval is only available in write tests");
3744 ret = -1;
3745 goto out;
3746 }
3747 if (flush_interval && flush_interval < depth) {
3748 error_report("Flush interval can't be smaller than depth");
3749 ret = -1;
3750 goto out;
3751 }
3752
Kevin Wolfb6133b82014-08-05 14:17:13 +02003753 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);
3754 if (!blk) {
3755 ret = -1;
3756 goto out;
3757 }
3758
3759 image_size = blk_getlength(blk);
3760 if (image_size < 0) {
3761 ret = image_size;
3762 goto out;
3763 }
3764
3765 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003766 .blk = blk,
3767 .image_size = image_size,
3768 .bufsize = bufsize,
3769 .step = step ?: bufsize,
3770 .nrreq = depth,
3771 .n = count,
3772 .offset = offset,
3773 .write = is_write,
3774 .flush_interval = flush_interval,
3775 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02003776 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02003777 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02003778 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02003779 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02003780 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02003781 if (flush_interval) {
3782 printf("Sending flush every %d requests\n", flush_interval);
3783 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003784
3785 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003786 memset(data.buf, pattern, data.nrreq * data.bufsize);
3787
Kevin Wolfb6133b82014-08-05 14:17:13 +02003788 data.qiov = g_new(QEMUIOVector, data.nrreq);
3789 for (i = 0; i < data.nrreq; i++) {
3790 qemu_iovec_init(&data.qiov[i], 1);
3791 qemu_iovec_add(&data.qiov[i],
3792 data.buf + i * data.bufsize, data.bufsize);
3793 }
3794
3795 gettimeofday(&t1, NULL);
3796 bench_cb(&data, 0);
3797
3798 while (data.n > 0) {
3799 main_loop_wait(false);
3800 }
3801 gettimeofday(&t2, NULL);
3802
3803 printf("Run completed in %3.3f seconds.\n",
3804 (t2.tv_sec - t1.tv_sec)
3805 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
3806
3807out:
3808 qemu_vfree(data.buf);
3809 blk_unref(blk);
3810
3811 if (ret) {
3812 return 1;
3813 }
3814 return 0;
3815}
3816
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003817#define C_BS 01
3818#define C_COUNT 02
3819#define C_IF 04
3820#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02003821#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003822
3823struct DdInfo {
3824 unsigned int flags;
3825 int64_t count;
3826};
3827
3828struct DdIo {
3829 int bsz; /* Block size */
3830 char *filename;
3831 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02003832 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003833};
3834
3835struct DdOpts {
3836 const char *name;
3837 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
3838 unsigned int flag;
3839};
3840
3841static int img_dd_bs(const char *arg,
3842 struct DdIo *in, struct DdIo *out,
3843 struct DdInfo *dd)
3844{
3845 char *end;
3846 int64_t res;
3847
Markus Armbruster466dea12017-02-21 21:14:00 +01003848 res = qemu_strtosz(arg, &end);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003849
3850 if (res <= 0 || res > INT_MAX || *end) {
3851 error_report("invalid number: '%s'", arg);
3852 return 1;
3853 }
3854 in->bsz = out->bsz = res;
3855
3856 return 0;
3857}
3858
3859static int img_dd_count(const char *arg,
3860 struct DdIo *in, struct DdIo *out,
3861 struct DdInfo *dd)
3862{
3863 char *end;
3864
Markus Armbruster466dea12017-02-21 21:14:00 +01003865 dd->count = qemu_strtosz(arg, &end);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003866
3867 if (dd->count < 0 || *end) {
3868 error_report("invalid number: '%s'", arg);
3869 return 1;
3870 }
3871
3872 return 0;
3873}
3874
3875static int img_dd_if(const char *arg,
3876 struct DdIo *in, struct DdIo *out,
3877 struct DdInfo *dd)
3878{
3879 in->filename = g_strdup(arg);
3880
3881 return 0;
3882}
3883
3884static int img_dd_of(const char *arg,
3885 struct DdIo *in, struct DdIo *out,
3886 struct DdInfo *dd)
3887{
3888 out->filename = g_strdup(arg);
3889
3890 return 0;
3891}
3892
Reda Sallahif7c15532016-08-10 16:16:09 +02003893static int img_dd_skip(const char *arg,
3894 struct DdIo *in, struct DdIo *out,
3895 struct DdInfo *dd)
3896{
3897 char *end;
3898
Markus Armbruster466dea12017-02-21 21:14:00 +01003899 in->offset = qemu_strtosz(arg, &end);
Reda Sallahif7c15532016-08-10 16:16:09 +02003900
3901 if (in->offset < 0 || *end) {
3902 error_report("invalid number: '%s'", arg);
3903 return 1;
3904 }
3905
3906 return 0;
3907}
3908
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003909static int img_dd(int argc, char **argv)
3910{
3911 int ret = 0;
3912 char *arg = NULL;
3913 char *tmp;
3914 BlockDriver *drv = NULL, *proto_drv = NULL;
3915 BlockBackend *blk1 = NULL, *blk2 = NULL;
3916 QemuOpts *opts = NULL;
3917 QemuOptsList *create_opts = NULL;
3918 Error *local_err = NULL;
3919 bool image_opts = false;
3920 int c, i;
3921 const char *out_fmt = "raw";
3922 const char *fmt = NULL;
3923 int64_t size = 0;
3924 int64_t block_count = 0, out_pos, in_pos;
3925 struct DdInfo dd = {
3926 .flags = 0,
3927 .count = 0,
3928 };
3929 struct DdIo in = {
3930 .bsz = 512, /* Block size is by default 512 bytes */
3931 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003932 .buf = NULL,
3933 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003934 };
3935 struct DdIo out = {
3936 .bsz = 512,
3937 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02003938 .buf = NULL,
3939 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003940 };
3941
3942 const struct DdOpts options[] = {
3943 { "bs", img_dd_bs, C_BS },
3944 { "count", img_dd_count, C_COUNT },
3945 { "if", img_dd_if, C_IF },
3946 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02003947 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02003948 { NULL, NULL, 0 }
3949 };
3950 const struct option long_options[] = {
3951 { "help", no_argument, 0, 'h'},
3952 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
3953 { 0, 0, 0, 0 }
3954 };
3955
3956 while ((c = getopt_long(argc, argv, "hf:O:", long_options, NULL))) {
3957 if (c == EOF) {
3958 break;
3959 }
3960 switch (c) {
3961 case 'O':
3962 out_fmt = optarg;
3963 break;
3964 case 'f':
3965 fmt = optarg;
3966 break;
3967 case '?':
3968 error_report("Try 'qemu-img --help' for more information.");
3969 ret = -1;
3970 goto out;
3971 case 'h':
3972 help();
3973 break;
3974 case OPTION_IMAGE_OPTS:
3975 image_opts = true;
3976 break;
3977 }
3978 }
3979
3980 for (i = optind; i < argc; i++) {
3981 int j;
3982 arg = g_strdup(argv[i]);
3983
3984 tmp = strchr(arg, '=');
3985 if (tmp == NULL) {
3986 error_report("unrecognized operand %s", arg);
3987 ret = -1;
3988 goto out;
3989 }
3990
3991 *tmp++ = '\0';
3992
3993 for (j = 0; options[j].name != NULL; j++) {
3994 if (!strcmp(arg, options[j].name)) {
3995 break;
3996 }
3997 }
3998 if (options[j].name == NULL) {
3999 error_report("unrecognized operand %s", arg);
4000 ret = -1;
4001 goto out;
4002 }
4003
4004 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4005 ret = -1;
4006 goto out;
4007 }
4008 dd.flags |= options[j].flag;
4009 g_free(arg);
4010 arg = NULL;
4011 }
4012
4013 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4014 error_report("Must specify both input and output files");
4015 ret = -1;
4016 goto out;
4017 }
4018 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false);
4019
4020 if (!blk1) {
4021 ret = -1;
4022 goto out;
4023 }
4024
4025 drv = bdrv_find_format(out_fmt);
4026 if (!drv) {
4027 error_report("Unknown file format");
4028 ret = -1;
4029 goto out;
4030 }
4031 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4032
4033 if (!proto_drv) {
4034 error_report_err(local_err);
4035 ret = -1;
4036 goto out;
4037 }
4038 if (!drv->create_opts) {
4039 error_report("Format driver '%s' does not support image creation",
4040 drv->format_name);
4041 ret = -1;
4042 goto out;
4043 }
4044 if (!proto_drv->create_opts) {
4045 error_report("Protocol driver '%s' does not support image creation",
4046 proto_drv->format_name);
4047 ret = -1;
4048 goto out;
4049 }
4050 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4051 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4052
4053 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4054
4055 size = blk_getlength(blk1);
4056 if (size < 0) {
4057 error_report("Failed to get size for '%s'", in.filename);
4058 ret = -1;
4059 goto out;
4060 }
4061
4062 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4063 dd.count * in.bsz < size) {
4064 size = dd.count * in.bsz;
4065 }
4066
Reda Sallahif7c15532016-08-10 16:16:09 +02004067 /* Overflow means the specified offset is beyond input image's size */
4068 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4069 size < in.bsz * in.offset)) {
4070 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4071 } else {
4072 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4073 size - in.bsz * in.offset, &error_abort);
4074 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004075
4076 ret = bdrv_create(drv, out.filename, opts, &local_err);
4077 if (ret < 0) {
4078 error_reportf_err(local_err,
4079 "%s: error while creating output image: ",
4080 out.filename);
4081 ret = -1;
4082 goto out;
4083 }
4084
4085 blk2 = img_open(image_opts, out.filename, out_fmt, BDRV_O_RDWR,
4086 false, false);
4087
4088 if (!blk2) {
4089 ret = -1;
4090 goto out;
4091 }
4092
Reda Sallahif7c15532016-08-10 16:16:09 +02004093 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4094 size < in.offset * in.bsz)) {
4095 /* We give a warning if the skip option is bigger than the input
4096 * size and create an empty output disk image (i.e. like dd(1)).
4097 */
4098 error_report("%s: cannot skip to specified offset", in.filename);
4099 in_pos = size;
4100 } else {
4101 in_pos = in.offset * in.bsz;
4102 }
4103
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004104 in.buf = g_new(uint8_t, in.bsz);
4105
Reda Sallahif7c15532016-08-10 16:16:09 +02004106 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004107 int in_ret, out_ret;
4108
4109 if (in_pos + in.bsz > size) {
4110 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4111 } else {
4112 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4113 }
4114 if (in_ret < 0) {
4115 error_report("error while reading from input image file: %s",
4116 strerror(-in_ret));
4117 ret = -1;
4118 goto out;
4119 }
4120 in_pos += in_ret;
4121
4122 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4123
4124 if (out_ret < 0) {
4125 error_report("error while writing to output image file: %s",
4126 strerror(-out_ret));
4127 ret = -1;
4128 goto out;
4129 }
4130 out_pos += out_ret;
4131 }
4132
4133out:
4134 g_free(arg);
4135 qemu_opts_del(opts);
4136 qemu_opts_free(create_opts);
4137 blk_unref(blk1);
4138 blk_unref(blk2);
4139 g_free(in.filename);
4140 g_free(out.filename);
4141 g_free(in.buf);
4142 g_free(out.buf);
4143
4144 if (ret) {
4145 return 1;
4146 }
4147 return 0;
4148}
4149
Kevin Wolfb6133b82014-08-05 14:17:13 +02004150
Anthony Liguoric227f092009-10-01 16:12:16 -05004151static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004152#define DEF(option, callback, arg_string) \
4153 { option, callback },
4154#include "qemu-img-cmds.h"
4155#undef DEF
4156#undef GEN_DOCS
4157 { NULL, NULL, },
4158};
4159
bellardea2384d2004-08-01 21:59:26 +00004160int main(int argc, char **argv)
4161{
Anthony Liguoric227f092009-10-01 16:12:16 -05004162 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004163 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004164 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004165 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004166 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004167 static const struct option long_options[] = {
4168 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004169 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004170 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004171 {0, 0, 0, 0}
4172 };
bellardea2384d2004-08-01 21:59:26 +00004173
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004174#ifdef CONFIG_POSIX
4175 signal(SIGPIPE, SIG_IGN);
4176#endif
4177
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004178 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004179 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004180 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004181
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004182 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004183 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004184 exit(EXIT_FAILURE);
4185 }
4186
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004187 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004188
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004189 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004190 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004191 if (argc < 2) {
4192 error_exit("Not enough arguments");
4193 }
Stuart Brady153859b2009-06-07 00:42:17 +01004194
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004195 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004196 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004197 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004198
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004199 while ((c = getopt_long(argc, argv, "+hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004200 switch (c) {
4201 case 'h':
4202 help();
4203 return 0;
4204 case 'V':
4205 printf(QEMU_IMG_VERSION);
4206 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004207 case 'T':
4208 g_free(trace_file);
4209 trace_file = trace_opt_parse(optarg);
4210 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004211 }
bellardea2384d2004-08-01 21:59:26 +00004212 }
Stuart Brady153859b2009-06-07 00:42:17 +01004213
Denis V. Lunev10985132016-06-17 17:44:13 +03004214 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004215
Denis V. Lunev10985132016-06-17 17:44:13 +03004216 /* reset getopt_long scanning */
4217 argc -= optind;
4218 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004219 return 0;
4220 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004221 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004222 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004223
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004224 if (!trace_init_backends()) {
4225 exit(1);
4226 }
4227 trace_init_file(trace_file);
4228 qemu_set_log(LOG_TRACE);
4229
Denis V. Lunev10985132016-06-17 17:44:13 +03004230 /* find the command */
4231 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4232 if (!strcmp(cmdname, cmd->name)) {
4233 return cmd->handler(argc, argv);
4234 }
4235 }
Jeff Cody7db16892014-04-25 17:02:32 -04004236
Stuart Brady153859b2009-06-07 00:42:17 +01004237 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004238 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004239}