blob: e4b84c4f563894eb0bd60441c09375c9e5e84bf9 [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"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050025#include <getopt.h>
26
Fam Zheng67a1de02016-06-01 17:44:21 +080027#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010028#include "qapi/error.h"
BenoƮt Canetc054b3f2012-09-05 13:09:02 +020029#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010030#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010031#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Fam Zheng335e9932017-05-03 00:35:39 +080033#include "qapi/qmp/qbool.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020034#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000035#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010036#include "qemu/option.h"
37#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030038#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000039#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010040#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020041#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010042#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020043#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080044#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010045#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030046#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000047
Don Slutz61979a62015-01-09 10:17:35 -050048#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020049 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040050
Anthony Liguoric227f092009-10-01 16:12:16 -050051typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010052 const char *name;
53 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050054} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010055
Federico Simoncelli8599ea42013-01-28 06:59:47 -050056enum {
57 OPTION_OUTPUT = 256,
58 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000059 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000060 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020061 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020062 OPTION_FLUSH_INTERVAL = 261,
63 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010064 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010065 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020066 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030067 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050068};
69
70typedef enum OutputFormat {
71 OFORMAT_JSON,
72 OFORMAT_HUMAN,
73} OutputFormat;
74
Kevin Wolfe6996142016-03-15 13:03:11 +010075/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040076#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000077
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010078static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000079{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010080 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000081}
82
Fam Zhengac1307a2014-04-22 13:36:11 +080083static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
84{
85 va_list ap;
86
87 error_printf("qemu-img: ");
88
89 va_start(ap, fmt);
90 error_vprintf(fmt, ap);
91 va_end(ap);
92
93 error_printf("\nTry 'qemu-img --help' for more information\n");
94 exit(EXIT_FAILURE);
95}
96
Stefan Hajnoczic9192972017-03-17 18:45:41 +080097static void QEMU_NORETURN missing_argument(const char *option)
98{
99 error_exit("missing argument for option '%s'", option);
100}
101
102static void QEMU_NORETURN unrecognized_option(const char *option)
103{
104 error_exit("unrecognized option '%s'", option);
105}
106
blueswir1d2c639d2009-01-24 18:19:25 +0000107/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800108static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000109{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100110 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400111 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300112 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300113 "QEMU disk image utility\n"
114 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300119 "\n"
malc3f020d72010-02-08 12:04:56 +0300120 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100121#define DEF(option, callback, arg_string) \
122 " " arg_string "\n"
123#include "qemu-img-cmds.h"
124#undef DEF
125#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300139 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
151 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
152 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300153 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300159 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200160 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100161 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
166 " fully allocated\n"
BenoƮt Canetc054b3f2012-09-05 13:09:02 +0200167 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300170 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200175 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200176 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
181 "\n"
malc3f020d72010-02-08 12:04:56 +0300182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100187 " '-l' lists all snapshots in the given image\n"
188 "\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 "(default: 512)\n"
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100201
202 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100203 bdrv_iterate_format(format_print, NULL);
Eric Blakef5048cb2017-08-03 11:33:53 -0500204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800205 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000206}
207
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000208static QemuOptsList qemu_object_opts = {
209 .name = "object",
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
212 .desc = {
213 { }
214 },
215};
216
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000217static QemuOptsList qemu_source_opts = {
218 .name = "source",
219 .implied_opt_name = "file",
220 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
221 .desc = {
222 { }
223 },
224};
225
Stefan Weil7c30f652013-06-16 17:01:05 +0200226static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100227{
228 int ret = 0;
229 if (!quiet) {
230 va_list args;
231 va_start(args, fmt);
232 ret = vprintf(fmt, args);
233 va_end(args);
234 }
235 return ret;
236}
237
bellardea2384d2004-08-01 21:59:26 +0000238
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100239static int print_block_option_help(const char *filename, const char *fmt)
240{
241 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800242 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500243 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100244
245 /* Find driver and parse its options */
246 drv = bdrv_find_format(fmt);
247 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100248 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100249 return 1;
250 }
251
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800252 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100253 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500254 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100255 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100256 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800257 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 return 1;
259 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800260 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100261 }
262
Chunyan Liu83d05212014-06-05 17:20:51 +0800263 qemu_opts_print_help(create_opts);
264 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100265 return 0;
266}
267
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000268
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,
Fam Zheng335e9932017-05-03 00:35:39 +0800271 bool quiet, bool force_share)
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);
Fam Zheng335e9932017-05-03 00:35:39 +0800277 if (force_share) {
278 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
279 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
280 error_report("--force-share/-U conflicts with image options");
Fam Zhengadb998c2017-05-15 22:10:14 +0800281 QDECREF(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800282 return NULL;
283 }
Eric Blake579cf1d2017-05-15 14:54:39 -0500284 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800285 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100286 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000287 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100288 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000289 return NULL;
290 }
Kevin Wolfce099542016-03-15 13:01:04 +0100291 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000293 return blk;
294}
295
Max Reitzefaa7c42016-03-16 19:54:38 +0100296static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100297 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000298 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800299 bool writethrough, bool quiet,
300 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000301{
302 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200303 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100304
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100305 if (!options) {
306 options = qdict_new();
307 }
bellard75c23802004-08-27 21:28:58 +0000308 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500309 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000310 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100311
Fam Zheng335e9932017-05-03 00:35:39 +0800312 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500313 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800314 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100315 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500316 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100317 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318 return NULL;
bellard75c23802004-08-27 21:28:58 +0000319 }
Kevin Wolfce099542016-03-15 13:01:04 +0100320 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100321
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200322 return blk;
bellard75c23802004-08-27 21:28:58 +0000323}
324
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000325
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100326static int img_add_key_secrets(void *opaque,
327 const char *name, const char *value,
328 Error **errp)
329{
330 QDict *options = opaque;
331
332 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600333 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100334 }
335
336 return 0;
337}
338
339static BlockBackend *img_open_new_file(const char *filename,
340 QemuOpts *create_opts,
341 const char *fmt, int flags,
342 bool writethrough, bool quiet,
343 bool force_share)
344{
345 QDict *options = NULL;
346
347 options = qdict_new();
348 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
349
350 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
351 force_share);
352}
353
354
Max Reitzefaa7c42016-03-16 19:54:38 +0100355static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000356 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100357 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800358 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000359{
360 BlockBackend *blk;
361 if (image_opts) {
362 QemuOpts *opts;
363 if (fmt) {
364 error_report("--image-opts and --format are mutually exclusive");
365 return NULL;
366 }
367 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
368 filename, true);
369 if (!opts) {
370 return NULL;
371 }
Fam Zheng335e9932017-05-03 00:35:39 +0800372 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
373 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000374 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100375 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800376 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000377 }
378 return blk;
379}
380
381
Chunyan Liu83d05212014-06-05 17:20:51 +0800382static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100383 const char *base_filename,
384 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200385{
Markus Armbruster6750e792015-02-12 17:43:08 +0100386 Error *err = NULL;
387
Kevin Wolfefa84d42009-05-18 16:42:12 +0200388 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100389 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100390 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100391 error_report("Backing file not supported for file format '%s'",
392 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100393 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900394 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200395 }
396 }
397 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100399 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100400 error_report("Backing file format not supported for file "
401 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100402 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900403 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200404 }
405 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900406 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200407}
408
Markus Armbruster606caa02017-02-21 21:14:04 +0100409static int64_t cvtnum(const char *s)
410{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100411 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100412 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100413
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100414 err = qemu_strtosz(s, NULL, &value);
415 if (err < 0) {
416 return err;
417 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100418 if (value > INT64_MAX) {
419 return -ERANGE;
420 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100421 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100422}
423
bellardea2384d2004-08-01 21:59:26 +0000424static int img_create(int argc, char **argv)
425{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200426 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100427 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000428 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000429 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000430 const char *filename;
431 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200432 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200433 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100434 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400435 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000436
bellardea2384d2004-08-01 21:59:26 +0000437 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000438 static const struct option long_options[] = {
439 {"help", no_argument, 0, 'h'},
440 {"object", required_argument, 0, OPTION_OBJECT},
441 {0, 0, 0, 0}
442 };
John Snow6e6e55f2017-07-17 20:34:22 -0400443 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000444 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100445 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000446 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100447 }
bellardea2384d2004-08-01 21:59:26 +0000448 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800449 case ':':
450 missing_argument(argv[optind - 1]);
451 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100452 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800453 unrecognized_option(argv[optind - 1]);
454 break;
bellardea2384d2004-08-01 21:59:26 +0000455 case 'h':
456 help();
457 break;
aliguori9230eaf2009-03-28 17:55:19 +0000458 case 'F':
459 base_fmt = optarg;
460 break;
bellardea2384d2004-08-01 21:59:26 +0000461 case 'b':
462 base_filename = optarg;
463 break;
464 case 'f':
465 fmt = optarg;
466 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200467 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100468 if (!is_valid_option_list(optarg)) {
469 error_report("Invalid option list: %s", optarg);
470 goto fail;
471 }
472 if (!options) {
473 options = g_strdup(optarg);
474 } else {
475 char *old_options = options;
476 options = g_strdup_printf("%s,%s", options, optarg);
477 g_free(old_options);
478 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200479 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100480 case 'q':
481 quiet = true;
482 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400483 case 'u':
484 flags |= BDRV_O_NO_BACKING;
485 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000486 case OPTION_OBJECT: {
487 QemuOpts *opts;
488 opts = qemu_opts_parse_noisily(&qemu_object_opts,
489 optarg, true);
490 if (!opts) {
491 goto fail;
492 }
493 } break;
bellardea2384d2004-08-01 21:59:26 +0000494 }
495 }
aliguori9230eaf2009-03-28 17:55:19 +0000496
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900497 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100498 filename = (optind < argc) ? argv[optind] : NULL;
499 if (options && has_help_option(options)) {
500 g_free(options);
501 return print_block_option_help(filename, fmt);
502 }
503
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100504 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800505 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100506 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100507 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900508
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000509 if (qemu_opts_foreach(&qemu_object_opts,
510 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200511 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000512 goto fail;
513 }
514
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100515 /* Get image size, if specified */
516 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100517 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100518
519 sval = cvtnum(argv[optind++]);
520 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800521 if (sval == -ERANGE) {
522 error_report("Image size must be less than 8 EiB!");
523 } else {
524 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200525 "G, T, P or E suffixes for ");
526 error_report("kilobytes, megabytes, gigabytes, terabytes, "
527 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800528 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100529 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100530 }
531 img_size = (uint64_t)sval;
532 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200533 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800534 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200535 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100536
Luiz Capitulino9b375252012-11-30 10:52:05 -0200537 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400538 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100539 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100540 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100541 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900542 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200543
Kevin Wolf77386bf2014-02-21 16:24:04 +0100544 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000545 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546
547fail:
548 g_free(options);
549 return 1;
bellardea2384d2004-08-01 21:59:26 +0000550}
551
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100552static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500553{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500555 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100556 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600557
558 visit_type_ImageCheck(v, NULL, &check, &error_abort);
559 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560 str = qobject_to_json_pretty(obj);
561 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100562 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600564 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 QDECREF(str);
566}
567
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500569{
570 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100571 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572 } else {
573 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100574 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
575 "Data may be corrupted, or further writes to the image "
576 "may corrupt it.\n",
577 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578 }
579
580 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100581 qprintf(quiet,
582 "\n%" PRId64 " leaked clusters were found on the image.\n"
583 "This means waste of disk space, but no harm to data.\n",
584 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585 }
586
587 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100588 qprintf(quiet,
589 "\n%" PRId64
590 " internal errors have occurred during the check.\n",
591 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500592 }
593 }
594
595 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100596 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
597 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
598 check->allocated_clusters, check->total_clusters,
599 check->allocated_clusters * 100.0 / check->total_clusters,
600 check->fragmented_clusters * 100.0 / check->allocated_clusters,
601 check->compressed_clusters * 100.0 /
602 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 }
604
605 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100606 qprintf(quiet,
607 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 }
609}
610
611static int collect_image_check(BlockDriverState *bs,
612 ImageCheck *check,
613 const char *filename,
614 const char *fmt,
615 int fix)
616{
617 int ret;
618 BdrvCheckResult result;
619
620 ret = bdrv_check(bs, &result, fix);
621 if (ret < 0) {
622 return ret;
623 }
624
625 check->filename = g_strdup(filename);
626 check->format = g_strdup(bdrv_get_format_name(bs));
627 check->check_errors = result.check_errors;
628 check->corruptions = result.corruptions;
629 check->has_corruptions = result.corruptions != 0;
630 check->leaks = result.leaks;
631 check->has_leaks = result.leaks != 0;
632 check->corruptions_fixed = result.corruptions_fixed;
633 check->has_corruptions_fixed = result.corruptions != 0;
634 check->leaks_fixed = result.leaks_fixed;
635 check->has_leaks_fixed = result.leaks != 0;
636 check->image_end_offset = result.image_end_offset;
637 check->has_image_end_offset = result.image_end_offset != 0;
638 check->total_clusters = result.bfi.total_clusters;
639 check->has_total_clusters = result.bfi.total_clusters != 0;
640 check->allocated_clusters = result.bfi.allocated_clusters;
641 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
642 check->fragmented_clusters = result.bfi.fragmented_clusters;
643 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100644 check->compressed_clusters = result.bfi.compressed_clusters;
645 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500646
647 return 0;
648}
649
Kevin Wolfe076f332010-06-29 11:43:13 +0200650/*
651 * Checks an image for consistency. Exit codes:
652 *
Max Reitzd6635c42014-06-02 22:15:21 +0200653 * 0 - Check completed, image is good
654 * 1 - Check not completed because of internal errors
655 * 2 - Check completed, image is corrupted
656 * 3 - Check completed, image has leaked clusters, but is good otherwise
657 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200658 */
aliguori15859692009-04-21 23:11:53 +0000659static int img_check(int argc, char **argv)
660{
661 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500662 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200663 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200664 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000665 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200666 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100667 int flags = BDRV_O_CHECK;
668 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200669 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100670 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000671 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800672 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000673
674 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500675 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200676 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100677
aliguori15859692009-04-21 23:11:53 +0000678 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 int option_index = 0;
680 static const struct option long_options[] = {
681 {"help", no_argument, 0, 'h'},
682 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530683 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000685 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000686 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800687 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500688 {0, 0, 0, 0}
689 };
Fam Zheng335e9932017-05-03 00:35:39 +0800690 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500691 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100692 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000693 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100694 }
aliguori15859692009-04-21 23:11:53 +0000695 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800696 case ':':
697 missing_argument(argv[optind - 1]);
698 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100699 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800700 unrecognized_option(argv[optind - 1]);
701 break;
aliguori15859692009-04-21 23:11:53 +0000702 case 'h':
703 help();
704 break;
705 case 'f':
706 fmt = optarg;
707 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200708 case 'r':
709 flags |= BDRV_O_RDWR;
710
711 if (!strcmp(optarg, "leaks")) {
712 fix = BDRV_FIX_LEAKS;
713 } else if (!strcmp(optarg, "all")) {
714 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
715 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800716 error_exit("Unknown option value for -r "
717 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200718 }
719 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500720 case OPTION_OUTPUT:
721 output = optarg;
722 break;
Max Reitz40055952014-07-22 22:58:42 +0200723 case 'T':
724 cache = optarg;
725 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100726 case 'q':
727 quiet = true;
728 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800729 case 'U':
730 force_share = true;
731 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000732 case OPTION_OBJECT: {
733 QemuOpts *opts;
734 opts = qemu_opts_parse_noisily(&qemu_object_opts,
735 optarg, true);
736 if (!opts) {
737 return 1;
738 }
739 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000740 case OPTION_IMAGE_OPTS:
741 image_opts = true;
742 break;
aliguori15859692009-04-21 23:11:53 +0000743 }
744 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200745 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800746 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100747 }
aliguori15859692009-04-21 23:11:53 +0000748 filename = argv[optind++];
749
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500750 if (output && !strcmp(output, "json")) {
751 output_format = OFORMAT_JSON;
752 } else if (output && !strcmp(output, "human")) {
753 output_format = OFORMAT_HUMAN;
754 } else if (output) {
755 error_report("--output must be used with human or json as argument.");
756 return 1;
757 }
758
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000759 if (qemu_opts_foreach(&qemu_object_opts,
760 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200761 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000762 return 1;
763 }
764
Kevin Wolfce099542016-03-15 13:01:04 +0100765 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200766 if (ret < 0) {
767 error_report("Invalid source cache option: %s", cache);
768 return 1;
769 }
770
Fam Zheng335e9932017-05-03 00:35:39 +0800771 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
772 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200773 if (!blk) {
774 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900775 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200776 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500777
778 check = g_new0(ImageCheck, 1);
779 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200780
781 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200782 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200783 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500784 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200785 }
786
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500787 if (check->corruptions_fixed || check->leaks_fixed) {
788 int corruptions_fixed, leaks_fixed;
789
790 leaks_fixed = check->leaks_fixed;
791 corruptions_fixed = check->corruptions_fixed;
792
793 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100794 qprintf(quiet,
795 "The following inconsistencies were found and repaired:\n\n"
796 " %" PRId64 " leaked clusters\n"
797 " %" PRId64 " corruptions\n\n"
798 "Double checking the fixed image now...\n",
799 check->leaks_fixed,
800 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500801 }
802
803 ret = collect_image_check(bs, check, filename, fmt, 0);
804
805 check->leaks_fixed = leaks_fixed;
806 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200807 }
808
Max Reitz832390a2014-10-23 15:29:12 +0200809 if (!ret) {
810 switch (output_format) {
811 case OFORMAT_HUMAN:
812 dump_human_image_check(check, quiet);
813 break;
814 case OFORMAT_JSON:
815 dump_json_image_check(check, quiet);
816 break;
817 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500818 }
819
820 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200821 if (ret) {
822 error_report("Check failed: %s", strerror(-ret));
823 } else {
824 error_report("Check failed");
825 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826 ret = 1;
827 goto fail;
828 }
829
830 if (check->corruptions) {
831 ret = 2;
832 } else if (check->leaks) {
833 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200834 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000836 }
837
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500838fail:
839 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200840 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500841 return ret;
aliguori15859692009-04-21 23:11:53 +0000842}
843
Max Reitzd4a32382014-10-24 15:57:37 +0200844typedef struct CommonBlockJobCBInfo {
845 BlockDriverState *bs;
846 Error **errp;
847} CommonBlockJobCBInfo;
848
849static void common_block_job_cb(void *opaque, int ret)
850{
851 CommonBlockJobCBInfo *cbi = opaque;
852
853 if (ret < 0) {
854 error_setg_errno(cbi->errp, -ret, "Block job failed");
855 }
Max Reitzd4a32382014-10-24 15:57:37 +0200856}
857
858static void run_block_job(BlockJob *job, Error **errp)
859{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200860 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800861 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200862
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200863 aio_context_acquire(aio_context);
sochin.jiang4172a002017-06-15 14:47:33 +0800864 block_job_ref(job);
Max Reitzd4a32382014-10-24 15:57:37 +0200865 do {
866 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500867 qemu_progress_print(job->len ?
868 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
sochin.jiang4172a002017-06-15 14:47:33 +0800869 } while (!job->ready && !job->completed);
Max Reitzd4a32382014-10-24 15:57:37 +0200870
sochin.jiang4172a002017-06-15 14:47:33 +0800871 if (!job->completed) {
872 ret = block_job_complete_sync(job, errp);
873 } else {
874 ret = job->ret;
875 }
876 block_job_unref(job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200877 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200878
sochin.jiang4172a002017-06-15 14:47:33 +0800879 /* publish completion progress only when success */
880 if (!ret) {
881 qemu_progress_print(100.f, 0);
882 }
Max Reitzd4a32382014-10-24 15:57:37 +0200883}
884
bellardea2384d2004-08-01 21:59:26 +0000885static int img_commit(int argc, char **argv)
886{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400887 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200888 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200889 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200890 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100891 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200892 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100893 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200894 Error *local_err = NULL;
895 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000896 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200897 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000898
899 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400900 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200901 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000902 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000903 static const struct option long_options[] = {
904 {"help", no_argument, 0, 'h'},
905 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000906 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000907 {0, 0, 0, 0}
908 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800909 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000910 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100911 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000912 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100913 }
bellardea2384d2004-08-01 21:59:26 +0000914 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800915 case ':':
916 missing_argument(argv[optind - 1]);
917 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100918 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800919 unrecognized_option(argv[optind - 1]);
920 break;
bellardea2384d2004-08-01 21:59:26 +0000921 case 'h':
922 help();
923 break;
924 case 'f':
925 fmt = optarg;
926 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400927 case 't':
928 cache = optarg;
929 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200930 case 'b':
931 base = optarg;
932 /* -b implies -d */
933 drop = true;
934 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200935 case 'd':
936 drop = true;
937 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200938 case 'p':
939 progress = true;
940 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100941 case 'q':
942 quiet = true;
943 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000944 case OPTION_OBJECT: {
945 QemuOpts *opts;
946 opts = qemu_opts_parse_noisily(&qemu_object_opts,
947 optarg, true);
948 if (!opts) {
949 return 1;
950 }
951 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000952 case OPTION_IMAGE_OPTS:
953 image_opts = true;
954 break;
bellardea2384d2004-08-01 21:59:26 +0000955 }
956 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200957
958 /* Progress is not shown in Quiet mode */
959 if (quiet) {
960 progress = false;
961 }
962
Kevin Wolffc11eb22013-08-05 10:53:04 +0200963 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800964 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100965 }
bellardea2384d2004-08-01 21:59:26 +0000966 filename = argv[optind++];
967
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000968 if (qemu_opts_foreach(&qemu_object_opts,
969 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200970 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000971 return 1;
972 }
973
Max Reitz9a86fe42014-10-24 15:57:38 +0200974 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100975 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400976 if (ret < 0) {
977 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100978 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400979 }
980
Fam Zheng335e9932017-05-03 00:35:39 +0800981 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
982 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200983 if (!blk) {
984 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900985 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200986 bs = blk_bs(blk);
987
Max Reitz687fa1d2014-10-24 15:57:39 +0200988 qemu_progress_init(progress, 1.f);
989 qemu_progress_print(0.f, 100);
990
Max Reitz1b22bff2014-10-24 15:57:40 +0200991 if (base) {
992 base_bs = bdrv_find_backing_image(bs, base);
993 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100994 error_setg(&local_err,
995 "Did not find '%s' in the backing chain of '%s'",
996 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200997 goto done;
998 }
999 } else {
1000 /* This is different from QMP, which by default uses the deepest file in
1001 * the backing chain (i.e., the very base); however, the traditional
1002 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001003 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001004 if (!base_bs) {
1005 error_setg(&local_err, "Image does not have a backing file");
1006 goto done;
1007 }
bellardea2384d2004-08-01 21:59:26 +00001008 }
1009
Max Reitzd4a32382014-10-24 15:57:37 +02001010 cbi = (CommonBlockJobCBInfo){
1011 .errp = &local_err,
1012 .bs = bs,
1013 };
1014
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001015 aio_context = bdrv_get_aio_context(bs);
1016 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -04001017 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001018 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001019 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001020 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001021 if (local_err) {
1022 goto done;
1023 }
1024
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001025 /* When the block job completes, the BlockBackend reference will point to
1026 * the old backing file. In order to avoid that the top image is already
1027 * deleted, so we can still empty it afterwards, increment the reference
1028 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001029 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001030 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001031 }
1032
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001033 job = block_job_get("commit");
1034 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001035 if (local_err) {
1036 goto unref_backing;
1037 }
1038
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001039 if (!drop && bs->drv->bdrv_make_empty) {
1040 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001041 if (ret) {
1042 error_setg_errno(&local_err, -ret, "Could not empty %s",
1043 filename);
1044 goto unref_backing;
1045 }
1046 }
1047
1048unref_backing:
1049 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001050 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 }
Max Reitzd4a32382014-10-24 15:57:37 +02001052
1053done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001054 qemu_progress_end();
1055
Markus Armbruster26f54e92014-10-07 13:59:04 +02001056 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001057
1058 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001059 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001060 return 1;
1061 }
Max Reitzd4a32382014-10-24 15:57:37 +02001062
1063 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001064 return 0;
1065}
1066
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001067/*
thsf58c7b32008-06-05 21:53:49 +00001068 * Returns true iff the first sector pointed to by 'buf' contains at least
1069 * a non-NUL byte.
1070 *
1071 * 'pnum' is set to the number of sectors (including and immediately following
1072 * the first one) that are known to be in the same allocated/unallocated state.
1073 */
bellardea2384d2004-08-01 21:59:26 +00001074static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1075{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001076 bool is_zero;
1077 int i;
bellardea2384d2004-08-01 21:59:26 +00001078
1079 if (n <= 0) {
1080 *pnum = 0;
1081 return 0;
1082 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001083 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001084 for(i = 1; i < n; i++) {
1085 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001086 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001087 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001088 }
bellardea2384d2004-08-01 21:59:26 +00001089 }
1090 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001091 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001092}
1093
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001094/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001095 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1096 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1097 * breaking up write requests for only small sparse areas.
1098 */
1099static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1100 int min)
1101{
1102 int ret;
1103 int num_checked, num_used;
1104
1105 if (n < min) {
1106 min = n;
1107 }
1108
1109 ret = is_allocated_sectors(buf, n, pnum);
1110 if (!ret) {
1111 return ret;
1112 }
1113
1114 num_used = *pnum;
1115 buf += BDRV_SECTOR_SIZE * *pnum;
1116 n -= *pnum;
1117 num_checked = num_used;
1118
1119 while (n > 0) {
1120 ret = is_allocated_sectors(buf, n, pnum);
1121
1122 buf += BDRV_SECTOR_SIZE * *pnum;
1123 n -= *pnum;
1124 num_checked += *pnum;
1125 if (ret) {
1126 num_used = num_checked;
1127 } else if (*pnum >= min) {
1128 break;
1129 }
1130 }
1131
1132 *pnum = num_used;
1133 return 1;
1134}
1135
1136/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001137 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1138 * buffers matches, non-zero otherwise.
1139 *
1140 * pnum is set to the number of sectors (including and immediately following
1141 * the first one) that are known to have the same comparison result
1142 */
1143static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1144 int *pnum)
1145{
Radim KrčmÔř8c1ac472015-02-20 17:06:15 +01001146 bool res;
1147 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001148
1149 if (n <= 0) {
1150 *pnum = 0;
1151 return 0;
1152 }
1153
1154 res = !!memcmp(buf1, buf2, 512);
1155 for(i = 1; i < n; i++) {
1156 buf1 += 512;
1157 buf2 += 512;
1158
1159 if (!!memcmp(buf1, buf2, 512) != res) {
1160 break;
1161 }
1162 }
1163
1164 *pnum = i;
1165 return res;
1166}
1167
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001168#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001169
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001170static int64_t sectors_to_bytes(int64_t sectors)
1171{
1172 return sectors << BDRV_SECTOR_BITS;
1173}
1174
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001175/*
1176 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1177 *
1178 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1179 * data and negative value on error.
1180 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001181 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001182 * @param sect_num: Number of first sector to check
1183 * @param sect_count: Number of sectors to check
1184 * @param filename: Name of disk file we are checking (logging purpose)
1185 * @param buffer: Allocated buffer for storing read data
1186 * @param quiet: Flag for quiet mode
1187 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001188static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001189 int sect_count, const char *filename,
1190 uint8_t *buffer, bool quiet)
1191{
1192 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001193 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1194 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001195 if (ret < 0) {
1196 error_report("Error while reading offset %" PRId64 " of %s: %s",
1197 sectors_to_bytes(sect_num), filename, strerror(-ret));
1198 return ret;
1199 }
1200 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1201 if (ret || pnum != sect_count) {
1202 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1203 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1204 return 1;
1205 }
1206
1207 return 0;
1208}
1209
1210/*
1211 * Compares two images. Exit codes:
1212 *
1213 * 0 - Images are identical
1214 * 1 - Images differ
1215 * >1 - Error occurred
1216 */
1217static int img_compare(int argc, char **argv)
1218{
Max Reitz40055952014-07-22 22:58:42 +02001219 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001220 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 BlockDriverState *bs1, *bs2;
1222 int64_t total_sectors1, total_sectors2;
1223 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001224 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001225 int allocated1, allocated2;
1226 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1227 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001228 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001229 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001230 int64_t total_sectors;
1231 int64_t sector_num = 0;
1232 int64_t nb_sectors;
1233 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001235 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001236 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001237
Max Reitz40055952014-07-22 22:58:42 +02001238 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001240 static const struct option long_options[] = {
1241 {"help", no_argument, 0, 'h'},
1242 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001243 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001244 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001245 {0, 0, 0, 0}
1246 };
Fam Zheng335e9932017-05-03 00:35:39 +08001247 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001248 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001249 if (c == -1) {
1250 break;
1251 }
1252 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001253 case ':':
1254 missing_argument(argv[optind - 1]);
1255 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001256 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001257 unrecognized_option(argv[optind - 1]);
1258 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001259 case 'h':
1260 help();
1261 break;
1262 case 'f':
1263 fmt1 = optarg;
1264 break;
1265 case 'F':
1266 fmt2 = optarg;
1267 break;
Max Reitz40055952014-07-22 22:58:42 +02001268 case 'T':
1269 cache = optarg;
1270 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001271 case 'p':
1272 progress = true;
1273 break;
1274 case 'q':
1275 quiet = true;
1276 break;
1277 case 's':
1278 strict = true;
1279 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001280 case 'U':
1281 force_share = true;
1282 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001283 case OPTION_OBJECT: {
1284 QemuOpts *opts;
1285 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1286 optarg, true);
1287 if (!opts) {
1288 ret = 2;
1289 goto out4;
1290 }
1291 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001292 case OPTION_IMAGE_OPTS:
1293 image_opts = true;
1294 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 }
1296 }
1297
1298 /* Progress is not shown in Quiet mode */
1299 if (quiet) {
1300 progress = false;
1301 }
1302
1303
Kevin Wolffc11eb22013-08-05 10:53:04 +02001304 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001305 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001306 }
1307 filename1 = argv[optind++];
1308 filename2 = argv[optind++];
1309
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001310 if (qemu_opts_foreach(&qemu_object_opts,
1311 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001312 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001313 ret = 2;
1314 goto out4;
1315 }
1316
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001317 /* Initialize before goto out */
1318 qemu_progress_init(progress, 2.0);
1319
Kevin Wolfce099542016-03-15 13:01:04 +01001320 flags = 0;
1321 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001322 if (ret < 0) {
1323 error_report("Invalid source cache option: %s", cache);
1324 ret = 2;
1325 goto out3;
1326 }
1327
Fam Zheng335e9932017-05-03 00:35:39 +08001328 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1329 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001330 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001331 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001332 goto out3;
1333 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001334
Fam Zheng335e9932017-05-03 00:35:39 +08001335 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1336 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001337 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001338 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001339 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001340 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001341 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001342 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001343
Max Reitzf1d3cd72015-02-05 13:58:18 -05001344 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1345 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1346 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001347 if (total_sectors1 < 0) {
1348 error_report("Can't get size of %s: %s",
1349 filename1, strerror(-total_sectors1));
1350 ret = 4;
1351 goto out;
1352 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001353 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001354 if (total_sectors2 < 0) {
1355 error_report("Can't get size of %s: %s",
1356 filename2, strerror(-total_sectors2));
1357 ret = 4;
1358 goto out;
1359 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001360 total_sectors = MIN(total_sectors1, total_sectors2);
1361 progress_base = MAX(total_sectors1, total_sectors2);
1362
1363 qemu_progress_print(0, 100);
1364
1365 if (strict && total_sectors1 != total_sectors2) {
1366 ret = 1;
1367 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1368 goto out;
1369 }
1370
Eric Blake7daddc62017-10-11 22:47:09 -05001371 while (sector_num < total_sectors) {
Eric Blake31826642017-10-11 22:47:08 -05001372 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001373
Eric Blake31826642017-10-11 22:47:08 -05001374 status1 = bdrv_block_status_above(bs1, NULL,
1375 sector_num * BDRV_SECTOR_SIZE,
1376 (total_sectors1 - sector_num) *
1377 BDRV_SECTOR_SIZE,
1378 &pnum1, NULL, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001379 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001380 ret = 3;
1381 error_report("Sector allocation test failed for %s", filename1);
1382 goto out;
1383 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001384 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001385
Eric Blake31826642017-10-11 22:47:08 -05001386 status2 = bdrv_block_status_above(bs2, NULL,
1387 sector_num * BDRV_SECTOR_SIZE,
1388 (total_sectors2 - sector_num) *
1389 BDRV_SECTOR_SIZE,
1390 &pnum2, NULL, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001391 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 ret = 3;
1393 error_report("Sector allocation test failed for %s", filename2);
1394 goto out;
1395 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001396 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake31826642017-10-11 22:47:08 -05001397 /* TODO: Relax this once comparison is byte-based, and we no longer
1398 * have to worry about sector alignment */
1399 assert(QEMU_IS_ALIGNED(pnum1 | pnum2, BDRV_SECTOR_SIZE));
Eric Blake7daddc62017-10-11 22:47:09 -05001400
1401 assert(pnum1 && pnum2);
1402 nb_sectors = MIN(pnum1, pnum2) >> BDRV_SECTOR_BITS;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001403
Fam Zheng25ad8e62016-01-13 16:37:41 +08001404 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001405 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001406 ret = 1;
1407 qprintf(quiet, "Strict mode: Offset %" PRId64
1408 " block status mismatch!\n",
1409 sectors_to_bytes(sector_num));
1410 goto out;
1411 }
1412 }
1413 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001414 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001415 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 if (allocated1) {
Eric Blake7daddc62017-10-11 22:47:09 -05001417 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
Eric Blake91669202016-05-06 10:26:43 -06001418 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1419 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001420 if (ret < 0) {
1421 error_report("Error while reading offset %" PRId64 " of %s:"
1422 " %s", sectors_to_bytes(sector_num), filename1,
1423 strerror(-ret));
1424 ret = 4;
1425 goto out;
1426 }
Eric Blake91669202016-05-06 10:26:43 -06001427 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1428 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001429 if (ret < 0) {
1430 error_report("Error while reading offset %" PRId64
1431 " of %s: %s", sectors_to_bytes(sector_num),
1432 filename2, strerror(-ret));
1433 ret = 4;
1434 goto out;
1435 }
1436 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1437 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001438 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1439 sectors_to_bytes(
1440 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001441 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001442 goto out;
1443 }
1444 }
1445 } else {
Eric Blake7daddc62017-10-11 22:47:09 -05001446 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001448 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449 filename1, buf1, quiet);
1450 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001451 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001452 filename2, buf1, quiet);
1453 }
1454 if (ret) {
1455 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001456 error_report("Error while reading offset %" PRId64 ": %s",
1457 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001458 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001459 }
1460 goto out;
1461 }
1462 }
1463 sector_num += nb_sectors;
1464 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1465 }
1466
1467 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001468 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001469 const char *filename_over;
1470
1471 qprintf(quiet, "Warning: Image size mismatch!\n");
1472 if (total_sectors1 > total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001473 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 filename_over = filename1;
1475 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001476 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477 filename_over = filename2;
1478 }
1479
Eric Blake7daddc62017-10-11 22:47:09 -05001480 while (sector_num < progress_base) {
Eric Blake51b0a482017-07-07 07:44:59 -05001481 int64_t count;
1482
Eric Blake391cb1a2017-10-11 22:47:10 -05001483 ret = bdrv_block_status_above(blk_bs(blk_over), NULL,
Eric Blake51b0a482017-07-07 07:44:59 -05001484 sector_num * BDRV_SECTOR_SIZE,
Eric Blake7daddc62017-10-11 22:47:09 -05001485 (progress_base - sector_num) *
1486 BDRV_SECTOR_SIZE,
Eric Blake391cb1a2017-10-11 22:47:10 -05001487 &count, NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001488 if (ret < 0) {
1489 ret = 3;
1490 error_report("Sector allocation test failed for %s",
1491 filename_over);
1492 goto out;
1493
1494 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001495 /* TODO relax this once bdrv_block_status_above does not enforce
Eric Blake51b0a482017-07-07 07:44:59 -05001496 * sector alignment */
1497 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1498 nb_sectors = count >> BDRV_SECTOR_BITS;
Eric Blake391cb1a2017-10-11 22:47:10 -05001499 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001500 nb_sectors = MIN(nb_sectors, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
Max Reitzf1d3cd72015-02-05 13:58:18 -05001501 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 filename_over, buf1, quiet);
1503 if (ret) {
1504 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 error_report("Error while reading offset %" PRId64
1506 " of %s: %s", sectors_to_bytes(sector_num),
1507 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001508 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 }
1510 goto out;
1511 }
1512 }
1513 sector_num += nb_sectors;
1514 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1515 }
1516 }
1517
1518 qprintf(quiet, "Images are identical.\n");
1519 ret = 0;
1520
1521out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 qemu_vfree(buf1);
1523 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001524 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001526 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001527out3:
1528 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001529out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530 return ret;
1531}
1532
Kevin Wolf690c7302015-03-19 13:33:32 +01001533enum ImgConvertBlockStatus {
1534 BLK_DATA,
1535 BLK_ZERO,
1536 BLK_BACKING_FILE,
1537};
1538
Peter Lieven2d9187b2017-02-28 13:40:07 +01001539#define MAX_COROUTINES 16
1540
Kevin Wolf690c7302015-03-19 13:33:32 +01001541typedef struct ImgConvertState {
1542 BlockBackend **src;
1543 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001544 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001545 int64_t total_sectors;
1546 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001547 int64_t allocated_done;
1548 int64_t sector_num;
1549 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001550 enum ImgConvertBlockStatus status;
1551 int64_t sector_next_status;
1552 BlockBackend *target;
1553 bool has_zero_init;
1554 bool compressed;
1555 bool target_has_backing;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001556 bool wr_in_order;
Kevin Wolf690c7302015-03-19 13:33:32 +01001557 int min_sparse;
1558 size_t cluster_sectors;
1559 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001560 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001561 int running_coroutines;
1562 Coroutine *co[MAX_COROUTINES];
1563 int64_t wait_sector_num[MAX_COROUTINES];
1564 CoMutex lock;
1565 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001566} ImgConvertState;
1567
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1569 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001570{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001571 *src_cur = 0;
1572 *src_cur_offset = 0;
1573 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1574 *src_cur_offset += s->src_sectors[*src_cur];
1575 (*src_cur)++;
1576 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001577 }
1578}
1579
1580static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1581{
Eric Blake31826642017-10-11 22:47:08 -05001582 int64_t src_cur_offset;
1583 int ret, n, src_cur;
Kevin Wolf690c7302015-03-19 13:33:32 +01001584
Peter Lieven2d9187b2017-02-28 13:40:07 +01001585 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001586
1587 assert(s->total_sectors > sector_num);
1588 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1589
1590 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001591 int64_t count = n * BDRV_SECTOR_SIZE;
1592
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001593 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001594
1595 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1596 (sector_num - src_cur_offset) *
1597 BDRV_SECTOR_SIZE,
1598 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001599 } else {
Eric Blake31826642017-10-11 22:47:08 -05001600 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1601 (sector_num - src_cur_offset) *
1602 BDRV_SECTOR_SIZE,
1603 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001604 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001605 if (ret < 0) {
1606 return ret;
1607 }
Eric Blake31826642017-10-11 22:47:08 -05001608 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001609
1610 if (ret & BDRV_BLOCK_ZERO) {
1611 s->status = BLK_ZERO;
1612 } else if (ret & BDRV_BLOCK_DATA) {
1613 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001614 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001615 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001616 }
1617
1618 s->sector_next_status = sector_num + n;
1619 }
1620
1621 n = MIN(n, s->sector_next_status - sector_num);
1622 if (s->status == BLK_DATA) {
1623 n = MIN(n, s->buf_sectors);
1624 }
1625
1626 /* We need to write complete clusters for compressed images, so if an
1627 * unallocated area is shorter than that, we must consider the whole
1628 * cluster allocated. */
1629 if (s->compressed) {
1630 if (n < s->cluster_sectors) {
1631 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1632 s->status = BLK_DATA;
1633 } else {
1634 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1635 }
1636 }
1637
1638 return n;
1639}
1640
Peter Lieven2d9187b2017-02-28 13:40:07 +01001641static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1642 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001643{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001644 int n, ret;
1645 QEMUIOVector qiov;
1646 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001647
Kevin Wolf690c7302015-03-19 13:33:32 +01001648 assert(nb_sectors <= s->buf_sectors);
1649 while (nb_sectors > 0) {
1650 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001651 int src_cur;
1652 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001653
1654 /* In the case of compression with multiple source files, we can get a
1655 * nb_sectors that spreads into the next part. So we must be able to
1656 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001657 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1658 blk = s->src[src_cur];
1659 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001660
Peter Lieven2d9187b2017-02-28 13:40:07 +01001661 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1662 iov.iov_base = buf;
1663 iov.iov_len = n << BDRV_SECTOR_BITS;
1664 qemu_iovec_init_external(&qiov, &iov, 1);
1665
1666 ret = blk_co_preadv(
1667 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1668 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001669 if (ret < 0) {
1670 return ret;
1671 }
1672
1673 sector_num += n;
1674 nb_sectors -= n;
1675 buf += n * BDRV_SECTOR_SIZE;
1676 }
1677
1678 return 0;
1679}
1680
Peter Lieven2d9187b2017-02-28 13:40:07 +01001681
1682static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1683 int nb_sectors, uint8_t *buf,
1684 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001685{
1686 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001687 QEMUIOVector qiov;
1688 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001689
1690 while (nb_sectors > 0) {
1691 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001692 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1693
Peter Lieven2d9187b2017-02-28 13:40:07 +01001694 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001695 case BLK_BACKING_FILE:
1696 /* If we have a backing file, leave clusters unallocated that are
1697 * unallocated in the source image, so that the backing file is
1698 * visible at the respective offset. */
1699 assert(s->target_has_backing);
1700 break;
1701
1702 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001703 /* If we're told to keep the target fully allocated (-S 0) or there
1704 * is real non-zero data, we must write it. Otherwise we can treat
1705 * it as zero sectors.
1706 * Compressed clusters need to be written as a whole, so in that
1707 * case we can only save the write if the buffer is completely
1708 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001709 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001710 (!s->compressed &&
1711 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1712 (s->compressed &&
1713 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001714 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001715 iov.iov_base = buf;
1716 iov.iov_len = n << BDRV_SECTOR_BITS;
1717 qemu_iovec_init_external(&qiov, &iov, 1);
1718
1719 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001720 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001721 if (ret < 0) {
1722 return ret;
1723 }
1724 break;
1725 }
1726 /* fall-through */
1727
1728 case BLK_ZERO:
1729 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001730 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001731 break;
1732 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001733 ret = blk_co_pwrite_zeroes(s->target,
1734 sector_num << BDRV_SECTOR_BITS,
1735 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001736 if (ret < 0) {
1737 return ret;
1738 }
1739 break;
1740 }
1741
1742 sector_num += n;
1743 nb_sectors -= n;
1744 buf += n * BDRV_SECTOR_SIZE;
1745 }
1746
1747 return 0;
1748}
1749
Peter Lieven2d9187b2017-02-28 13:40:07 +01001750static void coroutine_fn convert_co_do_copy(void *opaque)
1751{
1752 ImgConvertState *s = opaque;
1753 uint8_t *buf = NULL;
1754 int ret, i;
1755 int index = -1;
1756
1757 for (i = 0; i < s->num_coroutines; i++) {
1758 if (s->co[i] == qemu_coroutine_self()) {
1759 index = i;
1760 break;
1761 }
1762 }
1763 assert(index >= 0);
1764
1765 s->running_coroutines++;
1766 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1767
1768 while (1) {
1769 int n;
1770 int64_t sector_num;
1771 enum ImgConvertBlockStatus status;
1772
1773 qemu_co_mutex_lock(&s->lock);
1774 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1775 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001776 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001777 }
1778 n = convert_iteration_sectors(s, s->sector_num);
1779 if (n < 0) {
1780 qemu_co_mutex_unlock(&s->lock);
1781 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001782 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001783 }
1784 /* save current sector and allocation status to local variables */
1785 sector_num = s->sector_num;
1786 status = s->status;
1787 if (!s->min_sparse && s->status == BLK_ZERO) {
1788 n = MIN(n, s->buf_sectors);
1789 }
1790 /* increment global sector counter so that other coroutines can
1791 * already continue reading beyond this request */
1792 s->sector_num += n;
1793 qemu_co_mutex_unlock(&s->lock);
1794
1795 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1796 s->allocated_done += n;
1797 qemu_progress_print(100.0 * s->allocated_done /
1798 s->allocated_sectors, 0);
1799 }
1800
1801 if (status == BLK_DATA) {
1802 ret = convert_co_read(s, sector_num, n, buf);
1803 if (ret < 0) {
1804 error_report("error while reading sector %" PRId64
1805 ": %s", sector_num, strerror(-ret));
1806 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001807 }
1808 } else if (!s->min_sparse && status == BLK_ZERO) {
1809 status = BLK_DATA;
1810 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1811 }
1812
1813 if (s->wr_in_order) {
1814 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001815 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001816 s->wait_sector_num[index] = sector_num;
1817 qemu_coroutine_yield();
1818 }
1819 s->wait_sector_num[index] = -1;
1820 }
1821
Anton Nefedovb91127e2017-04-26 11:33:15 +03001822 if (s->ret == -EINPROGRESS) {
1823 ret = convert_co_write(s, sector_num, n, buf, status);
1824 if (ret < 0) {
1825 error_report("error while writing sector %" PRId64
1826 ": %s", sector_num, strerror(-ret));
1827 s->ret = ret;
1828 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001829 }
1830
1831 if (s->wr_in_order) {
1832 /* reenter the coroutine that might have waited
1833 * for this write to complete */
1834 s->wr_offs = sector_num + n;
1835 for (i = 0; i < s->num_coroutines; i++) {
1836 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1837 /*
1838 * A -> B -> A cannot occur because A has
1839 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1840 * B will never enter A during this time window.
1841 */
1842 qemu_coroutine_enter(s->co[i]);
1843 break;
1844 }
1845 }
1846 }
1847 }
1848
Peter Lieven2d9187b2017-02-28 13:40:07 +01001849 qemu_vfree(buf);
1850 s->co[index] = NULL;
1851 s->running_coroutines--;
1852 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1853 /* the convert job finished successfully */
1854 s->ret = 0;
1855 }
1856}
1857
Kevin Wolf690c7302015-03-19 13:33:32 +01001858static int convert_do_copy(ImgConvertState *s)
1859{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001860 int ret, i, n;
1861 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001862
1863 /* Check whether we have zero initialisation or can get it efficiently */
1864 s->has_zero_init = s->min_sparse && !s->target_has_backing
1865 ? bdrv_has_zero_init(blk_bs(s->target))
1866 : false;
1867
1868 if (!s->has_zero_init && !s->target_has_backing &&
1869 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1870 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001871 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001872 if (ret == 0) {
1873 s->has_zero_init = true;
1874 }
1875 }
1876
1877 /* Allocate buffer for copied data. For compressed images, only one cluster
1878 * can be copied at a time. */
1879 if (s->compressed) {
1880 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1881 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001882 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001883 }
1884 s->buf_sectors = s->cluster_sectors;
1885 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001886
Kevin Wolf690c7302015-03-19 13:33:32 +01001887 while (sector_num < s->total_sectors) {
1888 n = convert_iteration_sectors(s, sector_num);
1889 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001890 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001891 }
Max Reitzaad15de2016-03-24 23:33:57 +01001892 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1893 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001894 s->allocated_sectors += n;
1895 }
1896 sector_num += n;
1897 }
1898
1899 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001900 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001901 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001902
Peter Lieven2d9187b2017-02-28 13:40:07 +01001903 qemu_co_mutex_init(&s->lock);
1904 for (i = 0; i < s->num_coroutines; i++) {
1905 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1906 s->wait_sector_num[i] = -1;
1907 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001908 }
1909
Anton Nefedovb91127e2017-04-26 11:33:15 +03001910 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001911 main_loop_wait(false);
1912 }
1913
1914 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001915 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001916 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001917 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001918 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001919 }
1920 }
1921
Peter Lieven2d9187b2017-02-28 13:40:07 +01001922 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001923}
1924
bellardea2384d2004-08-01 21:59:26 +00001925static int img_convert(int argc, char **argv)
1926{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001927 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001928 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001929 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1930 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001931 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001932 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001933 BlockDriverState *out_bs;
1934 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001935 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001936 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001937 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001938 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001939 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001940 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08001941 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00001942
Peter Lieven9fd77f92017-04-21 11:11:55 +02001943 ImgConvertState s = (ImgConvertState) {
1944 /* Need at least 4k of zeros for sparse detection */
1945 .min_sparse = 8,
1946 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1947 .wr_in_order = true,
1948 .num_coroutines = 8,
1949 };
1950
bellardea2384d2004-08-01 21:59:26 +00001951 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001952 static const struct option long_options[] = {
1953 {"help", no_argument, 0, 'h'},
1954 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001955 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001956 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001957 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001958 {0, 0, 0, 0}
1959 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01001960 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001961 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001962 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001963 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001964 }
bellardea2384d2004-08-01 21:59:26 +00001965 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001966 case ':':
1967 missing_argument(argv[optind - 1]);
1968 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001969 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001970 unrecognized_option(argv[optind - 1]);
1971 break;
bellardea2384d2004-08-01 21:59:26 +00001972 case 'h':
1973 help();
1974 break;
1975 case 'f':
1976 fmt = optarg;
1977 break;
1978 case 'O':
1979 out_fmt = optarg;
1980 break;
thsf58c7b32008-06-05 21:53:49 +00001981 case 'B':
1982 out_baseimg = optarg;
1983 break;
bellardea2384d2004-08-01 21:59:26 +00001984 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02001985 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00001986 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001987 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001988 if (!is_valid_option_list(optarg)) {
1989 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001990 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001991 }
1992 if (!options) {
1993 options = g_strdup(optarg);
1994 } else {
1995 char *old_options = options;
1996 options = g_strdup_printf("%s,%s", options, optarg);
1997 g_free(old_options);
1998 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001999 break;
edison51ef6722010-09-21 19:58:41 -07002000 case 's':
2001 snapshot_name = optarg;
2002 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002003 case 'l':
2004 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002005 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2006 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002007 if (!sn_opts) {
2008 error_report("Failed in parsing snapshot param '%s'",
2009 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002010 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002011 }
2012 } else {
2013 snapshot_name = optarg;
2014 }
2015 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002016 case 'S':
2017 {
2018 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002019
2020 sval = cvtnum(optarg);
2021 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002022 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002023 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002024 }
2025
Peter Lieven9fd77f92017-04-21 11:11:55 +02002026 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002027 break;
2028 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002029 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002030 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002031 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002032 case 't':
2033 cache = optarg;
2034 break;
Max Reitz40055952014-07-22 22:58:42 +02002035 case 'T':
2036 src_cache = optarg;
2037 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002038 case 'q':
2039 quiet = true;
2040 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002041 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002042 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002043 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002044 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002045 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2046 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002047 error_report("Invalid number of coroutines. Allowed number of"
2048 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002049 goto fail_getopt;
2050 }
2051 break;
2052 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002053 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002054 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002055 case 'U':
2056 force_share = true;
2057 break;
Max Reitz3258b912017-04-26 15:46:47 +02002058 case OPTION_OBJECT: {
2059 QemuOpts *object_opts;
2060 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2061 optarg, true);
2062 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002063 goto fail_getopt;
2064 }
2065 break;
Max Reitz3258b912017-04-26 15:46:47 +02002066 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002067 case OPTION_IMAGE_OPTS:
2068 image_opts = true;
2069 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002070 case OPTION_TARGET_IMAGE_OPTS:
2071 tgt_image_opts = true;
2072 break;
bellardea2384d2004-08-01 21:59:26 +00002073 }
2074 }
ths3b46e622007-09-17 08:09:54 +00002075
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002076 if (!out_fmt && !tgt_image_opts) {
2077 out_fmt = "raw";
2078 }
2079
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002080 if (qemu_opts_foreach(&qemu_object_opts,
2081 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002082 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002083 goto fail_getopt;
2084 }
2085
Peter Lieven9fd77f92017-04-21 11:11:55 +02002086 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002087 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002088 goto fail_getopt;
2089 }
2090
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002091 if (tgt_image_opts && !skip_create) {
2092 error_report("--target-image-opts requires use of -n flag");
2093 goto fail_getopt;
2094 }
2095
Peter Lieven9fd77f92017-04-21 11:11:55 +02002096 s.src_num = argc - optind - 1;
2097 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2098
2099 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002100 if (out_fmt) {
2101 ret = print_block_option_help(out_filename, out_fmt);
2102 goto fail_getopt;
2103 } else {
2104 error_report("Option help requires a format be specified");
2105 goto fail_getopt;
2106 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002107 }
2108
2109 if (s.src_num < 1) {
2110 error_report("Must specify image file name");
2111 goto fail_getopt;
2112 }
2113
2114
Peter Lieven9fd77f92017-04-21 11:11:55 +02002115 /* ret is still -EINVAL until here */
2116 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2117 if (ret < 0) {
2118 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002119 goto fail_getopt;
2120 }
2121
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002122 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002123 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002124 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002125 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002126 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002127 qemu_progress_print(0, 100);
2128
Peter Lieven9fd77f92017-04-21 11:11:55 +02002129 s.src = g_new0(BlockBackend *, s.src_num);
2130 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002131
Peter Lieven9fd77f92017-04-21 11:11:55 +02002132 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2133 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002134 fmt, src_flags, src_writethrough, quiet,
2135 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002136 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002137 ret = -1;
2138 goto out;
2139 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002140 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2141 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002142 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002143 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002144 ret = -1;
2145 goto out;
2146 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002147 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002148 }
bellardea2384d2004-08-01 21:59:26 +00002149
Wenchao Xiaef806542013-12-04 17:10:57 +08002150 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002151 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002152 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2153 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2154 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002155 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002156 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002157 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002158 ret = -1;
2159 goto out;
2160 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002161
Peter Lieven9fd77f92017-04-21 11:11:55 +02002162 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2163 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002164 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002165 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002166 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002167 ret = -1;
2168 goto out;
edison51ef6722010-09-21 19:58:41 -07002169 }
2170
Max Reitz2e024cd2015-02-11 09:58:46 -05002171 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002172 /* Find driver and parse its options */
2173 drv = bdrv_find_format(out_fmt);
2174 if (!drv) {
2175 error_report("Unknown file format '%s'", out_fmt);
2176 ret = -1;
2177 goto out;
2178 }
2179
2180 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2181 if (!proto_drv) {
2182 error_report_err(local_err);
2183 ret = -1;
2184 goto out;
2185 }
2186
Max Reitz2e024cd2015-02-11 09:58:46 -05002187 if (!drv->create_opts) {
2188 error_report("Format driver '%s' does not support image creation",
2189 drv->format_name);
2190 ret = -1;
2191 goto out;
2192 }
Max Reitzf75613c2014-12-02 18:32:46 +01002193
Max Reitz2e024cd2015-02-11 09:58:46 -05002194 if (!proto_drv->create_opts) {
2195 error_report("Protocol driver '%s' does not support image creation",
2196 proto_drv->format_name);
2197 ret = -1;
2198 goto out;
2199 }
Max Reitzf75613c2014-12-02 18:32:46 +01002200
Max Reitz2e024cd2015-02-11 09:58:46 -05002201 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2202 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002203
Max Reitz2e024cd2015-02-11 09:58:46 -05002204 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002205 if (options) {
2206 qemu_opts_do_parse(opts, options, NULL, &local_err);
2207 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002208 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002209 ret = -1;
2210 goto out;
2211 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002212 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002213
Peter Lieven9fd77f92017-04-21 11:11:55 +02002214 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002215 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002216 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2217 if (ret < 0) {
2218 goto out;
2219 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002220 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002221
Kevin Wolfa18953f2010-10-14 15:46:04 +02002222 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002223 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002224 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002225 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002226 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002228
Max Reitz48758a82017-04-26 15:46:48 +02002229 if (s.src_num > 1 && out_baseimg) {
2230 error_report("Having a backing file for the target makes no sense when "
2231 "concatenating multiple input images");
2232 ret = -1;
2233 goto out;
2234 }
2235
Kevin Wolfefa84d42009-05-18 16:42:12 +02002236 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002237 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002238 bool encryption =
2239 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002240 const char *encryptfmt =
2241 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002242 const char *preallocation =
2243 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002244
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002245 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002246 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002247 ret = -1;
2248 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002249 }
2250
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002251 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002252 error_report("Compression and encryption not supported at "
2253 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002254 ret = -1;
2255 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002256 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002257
Chunyan Liu83d05212014-06-05 17:20:51 +08002258 if (preallocation
2259 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002260 {
2261 error_report("Compression and preallocation not supported at "
2262 "the same time");
2263 ret = -1;
2264 goto out;
2265 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002266 }
2267
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002268 if (!skip_create) {
2269 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002270 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002271 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002272 error_reportf_err(local_err, "%s: error while converting %s: ",
2273 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002274 goto out;
bellardea2384d2004-08-01 21:59:26 +00002275 }
2276 }
ths3b46e622007-09-17 08:09:54 +00002277
Peter Lieven9fd77f92017-04-21 11:11:55 +02002278 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002279 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002280 if (ret < 0) {
2281 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002282 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002283 }
2284
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002285 if (skip_create) {
2286 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2287 flags, writethrough, quiet, false);
2288 } else {
2289 /* TODO ultimately we should allow --target-image-opts
2290 * to be used even when -n is not given.
2291 * That has to wait for bdrv_create to be improved
2292 * to allow filenames in option syntax
2293 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002294 s.target = img_open_new_file(out_filename, opts, out_fmt,
2295 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002296 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002298 ret = -1;
2299 goto out;
2300 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002301 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002302
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002303 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2304 error_report("Compression not supported for this file format");
2305 ret = -1;
2306 goto out;
2307 }
2308
Eric Blake5def6b82016-06-23 16:37:19 -06002309 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002310 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2311 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002312 s.buf_sectors = MIN(32768,
2313 MAX(s.buf_sectors,
2314 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2315 out_bs->bl.pdiscard_alignment >>
2316 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002317
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002318 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002319 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002320 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002321 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002322 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002323 ret = -1;
2324 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002325 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002326 error_report("output file is smaller than input file");
2327 ret = -1;
2328 goto out;
2329 }
2330 }
2331
Peter Lieven24f833c2013-11-27 11:07:07 +01002332 ret = bdrv_get_info(out_bs, &bdi);
2333 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002334 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002335 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002336 goto out;
2337 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002338 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002339 s.compressed = s.compressed || bdi.needs_compressed_writes;
2340 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002341 }
2342
Peter Lieven9fd77f92017-04-21 11:11:55 +02002343 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002344out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002345 if (!ret) {
2346 qemu_progress_print(100, 0);
2347 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002348 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002349 qemu_opts_del(opts);
2350 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002351 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002352 blk_unref(s.target);
2353 if (s.src) {
2354 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2355 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002356 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002357 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002358 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002359 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002360fail_getopt:
2361 g_free(options);
2362
Peter Lieven9fd77f92017-04-21 11:11:55 +02002363 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002364}
2365
bellard57d1a2b2004-08-03 21:15:11 +00002366
bellardfaea38e2006-08-05 21:31:00 +00002367static void dump_snapshots(BlockDriverState *bs)
2368{
2369 QEMUSnapshotInfo *sn_tab, *sn;
2370 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002371
2372 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2373 if (nb_sns <= 0)
2374 return;
2375 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002376 bdrv_snapshot_dump(fprintf, stdout, NULL);
2377 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002378 for(i = 0; i < nb_sns; i++) {
2379 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002380 bdrv_snapshot_dump(fprintf, stdout, sn);
2381 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002382 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002383 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002384}
2385
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002386static void dump_json_image_info_list(ImageInfoList *list)
2387{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002388 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002389 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002390 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002391
2392 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2393 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002394 str = qobject_to_json_pretty(obj);
2395 assert(str != NULL);
2396 printf("%s\n", qstring_get_str(str));
2397 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002398 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002399 QDECREF(str);
2400}
2401
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002402static void dump_json_image_info(ImageInfo *info)
2403{
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002404 QString *str;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002405 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002406 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002407
2408 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2409 visit_complete(v, &obj);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002410 str = qobject_to_json_pretty(obj);
2411 assert(str != NULL);
2412 printf("%s\n", qstring_get_str(str));
2413 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002414 visit_free(v);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002415 QDECREF(str);
2416}
2417
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002418static void dump_human_image_info_list(ImageInfoList *list)
2419{
2420 ImageInfoList *elem;
2421 bool delim = false;
2422
2423 for (elem = list; elem; elem = elem->next) {
2424 if (delim) {
2425 printf("\n");
2426 }
2427 delim = true;
2428
Wenchao Xia5b917042013-05-25 11:09:45 +08002429 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002430 }
2431}
2432
2433static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2434{
2435 return strcmp(a, b) == 0;
2436}
2437
2438/**
2439 * Open an image file chain and return an ImageInfoList
2440 *
2441 * @filename: topmost image filename
2442 * @fmt: topmost image format (may be NULL to autodetect)
2443 * @chain: true - enumerate entire backing file chain
2444 * false - only topmost image file
2445 *
2446 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2447 * image file. If there was an error a message will have been printed to
2448 * stderr.
2449 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002450static ImageInfoList *collect_image_info_list(bool image_opts,
2451 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002452 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002453 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002454{
2455 ImageInfoList *head = NULL;
2456 ImageInfoList **last = &head;
2457 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002458 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002459
2460 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2461
2462 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002463 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002464 BlockDriverState *bs;
2465 ImageInfo *info;
2466 ImageInfoList *elem;
2467
2468 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2469 error_report("Backing file '%s' creates an infinite loop.",
2470 filename);
2471 goto err;
2472 }
2473 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2474
Max Reitzefaa7c42016-03-16 19:54:38 +01002475 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002476 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2477 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002478 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002479 goto err;
2480 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002481 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002482
Wenchao Xia43526ec2013-06-06 12:27:58 +08002483 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002484 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002485 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002486 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002487 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002488 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002489
2490 elem = g_new0(ImageInfoList, 1);
2491 elem->value = info;
2492 *last = elem;
2493 last = &elem->next;
2494
Markus Armbruster26f54e92014-10-07 13:59:04 +02002495 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002496
2497 filename = fmt = NULL;
2498 if (chain) {
2499 if (info->has_full_backing_filename) {
2500 filename = info->full_backing_filename;
2501 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002502 error_report("Could not determine absolute backing filename,"
2503 " but backing filename '%s' present",
2504 info->backing_filename);
2505 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002506 }
2507 if (info->has_backing_filename_format) {
2508 fmt = info->backing_filename_format;
2509 }
2510 }
2511 }
2512 g_hash_table_destroy(filenames);
2513 return head;
2514
2515err:
2516 qapi_free_ImageInfoList(head);
2517 g_hash_table_destroy(filenames);
2518 return NULL;
2519}
2520
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002521static int img_info(int argc, char **argv)
2522{
2523 int c;
2524 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002525 bool chain = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002526 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002527 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002528 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002529 bool force_share = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002530
bellardea2384d2004-08-01 21:59:26 +00002531 fmt = NULL;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002532 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002533 for(;;) {
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002534 int option_index = 0;
2535 static const struct option long_options[] = {
2536 {"help", no_argument, 0, 'h'},
2537 {"format", required_argument, 0, 'f'},
2538 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002539 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002540 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002541 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002542 {"force-share", no_argument, 0, 'U'},
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002543 {0, 0, 0, 0}
2544 };
Fam Zheng335e9932017-05-03 00:35:39 +08002545 c = getopt_long(argc, argv, ":f:hU",
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002546 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002547 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002548 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002549 }
bellardea2384d2004-08-01 21:59:26 +00002550 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002551 case ':':
2552 missing_argument(argv[optind - 1]);
2553 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002554 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002555 unrecognized_option(argv[optind - 1]);
2556 break;
bellardea2384d2004-08-01 21:59:26 +00002557 case 'h':
2558 help();
2559 break;
2560 case 'f':
2561 fmt = optarg;
2562 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002563 case 'U':
2564 force_share = true;
2565 break;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002566 case OPTION_OUTPUT:
2567 output = optarg;
2568 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002569 case OPTION_BACKING_CHAIN:
2570 chain = true;
2571 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002572 case OPTION_OBJECT: {
2573 QemuOpts *opts;
2574 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2575 optarg, true);
2576 if (!opts) {
2577 return 1;
2578 }
2579 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002580 case OPTION_IMAGE_OPTS:
2581 image_opts = true;
2582 break;
bellardea2384d2004-08-01 21:59:26 +00002583 }
2584 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002585 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002586 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002587 }
bellardea2384d2004-08-01 21:59:26 +00002588 filename = argv[optind++];
2589
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002590 if (output && !strcmp(output, "json")) {
2591 output_format = OFORMAT_JSON;
2592 } else if (output && !strcmp(output, "human")) {
2593 output_format = OFORMAT_HUMAN;
2594 } else if (output) {
2595 error_report("--output must be used with human or json as argument.");
2596 return 1;
2597 }
2598
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002599 if (qemu_opts_foreach(&qemu_object_opts,
2600 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002601 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002602 return 1;
2603 }
2604
Fam Zheng335e9932017-05-03 00:35:39 +08002605 list = collect_image_info_list(image_opts, filename, fmt, chain,
2606 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002607 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002608 return 1;
2609 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002610
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002611 switch (output_format) {
2612 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002613 dump_human_image_info_list(list);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002614 break;
2615 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002616 if (chain) {
2617 dump_json_image_info_list(list);
2618 } else {
2619 dump_json_image_info(list->value);
2620 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002621 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002622 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002623
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002624 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002625 return 0;
2626}
2627
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002628static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2629 MapEntry *next)
2630{
2631 switch (output_format) {
2632 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002633 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002634 error_report("File contains external, encrypted or compressed clusters.");
2635 exit(1);
2636 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002637 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002638 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002639 e->start, e->length,
2640 e->has_offset ? e->offset : 0,
2641 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002642 }
2643 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2644 * Modify the flags here to allow more coalescing.
2645 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002646 if (next && (!next->data || next->zero)) {
2647 next->data = false;
2648 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002649 }
2650 break;
2651 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002652 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2653 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002654 (e->start == 0 ? "[" : ",\n"),
2655 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002656 e->zero ? "true" : "false",
2657 e->data ? "true" : "false");
2658 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002659 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002660 }
2661 putchar('}');
2662
2663 if (!next) {
2664 printf("]\n");
2665 }
2666 break;
2667 }
2668}
2669
Eric Blake5e344dd2017-10-11 22:47:02 -05002670static int get_block_status(BlockDriverState *bs, int64_t offset,
2671 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002672{
Eric Blake237d78f2017-10-11 22:47:03 -05002673 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002674 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002675 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002676 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002677 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002678
2679 /* As an optimization, we could cache the current range of unallocated
2680 * clusters in each file of the chain, and avoid querying the same
2681 * range repeatedly.
2682 */
2683
2684 depth = 0;
2685 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002686 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002687 if (ret < 0) {
2688 return ret;
2689 }
Eric Blake237d78f2017-10-11 22:47:03 -05002690 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002691 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2692 break;
2693 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002694 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002695 if (bs == NULL) {
2696 ret = 0;
2697 break;
2698 }
2699
2700 depth++;
2701 }
2702
John Snow28756452016-02-05 13:12:33 -05002703 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2704
2705 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002706 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002707 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002708 .data = !!(ret & BDRV_BLOCK_DATA),
2709 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002710 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002711 .has_offset = has_offset,
2712 .depth = depth,
2713 .has_filename = file && has_offset,
2714 .filename = file && has_offset ? file->filename : NULL,
2715 };
2716
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002717 return 0;
2718}
2719
Fam Zheng16b0d552016-01-26 11:59:02 +08002720static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2721{
2722 if (curr->length == 0) {
2723 return false;
2724 }
2725 if (curr->zero != next->zero ||
2726 curr->data != next->data ||
2727 curr->depth != next->depth ||
2728 curr->has_filename != next->has_filename ||
2729 curr->has_offset != next->has_offset) {
2730 return false;
2731 }
2732 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2733 return false;
2734 }
2735 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2736 return false;
2737 }
2738 return true;
2739}
2740
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002741static int img_map(int argc, char **argv)
2742{
2743 int c;
2744 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002745 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002746 BlockDriverState *bs;
2747 const char *filename, *fmt, *output;
2748 int64_t length;
2749 MapEntry curr = { .length = 0 }, next;
2750 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002751 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002752 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002753
2754 fmt = NULL;
2755 output = NULL;
2756 for (;;) {
2757 int option_index = 0;
2758 static const struct option long_options[] = {
2759 {"help", no_argument, 0, 'h'},
2760 {"format", required_argument, 0, 'f'},
2761 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002762 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002763 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002764 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002765 {0, 0, 0, 0}
2766 };
Fam Zheng335e9932017-05-03 00:35:39 +08002767 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002768 long_options, &option_index);
2769 if (c == -1) {
2770 break;
2771 }
2772 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002773 case ':':
2774 missing_argument(argv[optind - 1]);
2775 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002776 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002777 unrecognized_option(argv[optind - 1]);
2778 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002779 case 'h':
2780 help();
2781 break;
2782 case 'f':
2783 fmt = optarg;
2784 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002785 case 'U':
2786 force_share = true;
2787 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002788 case OPTION_OUTPUT:
2789 output = optarg;
2790 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002791 case OPTION_OBJECT: {
2792 QemuOpts *opts;
2793 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2794 optarg, true);
2795 if (!opts) {
2796 return 1;
2797 }
2798 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002799 case OPTION_IMAGE_OPTS:
2800 image_opts = true;
2801 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002802 }
2803 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002804 if (optind != argc - 1) {
2805 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002806 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002807 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002808
2809 if (output && !strcmp(output, "json")) {
2810 output_format = OFORMAT_JSON;
2811 } else if (output && !strcmp(output, "human")) {
2812 output_format = OFORMAT_HUMAN;
2813 } else if (output) {
2814 error_report("--output must be used with human or json as argument.");
2815 return 1;
2816 }
2817
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002818 if (qemu_opts_foreach(&qemu_object_opts,
2819 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002820 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002821 return 1;
2822 }
2823
Fam Zheng335e9932017-05-03 00:35:39 +08002824 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002825 if (!blk) {
2826 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002827 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002828 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002829
2830 if (output_format == OFORMAT_HUMAN) {
2831 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2832 }
2833
Max Reitzf1d3cd72015-02-05 13:58:18 -05002834 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002835 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002836 int64_t offset = curr.start + curr.length;
2837 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002838
2839 /* Probe up to 1 GiB at a time. */
Eric Blake5e344dd2017-10-11 22:47:02 -05002840 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2841 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002842
2843 if (ret < 0) {
2844 error_report("Could not read file metadata: %s", strerror(-ret));
2845 goto out;
2846 }
2847
Fam Zheng16b0d552016-01-26 11:59:02 +08002848 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002849 curr.length += next.length;
2850 continue;
2851 }
2852
2853 if (curr.length > 0) {
2854 dump_map_entry(output_format, &curr, &next);
2855 }
2856 curr = next;
2857 }
2858
2859 dump_map_entry(output_format, &curr, NULL);
2860
2861out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002862 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002863 return ret < 0;
2864}
2865
aliguorif7b4a942009-01-07 17:40:15 +00002866#define SNAPSHOT_LIST 1
2867#define SNAPSHOT_CREATE 2
2868#define SNAPSHOT_APPLY 3
2869#define SNAPSHOT_DELETE 4
2870
Stuart Brady153859b2009-06-07 00:42:17 +01002871static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002872{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002873 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002874 BlockDriverState *bs;
2875 QEMUSnapshotInfo sn;
2876 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002877 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002878 int action = 0;
2879 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002880 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002881 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002882 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002883 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002884
Kevin Wolfce099542016-03-15 13:01:04 +01002885 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002886 /* Parse commandline parameters */
2887 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002888 static const struct option long_options[] = {
2889 {"help", no_argument, 0, 'h'},
2890 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002891 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002892 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002893 {0, 0, 0, 0}
2894 };
Fam Zheng335e9932017-05-03 00:35:39 +08002895 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002896 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002897 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002898 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002899 }
aliguorif7b4a942009-01-07 17:40:15 +00002900 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002901 case ':':
2902 missing_argument(argv[optind - 1]);
2903 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002904 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002905 unrecognized_option(argv[optind - 1]);
2906 break;
aliguorif7b4a942009-01-07 17:40:15 +00002907 case 'h':
2908 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002909 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002910 case 'l':
2911 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002912 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002913 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002914 }
2915 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002916 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002917 break;
2918 case 'a':
2919 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002920 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002921 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002922 }
2923 action = SNAPSHOT_APPLY;
2924 snapshot_name = optarg;
2925 break;
2926 case 'c':
2927 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002928 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002929 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002930 }
2931 action = SNAPSHOT_CREATE;
2932 snapshot_name = optarg;
2933 break;
2934 case 'd':
2935 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002936 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002937 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002938 }
2939 action = SNAPSHOT_DELETE;
2940 snapshot_name = optarg;
2941 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002942 case 'q':
2943 quiet = true;
2944 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002945 case 'U':
2946 force_share = true;
2947 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002948 case OPTION_OBJECT: {
2949 QemuOpts *opts;
2950 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2951 optarg, true);
2952 if (!opts) {
2953 return 1;
2954 }
2955 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002956 case OPTION_IMAGE_OPTS:
2957 image_opts = true;
2958 break;
aliguorif7b4a942009-01-07 17:40:15 +00002959 }
2960 }
2961
Kevin Wolffc11eb22013-08-05 10:53:04 +02002962 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002963 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002964 }
aliguorif7b4a942009-01-07 17:40:15 +00002965 filename = argv[optind++];
2966
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002967 if (qemu_opts_foreach(&qemu_object_opts,
2968 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002969 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002970 return 1;
2971 }
2972
aliguorif7b4a942009-01-07 17:40:15 +00002973 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08002974 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2975 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002976 if (!blk) {
2977 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002978 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002979 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002980
2981 /* Perform the requested action */
2982 switch(action) {
2983 case SNAPSHOT_LIST:
2984 dump_snapshots(bs);
2985 break;
2986
2987 case SNAPSHOT_CREATE:
2988 memset(&sn, 0, sizeof(sn));
2989 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2990
2991 qemu_gettimeofday(&tv);
2992 sn.date_sec = tv.tv_sec;
2993 sn.date_nsec = tv.tv_usec * 1000;
2994
2995 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002996 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002997 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002998 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002999 }
aliguorif7b4a942009-01-07 17:40:15 +00003000 break;
3001
3002 case SNAPSHOT_APPLY:
3003 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003004 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003005 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003006 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003007 }
aliguorif7b4a942009-01-07 17:40:15 +00003008 break;
3009
3010 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003011 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003012 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003013 error_reportf_err(err, "Could not delete snapshot '%s': ",
3014 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003015 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003016 }
aliguorif7b4a942009-01-07 17:40:15 +00003017 break;
3018 }
3019
3020 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003021 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003022 if (ret) {
3023 return 1;
3024 }
Stuart Brady153859b2009-06-07 00:42:17 +01003025 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003026}
3027
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003028static int img_rebase(int argc, char **argv)
3029{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003030 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003031 uint8_t *buf_old = NULL;
3032 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003033 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003034 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003035 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3036 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003037 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003038 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003039 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003040 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003041 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003042 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003043 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003044
3045 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003046 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003047 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003048 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003049 out_baseimg = NULL;
3050 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003051 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003052 static const struct option long_options[] = {
3053 {"help", no_argument, 0, 'h'},
3054 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003055 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003056 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003057 {0, 0, 0, 0}
3058 };
Fam Zheng335e9932017-05-03 00:35:39 +08003059 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003060 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003061 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003062 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003063 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003064 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003065 case ':':
3066 missing_argument(argv[optind - 1]);
3067 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003068 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003069 unrecognized_option(argv[optind - 1]);
3070 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003071 case 'h':
3072 help();
3073 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003074 case 'f':
3075 fmt = optarg;
3076 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003077 case 'F':
3078 out_basefmt = optarg;
3079 break;
3080 case 'b':
3081 out_baseimg = optarg;
3082 break;
3083 case 'u':
3084 unsafe = 1;
3085 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003086 case 'p':
3087 progress = 1;
3088 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003089 case 't':
3090 cache = optarg;
3091 break;
Max Reitz40055952014-07-22 22:58:42 +02003092 case 'T':
3093 src_cache = optarg;
3094 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003095 case 'q':
3096 quiet = true;
3097 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003098 case OPTION_OBJECT: {
3099 QemuOpts *opts;
3100 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3101 optarg, true);
3102 if (!opts) {
3103 return 1;
3104 }
3105 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003106 case OPTION_IMAGE_OPTS:
3107 image_opts = true;
3108 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003109 case 'U':
3110 force_share = true;
3111 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003112 }
3113 }
3114
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003115 if (quiet) {
3116 progress = 0;
3117 }
3118
Fam Zhengac1307a2014-04-22 13:36:11 +08003119 if (optind != argc - 1) {
3120 error_exit("Expecting one image file name");
3121 }
3122 if (!unsafe && !out_baseimg) {
3123 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003124 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003125 filename = argv[optind++];
3126
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003127 if (qemu_opts_foreach(&qemu_object_opts,
3128 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003129 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003130 return 1;
3131 }
3132
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003133 qemu_progress_init(progress, 2.0);
3134 qemu_progress_print(0, 100);
3135
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003136 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003137 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003138 if (ret < 0) {
3139 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003140 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003141 }
3142
Kevin Wolfce099542016-03-15 13:01:04 +01003143 src_flags = 0;
3144 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003145 if (ret < 0) {
3146 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003147 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003148 }
3149
Kevin Wolfce099542016-03-15 13:01:04 +01003150 /* The source files are opened read-only, don't care about WCE */
3151 assert((src_flags & BDRV_O_RDWR) == 0);
3152 (void) src_writethrough;
3153
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003154 /*
3155 * Open the images.
3156 *
3157 * Ignore the old backing file for unsafe rebase in case we want to correct
3158 * the reference to a renamed or moved backing file.
3159 */
Fam Zheng335e9932017-05-03 00:35:39 +08003160 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3161 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003162 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003163 ret = -1;
3164 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003165 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003166 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003167
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003168 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003169 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003170 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003171 ret = -1;
3172 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003173 }
3174 }
3175
3176 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003177 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003178 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003179 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003180
Max Reitz644483d2015-02-05 13:58:17 -05003181 if (bs->backing_format[0] != '\0') {
3182 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003183 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003184 }
3185
Fam Zheng335e9932017-05-03 00:35:39 +08003186 if (force_share) {
3187 if (!options) {
3188 options = qdict_new();
3189 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003190 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003191 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003192 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003193 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003194 options, src_flags, &local_err);
3195 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003196 error_reportf_err(local_err,
3197 "Could not open old backing file '%s': ",
3198 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003199 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003200 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003201 }
Max Reitz644483d2015-02-05 13:58:17 -05003202
Alex Bligha6166732012-10-16 13:46:18 +01003203 if (out_baseimg[0]) {
Fam Zheng335e9932017-05-03 00:35:39 +08003204 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003205 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003206 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003207 }
3208 if (force_share) {
3209 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003210 }
3211
Max Reitzefaa7c42016-03-16 19:54:38 +01003212 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003213 options, src_flags, &local_err);
3214 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003215 error_reportf_err(local_err,
3216 "Could not open new backing file '%s': ",
3217 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003218 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003219 goto out;
3220 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003221 }
3222 }
3223
3224 /*
3225 * Check each unallocated cluster in the COW file. If it is unallocated,
3226 * accesses go to the backing file. We must therefore compare this cluster
3227 * in the old and new backing file, and if they differ we need to copy it
3228 * from the old backing file into the COW file.
3229 *
3230 * If qemu-img crashes during this step, no harm is done. The content of
3231 * the image is the same as the original one at any time.
3232 */
3233 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003234 int64_t num_sectors;
3235 int64_t old_backing_num_sectors;
3236 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003237 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003238 int n;
Eric Blaked6a644b2017-07-07 07:44:57 -05003239 int64_t count;
Kevin Wolf1f710492012-10-12 14:29:18 +02003240 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003241
Max Reitzf1d3cd72015-02-05 13:58:18 -05003242 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3243 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003244
Max Reitzf1d3cd72015-02-05 13:58:18 -05003245 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003246 if (num_sectors < 0) {
3247 error_report("Could not get size of '%s': %s",
3248 filename, strerror(-num_sectors));
3249 ret = -1;
3250 goto out;
3251 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003252 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003253 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003254 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003255
3256 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3257 error_report("Could not get size of '%s': %s",
3258 backing_name, strerror(-old_backing_num_sectors));
3259 ret = -1;
3260 goto out;
3261 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003262 if (blk_new_backing) {
3263 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003264 if (new_backing_num_sectors < 0) {
3265 error_report("Could not get size of '%s': %s",
3266 out_baseimg, strerror(-new_backing_num_sectors));
3267 ret = -1;
3268 goto out;
3269 }
Alex Bligha6166732012-10-16 13:46:18 +01003270 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003271
Kevin Wolf1f710492012-10-12 14:29:18 +02003272 if (num_sectors != 0) {
3273 local_progress = (float)100 /
3274 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3275 }
3276
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003277 for (sector = 0; sector < num_sectors; sector += n) {
3278
3279 /* How many sectors can we handle with the next read? */
3280 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3281 n = (IO_BUF_SIZE / 512);
3282 } else {
3283 n = num_sectors - sector;
3284 }
3285
3286 /* If the cluster is allocated, we don't need to take action */
Eric Blaked6a644b2017-07-07 07:44:57 -05003287 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3288 n << BDRV_SECTOR_BITS, &count);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003289 if (ret < 0) {
3290 error_report("error while reading image metadata: %s",
3291 strerror(-ret));
3292 goto out;
3293 }
Eric Blaked6a644b2017-07-07 07:44:57 -05003294 /* TODO relax this once bdrv_is_allocated does not enforce
3295 * sector alignment */
3296 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3297 n = count >> BDRV_SECTOR_BITS;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003298 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003299 continue;
3300 }
3301
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003302 /*
3303 * Read old and new backing file and take into consideration that
3304 * backing files may be smaller than the COW image.
3305 */
3306 if (sector >= old_backing_num_sectors) {
3307 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3308 } else {
3309 if (sector + n > old_backing_num_sectors) {
3310 n = old_backing_num_sectors - sector;
3311 }
3312
Eric Blake91669202016-05-06 10:26:43 -06003313 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3314 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003315 if (ret < 0) {
3316 error_report("error while reading from old backing file");
3317 goto out;
3318 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003319 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003320
Max Reitzf1d3cd72015-02-05 13:58:18 -05003321 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003322 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3323 } else {
3324 if (sector + n > new_backing_num_sectors) {
3325 n = new_backing_num_sectors - sector;
3326 }
3327
Eric Blake91669202016-05-06 10:26:43 -06003328 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3329 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003330 if (ret < 0) {
3331 error_report("error while reading from new backing file");
3332 goto out;
3333 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003334 }
3335
3336 /* If they differ, we need to write to the COW file */
3337 uint64_t written = 0;
3338
3339 while (written < n) {
3340 int pnum;
3341
3342 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003343 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003344 {
Eric Blake91669202016-05-06 10:26:43 -06003345 ret = blk_pwrite(blk,
3346 (sector + written) << BDRV_SECTOR_BITS,
3347 buf_old + written * 512,
3348 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003349 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003350 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003351 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003352 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003353 }
3354 }
3355
3356 written += pnum;
3357 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003358 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003359 }
3360 }
3361
3362 /*
3363 * Change the backing file. All clusters that are different from the old
3364 * backing file are overwritten in the COW file now, so the visible content
3365 * doesn't change when we switch the backing file.
3366 */
Alex Bligha6166732012-10-16 13:46:18 +01003367 if (out_baseimg && *out_baseimg) {
3368 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3369 } else {
3370 ret = bdrv_change_backing_file(bs, NULL, NULL);
3371 }
3372
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003373 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003374 error_report("Could not change the backing file to '%s': No "
3375 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003376 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003377 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003378 out_baseimg, strerror(-ret));
3379 }
3380
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003381 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003382 /*
3383 * TODO At this point it is possible to check if any clusters that are
3384 * allocated in the COW file are the same in the backing file. If so, they
3385 * could be dropped from the COW file. Don't do this before switching the
3386 * backing file, in case of a crash this would lead to corruption.
3387 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003388out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003389 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003390 /* Cleanup */
3391 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003392 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003393 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003394 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003395 qemu_vfree(buf_old);
3396 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003397
Markus Armbruster26f54e92014-10-07 13:59:04 +02003398 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003399 if (ret) {
3400 return 1;
3401 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003402 return 0;
3403}
3404
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003405static int img_resize(int argc, char **argv)
3406{
Markus Armbruster6750e792015-02-12 17:43:08 +01003407 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003408 int c, ret, relative;
3409 const char *filename, *fmt, *size;
Max Reitzdc5f6902017-06-13 22:20:55 +02003410 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003411 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003412 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003413 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003414 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003415
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003416 static QemuOptsList resize_options = {
3417 .name = "resize_options",
3418 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3419 .desc = {
3420 {
3421 .name = BLOCK_OPT_SIZE,
3422 .type = QEMU_OPT_SIZE,
3423 .help = "Virtual disk size"
3424 }, {
3425 /* end of list */
3426 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003427 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003428 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003429 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003430 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003431
Kevin Wolfe80fec72011-04-29 10:58:12 +02003432 /* Remove size from argv manually so that negative numbers are not treated
3433 * as options by getopt. */
3434 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003435 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003436 return 1;
3437 }
3438
3439 size = argv[--argc];
3440
3441 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003442 fmt = NULL;
3443 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003444 static const struct option long_options[] = {
3445 {"help", no_argument, 0, 'h'},
3446 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003447 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003448 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003449 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003450 {0, 0, 0, 0}
3451 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003452 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003453 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003454 if (c == -1) {
3455 break;
3456 }
3457 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003458 case ':':
3459 missing_argument(argv[optind - 1]);
3460 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003461 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003462 unrecognized_option(argv[optind - 1]);
3463 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003464 case 'h':
3465 help();
3466 break;
3467 case 'f':
3468 fmt = optarg;
3469 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003470 case 'q':
3471 quiet = true;
3472 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003473 case OPTION_OBJECT: {
3474 QemuOpts *opts;
3475 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3476 optarg, true);
3477 if (!opts) {
3478 return 1;
3479 }
3480 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003481 case OPTION_IMAGE_OPTS:
3482 image_opts = true;
3483 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003484 case OPTION_PREALLOCATION:
Marc-AndrƩ Lureauf7abe0e2017-08-24 10:46:10 +02003485 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003486 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003487 if (prealloc == PREALLOC_MODE__MAX) {
3488 error_report("Invalid preallocation mode '%s'", optarg);
3489 return 1;
3490 }
3491 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003492 case OPTION_SHRINK:
3493 shrink = true;
3494 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003495 }
3496 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003497 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003498 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003499 }
3500 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003501
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003502 if (qemu_opts_foreach(&qemu_object_opts,
3503 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003504 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003505 return 1;
3506 }
3507
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003508 /* Choose grow, shrink, or absolute resize mode */
3509 switch (size[0]) {
3510 case '+':
3511 relative = 1;
3512 size++;
3513 break;
3514 case '-':
3515 relative = -1;
3516 size++;
3517 break;
3518 default:
3519 relative = 0;
3520 break;
3521 }
3522
3523 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003524 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003525 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003526 if (err) {
3527 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003528 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003529 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003530 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003531 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003532 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3533 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003534
Max Reitzefaa7c42016-03-16 19:54:38 +01003535 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003536 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3537 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003538 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003539 ret = -1;
3540 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003541 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003542
Max Reitzdc5f6902017-06-13 22:20:55 +02003543 current_size = blk_getlength(blk);
3544 if (current_size < 0) {
3545 error_report("Failed to inquire current image length: %s",
3546 strerror(-current_size));
3547 ret = -1;
3548 goto out;
3549 }
3550
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003551 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003552 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003553 } else {
3554 total_size = n;
3555 }
3556 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003557 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003558 ret = -1;
3559 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003560 }
3561
Max Reitzdc5f6902017-06-13 22:20:55 +02003562 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3563 error_report("Preallocation can only be used for growing images");
3564 ret = -1;
3565 goto out;
3566 }
3567
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003568 if (total_size < current_size && !shrink) {
3569 warn_report("Shrinking an image will delete all data beyond the "
3570 "shrunken image's end. Before performing such an "
3571 "operation, make sure there is no important data there.");
3572
3573 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3574 error_report(
3575 "Use the --shrink option to perform a shrink operation.");
3576 ret = -1;
3577 goto out;
3578 } else {
3579 warn_report("Using the --shrink option will suppress this message. "
3580 "Note that future versions of qemu-img may refuse to "
3581 "shrink images without this option.");
3582 }
3583 }
3584
Max Reitzdc5f6902017-06-13 22:20:55 +02003585 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitzed3d2ec2017-03-28 22:51:27 +02003586 if (!ret) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003587 qprintf(quiet, "Image resized.\n");
Max Reitzed3d2ec2017-03-28 22:51:27 +02003588 } else {
3589 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003590 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003591out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003592 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003593 if (ret) {
3594 return 1;
3595 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003596 return 0;
3597}
3598
Max Reitz76a3a342014-10-27 11:12:51 +01003599static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003600 int64_t offset, int64_t total_work_size,
3601 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003602{
3603 qemu_progress_print(100.f * offset / total_work_size, 0);
3604}
3605
Max Reitz6f176b42013-09-03 10:09:50 +02003606static int img_amend(int argc, char **argv)
3607{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003608 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003609 int c, ret = 0;
3610 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003611 QemuOptsList *create_opts = NULL;
3612 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003613 const char *fmt = NULL, *filename, *cache;
3614 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003615 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003616 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003617 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003618 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003619 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003620
Max Reitzbd39e6e2014-07-22 22:58:43 +02003621 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003622 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003623 static const struct option long_options[] = {
3624 {"help", no_argument, 0, 'h'},
3625 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003626 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003627 {0, 0, 0, 0}
3628 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003629 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003630 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003631 if (c == -1) {
3632 break;
3633 }
3634
3635 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003636 case ':':
3637 missing_argument(argv[optind - 1]);
3638 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003639 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003640 unrecognized_option(argv[optind - 1]);
3641 break;
3642 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003643 help();
3644 break;
3645 case 'o':
3646 if (!is_valid_option_list(optarg)) {
3647 error_report("Invalid option list: %s", optarg);
3648 ret = -1;
3649 goto out_no_progress;
3650 }
3651 if (!options) {
3652 options = g_strdup(optarg);
3653 } else {
3654 char *old_options = options;
3655 options = g_strdup_printf("%s,%s", options, optarg);
3656 g_free(old_options);
3657 }
3658 break;
3659 case 'f':
3660 fmt = optarg;
3661 break;
3662 case 't':
3663 cache = optarg;
3664 break;
3665 case 'p':
3666 progress = true;
3667 break;
3668 case 'q':
3669 quiet = true;
3670 break;
3671 case OPTION_OBJECT:
3672 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3673 optarg, true);
3674 if (!opts) {
3675 ret = -1;
3676 goto out_no_progress;
3677 }
3678 break;
3679 case OPTION_IMAGE_OPTS:
3680 image_opts = true;
3681 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003682 }
3683 }
3684
Max Reitz6f176b42013-09-03 10:09:50 +02003685 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003686 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003687 }
3688
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003689 if (qemu_opts_foreach(&qemu_object_opts,
3690 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003691 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003692 ret = -1;
3693 goto out_no_progress;
3694 }
3695
Max Reitz76a3a342014-10-27 11:12:51 +01003696 if (quiet) {
3697 progress = false;
3698 }
3699 qemu_progress_init(progress, 1.0);
3700
Kevin Wolfa283cb62014-02-21 16:24:07 +01003701 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3702 if (fmt && has_help_option(options)) {
3703 /* If a format is explicitly specified (and possibly no filename is
3704 * given), print option help here */
3705 ret = print_block_option_help(filename, fmt);
3706 goto out;
3707 }
3708
3709 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003710 error_report("Expecting one image file name");
3711 ret = -1;
3712 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003713 }
Max Reitz6f176b42013-09-03 10:09:50 +02003714
Kevin Wolfce099542016-03-15 13:01:04 +01003715 flags = BDRV_O_RDWR;
3716 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003717 if (ret < 0) {
3718 error_report("Invalid cache option: %s", cache);
3719 goto out;
3720 }
3721
Fam Zheng335e9932017-05-03 00:35:39 +08003722 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3723 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003724 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003725 ret = -1;
3726 goto out;
3727 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003728 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003729
3730 fmt = bs->drv->format_name;
3731
Kevin Wolf626f84f2014-02-21 16:24:06 +01003732 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003733 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003734 ret = print_block_option_help(filename, fmt);
3735 goto out;
3736 }
3737
Max Reitzb2439d22014-12-02 18:32:47 +01003738 if (!bs->drv->create_opts) {
3739 error_report("Format driver '%s' does not support any options to amend",
3740 fmt);
3741 ret = -1;
3742 goto out;
3743 }
3744
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003745 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003746 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003747 qemu_opts_do_parse(opts, options, NULL, &err);
3748 if (err) {
3749 error_report_err(err);
3750 ret = -1;
3751 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003752 }
3753
Max Reitz76a3a342014-10-27 11:12:51 +01003754 /* In case the driver does not call amend_status_cb() */
3755 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003756 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003757 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003758 if (ret < 0) {
3759 error_report("Error while amending options: %s", strerror(-ret));
3760 goto out;
3761 }
3762
3763out:
Max Reitz76a3a342014-10-27 11:12:51 +01003764 qemu_progress_end();
3765
Max Reitze814dff2015-08-20 16:00:38 -07003766out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003767 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003768 qemu_opts_del(opts);
3769 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003770 g_free(options);
3771
Max Reitz6f176b42013-09-03 10:09:50 +02003772 if (ret) {
3773 return 1;
3774 }
3775 return 0;
3776}
3777
Kevin Wolfb6133b82014-08-05 14:17:13 +02003778typedef struct BenchData {
3779 BlockBackend *blk;
3780 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003781 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003782 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003783 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003784 int nrreq;
3785 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003786 int flush_interval;
3787 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003788 uint8_t *buf;
3789 QEMUIOVector *qiov;
3790
3791 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003792 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003793 uint64_t offset;
3794} BenchData;
3795
Kevin Wolf55d539c2016-06-03 13:59:41 +02003796static void bench_undrained_flush_cb(void *opaque, int ret)
3797{
3798 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003799 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003800 exit(EXIT_FAILURE);
3801 }
3802}
3803
Kevin Wolfb6133b82014-08-05 14:17:13 +02003804static void bench_cb(void *opaque, int ret)
3805{
3806 BenchData *b = opaque;
3807 BlockAIOCB *acb;
3808
3809 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003810 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003811 exit(EXIT_FAILURE);
3812 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003813
3814 if (b->in_flush) {
3815 /* Just finished a flush with drained queue: Start next requests */
3816 assert(b->in_flight == 0);
3817 b->in_flush = false;
3818 } else if (b->in_flight > 0) {
3819 int remaining = b->n - b->in_flight;
3820
Kevin Wolfb6133b82014-08-05 14:17:13 +02003821 b->n--;
3822 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003823
3824 /* Time for flush? Drain queue if requested, then flush */
3825 if (b->flush_interval && remaining % b->flush_interval == 0) {
3826 if (!b->in_flight || !b->drain_on_flush) {
3827 BlockCompletionFunc *cb;
3828
3829 if (b->drain_on_flush) {
3830 b->in_flush = true;
3831 cb = bench_cb;
3832 } else {
3833 cb = bench_undrained_flush_cb;
3834 }
3835
3836 acb = blk_aio_flush(b->blk, cb, b);
3837 if (!acb) {
3838 error_report("Failed to issue flush request");
3839 exit(EXIT_FAILURE);
3840 }
3841 }
3842 if (b->drain_on_flush) {
3843 return;
3844 }
3845 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003846 }
3847
3848 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003849 int64_t offset = b->offset;
3850 /* blk_aio_* might look for completed I/Os and kick bench_cb
3851 * again, so make sure this operation is counted by in_flight
3852 * and b->offset is ready for the next submission.
3853 */
3854 b->in_flight++;
3855 b->offset += b->step;
3856 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003857 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003858 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003859 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003860 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003861 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003862 if (!acb) {
3863 error_report("Failed to issue request");
3864 exit(EXIT_FAILURE);
3865 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003866 }
3867}
3868
3869static int img_bench(int argc, char **argv)
3870{
3871 int c, ret = 0;
3872 const char *fmt = NULL, *filename;
3873 bool quiet = false;
3874 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003875 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003876 int count = 75000;
3877 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003878 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003879 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003880 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003881 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003882 int flush_interval = 0;
3883 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003884 int64_t image_size;
3885 BlockBackend *blk = NULL;
3886 BenchData data = {};
3887 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003888 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003889 struct timeval t1, t2;
3890 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08003891 bool force_share = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003892
3893 for (;;) {
3894 static const struct option long_options[] = {
3895 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003896 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003897 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003898 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003899 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08003900 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003901 {0, 0, 0, 0}
3902 };
Fam Zheng335e9932017-05-03 00:35:39 +08003903 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003904 if (c == -1) {
3905 break;
3906 }
3907
3908 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003909 case ':':
3910 missing_argument(argv[optind - 1]);
3911 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003912 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003913 unrecognized_option(argv[optind - 1]);
3914 break;
3915 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02003916 help();
3917 break;
3918 case 'c':
3919 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003920 unsigned long res;
3921
3922 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003923 error_report("Invalid request count specified");
3924 return 1;
3925 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003926 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003927 break;
3928 }
3929 case 'd':
3930 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003931 unsigned long res;
3932
3933 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003934 error_report("Invalid queue depth specified");
3935 return 1;
3936 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003937 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003938 break;
3939 }
3940 case 'f':
3941 fmt = optarg;
3942 break;
3943 case 'n':
3944 flags |= BDRV_O_NATIVE_AIO;
3945 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003946 case 'o':
3947 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003948 offset = cvtnum(optarg);
3949 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003950 error_report("Invalid offset specified");
3951 return 1;
3952 }
3953 break;
3954 }
3955 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003956 case 'q':
3957 quiet = true;
3958 break;
3959 case 's':
3960 {
3961 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003962
Markus Armbruster606caa02017-02-21 21:14:04 +01003963 sval = cvtnum(optarg);
3964 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003965 error_report("Invalid buffer size specified");
3966 return 1;
3967 }
3968
3969 bufsize = sval;
3970 break;
3971 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003972 case 'S':
3973 {
3974 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003975
Markus Armbruster606caa02017-02-21 21:14:04 +01003976 sval = cvtnum(optarg);
3977 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003978 error_report("Invalid step size specified");
3979 return 1;
3980 }
3981
3982 step = sval;
3983 break;
3984 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003985 case 't':
3986 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3987 if (ret < 0) {
3988 error_report("Invalid cache mode");
3989 ret = -1;
3990 goto out;
3991 }
3992 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003993 case 'w':
3994 flags |= BDRV_O_RDWR;
3995 is_write = true;
3996 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003997 case 'U':
3998 force_share = true;
3999 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004000 case OPTION_PATTERN:
4001 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004002 unsigned long res;
4003
4004 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004005 error_report("Invalid pattern byte specified");
4006 return 1;
4007 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004008 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004009 break;
4010 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004011 case OPTION_FLUSH_INTERVAL:
4012 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004013 unsigned long res;
4014
4015 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004016 error_report("Invalid flush interval specified");
4017 return 1;
4018 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004019 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004020 break;
4021 }
4022 case OPTION_NO_DRAIN:
4023 drain_on_flush = false;
4024 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004025 case OPTION_IMAGE_OPTS:
4026 image_opts = true;
4027 break;
4028 }
4029 }
4030
4031 if (optind != argc - 1) {
4032 error_exit("Expecting one image file name");
4033 }
4034 filename = argv[argc - 1];
4035
Kevin Wolf55d539c2016-06-03 13:59:41 +02004036 if (!is_write && flush_interval) {
4037 error_report("--flush-interval is only available in write tests");
4038 ret = -1;
4039 goto out;
4040 }
4041 if (flush_interval && flush_interval < depth) {
4042 error_report("Flush interval can't be smaller than depth");
4043 ret = -1;
4044 goto out;
4045 }
4046
Fam Zheng335e9932017-05-03 00:35:39 +08004047 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4048 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004049 if (!blk) {
4050 ret = -1;
4051 goto out;
4052 }
4053
4054 image_size = blk_getlength(blk);
4055 if (image_size < 0) {
4056 ret = image_size;
4057 goto out;
4058 }
4059
4060 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004061 .blk = blk,
4062 .image_size = image_size,
4063 .bufsize = bufsize,
4064 .step = step ?: bufsize,
4065 .nrreq = depth,
4066 .n = count,
4067 .offset = offset,
4068 .write = is_write,
4069 .flush_interval = flush_interval,
4070 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004071 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004072 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004073 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004074 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004075 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004076 if (flush_interval) {
4077 printf("Sending flush every %d requests\n", flush_interval);
4078 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004079
4080 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004081 memset(data.buf, pattern, data.nrreq * data.bufsize);
4082
Kevin Wolfb6133b82014-08-05 14:17:13 +02004083 data.qiov = g_new(QEMUIOVector, data.nrreq);
4084 for (i = 0; i < data.nrreq; i++) {
4085 qemu_iovec_init(&data.qiov[i], 1);
4086 qemu_iovec_add(&data.qiov[i],
4087 data.buf + i * data.bufsize, data.bufsize);
4088 }
4089
4090 gettimeofday(&t1, NULL);
4091 bench_cb(&data, 0);
4092
4093 while (data.n > 0) {
4094 main_loop_wait(false);
4095 }
4096 gettimeofday(&t2, NULL);
4097
4098 printf("Run completed in %3.3f seconds.\n",
4099 (t2.tv_sec - t1.tv_sec)
4100 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4101
4102out:
4103 qemu_vfree(data.buf);
4104 blk_unref(blk);
4105
4106 if (ret) {
4107 return 1;
4108 }
4109 return 0;
4110}
4111
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004112#define C_BS 01
4113#define C_COUNT 02
4114#define C_IF 04
4115#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004116#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004117
4118struct DdInfo {
4119 unsigned int flags;
4120 int64_t count;
4121};
4122
4123struct DdIo {
4124 int bsz; /* Block size */
4125 char *filename;
4126 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004127 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004128};
4129
4130struct DdOpts {
4131 const char *name;
4132 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4133 unsigned int flag;
4134};
4135
4136static int img_dd_bs(const char *arg,
4137 struct DdIo *in, struct DdIo *out,
4138 struct DdInfo *dd)
4139{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004140 int64_t res;
4141
Markus Armbruster606caa02017-02-21 21:14:04 +01004142 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004143
Markus Armbruster606caa02017-02-21 21:14:04 +01004144 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004145 error_report("invalid number: '%s'", arg);
4146 return 1;
4147 }
4148 in->bsz = out->bsz = res;
4149
4150 return 0;
4151}
4152
4153static int img_dd_count(const char *arg,
4154 struct DdIo *in, struct DdIo *out,
4155 struct DdInfo *dd)
4156{
Markus Armbruster606caa02017-02-21 21:14:04 +01004157 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004158
Markus Armbruster606caa02017-02-21 21:14:04 +01004159 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004160 error_report("invalid number: '%s'", arg);
4161 return 1;
4162 }
4163
4164 return 0;
4165}
4166
4167static int img_dd_if(const char *arg,
4168 struct DdIo *in, struct DdIo *out,
4169 struct DdInfo *dd)
4170{
4171 in->filename = g_strdup(arg);
4172
4173 return 0;
4174}
4175
4176static int img_dd_of(const char *arg,
4177 struct DdIo *in, struct DdIo *out,
4178 struct DdInfo *dd)
4179{
4180 out->filename = g_strdup(arg);
4181
4182 return 0;
4183}
4184
Reda Sallahif7c15532016-08-10 16:16:09 +02004185static int img_dd_skip(const char *arg,
4186 struct DdIo *in, struct DdIo *out,
4187 struct DdInfo *dd)
4188{
Markus Armbruster606caa02017-02-21 21:14:04 +01004189 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004190
Markus Armbruster606caa02017-02-21 21:14:04 +01004191 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004192 error_report("invalid number: '%s'", arg);
4193 return 1;
4194 }
4195
4196 return 0;
4197}
4198
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004199static int img_dd(int argc, char **argv)
4200{
4201 int ret = 0;
4202 char *arg = NULL;
4203 char *tmp;
4204 BlockDriver *drv = NULL, *proto_drv = NULL;
4205 BlockBackend *blk1 = NULL, *blk2 = NULL;
4206 QemuOpts *opts = NULL;
4207 QemuOptsList *create_opts = NULL;
4208 Error *local_err = NULL;
4209 bool image_opts = false;
4210 int c, i;
4211 const char *out_fmt = "raw";
4212 const char *fmt = NULL;
4213 int64_t size = 0;
4214 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004215 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004216 struct DdInfo dd = {
4217 .flags = 0,
4218 .count = 0,
4219 };
4220 struct DdIo in = {
4221 .bsz = 512, /* Block size is by default 512 bytes */
4222 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004223 .buf = NULL,
4224 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004225 };
4226 struct DdIo out = {
4227 .bsz = 512,
4228 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004229 .buf = NULL,
4230 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004231 };
4232
4233 const struct DdOpts options[] = {
4234 { "bs", img_dd_bs, C_BS },
4235 { "count", img_dd_count, C_COUNT },
4236 { "if", img_dd_if, C_IF },
4237 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004238 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004239 { NULL, NULL, 0 }
4240 };
4241 const struct option long_options[] = {
4242 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004243 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004244 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004245 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004246 { 0, 0, 0, 0 }
4247 };
4248
Fam Zheng335e9932017-05-03 00:35:39 +08004249 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004250 if (c == EOF) {
4251 break;
4252 }
4253 switch (c) {
4254 case 'O':
4255 out_fmt = optarg;
4256 break;
4257 case 'f':
4258 fmt = optarg;
4259 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004260 case ':':
4261 missing_argument(argv[optind - 1]);
4262 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004263 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004264 unrecognized_option(argv[optind - 1]);
4265 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004266 case 'h':
4267 help();
4268 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004269 case 'U':
4270 force_share = true;
4271 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004272 case OPTION_OBJECT:
4273 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004274 ret = -1;
4275 goto out;
4276 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004277 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004278 case OPTION_IMAGE_OPTS:
4279 image_opts = true;
4280 break;
4281 }
4282 }
4283
4284 for (i = optind; i < argc; i++) {
4285 int j;
4286 arg = g_strdup(argv[i]);
4287
4288 tmp = strchr(arg, '=');
4289 if (tmp == NULL) {
4290 error_report("unrecognized operand %s", arg);
4291 ret = -1;
4292 goto out;
4293 }
4294
4295 *tmp++ = '\0';
4296
4297 for (j = 0; options[j].name != NULL; j++) {
4298 if (!strcmp(arg, options[j].name)) {
4299 break;
4300 }
4301 }
4302 if (options[j].name == NULL) {
4303 error_report("unrecognized operand %s", arg);
4304 ret = -1;
4305 goto out;
4306 }
4307
4308 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4309 ret = -1;
4310 goto out;
4311 }
4312 dd.flags |= options[j].flag;
4313 g_free(arg);
4314 arg = NULL;
4315 }
4316
4317 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4318 error_report("Must specify both input and output files");
4319 ret = -1;
4320 goto out;
4321 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004322
4323 if (qemu_opts_foreach(&qemu_object_opts,
4324 user_creatable_add_opts_foreach,
4325 NULL, NULL)) {
4326 ret = -1;
4327 goto out;
4328 }
4329
Fam Zheng335e9932017-05-03 00:35:39 +08004330 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4331 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004332
4333 if (!blk1) {
4334 ret = -1;
4335 goto out;
4336 }
4337
4338 drv = bdrv_find_format(out_fmt);
4339 if (!drv) {
4340 error_report("Unknown file format");
4341 ret = -1;
4342 goto out;
4343 }
4344 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4345
4346 if (!proto_drv) {
4347 error_report_err(local_err);
4348 ret = -1;
4349 goto out;
4350 }
4351 if (!drv->create_opts) {
4352 error_report("Format driver '%s' does not support image creation",
4353 drv->format_name);
4354 ret = -1;
4355 goto out;
4356 }
4357 if (!proto_drv->create_opts) {
4358 error_report("Protocol driver '%s' does not support image creation",
4359 proto_drv->format_name);
4360 ret = -1;
4361 goto out;
4362 }
4363 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4364 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4365
4366 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4367
4368 size = blk_getlength(blk1);
4369 if (size < 0) {
4370 error_report("Failed to get size for '%s'", in.filename);
4371 ret = -1;
4372 goto out;
4373 }
4374
4375 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4376 dd.count * in.bsz < size) {
4377 size = dd.count * in.bsz;
4378 }
4379
Reda Sallahif7c15532016-08-10 16:16:09 +02004380 /* Overflow means the specified offset is beyond input image's size */
4381 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4382 size < in.bsz * in.offset)) {
4383 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4384 } else {
4385 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4386 size - in.bsz * in.offset, &error_abort);
4387 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004388
4389 ret = bdrv_create(drv, out.filename, opts, &local_err);
4390 if (ret < 0) {
4391 error_reportf_err(local_err,
4392 "%s: error while creating output image: ",
4393 out.filename);
4394 ret = -1;
4395 goto out;
4396 }
4397
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004398 /* TODO, we can't honour --image-opts for the target,
4399 * since it needs to be given in a format compatible
4400 * with the bdrv_create() call above which does not
4401 * support image-opts style.
4402 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004403 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004404 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004405
4406 if (!blk2) {
4407 ret = -1;
4408 goto out;
4409 }
4410
Reda Sallahif7c15532016-08-10 16:16:09 +02004411 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4412 size < in.offset * in.bsz)) {
4413 /* We give a warning if the skip option is bigger than the input
4414 * size and create an empty output disk image (i.e. like dd(1)).
4415 */
4416 error_report("%s: cannot skip to specified offset", in.filename);
4417 in_pos = size;
4418 } else {
4419 in_pos = in.offset * in.bsz;
4420 }
4421
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004422 in.buf = g_new(uint8_t, in.bsz);
4423
Reda Sallahif7c15532016-08-10 16:16:09 +02004424 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004425 int in_ret, out_ret;
4426
4427 if (in_pos + in.bsz > size) {
4428 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4429 } else {
4430 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4431 }
4432 if (in_ret < 0) {
4433 error_report("error while reading from input image file: %s",
4434 strerror(-in_ret));
4435 ret = -1;
4436 goto out;
4437 }
4438 in_pos += in_ret;
4439
4440 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4441
4442 if (out_ret < 0) {
4443 error_report("error while writing to output image file: %s",
4444 strerror(-out_ret));
4445 ret = -1;
4446 goto out;
4447 }
4448 out_pos += out_ret;
4449 }
4450
4451out:
4452 g_free(arg);
4453 qemu_opts_del(opts);
4454 qemu_opts_free(create_opts);
4455 blk_unref(blk1);
4456 blk_unref(blk2);
4457 g_free(in.filename);
4458 g_free(out.filename);
4459 g_free(in.buf);
4460 g_free(out.buf);
4461
4462 if (ret) {
4463 return 1;
4464 }
4465 return 0;
4466}
4467
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004468static void dump_json_block_measure_info(BlockMeasureInfo *info)
4469{
4470 QString *str;
4471 QObject *obj;
4472 Visitor *v = qobject_output_visitor_new(&obj);
4473
4474 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4475 visit_complete(v, &obj);
4476 str = qobject_to_json_pretty(obj);
4477 assert(str != NULL);
4478 printf("%s\n", qstring_get_str(str));
4479 qobject_decref(obj);
4480 visit_free(v);
4481 QDECREF(str);
4482}
4483
4484static int img_measure(int argc, char **argv)
4485{
4486 static const struct option long_options[] = {
4487 {"help", no_argument, 0, 'h'},
4488 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4489 {"object", required_argument, 0, OPTION_OBJECT},
4490 {"output", required_argument, 0, OPTION_OUTPUT},
4491 {"size", required_argument, 0, OPTION_SIZE},
4492 {"force-share", no_argument, 0, 'U'},
4493 {0, 0, 0, 0}
4494 };
4495 OutputFormat output_format = OFORMAT_HUMAN;
4496 BlockBackend *in_blk = NULL;
4497 BlockDriver *drv;
4498 const char *filename = NULL;
4499 const char *fmt = NULL;
4500 const char *out_fmt = "raw";
4501 char *options = NULL;
4502 char *snapshot_name = NULL;
4503 bool force_share = false;
4504 QemuOpts *opts = NULL;
4505 QemuOpts *object_opts = NULL;
4506 QemuOpts *sn_opts = NULL;
4507 QemuOptsList *create_opts = NULL;
4508 bool image_opts = false;
4509 uint64_t img_size = UINT64_MAX;
4510 BlockMeasureInfo *info = NULL;
4511 Error *local_err = NULL;
4512 int ret = 1;
4513 int c;
4514
4515 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4516 long_options, NULL)) != -1) {
4517 switch (c) {
4518 case '?':
4519 case 'h':
4520 help();
4521 break;
4522 case 'f':
4523 fmt = optarg;
4524 break;
4525 case 'O':
4526 out_fmt = optarg;
4527 break;
4528 case 'o':
4529 if (!is_valid_option_list(optarg)) {
4530 error_report("Invalid option list: %s", optarg);
4531 goto out;
4532 }
4533 if (!options) {
4534 options = g_strdup(optarg);
4535 } else {
4536 char *old_options = options;
4537 options = g_strdup_printf("%s,%s", options, optarg);
4538 g_free(old_options);
4539 }
4540 break;
4541 case 'l':
4542 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4543 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4544 optarg, false);
4545 if (!sn_opts) {
4546 error_report("Failed in parsing snapshot param '%s'",
4547 optarg);
4548 goto out;
4549 }
4550 } else {
4551 snapshot_name = optarg;
4552 }
4553 break;
4554 case 'U':
4555 force_share = true;
4556 break;
4557 case OPTION_OBJECT:
4558 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4559 optarg, true);
4560 if (!object_opts) {
4561 goto out;
4562 }
4563 break;
4564 case OPTION_IMAGE_OPTS:
4565 image_opts = true;
4566 break;
4567 case OPTION_OUTPUT:
4568 if (!strcmp(optarg, "json")) {
4569 output_format = OFORMAT_JSON;
4570 } else if (!strcmp(optarg, "human")) {
4571 output_format = OFORMAT_HUMAN;
4572 } else {
4573 error_report("--output must be used with human or json "
4574 "as argument.");
4575 goto out;
4576 }
4577 break;
4578 case OPTION_SIZE:
4579 {
4580 int64_t sval;
4581
4582 sval = cvtnum(optarg);
4583 if (sval < 0) {
4584 if (sval == -ERANGE) {
4585 error_report("Image size must be less than 8 EiB!");
4586 } else {
4587 error_report("Invalid image size specified! You may use "
4588 "k, M, G, T, P or E suffixes for ");
4589 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4590 "petabytes and exabytes.");
4591 }
4592 goto out;
4593 }
4594 img_size = (uint64_t)sval;
4595 }
4596 break;
4597 }
4598 }
4599
4600 if (qemu_opts_foreach(&qemu_object_opts,
4601 user_creatable_add_opts_foreach,
4602 NULL, NULL)) {
4603 goto out;
4604 }
4605
4606 if (argc - optind > 1) {
4607 error_report("At most one filename argument is allowed.");
4608 goto out;
4609 } else if (argc - optind == 1) {
4610 filename = argv[optind];
4611 }
4612
4613 if (!filename &&
4614 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4615 error_report("--object, --image-opts, -f, and -l "
4616 "require a filename argument.");
4617 goto out;
4618 }
4619 if (filename && img_size != UINT64_MAX) {
4620 error_report("--size N cannot be used together with a filename.");
4621 goto out;
4622 }
4623 if (!filename && img_size == UINT64_MAX) {
4624 error_report("Either --size N or one filename must be specified.");
4625 goto out;
4626 }
4627
4628 if (filename) {
4629 in_blk = img_open(image_opts, filename, fmt, 0,
4630 false, false, force_share);
4631 if (!in_blk) {
4632 goto out;
4633 }
4634
4635 if (sn_opts) {
4636 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4637 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4638 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4639 &local_err);
4640 } else if (snapshot_name != NULL) {
4641 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4642 snapshot_name, &local_err);
4643 }
4644 if (local_err) {
4645 error_reportf_err(local_err, "Failed to load snapshot: ");
4646 goto out;
4647 }
4648 }
4649
4650 drv = bdrv_find_format(out_fmt);
4651 if (!drv) {
4652 error_report("Unknown file format '%s'", out_fmt);
4653 goto out;
4654 }
4655 if (!drv->create_opts) {
4656 error_report("Format driver '%s' does not support image creation",
4657 drv->format_name);
4658 goto out;
4659 }
4660
4661 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4662 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4663 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4664 if (options) {
4665 qemu_opts_do_parse(opts, options, NULL, &local_err);
4666 if (local_err) {
4667 error_report_err(local_err);
4668 error_report("Invalid options for file format '%s'", out_fmt);
4669 goto out;
4670 }
4671 }
4672 if (img_size != UINT64_MAX) {
4673 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4674 }
4675
4676 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4677 if (local_err) {
4678 error_report_err(local_err);
4679 goto out;
4680 }
4681
4682 if (output_format == OFORMAT_HUMAN) {
4683 printf("required size: %" PRIu64 "\n", info->required);
4684 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4685 } else {
4686 dump_json_block_measure_info(info);
4687 }
4688
4689 ret = 0;
4690
4691out:
4692 qapi_free_BlockMeasureInfo(info);
4693 qemu_opts_del(object_opts);
4694 qemu_opts_del(opts);
4695 qemu_opts_del(sn_opts);
4696 qemu_opts_free(create_opts);
4697 g_free(options);
4698 blk_unref(in_blk);
4699 return ret;
4700}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004701
Anthony Liguoric227f092009-10-01 16:12:16 -05004702static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004703#define DEF(option, callback, arg_string) \
4704 { option, callback },
4705#include "qemu-img-cmds.h"
4706#undef DEF
4707#undef GEN_DOCS
4708 { NULL, NULL, },
4709};
4710
bellardea2384d2004-08-01 21:59:26 +00004711int main(int argc, char **argv)
4712{
Anthony Liguoric227f092009-10-01 16:12:16 -05004713 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004714 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004715 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004716 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004717 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004718 static const struct option long_options[] = {
4719 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004720 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004721 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004722 {0, 0, 0, 0}
4723 };
bellardea2384d2004-08-01 21:59:26 +00004724
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004725#ifdef CONFIG_POSIX
4726 signal(SIGPIPE, SIG_IGN);
4727#endif
4728
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004729 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004730 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004731 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004732
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004733 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004734 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004735 exit(EXIT_FAILURE);
4736 }
4737
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004738 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004739
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004740 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004741 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004742 if (argc < 2) {
4743 error_exit("Not enough arguments");
4744 }
Stuart Brady153859b2009-06-07 00:42:17 +01004745
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004746 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004747 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004748 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004749
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004750 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004751 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004752 case ':':
4753 missing_argument(argv[optind - 1]);
4754 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004755 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004756 unrecognized_option(argv[optind - 1]);
4757 return 0;
4758 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004759 help();
4760 return 0;
4761 case 'V':
4762 printf(QEMU_IMG_VERSION);
4763 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004764 case 'T':
4765 g_free(trace_file);
4766 trace_file = trace_opt_parse(optarg);
4767 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004768 }
bellardea2384d2004-08-01 21:59:26 +00004769 }
Stuart Brady153859b2009-06-07 00:42:17 +01004770
Denis V. Lunev10985132016-06-17 17:44:13 +03004771 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004772
Denis V. Lunev10985132016-06-17 17:44:13 +03004773 /* reset getopt_long scanning */
4774 argc -= optind;
4775 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004776 return 0;
4777 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004778 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004779 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004780
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004781 if (!trace_init_backends()) {
4782 exit(1);
4783 }
4784 trace_init_file(trace_file);
4785 qemu_set_log(LOG_TRACE);
4786
Denis V. Lunev10985132016-06-17 17:44:13 +03004787 /* find the command */
4788 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4789 if (!strcmp(cmdname, cmd->name)) {
4790 return cmd->handler(argc, argv);
4791 }
4792 }
Jeff Cody7db16892014-04-25 17:02:32 -04004793
Stuart Brady153859b2009-06-07 00:42:17 +01004794 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004795 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004796}