blob: 78c820e487811c3b5bd7fbb2238e7d01ed133431 [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
1175static int64_t sectors_to_process(int64_t total, int64_t from)
1176{
1177 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1178}
1179
1180/*
1181 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1182 *
1183 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1184 * data and negative value on error.
1185 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001186 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001187 * @param sect_num: Number of first sector to check
1188 * @param sect_count: Number of sectors to check
1189 * @param filename: Name of disk file we are checking (logging purpose)
1190 * @param buffer: Allocated buffer for storing read data
1191 * @param quiet: Flag for quiet mode
1192 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001193static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001194 int sect_count, const char *filename,
1195 uint8_t *buffer, bool quiet)
1196{
1197 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001198 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1199 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001200 if (ret < 0) {
1201 error_report("Error while reading offset %" PRId64 " of %s: %s",
1202 sectors_to_bytes(sect_num), filename, strerror(-ret));
1203 return ret;
1204 }
1205 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1206 if (ret || pnum != sect_count) {
1207 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1208 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1209 return 1;
1210 }
1211
1212 return 0;
1213}
1214
1215/*
1216 * Compares two images. Exit codes:
1217 *
1218 * 0 - Images are identical
1219 * 1 - Images differ
1220 * >1 - Error occurred
1221 */
1222static int img_compare(int argc, char **argv)
1223{
Max Reitz40055952014-07-22 22:58:42 +02001224 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001225 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001226 BlockDriverState *bs1, *bs2;
1227 int64_t total_sectors1, total_sectors2;
1228 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001229 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001230 int allocated1, allocated2;
1231 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1232 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001233 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001234 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001235 int64_t total_sectors;
1236 int64_t sector_num = 0;
1237 int64_t nb_sectors;
1238 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001240 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001241 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242
Max Reitz40055952014-07-22 22:58:42 +02001243 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001245 static const struct option long_options[] = {
1246 {"help", no_argument, 0, 'h'},
1247 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001248 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001249 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001250 {0, 0, 0, 0}
1251 };
Fam Zheng335e9932017-05-03 00:35:39 +08001252 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001253 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254 if (c == -1) {
1255 break;
1256 }
1257 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001258 case ':':
1259 missing_argument(argv[optind - 1]);
1260 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001262 unrecognized_option(argv[optind - 1]);
1263 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001264 case 'h':
1265 help();
1266 break;
1267 case 'f':
1268 fmt1 = optarg;
1269 break;
1270 case 'F':
1271 fmt2 = optarg;
1272 break;
Max Reitz40055952014-07-22 22:58:42 +02001273 case 'T':
1274 cache = optarg;
1275 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 case 'p':
1277 progress = true;
1278 break;
1279 case 'q':
1280 quiet = true;
1281 break;
1282 case 's':
1283 strict = true;
1284 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001285 case 'U':
1286 force_share = true;
1287 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001288 case OPTION_OBJECT: {
1289 QemuOpts *opts;
1290 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1291 optarg, true);
1292 if (!opts) {
1293 ret = 2;
1294 goto out4;
1295 }
1296 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001297 case OPTION_IMAGE_OPTS:
1298 image_opts = true;
1299 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300 }
1301 }
1302
1303 /* Progress is not shown in Quiet mode */
1304 if (quiet) {
1305 progress = false;
1306 }
1307
1308
Kevin Wolffc11eb22013-08-05 10:53:04 +02001309 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001310 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 }
1312 filename1 = argv[optind++];
1313 filename2 = argv[optind++];
1314
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001315 if (qemu_opts_foreach(&qemu_object_opts,
1316 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001317 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001318 ret = 2;
1319 goto out4;
1320 }
1321
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001322 /* Initialize before goto out */
1323 qemu_progress_init(progress, 2.0);
1324
Kevin Wolfce099542016-03-15 13:01:04 +01001325 flags = 0;
1326 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001327 if (ret < 0) {
1328 error_report("Invalid source cache option: %s", cache);
1329 ret = 2;
1330 goto out3;
1331 }
1332
Fam Zheng335e9932017-05-03 00:35:39 +08001333 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1334 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001335 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001336 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001337 goto out3;
1338 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001339
Fam Zheng335e9932017-05-03 00:35:39 +08001340 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1341 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001342 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001343 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001344 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001346 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001347 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348
Max Reitzf1d3cd72015-02-05 13:58:18 -05001349 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1350 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1351 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001352 if (total_sectors1 < 0) {
1353 error_report("Can't get size of %s: %s",
1354 filename1, strerror(-total_sectors1));
1355 ret = 4;
1356 goto out;
1357 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001358 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001359 if (total_sectors2 < 0) {
1360 error_report("Can't get size of %s: %s",
1361 filename2, strerror(-total_sectors2));
1362 ret = 4;
1363 goto out;
1364 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001365 total_sectors = MIN(total_sectors1, total_sectors2);
1366 progress_base = MAX(total_sectors1, total_sectors2);
1367
1368 qemu_progress_print(0, 100);
1369
1370 if (strict && total_sectors1 != total_sectors2) {
1371 ret = 1;
1372 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1373 goto out;
1374 }
1375
1376 for (;;) {
Eric Blake31826642017-10-11 22:47:08 -05001377 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001378
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001379 nb_sectors = sectors_to_process(total_sectors, sector_num);
1380 if (nb_sectors <= 0) {
1381 break;
1382 }
Eric Blake31826642017-10-11 22:47:08 -05001383 status1 = bdrv_block_status_above(bs1, NULL,
1384 sector_num * BDRV_SECTOR_SIZE,
1385 (total_sectors1 - sector_num) *
1386 BDRV_SECTOR_SIZE,
1387 &pnum1, NULL, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001388 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001389 ret = 3;
1390 error_report("Sector allocation test failed for %s", filename1);
1391 goto out;
1392 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001393 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394
Eric Blake31826642017-10-11 22:47:08 -05001395 status2 = bdrv_block_status_above(bs2, NULL,
1396 sector_num * BDRV_SECTOR_SIZE,
1397 (total_sectors2 - sector_num) *
1398 BDRV_SECTOR_SIZE,
1399 &pnum2, NULL, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001400 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001401 ret = 3;
1402 error_report("Sector allocation test failed for %s", filename2);
1403 goto out;
1404 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001405 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake31826642017-10-11 22:47:08 -05001406 /* TODO: Relax this once comparison is byte-based, and we no longer
1407 * have to worry about sector alignment */
1408 assert(QEMU_IS_ALIGNED(pnum1 | pnum2, BDRV_SECTOR_SIZE));
Fam Zheng25ad8e62016-01-13 16:37:41 +08001409 if (pnum1) {
Eric Blake31826642017-10-11 22:47:08 -05001410 nb_sectors = MIN(nb_sectors, pnum1 >> BDRV_SECTOR_BITS);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001411 }
1412 if (pnum2) {
Eric Blake31826642017-10-11 22:47:08 -05001413 nb_sectors = MIN(nb_sectors, pnum2 >> BDRV_SECTOR_BITS);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001414 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415
Fam Zheng25ad8e62016-01-13 16:37:41 +08001416 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001417 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001418 ret = 1;
1419 qprintf(quiet, "Strict mode: Offset %" PRId64
1420 " block status mismatch!\n",
1421 sectors_to_bytes(sector_num));
1422 goto out;
1423 }
1424 }
1425 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake31826642017-10-11 22:47:08 -05001426 nb_sectors = DIV_ROUND_UP(MIN(pnum1, pnum2), BDRV_SECTOR_SIZE);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001427 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001429 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1430 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001431 if (ret < 0) {
1432 error_report("Error while reading offset %" PRId64 " of %s:"
1433 " %s", sectors_to_bytes(sector_num), filename1,
1434 strerror(-ret));
1435 ret = 4;
1436 goto out;
1437 }
Eric Blake91669202016-05-06 10:26:43 -06001438 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1439 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001440 if (ret < 0) {
1441 error_report("Error while reading offset %" PRId64
1442 " of %s: %s", sectors_to_bytes(sector_num),
1443 filename2, strerror(-ret));
1444 ret = 4;
1445 goto out;
1446 }
1447 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1448 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1450 sectors_to_bytes(
1451 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001452 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001453 goto out;
1454 }
1455 }
1456 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457
1458 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001459 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001460 filename1, buf1, quiet);
1461 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001462 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001463 filename2, buf1, quiet);
1464 }
1465 if (ret) {
1466 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001467 error_report("Error while reading offset %" PRId64 ": %s",
1468 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001469 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 }
1471 goto out;
1472 }
1473 }
1474 sector_num += nb_sectors;
1475 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1476 }
1477
1478 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001479 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 int64_t total_sectors_over;
1481 const char *filename_over;
1482
1483 qprintf(quiet, "Warning: Image size mismatch!\n");
1484 if (total_sectors1 > total_sectors2) {
1485 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001486 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487 filename_over = filename1;
1488 } else {
1489 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001490 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 filename_over = filename2;
1492 }
1493
1494 for (;;) {
Eric Blake51b0a482017-07-07 07:44:59 -05001495 int64_t count;
1496
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001497 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1498 if (nb_sectors <= 0) {
1499 break;
1500 }
Eric Blake51b0a482017-07-07 07:44:59 -05001501 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL,
1502 sector_num * BDRV_SECTOR_SIZE,
1503 nb_sectors * BDRV_SECTOR_SIZE,
1504 &count);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 if (ret < 0) {
1506 ret = 3;
1507 error_report("Sector allocation test failed for %s",
1508 filename_over);
1509 goto out;
1510
1511 }
Eric Blake51b0a482017-07-07 07:44:59 -05001512 /* TODO relax this once bdrv_is_allocated_above does not enforce
1513 * sector alignment */
1514 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1515 nb_sectors = count >> BDRV_SECTOR_BITS;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001517 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001518 filename_over, buf1, quiet);
1519 if (ret) {
1520 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 error_report("Error while reading offset %" PRId64
1522 " of %s: %s", sectors_to_bytes(sector_num),
1523 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001524 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525 }
1526 goto out;
1527 }
1528 }
1529 sector_num += nb_sectors;
1530 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1531 }
1532 }
1533
1534 qprintf(quiet, "Images are identical.\n");
1535 ret = 0;
1536
1537out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001538 qemu_vfree(buf1);
1539 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001540 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001541out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001542 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001543out3:
1544 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001545out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546 return ret;
1547}
1548
Kevin Wolf690c7302015-03-19 13:33:32 +01001549enum ImgConvertBlockStatus {
1550 BLK_DATA,
1551 BLK_ZERO,
1552 BLK_BACKING_FILE,
1553};
1554
Peter Lieven2d9187b2017-02-28 13:40:07 +01001555#define MAX_COROUTINES 16
1556
Kevin Wolf690c7302015-03-19 13:33:32 +01001557typedef struct ImgConvertState {
1558 BlockBackend **src;
1559 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001560 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001561 int64_t total_sectors;
1562 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001563 int64_t allocated_done;
1564 int64_t sector_num;
1565 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001566 enum ImgConvertBlockStatus status;
1567 int64_t sector_next_status;
1568 BlockBackend *target;
1569 bool has_zero_init;
1570 bool compressed;
1571 bool target_has_backing;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001572 bool wr_in_order;
Kevin Wolf690c7302015-03-19 13:33:32 +01001573 int min_sparse;
1574 size_t cluster_sectors;
1575 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001576 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001577 int running_coroutines;
1578 Coroutine *co[MAX_COROUTINES];
1579 int64_t wait_sector_num[MAX_COROUTINES];
1580 CoMutex lock;
1581 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001582} ImgConvertState;
1583
Peter Lieven2d9187b2017-02-28 13:40:07 +01001584static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1585 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001586{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001587 *src_cur = 0;
1588 *src_cur_offset = 0;
1589 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1590 *src_cur_offset += s->src_sectors[*src_cur];
1591 (*src_cur)++;
1592 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001593 }
1594}
1595
1596static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1597{
Eric Blake31826642017-10-11 22:47:08 -05001598 int64_t src_cur_offset;
1599 int ret, n, src_cur;
Kevin Wolf690c7302015-03-19 13:33:32 +01001600
Peter Lieven2d9187b2017-02-28 13:40:07 +01001601 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001602
1603 assert(s->total_sectors > sector_num);
1604 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1605
1606 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001607 int64_t count = n * BDRV_SECTOR_SIZE;
1608
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001609 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001610
1611 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1612 (sector_num - src_cur_offset) *
1613 BDRV_SECTOR_SIZE,
1614 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001615 } else {
Eric Blake31826642017-10-11 22:47:08 -05001616 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1617 (sector_num - src_cur_offset) *
1618 BDRV_SECTOR_SIZE,
1619 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001620 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001621 if (ret < 0) {
1622 return ret;
1623 }
Eric Blake31826642017-10-11 22:47:08 -05001624 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001625
1626 if (ret & BDRV_BLOCK_ZERO) {
1627 s->status = BLK_ZERO;
1628 } else if (ret & BDRV_BLOCK_DATA) {
1629 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001631 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001632 }
1633
1634 s->sector_next_status = sector_num + n;
1635 }
1636
1637 n = MIN(n, s->sector_next_status - sector_num);
1638 if (s->status == BLK_DATA) {
1639 n = MIN(n, s->buf_sectors);
1640 }
1641
1642 /* We need to write complete clusters for compressed images, so if an
1643 * unallocated area is shorter than that, we must consider the whole
1644 * cluster allocated. */
1645 if (s->compressed) {
1646 if (n < s->cluster_sectors) {
1647 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1648 s->status = BLK_DATA;
1649 } else {
1650 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1651 }
1652 }
1653
1654 return n;
1655}
1656
Peter Lieven2d9187b2017-02-28 13:40:07 +01001657static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1658 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001659{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001660 int n, ret;
1661 QEMUIOVector qiov;
1662 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001663
Kevin Wolf690c7302015-03-19 13:33:32 +01001664 assert(nb_sectors <= s->buf_sectors);
1665 while (nb_sectors > 0) {
1666 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001667 int src_cur;
1668 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001669
1670 /* In the case of compression with multiple source files, we can get a
1671 * nb_sectors that spreads into the next part. So we must be able to
1672 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001673 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1674 blk = s->src[src_cur];
1675 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001676
Peter Lieven2d9187b2017-02-28 13:40:07 +01001677 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1678 iov.iov_base = buf;
1679 iov.iov_len = n << BDRV_SECTOR_BITS;
1680 qemu_iovec_init_external(&qiov, &iov, 1);
1681
1682 ret = blk_co_preadv(
1683 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1684 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 if (ret < 0) {
1686 return ret;
1687 }
1688
1689 sector_num += n;
1690 nb_sectors -= n;
1691 buf += n * BDRV_SECTOR_SIZE;
1692 }
1693
1694 return 0;
1695}
1696
Peter Lieven2d9187b2017-02-28 13:40:07 +01001697
1698static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1699 int nb_sectors, uint8_t *buf,
1700 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001701{
1702 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001703 QEMUIOVector qiov;
1704 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001705
1706 while (nb_sectors > 0) {
1707 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001708 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1709
Peter Lieven2d9187b2017-02-28 13:40:07 +01001710 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001711 case BLK_BACKING_FILE:
1712 /* If we have a backing file, leave clusters unallocated that are
1713 * unallocated in the source image, so that the backing file is
1714 * visible at the respective offset. */
1715 assert(s->target_has_backing);
1716 break;
1717
1718 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001719 /* If we're told to keep the target fully allocated (-S 0) or there
1720 * is real non-zero data, we must write it. Otherwise we can treat
1721 * it as zero sectors.
1722 * Compressed clusters need to be written as a whole, so in that
1723 * case we can only save the write if the buffer is completely
1724 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001725 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001726 (!s->compressed &&
1727 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1728 (s->compressed &&
1729 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001730 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001731 iov.iov_base = buf;
1732 iov.iov_len = n << BDRV_SECTOR_BITS;
1733 qemu_iovec_init_external(&qiov, &iov, 1);
1734
1735 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001736 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001737 if (ret < 0) {
1738 return ret;
1739 }
1740 break;
1741 }
1742 /* fall-through */
1743
1744 case BLK_ZERO:
1745 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001746 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 break;
1748 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001749 ret = blk_co_pwrite_zeroes(s->target,
1750 sector_num << BDRV_SECTOR_BITS,
1751 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001752 if (ret < 0) {
1753 return ret;
1754 }
1755 break;
1756 }
1757
1758 sector_num += n;
1759 nb_sectors -= n;
1760 buf += n * BDRV_SECTOR_SIZE;
1761 }
1762
1763 return 0;
1764}
1765
Peter Lieven2d9187b2017-02-28 13:40:07 +01001766static void coroutine_fn convert_co_do_copy(void *opaque)
1767{
1768 ImgConvertState *s = opaque;
1769 uint8_t *buf = NULL;
1770 int ret, i;
1771 int index = -1;
1772
1773 for (i = 0; i < s->num_coroutines; i++) {
1774 if (s->co[i] == qemu_coroutine_self()) {
1775 index = i;
1776 break;
1777 }
1778 }
1779 assert(index >= 0);
1780
1781 s->running_coroutines++;
1782 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1783
1784 while (1) {
1785 int n;
1786 int64_t sector_num;
1787 enum ImgConvertBlockStatus status;
1788
1789 qemu_co_mutex_lock(&s->lock);
1790 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1791 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001792 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001793 }
1794 n = convert_iteration_sectors(s, s->sector_num);
1795 if (n < 0) {
1796 qemu_co_mutex_unlock(&s->lock);
1797 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001798 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001799 }
1800 /* save current sector and allocation status to local variables */
1801 sector_num = s->sector_num;
1802 status = s->status;
1803 if (!s->min_sparse && s->status == BLK_ZERO) {
1804 n = MIN(n, s->buf_sectors);
1805 }
1806 /* increment global sector counter so that other coroutines can
1807 * already continue reading beyond this request */
1808 s->sector_num += n;
1809 qemu_co_mutex_unlock(&s->lock);
1810
1811 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1812 s->allocated_done += n;
1813 qemu_progress_print(100.0 * s->allocated_done /
1814 s->allocated_sectors, 0);
1815 }
1816
1817 if (status == BLK_DATA) {
1818 ret = convert_co_read(s, sector_num, n, buf);
1819 if (ret < 0) {
1820 error_report("error while reading sector %" PRId64
1821 ": %s", sector_num, strerror(-ret));
1822 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001823 }
1824 } else if (!s->min_sparse && status == BLK_ZERO) {
1825 status = BLK_DATA;
1826 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1827 }
1828
1829 if (s->wr_in_order) {
1830 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001831 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001832 s->wait_sector_num[index] = sector_num;
1833 qemu_coroutine_yield();
1834 }
1835 s->wait_sector_num[index] = -1;
1836 }
1837
Anton Nefedovb91127e2017-04-26 11:33:15 +03001838 if (s->ret == -EINPROGRESS) {
1839 ret = convert_co_write(s, sector_num, n, buf, status);
1840 if (ret < 0) {
1841 error_report("error while writing sector %" PRId64
1842 ": %s", sector_num, strerror(-ret));
1843 s->ret = ret;
1844 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001845 }
1846
1847 if (s->wr_in_order) {
1848 /* reenter the coroutine that might have waited
1849 * for this write to complete */
1850 s->wr_offs = sector_num + n;
1851 for (i = 0; i < s->num_coroutines; i++) {
1852 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1853 /*
1854 * A -> B -> A cannot occur because A has
1855 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1856 * B will never enter A during this time window.
1857 */
1858 qemu_coroutine_enter(s->co[i]);
1859 break;
1860 }
1861 }
1862 }
1863 }
1864
Peter Lieven2d9187b2017-02-28 13:40:07 +01001865 qemu_vfree(buf);
1866 s->co[index] = NULL;
1867 s->running_coroutines--;
1868 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1869 /* the convert job finished successfully */
1870 s->ret = 0;
1871 }
1872}
1873
Kevin Wolf690c7302015-03-19 13:33:32 +01001874static int convert_do_copy(ImgConvertState *s)
1875{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001876 int ret, i, n;
1877 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001878
1879 /* Check whether we have zero initialisation or can get it efficiently */
1880 s->has_zero_init = s->min_sparse && !s->target_has_backing
1881 ? bdrv_has_zero_init(blk_bs(s->target))
1882 : false;
1883
1884 if (!s->has_zero_init && !s->target_has_backing &&
1885 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1886 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001887 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001888 if (ret == 0) {
1889 s->has_zero_init = true;
1890 }
1891 }
1892
1893 /* Allocate buffer for copied data. For compressed images, only one cluster
1894 * can be copied at a time. */
1895 if (s->compressed) {
1896 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1897 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001898 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001899 }
1900 s->buf_sectors = s->cluster_sectors;
1901 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001902
Kevin Wolf690c7302015-03-19 13:33:32 +01001903 while (sector_num < s->total_sectors) {
1904 n = convert_iteration_sectors(s, sector_num);
1905 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001906 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001907 }
Max Reitzaad15de2016-03-24 23:33:57 +01001908 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1909 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001910 s->allocated_sectors += n;
1911 }
1912 sector_num += n;
1913 }
1914
1915 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001916 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001917 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001918
Peter Lieven2d9187b2017-02-28 13:40:07 +01001919 qemu_co_mutex_init(&s->lock);
1920 for (i = 0; i < s->num_coroutines; i++) {
1921 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1922 s->wait_sector_num[i] = -1;
1923 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001924 }
1925
Anton Nefedovb91127e2017-04-26 11:33:15 +03001926 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001927 main_loop_wait(false);
1928 }
1929
1930 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001931 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001932 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001933 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001934 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001935 }
1936 }
1937
Peter Lieven2d9187b2017-02-28 13:40:07 +01001938 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001939}
1940
bellardea2384d2004-08-01 21:59:26 +00001941static int img_convert(int argc, char **argv)
1942{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001943 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001944 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001945 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1946 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001947 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001948 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001949 BlockDriverState *out_bs;
1950 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001951 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001952 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001953 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001954 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001955 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001956 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08001957 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00001958
Peter Lieven9fd77f92017-04-21 11:11:55 +02001959 ImgConvertState s = (ImgConvertState) {
1960 /* Need at least 4k of zeros for sparse detection */
1961 .min_sparse = 8,
1962 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1963 .wr_in_order = true,
1964 .num_coroutines = 8,
1965 };
1966
bellardea2384d2004-08-01 21:59:26 +00001967 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001968 static const struct option long_options[] = {
1969 {"help", no_argument, 0, 'h'},
1970 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001971 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001972 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001973 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001974 {0, 0, 0, 0}
1975 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01001976 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001977 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001978 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001979 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001980 }
bellardea2384d2004-08-01 21:59:26 +00001981 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001982 case ':':
1983 missing_argument(argv[optind - 1]);
1984 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001985 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001986 unrecognized_option(argv[optind - 1]);
1987 break;
bellardea2384d2004-08-01 21:59:26 +00001988 case 'h':
1989 help();
1990 break;
1991 case 'f':
1992 fmt = optarg;
1993 break;
1994 case 'O':
1995 out_fmt = optarg;
1996 break;
thsf58c7b32008-06-05 21:53:49 +00001997 case 'B':
1998 out_baseimg = optarg;
1999 break;
bellardea2384d2004-08-01 21:59:26 +00002000 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002001 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002002 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002003 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002004 if (!is_valid_option_list(optarg)) {
2005 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002006 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002007 }
2008 if (!options) {
2009 options = g_strdup(optarg);
2010 } else {
2011 char *old_options = options;
2012 options = g_strdup_printf("%s,%s", options, optarg);
2013 g_free(old_options);
2014 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002015 break;
edison51ef6722010-09-21 19:58:41 -07002016 case 's':
2017 snapshot_name = optarg;
2018 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002019 case 'l':
2020 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002021 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2022 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002023 if (!sn_opts) {
2024 error_report("Failed in parsing snapshot param '%s'",
2025 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002026 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002027 }
2028 } else {
2029 snapshot_name = optarg;
2030 }
2031 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002032 case 'S':
2033 {
2034 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002035
2036 sval = cvtnum(optarg);
2037 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002038 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002039 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002040 }
2041
Peter Lieven9fd77f92017-04-21 11:11:55 +02002042 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002043 break;
2044 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002045 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002046 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002047 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002048 case 't':
2049 cache = optarg;
2050 break;
Max Reitz40055952014-07-22 22:58:42 +02002051 case 'T':
2052 src_cache = optarg;
2053 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002054 case 'q':
2055 quiet = true;
2056 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002057 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002058 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002059 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002060 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002061 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2062 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002063 error_report("Invalid number of coroutines. Allowed number of"
2064 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002065 goto fail_getopt;
2066 }
2067 break;
2068 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002069 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002070 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002071 case 'U':
2072 force_share = true;
2073 break;
Max Reitz3258b912017-04-26 15:46:47 +02002074 case OPTION_OBJECT: {
2075 QemuOpts *object_opts;
2076 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2077 optarg, true);
2078 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002079 goto fail_getopt;
2080 }
2081 break;
Max Reitz3258b912017-04-26 15:46:47 +02002082 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002083 case OPTION_IMAGE_OPTS:
2084 image_opts = true;
2085 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002086 case OPTION_TARGET_IMAGE_OPTS:
2087 tgt_image_opts = true;
2088 break;
bellardea2384d2004-08-01 21:59:26 +00002089 }
2090 }
ths3b46e622007-09-17 08:09:54 +00002091
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002092 if (!out_fmt && !tgt_image_opts) {
2093 out_fmt = "raw";
2094 }
2095
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002096 if (qemu_opts_foreach(&qemu_object_opts,
2097 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002098 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002099 goto fail_getopt;
2100 }
2101
Peter Lieven9fd77f92017-04-21 11:11:55 +02002102 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002103 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002104 goto fail_getopt;
2105 }
2106
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002107 if (tgt_image_opts && !skip_create) {
2108 error_report("--target-image-opts requires use of -n flag");
2109 goto fail_getopt;
2110 }
2111
Peter Lieven9fd77f92017-04-21 11:11:55 +02002112 s.src_num = argc - optind - 1;
2113 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2114
2115 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002116 if (out_fmt) {
2117 ret = print_block_option_help(out_filename, out_fmt);
2118 goto fail_getopt;
2119 } else {
2120 error_report("Option help requires a format be specified");
2121 goto fail_getopt;
2122 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002123 }
2124
2125 if (s.src_num < 1) {
2126 error_report("Must specify image file name");
2127 goto fail_getopt;
2128 }
2129
2130
Peter Lieven9fd77f92017-04-21 11:11:55 +02002131 /* ret is still -EINVAL until here */
2132 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2133 if (ret < 0) {
2134 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002135 goto fail_getopt;
2136 }
2137
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002138 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002139 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002140 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002141 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002142 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002143 qemu_progress_print(0, 100);
2144
Peter Lieven9fd77f92017-04-21 11:11:55 +02002145 s.src = g_new0(BlockBackend *, s.src_num);
2146 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002147
Peter Lieven9fd77f92017-04-21 11:11:55 +02002148 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2149 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002150 fmt, src_flags, src_writethrough, quiet,
2151 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002152 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002153 ret = -1;
2154 goto out;
2155 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002156 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2157 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002158 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002159 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002160 ret = -1;
2161 goto out;
2162 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002163 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002164 }
bellardea2384d2004-08-01 21:59:26 +00002165
Wenchao Xiaef806542013-12-04 17:10:57 +08002166 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002167 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002168 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2169 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2170 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002171 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002172 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002173 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002174 ret = -1;
2175 goto out;
2176 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002177
Peter Lieven9fd77f92017-04-21 11:11:55 +02002178 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2179 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002180 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002181 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002182 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002183 ret = -1;
2184 goto out;
edison51ef6722010-09-21 19:58:41 -07002185 }
2186
Max Reitz2e024cd2015-02-11 09:58:46 -05002187 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002188 /* Find driver and parse its options */
2189 drv = bdrv_find_format(out_fmt);
2190 if (!drv) {
2191 error_report("Unknown file format '%s'", out_fmt);
2192 ret = -1;
2193 goto out;
2194 }
2195
2196 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2197 if (!proto_drv) {
2198 error_report_err(local_err);
2199 ret = -1;
2200 goto out;
2201 }
2202
Max Reitz2e024cd2015-02-11 09:58:46 -05002203 if (!drv->create_opts) {
2204 error_report("Format driver '%s' does not support image creation",
2205 drv->format_name);
2206 ret = -1;
2207 goto out;
2208 }
Max Reitzf75613c2014-12-02 18:32:46 +01002209
Max Reitz2e024cd2015-02-11 09:58:46 -05002210 if (!proto_drv->create_opts) {
2211 error_report("Protocol driver '%s' does not support image creation",
2212 proto_drv->format_name);
2213 ret = -1;
2214 goto out;
2215 }
Max Reitzf75613c2014-12-02 18:32:46 +01002216
Max Reitz2e024cd2015-02-11 09:58:46 -05002217 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2218 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002219
Max Reitz2e024cd2015-02-11 09:58:46 -05002220 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002221 if (options) {
2222 qemu_opts_do_parse(opts, options, NULL, &local_err);
2223 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002224 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002225 ret = -1;
2226 goto out;
2227 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002228 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002229
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002231 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002232 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2233 if (ret < 0) {
2234 goto out;
2235 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002236 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002237
Kevin Wolfa18953f2010-10-14 15:46:04 +02002238 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002239 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002240 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002241 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002242 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002243 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002244
Max Reitz48758a82017-04-26 15:46:48 +02002245 if (s.src_num > 1 && out_baseimg) {
2246 error_report("Having a backing file for the target makes no sense when "
2247 "concatenating multiple input images");
2248 ret = -1;
2249 goto out;
2250 }
2251
Kevin Wolfefa84d42009-05-18 16:42:12 +02002252 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002253 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002254 bool encryption =
2255 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002256 const char *encryptfmt =
2257 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002258 const char *preallocation =
2259 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002260
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002261 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002262 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002263 ret = -1;
2264 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002265 }
2266
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002267 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002268 error_report("Compression and encryption not supported at "
2269 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002270 ret = -1;
2271 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002272 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002273
Chunyan Liu83d05212014-06-05 17:20:51 +08002274 if (preallocation
2275 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002276 {
2277 error_report("Compression and preallocation not supported at "
2278 "the same time");
2279 ret = -1;
2280 goto out;
2281 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002282 }
2283
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002284 if (!skip_create) {
2285 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002286 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002287 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002288 error_reportf_err(local_err, "%s: error while converting %s: ",
2289 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002290 goto out;
bellardea2384d2004-08-01 21:59:26 +00002291 }
2292 }
ths3b46e622007-09-17 08:09:54 +00002293
Peter Lieven9fd77f92017-04-21 11:11:55 +02002294 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002295 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002296 if (ret < 0) {
2297 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002298 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002299 }
2300
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002301 if (skip_create) {
2302 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2303 flags, writethrough, quiet, false);
2304 } else {
2305 /* TODO ultimately we should allow --target-image-opts
2306 * to be used even when -n is not given.
2307 * That has to wait for bdrv_create to be improved
2308 * to allow filenames in option syntax
2309 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002310 s.target = img_open_new_file(out_filename, opts, out_fmt,
2311 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002312 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002313 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002314 ret = -1;
2315 goto out;
2316 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002317 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002318
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002319 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2320 error_report("Compression not supported for this file format");
2321 ret = -1;
2322 goto out;
2323 }
2324
Eric Blake5def6b82016-06-23 16:37:19 -06002325 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002326 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2327 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002328 s.buf_sectors = MIN(32768,
2329 MAX(s.buf_sectors,
2330 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2331 out_bs->bl.pdiscard_alignment >>
2332 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002333
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002334 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002335 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002336 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002337 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002338 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002339 ret = -1;
2340 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002341 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002342 error_report("output file is smaller than input file");
2343 ret = -1;
2344 goto out;
2345 }
2346 }
2347
Peter Lieven24f833c2013-11-27 11:07:07 +01002348 ret = bdrv_get_info(out_bs, &bdi);
2349 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002350 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002351 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002352 goto out;
2353 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002354 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002355 s.compressed = s.compressed || bdi.needs_compressed_writes;
2356 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002357 }
2358
Peter Lieven9fd77f92017-04-21 11:11:55 +02002359 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002360out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002361 if (!ret) {
2362 qemu_progress_print(100, 0);
2363 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002364 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002365 qemu_opts_del(opts);
2366 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002367 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002368 blk_unref(s.target);
2369 if (s.src) {
2370 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2371 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002372 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002373 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002374 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002375 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002376fail_getopt:
2377 g_free(options);
2378
Peter Lieven9fd77f92017-04-21 11:11:55 +02002379 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002380}
2381
bellard57d1a2b2004-08-03 21:15:11 +00002382
bellardfaea38e2006-08-05 21:31:00 +00002383static void dump_snapshots(BlockDriverState *bs)
2384{
2385 QEMUSnapshotInfo *sn_tab, *sn;
2386 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002387
2388 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2389 if (nb_sns <= 0)
2390 return;
2391 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002392 bdrv_snapshot_dump(fprintf, stdout, NULL);
2393 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002394 for(i = 0; i < nb_sns; i++) {
2395 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002396 bdrv_snapshot_dump(fprintf, stdout, sn);
2397 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002398 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002399 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002400}
2401
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002402static void dump_json_image_info_list(ImageInfoList *list)
2403{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002404 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +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_ImageInfoList(v, NULL, &list, &error_abort);
2409 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +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);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002415 QDECREF(str);
2416}
2417
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002418static void dump_json_image_info(ImageInfo *info)
2419{
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002420 QString *str;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002421 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002422 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002423
2424 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2425 visit_complete(v, &obj);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002426 str = qobject_to_json_pretty(obj);
2427 assert(str != NULL);
2428 printf("%s\n", qstring_get_str(str));
2429 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002430 visit_free(v);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002431 QDECREF(str);
2432}
2433
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002434static void dump_human_image_info_list(ImageInfoList *list)
2435{
2436 ImageInfoList *elem;
2437 bool delim = false;
2438
2439 for (elem = list; elem; elem = elem->next) {
2440 if (delim) {
2441 printf("\n");
2442 }
2443 delim = true;
2444
Wenchao Xia5b917042013-05-25 11:09:45 +08002445 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002446 }
2447}
2448
2449static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2450{
2451 return strcmp(a, b) == 0;
2452}
2453
2454/**
2455 * Open an image file chain and return an ImageInfoList
2456 *
2457 * @filename: topmost image filename
2458 * @fmt: topmost image format (may be NULL to autodetect)
2459 * @chain: true - enumerate entire backing file chain
2460 * false - only topmost image file
2461 *
2462 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2463 * image file. If there was an error a message will have been printed to
2464 * stderr.
2465 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002466static ImageInfoList *collect_image_info_list(bool image_opts,
2467 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002468 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002469 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002470{
2471 ImageInfoList *head = NULL;
2472 ImageInfoList **last = &head;
2473 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002474 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002475
2476 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2477
2478 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002479 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002480 BlockDriverState *bs;
2481 ImageInfo *info;
2482 ImageInfoList *elem;
2483
2484 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2485 error_report("Backing file '%s' creates an infinite loop.",
2486 filename);
2487 goto err;
2488 }
2489 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2490
Max Reitzefaa7c42016-03-16 19:54:38 +01002491 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002492 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2493 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002494 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002495 goto err;
2496 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002497 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002498
Wenchao Xia43526ec2013-06-06 12:27:58 +08002499 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002500 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002501 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002502 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002503 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002504 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505
2506 elem = g_new0(ImageInfoList, 1);
2507 elem->value = info;
2508 *last = elem;
2509 last = &elem->next;
2510
Markus Armbruster26f54e92014-10-07 13:59:04 +02002511 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002512
2513 filename = fmt = NULL;
2514 if (chain) {
2515 if (info->has_full_backing_filename) {
2516 filename = info->full_backing_filename;
2517 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002518 error_report("Could not determine absolute backing filename,"
2519 " but backing filename '%s' present",
2520 info->backing_filename);
2521 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002522 }
2523 if (info->has_backing_filename_format) {
2524 fmt = info->backing_filename_format;
2525 }
2526 }
2527 }
2528 g_hash_table_destroy(filenames);
2529 return head;
2530
2531err:
2532 qapi_free_ImageInfoList(head);
2533 g_hash_table_destroy(filenames);
2534 return NULL;
2535}
2536
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002537static int img_info(int argc, char **argv)
2538{
2539 int c;
2540 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002541 bool chain = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002542 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002543 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002544 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002545 bool force_share = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002546
bellardea2384d2004-08-01 21:59:26 +00002547 fmt = NULL;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002548 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002549 for(;;) {
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002550 int option_index = 0;
2551 static const struct option long_options[] = {
2552 {"help", no_argument, 0, 'h'},
2553 {"format", required_argument, 0, 'f'},
2554 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002555 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002556 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002557 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002558 {"force-share", no_argument, 0, 'U'},
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002559 {0, 0, 0, 0}
2560 };
Fam Zheng335e9932017-05-03 00:35:39 +08002561 c = getopt_long(argc, argv, ":f:hU",
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002562 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002563 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002564 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002565 }
bellardea2384d2004-08-01 21:59:26 +00002566 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002567 case ':':
2568 missing_argument(argv[optind - 1]);
2569 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002570 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002571 unrecognized_option(argv[optind - 1]);
2572 break;
bellardea2384d2004-08-01 21:59:26 +00002573 case 'h':
2574 help();
2575 break;
2576 case 'f':
2577 fmt = optarg;
2578 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002579 case 'U':
2580 force_share = true;
2581 break;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002582 case OPTION_OUTPUT:
2583 output = optarg;
2584 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002585 case OPTION_BACKING_CHAIN:
2586 chain = true;
2587 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002588 case OPTION_OBJECT: {
2589 QemuOpts *opts;
2590 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2591 optarg, true);
2592 if (!opts) {
2593 return 1;
2594 }
2595 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002596 case OPTION_IMAGE_OPTS:
2597 image_opts = true;
2598 break;
bellardea2384d2004-08-01 21:59:26 +00002599 }
2600 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002601 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002602 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002603 }
bellardea2384d2004-08-01 21:59:26 +00002604 filename = argv[optind++];
2605
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002606 if (output && !strcmp(output, "json")) {
2607 output_format = OFORMAT_JSON;
2608 } else if (output && !strcmp(output, "human")) {
2609 output_format = OFORMAT_HUMAN;
2610 } else if (output) {
2611 error_report("--output must be used with human or json as argument.");
2612 return 1;
2613 }
2614
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002615 if (qemu_opts_foreach(&qemu_object_opts,
2616 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002617 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002618 return 1;
2619 }
2620
Fam Zheng335e9932017-05-03 00:35:39 +08002621 list = collect_image_info_list(image_opts, filename, fmt, chain,
2622 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002623 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002624 return 1;
2625 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002626
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002627 switch (output_format) {
2628 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002629 dump_human_image_info_list(list);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002630 break;
2631 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002632 if (chain) {
2633 dump_json_image_info_list(list);
2634 } else {
2635 dump_json_image_info(list->value);
2636 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002637 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002638 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002639
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002640 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002641 return 0;
2642}
2643
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002644static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2645 MapEntry *next)
2646{
2647 switch (output_format) {
2648 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002649 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002650 error_report("File contains external, encrypted or compressed clusters.");
2651 exit(1);
2652 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002653 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002654 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002655 e->start, e->length,
2656 e->has_offset ? e->offset : 0,
2657 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002658 }
2659 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2660 * Modify the flags here to allow more coalescing.
2661 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002662 if (next && (!next->data || next->zero)) {
2663 next->data = false;
2664 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002665 }
2666 break;
2667 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002668 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2669 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002670 (e->start == 0 ? "[" : ",\n"),
2671 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002672 e->zero ? "true" : "false",
2673 e->data ? "true" : "false");
2674 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002675 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002676 }
2677 putchar('}');
2678
2679 if (!next) {
2680 printf("]\n");
2681 }
2682 break;
2683 }
2684}
2685
Eric Blake5e344dd2017-10-11 22:47:02 -05002686static int get_block_status(BlockDriverState *bs, int64_t offset,
2687 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002688{
Eric Blake237d78f2017-10-11 22:47:03 -05002689 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002690 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002691 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002692 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002693 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002694
2695 /* As an optimization, we could cache the current range of unallocated
2696 * clusters in each file of the chain, and avoid querying the same
2697 * range repeatedly.
2698 */
2699
2700 depth = 0;
2701 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002702 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002703 if (ret < 0) {
2704 return ret;
2705 }
Eric Blake237d78f2017-10-11 22:47:03 -05002706 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002707 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2708 break;
2709 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002710 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002711 if (bs == NULL) {
2712 ret = 0;
2713 break;
2714 }
2715
2716 depth++;
2717 }
2718
John Snow28756452016-02-05 13:12:33 -05002719 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2720
2721 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002722 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002723 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002724 .data = !!(ret & BDRV_BLOCK_DATA),
2725 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002726 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002727 .has_offset = has_offset,
2728 .depth = depth,
2729 .has_filename = file && has_offset,
2730 .filename = file && has_offset ? file->filename : NULL,
2731 };
2732
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002733 return 0;
2734}
2735
Fam Zheng16b0d552016-01-26 11:59:02 +08002736static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2737{
2738 if (curr->length == 0) {
2739 return false;
2740 }
2741 if (curr->zero != next->zero ||
2742 curr->data != next->data ||
2743 curr->depth != next->depth ||
2744 curr->has_filename != next->has_filename ||
2745 curr->has_offset != next->has_offset) {
2746 return false;
2747 }
2748 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2749 return false;
2750 }
2751 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2752 return false;
2753 }
2754 return true;
2755}
2756
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002757static int img_map(int argc, char **argv)
2758{
2759 int c;
2760 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002761 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002762 BlockDriverState *bs;
2763 const char *filename, *fmt, *output;
2764 int64_t length;
2765 MapEntry curr = { .length = 0 }, next;
2766 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002767 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002768 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002769
2770 fmt = NULL;
2771 output = NULL;
2772 for (;;) {
2773 int option_index = 0;
2774 static const struct option long_options[] = {
2775 {"help", no_argument, 0, 'h'},
2776 {"format", required_argument, 0, 'f'},
2777 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002778 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002779 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002780 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002781 {0, 0, 0, 0}
2782 };
Fam Zheng335e9932017-05-03 00:35:39 +08002783 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002784 long_options, &option_index);
2785 if (c == -1) {
2786 break;
2787 }
2788 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002789 case ':':
2790 missing_argument(argv[optind - 1]);
2791 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002792 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002793 unrecognized_option(argv[optind - 1]);
2794 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002795 case 'h':
2796 help();
2797 break;
2798 case 'f':
2799 fmt = optarg;
2800 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002801 case 'U':
2802 force_share = true;
2803 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002804 case OPTION_OUTPUT:
2805 output = optarg;
2806 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002807 case OPTION_OBJECT: {
2808 QemuOpts *opts;
2809 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2810 optarg, true);
2811 if (!opts) {
2812 return 1;
2813 }
2814 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002815 case OPTION_IMAGE_OPTS:
2816 image_opts = true;
2817 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002818 }
2819 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002820 if (optind != argc - 1) {
2821 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002822 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002823 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002824
2825 if (output && !strcmp(output, "json")) {
2826 output_format = OFORMAT_JSON;
2827 } else if (output && !strcmp(output, "human")) {
2828 output_format = OFORMAT_HUMAN;
2829 } else if (output) {
2830 error_report("--output must be used with human or json as argument.");
2831 return 1;
2832 }
2833
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002834 if (qemu_opts_foreach(&qemu_object_opts,
2835 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002836 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002837 return 1;
2838 }
2839
Fam Zheng335e9932017-05-03 00:35:39 +08002840 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002841 if (!blk) {
2842 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002843 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002844 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002845
2846 if (output_format == OFORMAT_HUMAN) {
2847 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2848 }
2849
Max Reitzf1d3cd72015-02-05 13:58:18 -05002850 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002851 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002852 int64_t offset = curr.start + curr.length;
2853 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002854
2855 /* Probe up to 1 GiB at a time. */
Eric Blake5e344dd2017-10-11 22:47:02 -05002856 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2857 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858
2859 if (ret < 0) {
2860 error_report("Could not read file metadata: %s", strerror(-ret));
2861 goto out;
2862 }
2863
Fam Zheng16b0d552016-01-26 11:59:02 +08002864 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002865 curr.length += next.length;
2866 continue;
2867 }
2868
2869 if (curr.length > 0) {
2870 dump_map_entry(output_format, &curr, &next);
2871 }
2872 curr = next;
2873 }
2874
2875 dump_map_entry(output_format, &curr, NULL);
2876
2877out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002878 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002879 return ret < 0;
2880}
2881
aliguorif7b4a942009-01-07 17:40:15 +00002882#define SNAPSHOT_LIST 1
2883#define SNAPSHOT_CREATE 2
2884#define SNAPSHOT_APPLY 3
2885#define SNAPSHOT_DELETE 4
2886
Stuart Brady153859b2009-06-07 00:42:17 +01002887static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002888{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002889 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002890 BlockDriverState *bs;
2891 QEMUSnapshotInfo sn;
2892 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002893 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002894 int action = 0;
2895 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002896 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002897 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002898 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002899 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002900
Kevin Wolfce099542016-03-15 13:01:04 +01002901 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002902 /* Parse commandline parameters */
2903 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002904 static const struct option long_options[] = {
2905 {"help", no_argument, 0, 'h'},
2906 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002907 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002908 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002909 {0, 0, 0, 0}
2910 };
Fam Zheng335e9932017-05-03 00:35:39 +08002911 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002912 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002913 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002914 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002915 }
aliguorif7b4a942009-01-07 17:40:15 +00002916 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002917 case ':':
2918 missing_argument(argv[optind - 1]);
2919 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002920 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002921 unrecognized_option(argv[optind - 1]);
2922 break;
aliguorif7b4a942009-01-07 17:40:15 +00002923 case 'h':
2924 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002925 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002926 case 'l':
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_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002932 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002933 break;
2934 case 'a':
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_APPLY;
2940 snapshot_name = optarg;
2941 break;
2942 case 'c':
2943 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002944 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002945 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002946 }
2947 action = SNAPSHOT_CREATE;
2948 snapshot_name = optarg;
2949 break;
2950 case 'd':
2951 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002952 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002953 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002954 }
2955 action = SNAPSHOT_DELETE;
2956 snapshot_name = optarg;
2957 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002958 case 'q':
2959 quiet = true;
2960 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002961 case 'U':
2962 force_share = true;
2963 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002964 case OPTION_OBJECT: {
2965 QemuOpts *opts;
2966 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2967 optarg, true);
2968 if (!opts) {
2969 return 1;
2970 }
2971 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002972 case OPTION_IMAGE_OPTS:
2973 image_opts = true;
2974 break;
aliguorif7b4a942009-01-07 17:40:15 +00002975 }
2976 }
2977
Kevin Wolffc11eb22013-08-05 10:53:04 +02002978 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002979 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002980 }
aliguorif7b4a942009-01-07 17:40:15 +00002981 filename = argv[optind++];
2982
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002983 if (qemu_opts_foreach(&qemu_object_opts,
2984 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002985 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002986 return 1;
2987 }
2988
aliguorif7b4a942009-01-07 17:40:15 +00002989 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08002990 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2991 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002992 if (!blk) {
2993 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002994 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002995 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002996
2997 /* Perform the requested action */
2998 switch(action) {
2999 case SNAPSHOT_LIST:
3000 dump_snapshots(bs);
3001 break;
3002
3003 case SNAPSHOT_CREATE:
3004 memset(&sn, 0, sizeof(sn));
3005 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3006
3007 qemu_gettimeofday(&tv);
3008 sn.date_sec = tv.tv_sec;
3009 sn.date_nsec = tv.tv_usec * 1000;
3010
3011 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003012 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003013 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003014 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003015 }
aliguorif7b4a942009-01-07 17:40:15 +00003016 break;
3017
3018 case SNAPSHOT_APPLY:
3019 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003020 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003021 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003022 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003023 }
aliguorif7b4a942009-01-07 17:40:15 +00003024 break;
3025
3026 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003027 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003028 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003029 error_reportf_err(err, "Could not delete snapshot '%s': ",
3030 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003031 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003032 }
aliguorif7b4a942009-01-07 17:40:15 +00003033 break;
3034 }
3035
3036 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003037 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003038 if (ret) {
3039 return 1;
3040 }
Stuart Brady153859b2009-06-07 00:42:17 +01003041 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003042}
3043
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003044static int img_rebase(int argc, char **argv)
3045{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003046 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003047 uint8_t *buf_old = NULL;
3048 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003049 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003050 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003051 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3052 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003053 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003054 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003055 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003056 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003057 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003058 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003059 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003060
3061 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003062 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003063 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003064 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003065 out_baseimg = NULL;
3066 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003067 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003068 static const struct option long_options[] = {
3069 {"help", no_argument, 0, 'h'},
3070 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003071 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003072 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003073 {0, 0, 0, 0}
3074 };
Fam Zheng335e9932017-05-03 00:35:39 +08003075 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003076 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003077 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003078 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003079 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003080 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003081 case ':':
3082 missing_argument(argv[optind - 1]);
3083 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003084 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003085 unrecognized_option(argv[optind - 1]);
3086 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003087 case 'h':
3088 help();
3089 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003090 case 'f':
3091 fmt = optarg;
3092 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003093 case 'F':
3094 out_basefmt = optarg;
3095 break;
3096 case 'b':
3097 out_baseimg = optarg;
3098 break;
3099 case 'u':
3100 unsafe = 1;
3101 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003102 case 'p':
3103 progress = 1;
3104 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003105 case 't':
3106 cache = optarg;
3107 break;
Max Reitz40055952014-07-22 22:58:42 +02003108 case 'T':
3109 src_cache = optarg;
3110 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003111 case 'q':
3112 quiet = true;
3113 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003114 case OPTION_OBJECT: {
3115 QemuOpts *opts;
3116 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3117 optarg, true);
3118 if (!opts) {
3119 return 1;
3120 }
3121 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003122 case OPTION_IMAGE_OPTS:
3123 image_opts = true;
3124 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003125 case 'U':
3126 force_share = true;
3127 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003128 }
3129 }
3130
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003131 if (quiet) {
3132 progress = 0;
3133 }
3134
Fam Zhengac1307a2014-04-22 13:36:11 +08003135 if (optind != argc - 1) {
3136 error_exit("Expecting one image file name");
3137 }
3138 if (!unsafe && !out_baseimg) {
3139 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003140 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003141 filename = argv[optind++];
3142
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003143 if (qemu_opts_foreach(&qemu_object_opts,
3144 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003145 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003146 return 1;
3147 }
3148
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003149 qemu_progress_init(progress, 2.0);
3150 qemu_progress_print(0, 100);
3151
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003152 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003153 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003154 if (ret < 0) {
3155 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003156 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003157 }
3158
Kevin Wolfce099542016-03-15 13:01:04 +01003159 src_flags = 0;
3160 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003161 if (ret < 0) {
3162 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003163 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003164 }
3165
Kevin Wolfce099542016-03-15 13:01:04 +01003166 /* The source files are opened read-only, don't care about WCE */
3167 assert((src_flags & BDRV_O_RDWR) == 0);
3168 (void) src_writethrough;
3169
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003170 /*
3171 * Open the images.
3172 *
3173 * Ignore the old backing file for unsafe rebase in case we want to correct
3174 * the reference to a renamed or moved backing file.
3175 */
Fam Zheng335e9932017-05-03 00:35:39 +08003176 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3177 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003178 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003179 ret = -1;
3180 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003181 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003182 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003183
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003184 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003185 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003186 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003187 ret = -1;
3188 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003189 }
3190 }
3191
3192 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003193 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003194 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003195 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003196
Max Reitz644483d2015-02-05 13:58:17 -05003197 if (bs->backing_format[0] != '\0') {
3198 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003199 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003200 }
3201
Fam Zheng335e9932017-05-03 00:35:39 +08003202 if (force_share) {
3203 if (!options) {
3204 options = qdict_new();
3205 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003206 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003207 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003208 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003209 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003210 options, src_flags, &local_err);
3211 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003212 error_reportf_err(local_err,
3213 "Could not open old backing file '%s': ",
3214 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003215 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003216 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003217 }
Max Reitz644483d2015-02-05 13:58:17 -05003218
Alex Bligha6166732012-10-16 13:46:18 +01003219 if (out_baseimg[0]) {
Fam Zheng335e9932017-05-03 00:35:39 +08003220 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003221 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003222 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003223 }
3224 if (force_share) {
3225 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003226 }
3227
Max Reitzefaa7c42016-03-16 19:54:38 +01003228 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003229 options, src_flags, &local_err);
3230 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003231 error_reportf_err(local_err,
3232 "Could not open new backing file '%s': ",
3233 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003234 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003235 goto out;
3236 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003237 }
3238 }
3239
3240 /*
3241 * Check each unallocated cluster in the COW file. If it is unallocated,
3242 * accesses go to the backing file. We must therefore compare this cluster
3243 * in the old and new backing file, and if they differ we need to copy it
3244 * from the old backing file into the COW file.
3245 *
3246 * If qemu-img crashes during this step, no harm is done. The content of
3247 * the image is the same as the original one at any time.
3248 */
3249 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003250 int64_t num_sectors;
3251 int64_t old_backing_num_sectors;
3252 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003253 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003254 int n;
Eric Blaked6a644b2017-07-07 07:44:57 -05003255 int64_t count;
Kevin Wolf1f710492012-10-12 14:29:18 +02003256 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003257
Max Reitzf1d3cd72015-02-05 13:58:18 -05003258 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3259 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003260
Max Reitzf1d3cd72015-02-05 13:58:18 -05003261 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003262 if (num_sectors < 0) {
3263 error_report("Could not get size of '%s': %s",
3264 filename, strerror(-num_sectors));
3265 ret = -1;
3266 goto out;
3267 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003268 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003269 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003270 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003271
3272 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3273 error_report("Could not get size of '%s': %s",
3274 backing_name, strerror(-old_backing_num_sectors));
3275 ret = -1;
3276 goto out;
3277 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003278 if (blk_new_backing) {
3279 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003280 if (new_backing_num_sectors < 0) {
3281 error_report("Could not get size of '%s': %s",
3282 out_baseimg, strerror(-new_backing_num_sectors));
3283 ret = -1;
3284 goto out;
3285 }
Alex Bligha6166732012-10-16 13:46:18 +01003286 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003287
Kevin Wolf1f710492012-10-12 14:29:18 +02003288 if (num_sectors != 0) {
3289 local_progress = (float)100 /
3290 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3291 }
3292
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003293 for (sector = 0; sector < num_sectors; sector += n) {
3294
3295 /* How many sectors can we handle with the next read? */
3296 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3297 n = (IO_BUF_SIZE / 512);
3298 } else {
3299 n = num_sectors - sector;
3300 }
3301
3302 /* If the cluster is allocated, we don't need to take action */
Eric Blaked6a644b2017-07-07 07:44:57 -05003303 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3304 n << BDRV_SECTOR_BITS, &count);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003305 if (ret < 0) {
3306 error_report("error while reading image metadata: %s",
3307 strerror(-ret));
3308 goto out;
3309 }
Eric Blaked6a644b2017-07-07 07:44:57 -05003310 /* TODO relax this once bdrv_is_allocated does not enforce
3311 * sector alignment */
3312 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3313 n = count >> BDRV_SECTOR_BITS;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003314 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003315 continue;
3316 }
3317
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003318 /*
3319 * Read old and new backing file and take into consideration that
3320 * backing files may be smaller than the COW image.
3321 */
3322 if (sector >= old_backing_num_sectors) {
3323 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3324 } else {
3325 if (sector + n > old_backing_num_sectors) {
3326 n = old_backing_num_sectors - sector;
3327 }
3328
Eric Blake91669202016-05-06 10:26:43 -06003329 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3330 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003331 if (ret < 0) {
3332 error_report("error while reading from old backing file");
3333 goto out;
3334 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003335 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003336
Max Reitzf1d3cd72015-02-05 13:58:18 -05003337 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003338 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3339 } else {
3340 if (sector + n > new_backing_num_sectors) {
3341 n = new_backing_num_sectors - sector;
3342 }
3343
Eric Blake91669202016-05-06 10:26:43 -06003344 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3345 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003346 if (ret < 0) {
3347 error_report("error while reading from new backing file");
3348 goto out;
3349 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003350 }
3351
3352 /* If they differ, we need to write to the COW file */
3353 uint64_t written = 0;
3354
3355 while (written < n) {
3356 int pnum;
3357
3358 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003359 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003360 {
Eric Blake91669202016-05-06 10:26:43 -06003361 ret = blk_pwrite(blk,
3362 (sector + written) << BDRV_SECTOR_BITS,
3363 buf_old + written * 512,
3364 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003365 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003366 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003367 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003368 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003369 }
3370 }
3371
3372 written += pnum;
3373 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003374 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003375 }
3376 }
3377
3378 /*
3379 * Change the backing file. All clusters that are different from the old
3380 * backing file are overwritten in the COW file now, so the visible content
3381 * doesn't change when we switch the backing file.
3382 */
Alex Bligha6166732012-10-16 13:46:18 +01003383 if (out_baseimg && *out_baseimg) {
3384 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3385 } else {
3386 ret = bdrv_change_backing_file(bs, NULL, NULL);
3387 }
3388
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003389 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003390 error_report("Could not change the backing file to '%s': No "
3391 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003392 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003393 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003394 out_baseimg, strerror(-ret));
3395 }
3396
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003397 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003398 /*
3399 * TODO At this point it is possible to check if any clusters that are
3400 * allocated in the COW file are the same in the backing file. If so, they
3401 * could be dropped from the COW file. Don't do this before switching the
3402 * backing file, in case of a crash this would lead to corruption.
3403 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003404out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003405 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003406 /* Cleanup */
3407 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003408 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003409 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003410 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003411 qemu_vfree(buf_old);
3412 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003413
Markus Armbruster26f54e92014-10-07 13:59:04 +02003414 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003415 if (ret) {
3416 return 1;
3417 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003418 return 0;
3419}
3420
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003421static int img_resize(int argc, char **argv)
3422{
Markus Armbruster6750e792015-02-12 17:43:08 +01003423 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003424 int c, ret, relative;
3425 const char *filename, *fmt, *size;
Max Reitzdc5f6902017-06-13 22:20:55 +02003426 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003427 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003428 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003429 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003430 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003431
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003432 static QemuOptsList resize_options = {
3433 .name = "resize_options",
3434 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3435 .desc = {
3436 {
3437 .name = BLOCK_OPT_SIZE,
3438 .type = QEMU_OPT_SIZE,
3439 .help = "Virtual disk size"
3440 }, {
3441 /* end of list */
3442 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003443 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003444 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003445 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003446 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003447
Kevin Wolfe80fec72011-04-29 10:58:12 +02003448 /* Remove size from argv manually so that negative numbers are not treated
3449 * as options by getopt. */
3450 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003451 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003452 return 1;
3453 }
3454
3455 size = argv[--argc];
3456
3457 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003458 fmt = NULL;
3459 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003460 static const struct option long_options[] = {
3461 {"help", no_argument, 0, 'h'},
3462 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003463 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003464 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003465 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003466 {0, 0, 0, 0}
3467 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003468 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003469 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003470 if (c == -1) {
3471 break;
3472 }
3473 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003474 case ':':
3475 missing_argument(argv[optind - 1]);
3476 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003477 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003478 unrecognized_option(argv[optind - 1]);
3479 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003480 case 'h':
3481 help();
3482 break;
3483 case 'f':
3484 fmt = optarg;
3485 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003486 case 'q':
3487 quiet = true;
3488 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003489 case OPTION_OBJECT: {
3490 QemuOpts *opts;
3491 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3492 optarg, true);
3493 if (!opts) {
3494 return 1;
3495 }
3496 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003497 case OPTION_IMAGE_OPTS:
3498 image_opts = true;
3499 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003500 case OPTION_PREALLOCATION:
Marc-AndrƩ Lureauf7abe0e2017-08-24 10:46:10 +02003501 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003502 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003503 if (prealloc == PREALLOC_MODE__MAX) {
3504 error_report("Invalid preallocation mode '%s'", optarg);
3505 return 1;
3506 }
3507 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003508 case OPTION_SHRINK:
3509 shrink = true;
3510 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003511 }
3512 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003513 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003514 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003515 }
3516 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003517
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003518 if (qemu_opts_foreach(&qemu_object_opts,
3519 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003520 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003521 return 1;
3522 }
3523
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003524 /* Choose grow, shrink, or absolute resize mode */
3525 switch (size[0]) {
3526 case '+':
3527 relative = 1;
3528 size++;
3529 break;
3530 case '-':
3531 relative = -1;
3532 size++;
3533 break;
3534 default:
3535 relative = 0;
3536 break;
3537 }
3538
3539 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003540 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003541 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003542 if (err) {
3543 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003544 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003545 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003546 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003547 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003548 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3549 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003550
Max Reitzefaa7c42016-03-16 19:54:38 +01003551 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003552 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3553 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003554 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003555 ret = -1;
3556 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003557 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003558
Max Reitzdc5f6902017-06-13 22:20:55 +02003559 current_size = blk_getlength(blk);
3560 if (current_size < 0) {
3561 error_report("Failed to inquire current image length: %s",
3562 strerror(-current_size));
3563 ret = -1;
3564 goto out;
3565 }
3566
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003567 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003568 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003569 } else {
3570 total_size = n;
3571 }
3572 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003573 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003574 ret = -1;
3575 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003576 }
3577
Max Reitzdc5f6902017-06-13 22:20:55 +02003578 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3579 error_report("Preallocation can only be used for growing images");
3580 ret = -1;
3581 goto out;
3582 }
3583
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003584 if (total_size < current_size && !shrink) {
3585 warn_report("Shrinking an image will delete all data beyond the "
3586 "shrunken image's end. Before performing such an "
3587 "operation, make sure there is no important data there.");
3588
3589 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3590 error_report(
3591 "Use the --shrink option to perform a shrink operation.");
3592 ret = -1;
3593 goto out;
3594 } else {
3595 warn_report("Using the --shrink option will suppress this message. "
3596 "Note that future versions of qemu-img may refuse to "
3597 "shrink images without this option.");
3598 }
3599 }
3600
Max Reitzdc5f6902017-06-13 22:20:55 +02003601 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitzed3d2ec2017-03-28 22:51:27 +02003602 if (!ret) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003603 qprintf(quiet, "Image resized.\n");
Max Reitzed3d2ec2017-03-28 22:51:27 +02003604 } else {
3605 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003606 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003607out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003608 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003609 if (ret) {
3610 return 1;
3611 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003612 return 0;
3613}
3614
Max Reitz76a3a342014-10-27 11:12:51 +01003615static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003616 int64_t offset, int64_t total_work_size,
3617 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003618{
3619 qemu_progress_print(100.f * offset / total_work_size, 0);
3620}
3621
Max Reitz6f176b42013-09-03 10:09:50 +02003622static int img_amend(int argc, char **argv)
3623{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003624 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003625 int c, ret = 0;
3626 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003627 QemuOptsList *create_opts = NULL;
3628 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003629 const char *fmt = NULL, *filename, *cache;
3630 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003631 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003632 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003633 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003634 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003635 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003636
Max Reitzbd39e6e2014-07-22 22:58:43 +02003637 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003638 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003639 static const struct option long_options[] = {
3640 {"help", no_argument, 0, 'h'},
3641 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003642 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003643 {0, 0, 0, 0}
3644 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003645 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003646 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003647 if (c == -1) {
3648 break;
3649 }
3650
3651 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003652 case ':':
3653 missing_argument(argv[optind - 1]);
3654 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003655 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003656 unrecognized_option(argv[optind - 1]);
3657 break;
3658 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003659 help();
3660 break;
3661 case 'o':
3662 if (!is_valid_option_list(optarg)) {
3663 error_report("Invalid option list: %s", optarg);
3664 ret = -1;
3665 goto out_no_progress;
3666 }
3667 if (!options) {
3668 options = g_strdup(optarg);
3669 } else {
3670 char *old_options = options;
3671 options = g_strdup_printf("%s,%s", options, optarg);
3672 g_free(old_options);
3673 }
3674 break;
3675 case 'f':
3676 fmt = optarg;
3677 break;
3678 case 't':
3679 cache = optarg;
3680 break;
3681 case 'p':
3682 progress = true;
3683 break;
3684 case 'q':
3685 quiet = true;
3686 break;
3687 case OPTION_OBJECT:
3688 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3689 optarg, true);
3690 if (!opts) {
3691 ret = -1;
3692 goto out_no_progress;
3693 }
3694 break;
3695 case OPTION_IMAGE_OPTS:
3696 image_opts = true;
3697 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003698 }
3699 }
3700
Max Reitz6f176b42013-09-03 10:09:50 +02003701 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003702 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003703 }
3704
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003705 if (qemu_opts_foreach(&qemu_object_opts,
3706 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003707 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003708 ret = -1;
3709 goto out_no_progress;
3710 }
3711
Max Reitz76a3a342014-10-27 11:12:51 +01003712 if (quiet) {
3713 progress = false;
3714 }
3715 qemu_progress_init(progress, 1.0);
3716
Kevin Wolfa283cb62014-02-21 16:24:07 +01003717 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3718 if (fmt && has_help_option(options)) {
3719 /* If a format is explicitly specified (and possibly no filename is
3720 * given), print option help here */
3721 ret = print_block_option_help(filename, fmt);
3722 goto out;
3723 }
3724
3725 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003726 error_report("Expecting one image file name");
3727 ret = -1;
3728 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003729 }
Max Reitz6f176b42013-09-03 10:09:50 +02003730
Kevin Wolfce099542016-03-15 13:01:04 +01003731 flags = BDRV_O_RDWR;
3732 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003733 if (ret < 0) {
3734 error_report("Invalid cache option: %s", cache);
3735 goto out;
3736 }
3737
Fam Zheng335e9932017-05-03 00:35:39 +08003738 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3739 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003740 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003741 ret = -1;
3742 goto out;
3743 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003744 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003745
3746 fmt = bs->drv->format_name;
3747
Kevin Wolf626f84f2014-02-21 16:24:06 +01003748 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003749 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003750 ret = print_block_option_help(filename, fmt);
3751 goto out;
3752 }
3753
Max Reitzb2439d22014-12-02 18:32:47 +01003754 if (!bs->drv->create_opts) {
3755 error_report("Format driver '%s' does not support any options to amend",
3756 fmt);
3757 ret = -1;
3758 goto out;
3759 }
3760
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003761 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003762 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003763 qemu_opts_do_parse(opts, options, NULL, &err);
3764 if (err) {
3765 error_report_err(err);
3766 ret = -1;
3767 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003768 }
3769
Max Reitz76a3a342014-10-27 11:12:51 +01003770 /* In case the driver does not call amend_status_cb() */
3771 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003772 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003773 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003774 if (ret < 0) {
3775 error_report("Error while amending options: %s", strerror(-ret));
3776 goto out;
3777 }
3778
3779out:
Max Reitz76a3a342014-10-27 11:12:51 +01003780 qemu_progress_end();
3781
Max Reitze814dff2015-08-20 16:00:38 -07003782out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003783 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003784 qemu_opts_del(opts);
3785 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003786 g_free(options);
3787
Max Reitz6f176b42013-09-03 10:09:50 +02003788 if (ret) {
3789 return 1;
3790 }
3791 return 0;
3792}
3793
Kevin Wolfb6133b82014-08-05 14:17:13 +02003794typedef struct BenchData {
3795 BlockBackend *blk;
3796 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003797 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003798 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003799 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003800 int nrreq;
3801 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003802 int flush_interval;
3803 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003804 uint8_t *buf;
3805 QEMUIOVector *qiov;
3806
3807 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003808 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003809 uint64_t offset;
3810} BenchData;
3811
Kevin Wolf55d539c2016-06-03 13:59:41 +02003812static void bench_undrained_flush_cb(void *opaque, int ret)
3813{
3814 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003815 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003816 exit(EXIT_FAILURE);
3817 }
3818}
3819
Kevin Wolfb6133b82014-08-05 14:17:13 +02003820static void bench_cb(void *opaque, int ret)
3821{
3822 BenchData *b = opaque;
3823 BlockAIOCB *acb;
3824
3825 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003826 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003827 exit(EXIT_FAILURE);
3828 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003829
3830 if (b->in_flush) {
3831 /* Just finished a flush with drained queue: Start next requests */
3832 assert(b->in_flight == 0);
3833 b->in_flush = false;
3834 } else if (b->in_flight > 0) {
3835 int remaining = b->n - b->in_flight;
3836
Kevin Wolfb6133b82014-08-05 14:17:13 +02003837 b->n--;
3838 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003839
3840 /* Time for flush? Drain queue if requested, then flush */
3841 if (b->flush_interval && remaining % b->flush_interval == 0) {
3842 if (!b->in_flight || !b->drain_on_flush) {
3843 BlockCompletionFunc *cb;
3844
3845 if (b->drain_on_flush) {
3846 b->in_flush = true;
3847 cb = bench_cb;
3848 } else {
3849 cb = bench_undrained_flush_cb;
3850 }
3851
3852 acb = blk_aio_flush(b->blk, cb, b);
3853 if (!acb) {
3854 error_report("Failed to issue flush request");
3855 exit(EXIT_FAILURE);
3856 }
3857 }
3858 if (b->drain_on_flush) {
3859 return;
3860 }
3861 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003862 }
3863
3864 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003865 int64_t offset = b->offset;
3866 /* blk_aio_* might look for completed I/Os and kick bench_cb
3867 * again, so make sure this operation is counted by in_flight
3868 * and b->offset is ready for the next submission.
3869 */
3870 b->in_flight++;
3871 b->offset += b->step;
3872 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003873 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003874 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003875 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003876 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003877 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003878 if (!acb) {
3879 error_report("Failed to issue request");
3880 exit(EXIT_FAILURE);
3881 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003882 }
3883}
3884
3885static int img_bench(int argc, char **argv)
3886{
3887 int c, ret = 0;
3888 const char *fmt = NULL, *filename;
3889 bool quiet = false;
3890 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003891 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003892 int count = 75000;
3893 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003894 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003895 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003896 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003897 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003898 int flush_interval = 0;
3899 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003900 int64_t image_size;
3901 BlockBackend *blk = NULL;
3902 BenchData data = {};
3903 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003904 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003905 struct timeval t1, t2;
3906 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08003907 bool force_share = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003908
3909 for (;;) {
3910 static const struct option long_options[] = {
3911 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003912 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003913 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003914 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003915 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08003916 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003917 {0, 0, 0, 0}
3918 };
Fam Zheng335e9932017-05-03 00:35:39 +08003919 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003920 if (c == -1) {
3921 break;
3922 }
3923
3924 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003925 case ':':
3926 missing_argument(argv[optind - 1]);
3927 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003928 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003929 unrecognized_option(argv[optind - 1]);
3930 break;
3931 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02003932 help();
3933 break;
3934 case 'c':
3935 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003936 unsigned long res;
3937
3938 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003939 error_report("Invalid request count specified");
3940 return 1;
3941 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003942 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003943 break;
3944 }
3945 case 'd':
3946 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003947 unsigned long res;
3948
3949 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003950 error_report("Invalid queue depth specified");
3951 return 1;
3952 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003953 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003954 break;
3955 }
3956 case 'f':
3957 fmt = optarg;
3958 break;
3959 case 'n':
3960 flags |= BDRV_O_NATIVE_AIO;
3961 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003962 case 'o':
3963 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003964 offset = cvtnum(optarg);
3965 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003966 error_report("Invalid offset specified");
3967 return 1;
3968 }
3969 break;
3970 }
3971 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003972 case 'q':
3973 quiet = true;
3974 break;
3975 case 's':
3976 {
3977 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003978
Markus Armbruster606caa02017-02-21 21:14:04 +01003979 sval = cvtnum(optarg);
3980 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003981 error_report("Invalid buffer size specified");
3982 return 1;
3983 }
3984
3985 bufsize = sval;
3986 break;
3987 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003988 case 'S':
3989 {
3990 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003991
Markus Armbruster606caa02017-02-21 21:14:04 +01003992 sval = cvtnum(optarg);
3993 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003994 error_report("Invalid step size specified");
3995 return 1;
3996 }
3997
3998 step = sval;
3999 break;
4000 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004001 case 't':
4002 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4003 if (ret < 0) {
4004 error_report("Invalid cache mode");
4005 ret = -1;
4006 goto out;
4007 }
4008 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004009 case 'w':
4010 flags |= BDRV_O_RDWR;
4011 is_write = true;
4012 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004013 case 'U':
4014 force_share = true;
4015 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004016 case OPTION_PATTERN:
4017 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004018 unsigned long res;
4019
4020 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004021 error_report("Invalid pattern byte specified");
4022 return 1;
4023 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004024 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004025 break;
4026 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004027 case OPTION_FLUSH_INTERVAL:
4028 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004029 unsigned long res;
4030
4031 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004032 error_report("Invalid flush interval specified");
4033 return 1;
4034 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004035 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004036 break;
4037 }
4038 case OPTION_NO_DRAIN:
4039 drain_on_flush = false;
4040 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004041 case OPTION_IMAGE_OPTS:
4042 image_opts = true;
4043 break;
4044 }
4045 }
4046
4047 if (optind != argc - 1) {
4048 error_exit("Expecting one image file name");
4049 }
4050 filename = argv[argc - 1];
4051
Kevin Wolf55d539c2016-06-03 13:59:41 +02004052 if (!is_write && flush_interval) {
4053 error_report("--flush-interval is only available in write tests");
4054 ret = -1;
4055 goto out;
4056 }
4057 if (flush_interval && flush_interval < depth) {
4058 error_report("Flush interval can't be smaller than depth");
4059 ret = -1;
4060 goto out;
4061 }
4062
Fam Zheng335e9932017-05-03 00:35:39 +08004063 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4064 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004065 if (!blk) {
4066 ret = -1;
4067 goto out;
4068 }
4069
4070 image_size = blk_getlength(blk);
4071 if (image_size < 0) {
4072 ret = image_size;
4073 goto out;
4074 }
4075
4076 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004077 .blk = blk,
4078 .image_size = image_size,
4079 .bufsize = bufsize,
4080 .step = step ?: bufsize,
4081 .nrreq = depth,
4082 .n = count,
4083 .offset = offset,
4084 .write = is_write,
4085 .flush_interval = flush_interval,
4086 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004087 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004088 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004089 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004090 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004091 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004092 if (flush_interval) {
4093 printf("Sending flush every %d requests\n", flush_interval);
4094 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004095
4096 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004097 memset(data.buf, pattern, data.nrreq * data.bufsize);
4098
Kevin Wolfb6133b82014-08-05 14:17:13 +02004099 data.qiov = g_new(QEMUIOVector, data.nrreq);
4100 for (i = 0; i < data.nrreq; i++) {
4101 qemu_iovec_init(&data.qiov[i], 1);
4102 qemu_iovec_add(&data.qiov[i],
4103 data.buf + i * data.bufsize, data.bufsize);
4104 }
4105
4106 gettimeofday(&t1, NULL);
4107 bench_cb(&data, 0);
4108
4109 while (data.n > 0) {
4110 main_loop_wait(false);
4111 }
4112 gettimeofday(&t2, NULL);
4113
4114 printf("Run completed in %3.3f seconds.\n",
4115 (t2.tv_sec - t1.tv_sec)
4116 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4117
4118out:
4119 qemu_vfree(data.buf);
4120 blk_unref(blk);
4121
4122 if (ret) {
4123 return 1;
4124 }
4125 return 0;
4126}
4127
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004128#define C_BS 01
4129#define C_COUNT 02
4130#define C_IF 04
4131#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004132#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004133
4134struct DdInfo {
4135 unsigned int flags;
4136 int64_t count;
4137};
4138
4139struct DdIo {
4140 int bsz; /* Block size */
4141 char *filename;
4142 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004143 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004144};
4145
4146struct DdOpts {
4147 const char *name;
4148 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4149 unsigned int flag;
4150};
4151
4152static int img_dd_bs(const char *arg,
4153 struct DdIo *in, struct DdIo *out,
4154 struct DdInfo *dd)
4155{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004156 int64_t res;
4157
Markus Armbruster606caa02017-02-21 21:14:04 +01004158 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004159
Markus Armbruster606caa02017-02-21 21:14:04 +01004160 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004161 error_report("invalid number: '%s'", arg);
4162 return 1;
4163 }
4164 in->bsz = out->bsz = res;
4165
4166 return 0;
4167}
4168
4169static int img_dd_count(const char *arg,
4170 struct DdIo *in, struct DdIo *out,
4171 struct DdInfo *dd)
4172{
Markus Armbruster606caa02017-02-21 21:14:04 +01004173 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004174
Markus Armbruster606caa02017-02-21 21:14:04 +01004175 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004176 error_report("invalid number: '%s'", arg);
4177 return 1;
4178 }
4179
4180 return 0;
4181}
4182
4183static int img_dd_if(const char *arg,
4184 struct DdIo *in, struct DdIo *out,
4185 struct DdInfo *dd)
4186{
4187 in->filename = g_strdup(arg);
4188
4189 return 0;
4190}
4191
4192static int img_dd_of(const char *arg,
4193 struct DdIo *in, struct DdIo *out,
4194 struct DdInfo *dd)
4195{
4196 out->filename = g_strdup(arg);
4197
4198 return 0;
4199}
4200
Reda Sallahif7c15532016-08-10 16:16:09 +02004201static int img_dd_skip(const char *arg,
4202 struct DdIo *in, struct DdIo *out,
4203 struct DdInfo *dd)
4204{
Markus Armbruster606caa02017-02-21 21:14:04 +01004205 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004206
Markus Armbruster606caa02017-02-21 21:14:04 +01004207 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004208 error_report("invalid number: '%s'", arg);
4209 return 1;
4210 }
4211
4212 return 0;
4213}
4214
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004215static int img_dd(int argc, char **argv)
4216{
4217 int ret = 0;
4218 char *arg = NULL;
4219 char *tmp;
4220 BlockDriver *drv = NULL, *proto_drv = NULL;
4221 BlockBackend *blk1 = NULL, *blk2 = NULL;
4222 QemuOpts *opts = NULL;
4223 QemuOptsList *create_opts = NULL;
4224 Error *local_err = NULL;
4225 bool image_opts = false;
4226 int c, i;
4227 const char *out_fmt = "raw";
4228 const char *fmt = NULL;
4229 int64_t size = 0;
4230 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004231 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004232 struct DdInfo dd = {
4233 .flags = 0,
4234 .count = 0,
4235 };
4236 struct DdIo in = {
4237 .bsz = 512, /* Block size is by default 512 bytes */
4238 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004239 .buf = NULL,
4240 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004241 };
4242 struct DdIo out = {
4243 .bsz = 512,
4244 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004245 .buf = NULL,
4246 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004247 };
4248
4249 const struct DdOpts options[] = {
4250 { "bs", img_dd_bs, C_BS },
4251 { "count", img_dd_count, C_COUNT },
4252 { "if", img_dd_if, C_IF },
4253 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004254 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004255 { NULL, NULL, 0 }
4256 };
4257 const struct option long_options[] = {
4258 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004259 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004260 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004261 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004262 { 0, 0, 0, 0 }
4263 };
4264
Fam Zheng335e9932017-05-03 00:35:39 +08004265 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004266 if (c == EOF) {
4267 break;
4268 }
4269 switch (c) {
4270 case 'O':
4271 out_fmt = optarg;
4272 break;
4273 case 'f':
4274 fmt = optarg;
4275 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004276 case ':':
4277 missing_argument(argv[optind - 1]);
4278 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004279 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004280 unrecognized_option(argv[optind - 1]);
4281 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004282 case 'h':
4283 help();
4284 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004285 case 'U':
4286 force_share = true;
4287 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004288 case OPTION_OBJECT:
4289 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004290 ret = -1;
4291 goto out;
4292 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004293 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004294 case OPTION_IMAGE_OPTS:
4295 image_opts = true;
4296 break;
4297 }
4298 }
4299
4300 for (i = optind; i < argc; i++) {
4301 int j;
4302 arg = g_strdup(argv[i]);
4303
4304 tmp = strchr(arg, '=');
4305 if (tmp == NULL) {
4306 error_report("unrecognized operand %s", arg);
4307 ret = -1;
4308 goto out;
4309 }
4310
4311 *tmp++ = '\0';
4312
4313 for (j = 0; options[j].name != NULL; j++) {
4314 if (!strcmp(arg, options[j].name)) {
4315 break;
4316 }
4317 }
4318 if (options[j].name == NULL) {
4319 error_report("unrecognized operand %s", arg);
4320 ret = -1;
4321 goto out;
4322 }
4323
4324 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4325 ret = -1;
4326 goto out;
4327 }
4328 dd.flags |= options[j].flag;
4329 g_free(arg);
4330 arg = NULL;
4331 }
4332
4333 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4334 error_report("Must specify both input and output files");
4335 ret = -1;
4336 goto out;
4337 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004338
4339 if (qemu_opts_foreach(&qemu_object_opts,
4340 user_creatable_add_opts_foreach,
4341 NULL, NULL)) {
4342 ret = -1;
4343 goto out;
4344 }
4345
Fam Zheng335e9932017-05-03 00:35:39 +08004346 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4347 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004348
4349 if (!blk1) {
4350 ret = -1;
4351 goto out;
4352 }
4353
4354 drv = bdrv_find_format(out_fmt);
4355 if (!drv) {
4356 error_report("Unknown file format");
4357 ret = -1;
4358 goto out;
4359 }
4360 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4361
4362 if (!proto_drv) {
4363 error_report_err(local_err);
4364 ret = -1;
4365 goto out;
4366 }
4367 if (!drv->create_opts) {
4368 error_report("Format driver '%s' does not support image creation",
4369 drv->format_name);
4370 ret = -1;
4371 goto out;
4372 }
4373 if (!proto_drv->create_opts) {
4374 error_report("Protocol driver '%s' does not support image creation",
4375 proto_drv->format_name);
4376 ret = -1;
4377 goto out;
4378 }
4379 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4380 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4381
4382 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4383
4384 size = blk_getlength(blk1);
4385 if (size < 0) {
4386 error_report("Failed to get size for '%s'", in.filename);
4387 ret = -1;
4388 goto out;
4389 }
4390
4391 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4392 dd.count * in.bsz < size) {
4393 size = dd.count * in.bsz;
4394 }
4395
Reda Sallahif7c15532016-08-10 16:16:09 +02004396 /* Overflow means the specified offset is beyond input image's size */
4397 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4398 size < in.bsz * in.offset)) {
4399 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4400 } else {
4401 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4402 size - in.bsz * in.offset, &error_abort);
4403 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004404
4405 ret = bdrv_create(drv, out.filename, opts, &local_err);
4406 if (ret < 0) {
4407 error_reportf_err(local_err,
4408 "%s: error while creating output image: ",
4409 out.filename);
4410 ret = -1;
4411 goto out;
4412 }
4413
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004414 /* TODO, we can't honour --image-opts for the target,
4415 * since it needs to be given in a format compatible
4416 * with the bdrv_create() call above which does not
4417 * support image-opts style.
4418 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004419 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004420 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004421
4422 if (!blk2) {
4423 ret = -1;
4424 goto out;
4425 }
4426
Reda Sallahif7c15532016-08-10 16:16:09 +02004427 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4428 size < in.offset * in.bsz)) {
4429 /* We give a warning if the skip option is bigger than the input
4430 * size and create an empty output disk image (i.e. like dd(1)).
4431 */
4432 error_report("%s: cannot skip to specified offset", in.filename);
4433 in_pos = size;
4434 } else {
4435 in_pos = in.offset * in.bsz;
4436 }
4437
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004438 in.buf = g_new(uint8_t, in.bsz);
4439
Reda Sallahif7c15532016-08-10 16:16:09 +02004440 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004441 int in_ret, out_ret;
4442
4443 if (in_pos + in.bsz > size) {
4444 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4445 } else {
4446 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4447 }
4448 if (in_ret < 0) {
4449 error_report("error while reading from input image file: %s",
4450 strerror(-in_ret));
4451 ret = -1;
4452 goto out;
4453 }
4454 in_pos += in_ret;
4455
4456 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4457
4458 if (out_ret < 0) {
4459 error_report("error while writing to output image file: %s",
4460 strerror(-out_ret));
4461 ret = -1;
4462 goto out;
4463 }
4464 out_pos += out_ret;
4465 }
4466
4467out:
4468 g_free(arg);
4469 qemu_opts_del(opts);
4470 qemu_opts_free(create_opts);
4471 blk_unref(blk1);
4472 blk_unref(blk2);
4473 g_free(in.filename);
4474 g_free(out.filename);
4475 g_free(in.buf);
4476 g_free(out.buf);
4477
4478 if (ret) {
4479 return 1;
4480 }
4481 return 0;
4482}
4483
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004484static void dump_json_block_measure_info(BlockMeasureInfo *info)
4485{
4486 QString *str;
4487 QObject *obj;
4488 Visitor *v = qobject_output_visitor_new(&obj);
4489
4490 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4491 visit_complete(v, &obj);
4492 str = qobject_to_json_pretty(obj);
4493 assert(str != NULL);
4494 printf("%s\n", qstring_get_str(str));
4495 qobject_decref(obj);
4496 visit_free(v);
4497 QDECREF(str);
4498}
4499
4500static int img_measure(int argc, char **argv)
4501{
4502 static const struct option long_options[] = {
4503 {"help", no_argument, 0, 'h'},
4504 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4505 {"object", required_argument, 0, OPTION_OBJECT},
4506 {"output", required_argument, 0, OPTION_OUTPUT},
4507 {"size", required_argument, 0, OPTION_SIZE},
4508 {"force-share", no_argument, 0, 'U'},
4509 {0, 0, 0, 0}
4510 };
4511 OutputFormat output_format = OFORMAT_HUMAN;
4512 BlockBackend *in_blk = NULL;
4513 BlockDriver *drv;
4514 const char *filename = NULL;
4515 const char *fmt = NULL;
4516 const char *out_fmt = "raw";
4517 char *options = NULL;
4518 char *snapshot_name = NULL;
4519 bool force_share = false;
4520 QemuOpts *opts = NULL;
4521 QemuOpts *object_opts = NULL;
4522 QemuOpts *sn_opts = NULL;
4523 QemuOptsList *create_opts = NULL;
4524 bool image_opts = false;
4525 uint64_t img_size = UINT64_MAX;
4526 BlockMeasureInfo *info = NULL;
4527 Error *local_err = NULL;
4528 int ret = 1;
4529 int c;
4530
4531 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4532 long_options, NULL)) != -1) {
4533 switch (c) {
4534 case '?':
4535 case 'h':
4536 help();
4537 break;
4538 case 'f':
4539 fmt = optarg;
4540 break;
4541 case 'O':
4542 out_fmt = optarg;
4543 break;
4544 case 'o':
4545 if (!is_valid_option_list(optarg)) {
4546 error_report("Invalid option list: %s", optarg);
4547 goto out;
4548 }
4549 if (!options) {
4550 options = g_strdup(optarg);
4551 } else {
4552 char *old_options = options;
4553 options = g_strdup_printf("%s,%s", options, optarg);
4554 g_free(old_options);
4555 }
4556 break;
4557 case 'l':
4558 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4559 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4560 optarg, false);
4561 if (!sn_opts) {
4562 error_report("Failed in parsing snapshot param '%s'",
4563 optarg);
4564 goto out;
4565 }
4566 } else {
4567 snapshot_name = optarg;
4568 }
4569 break;
4570 case 'U':
4571 force_share = true;
4572 break;
4573 case OPTION_OBJECT:
4574 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4575 optarg, true);
4576 if (!object_opts) {
4577 goto out;
4578 }
4579 break;
4580 case OPTION_IMAGE_OPTS:
4581 image_opts = true;
4582 break;
4583 case OPTION_OUTPUT:
4584 if (!strcmp(optarg, "json")) {
4585 output_format = OFORMAT_JSON;
4586 } else if (!strcmp(optarg, "human")) {
4587 output_format = OFORMAT_HUMAN;
4588 } else {
4589 error_report("--output must be used with human or json "
4590 "as argument.");
4591 goto out;
4592 }
4593 break;
4594 case OPTION_SIZE:
4595 {
4596 int64_t sval;
4597
4598 sval = cvtnum(optarg);
4599 if (sval < 0) {
4600 if (sval == -ERANGE) {
4601 error_report("Image size must be less than 8 EiB!");
4602 } else {
4603 error_report("Invalid image size specified! You may use "
4604 "k, M, G, T, P or E suffixes for ");
4605 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4606 "petabytes and exabytes.");
4607 }
4608 goto out;
4609 }
4610 img_size = (uint64_t)sval;
4611 }
4612 break;
4613 }
4614 }
4615
4616 if (qemu_opts_foreach(&qemu_object_opts,
4617 user_creatable_add_opts_foreach,
4618 NULL, NULL)) {
4619 goto out;
4620 }
4621
4622 if (argc - optind > 1) {
4623 error_report("At most one filename argument is allowed.");
4624 goto out;
4625 } else if (argc - optind == 1) {
4626 filename = argv[optind];
4627 }
4628
4629 if (!filename &&
4630 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4631 error_report("--object, --image-opts, -f, and -l "
4632 "require a filename argument.");
4633 goto out;
4634 }
4635 if (filename && img_size != UINT64_MAX) {
4636 error_report("--size N cannot be used together with a filename.");
4637 goto out;
4638 }
4639 if (!filename && img_size == UINT64_MAX) {
4640 error_report("Either --size N or one filename must be specified.");
4641 goto out;
4642 }
4643
4644 if (filename) {
4645 in_blk = img_open(image_opts, filename, fmt, 0,
4646 false, false, force_share);
4647 if (!in_blk) {
4648 goto out;
4649 }
4650
4651 if (sn_opts) {
4652 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4653 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4654 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4655 &local_err);
4656 } else if (snapshot_name != NULL) {
4657 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4658 snapshot_name, &local_err);
4659 }
4660 if (local_err) {
4661 error_reportf_err(local_err, "Failed to load snapshot: ");
4662 goto out;
4663 }
4664 }
4665
4666 drv = bdrv_find_format(out_fmt);
4667 if (!drv) {
4668 error_report("Unknown file format '%s'", out_fmt);
4669 goto out;
4670 }
4671 if (!drv->create_opts) {
4672 error_report("Format driver '%s' does not support image creation",
4673 drv->format_name);
4674 goto out;
4675 }
4676
4677 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4678 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4679 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4680 if (options) {
4681 qemu_opts_do_parse(opts, options, NULL, &local_err);
4682 if (local_err) {
4683 error_report_err(local_err);
4684 error_report("Invalid options for file format '%s'", out_fmt);
4685 goto out;
4686 }
4687 }
4688 if (img_size != UINT64_MAX) {
4689 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4690 }
4691
4692 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4693 if (local_err) {
4694 error_report_err(local_err);
4695 goto out;
4696 }
4697
4698 if (output_format == OFORMAT_HUMAN) {
4699 printf("required size: %" PRIu64 "\n", info->required);
4700 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4701 } else {
4702 dump_json_block_measure_info(info);
4703 }
4704
4705 ret = 0;
4706
4707out:
4708 qapi_free_BlockMeasureInfo(info);
4709 qemu_opts_del(object_opts);
4710 qemu_opts_del(opts);
4711 qemu_opts_del(sn_opts);
4712 qemu_opts_free(create_opts);
4713 g_free(options);
4714 blk_unref(in_blk);
4715 return ret;
4716}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004717
Anthony Liguoric227f092009-10-01 16:12:16 -05004718static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004719#define DEF(option, callback, arg_string) \
4720 { option, callback },
4721#include "qemu-img-cmds.h"
4722#undef DEF
4723#undef GEN_DOCS
4724 { NULL, NULL, },
4725};
4726
bellardea2384d2004-08-01 21:59:26 +00004727int main(int argc, char **argv)
4728{
Anthony Liguoric227f092009-10-01 16:12:16 -05004729 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004730 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004731 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004732 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004733 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004734 static const struct option long_options[] = {
4735 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004736 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004737 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004738 {0, 0, 0, 0}
4739 };
bellardea2384d2004-08-01 21:59:26 +00004740
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004741#ifdef CONFIG_POSIX
4742 signal(SIGPIPE, SIG_IGN);
4743#endif
4744
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004745 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004746 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004747 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004748
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004749 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004750 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004751 exit(EXIT_FAILURE);
4752 }
4753
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004754 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004755
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004756 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004757 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004758 if (argc < 2) {
4759 error_exit("Not enough arguments");
4760 }
Stuart Brady153859b2009-06-07 00:42:17 +01004761
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004762 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004763 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004764 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004765
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004766 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004767 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004768 case ':':
4769 missing_argument(argv[optind - 1]);
4770 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004771 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004772 unrecognized_option(argv[optind - 1]);
4773 return 0;
4774 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004775 help();
4776 return 0;
4777 case 'V':
4778 printf(QEMU_IMG_VERSION);
4779 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004780 case 'T':
4781 g_free(trace_file);
4782 trace_file = trace_opt_parse(optarg);
4783 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004784 }
bellardea2384d2004-08-01 21:59:26 +00004785 }
Stuart Brady153859b2009-06-07 00:42:17 +01004786
Denis V. Lunev10985132016-06-17 17:44:13 +03004787 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004788
Denis V. Lunev10985132016-06-17 17:44:13 +03004789 /* reset getopt_long scanning */
4790 argc -= optind;
4791 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004792 return 0;
4793 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004794 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004795 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004796
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004797 if (!trace_init_backends()) {
4798 exit(1);
4799 }
4800 trace_init_file(trace_file);
4801 qemu_set_log(LOG_TRACE);
4802
Denis V. Lunev10985132016-06-17 17:44:13 +03004803 /* find the command */
4804 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4805 if (!strcmp(cmdname, cmd->name)) {
4806 return cmd->handler(argc, argv);
4807 }
4808 }
Jeff Cody7db16892014-04-25 17:02:32 -04004809
Stuart Brady153859b2009-06-07 00:42:17 +01004810 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004811 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004812}