blob: 02a6e27beb1357593e69a0f20e6d22b97da596be [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/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001068 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1069 * of the first sector boundary within buf where the sector contains a
1070 * non-zero byte. This function is robust to a buffer that is not
1071 * sector-aligned.
1072 */
1073static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1074{
1075 int64_t i;
1076 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1077
1078 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1079 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1080 return i;
1081 }
1082 }
1083 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1084 return i;
1085 }
1086 return -1;
1087}
1088
1089/*
thsf58c7b32008-06-05 21:53:49 +00001090 * Returns true iff the first sector pointed to by 'buf' contains at least
1091 * a non-NUL byte.
1092 *
1093 * 'pnum' is set to the number of sectors (including and immediately following
1094 * the first one) that are known to be in the same allocated/unallocated state.
1095 */
bellardea2384d2004-08-01 21:59:26 +00001096static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1097{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001098 bool is_zero;
1099 int i;
bellardea2384d2004-08-01 21:59:26 +00001100
1101 if (n <= 0) {
1102 *pnum = 0;
1103 return 0;
1104 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001105 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001106 for(i = 1; i < n; i++) {
1107 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001108 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001109 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001110 }
bellardea2384d2004-08-01 21:59:26 +00001111 }
1112 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001113 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001114}
1115
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001116/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001117 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1118 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1119 * breaking up write requests for only small sparse areas.
1120 */
1121static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1122 int min)
1123{
1124 int ret;
1125 int num_checked, num_used;
1126
1127 if (n < min) {
1128 min = n;
1129 }
1130
1131 ret = is_allocated_sectors(buf, n, pnum);
1132 if (!ret) {
1133 return ret;
1134 }
1135
1136 num_used = *pnum;
1137 buf += BDRV_SECTOR_SIZE * *pnum;
1138 n -= *pnum;
1139 num_checked = num_used;
1140
1141 while (n > 0) {
1142 ret = is_allocated_sectors(buf, n, pnum);
1143
1144 buf += BDRV_SECTOR_SIZE * *pnum;
1145 n -= *pnum;
1146 num_checked += *pnum;
1147 if (ret) {
1148 num_used = num_checked;
1149 } else if (*pnum >= min) {
1150 break;
1151 }
1152 }
1153
1154 *pnum = num_used;
1155 return 1;
1156}
1157
1158/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001159 * Compares two buffers sector by sector. Returns 0 if the first
1160 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001161 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001162 * pnum is set to the sector-aligned size of the buffer prefix that
1163 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001164 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001165static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1166 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001167{
Radim KrčmÔř8c1ac472015-02-20 17:06:15 +01001168 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001169 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001170
Eric Blakedc61cd32017-10-11 22:47:14 -05001171 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001172
Eric Blakedc61cd32017-10-11 22:47:14 -05001173 res = !!memcmp(buf1, buf2, i);
1174 while (i < bytes) {
1175 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001176
Eric Blakedc61cd32017-10-11 22:47:14 -05001177 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001178 break;
1179 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001180 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001181 }
1182
1183 *pnum = i;
1184 return res;
1185}
1186
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001187#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001188
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001189/*
1190 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1191 *
Eric Blake0608e402017-10-11 22:47:12 -05001192 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1193 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1194 * failure), and 4 on error (the exit status for read errors), after emitting
1195 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001196 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001197 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001198 * @param offset: Starting offset to check
1199 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001200 * @param filename: Name of disk file we are checking (logging purpose)
1201 * @param buffer: Allocated buffer for storing read data
1202 * @param quiet: Flag for quiet mode
1203 */
Eric Blakec41508e2017-10-11 22:47:13 -05001204static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1205 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001206 uint8_t *buffer, bool quiet)
1207{
Eric Blakedebb38a2017-10-11 22:47:11 -05001208 int ret = 0;
1209 int64_t idx;
1210
Eric Blakec41508e2017-10-11 22:47:13 -05001211 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001212 if (ret < 0) {
1213 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001214 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001215 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001216 }
Eric Blakec41508e2017-10-11 22:47:13 -05001217 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001218 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001219 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001220 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 return 1;
1222 }
1223
1224 return 0;
1225}
1226
1227/*
1228 * Compares two images. Exit codes:
1229 *
1230 * 0 - Images are identical
1231 * 1 - Images differ
1232 * >1 - Error occurred
1233 */
1234static int img_compare(int argc, char **argv)
1235{
Max Reitz40055952014-07-22 22:58:42 +02001236 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001237 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001238 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001239 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001241 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 int allocated1, allocated2;
1243 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1244 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001245 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001246 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001247 int64_t total_size;
1248 int64_t offset = 0;
1249 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001250 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001251 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001252 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001253 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254
Max Reitz40055952014-07-22 22:58:42 +02001255 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001256 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001257 static const struct option long_options[] = {
1258 {"help", no_argument, 0, 'h'},
1259 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001260 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001261 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001262 {0, 0, 0, 0}
1263 };
Fam Zheng335e9932017-05-03 00:35:39 +08001264 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001265 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001266 if (c == -1) {
1267 break;
1268 }
1269 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001270 case ':':
1271 missing_argument(argv[optind - 1]);
1272 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001273 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001274 unrecognized_option(argv[optind - 1]);
1275 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 case 'h':
1277 help();
1278 break;
1279 case 'f':
1280 fmt1 = optarg;
1281 break;
1282 case 'F':
1283 fmt2 = optarg;
1284 break;
Max Reitz40055952014-07-22 22:58:42 +02001285 case 'T':
1286 cache = optarg;
1287 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288 case 'p':
1289 progress = true;
1290 break;
1291 case 'q':
1292 quiet = true;
1293 break;
1294 case 's':
1295 strict = true;
1296 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001297 case 'U':
1298 force_share = true;
1299 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001300 case OPTION_OBJECT: {
1301 QemuOpts *opts;
1302 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1303 optarg, true);
1304 if (!opts) {
1305 ret = 2;
1306 goto out4;
1307 }
1308 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001309 case OPTION_IMAGE_OPTS:
1310 image_opts = true;
1311 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001312 }
1313 }
1314
1315 /* Progress is not shown in Quiet mode */
1316 if (quiet) {
1317 progress = false;
1318 }
1319
1320
Kevin Wolffc11eb22013-08-05 10:53:04 +02001321 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001322 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001323 }
1324 filename1 = argv[optind++];
1325 filename2 = argv[optind++];
1326
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001327 if (qemu_opts_foreach(&qemu_object_opts,
1328 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001329 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001330 ret = 2;
1331 goto out4;
1332 }
1333
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001334 /* Initialize before goto out */
1335 qemu_progress_init(progress, 2.0);
1336
Kevin Wolfce099542016-03-15 13:01:04 +01001337 flags = 0;
1338 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001339 if (ret < 0) {
1340 error_report("Invalid source cache option: %s", cache);
1341 ret = 2;
1342 goto out3;
1343 }
1344
Fam Zheng335e9932017-05-03 00:35:39 +08001345 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1346 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001347 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001349 goto out3;
1350 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001351
Fam Zheng335e9932017-05-03 00:35:39 +08001352 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1353 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001354 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001355 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001356 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001357 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001358 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001359 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001360
Max Reitzf1d3cd72015-02-05 13:58:18 -05001361 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1362 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001363 total_size1 = blk_getlength(blk1);
1364 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001365 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001366 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001367 ret = 4;
1368 goto out;
1369 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001370 total_size2 = blk_getlength(blk2);
1371 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001372 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001373 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001374 ret = 4;
1375 goto out;
1376 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001377 total_size = MIN(total_size1, total_size2);
1378 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001379
1380 qemu_progress_print(0, 100);
1381
Eric Blake033d9fc2017-10-11 22:47:16 -05001382 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001383 ret = 1;
1384 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1385 goto out;
1386 }
1387
Eric Blake033d9fc2017-10-11 22:47:16 -05001388 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001389 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001390
Eric Blake033d9fc2017-10-11 22:47:16 -05001391 status1 = bdrv_block_status_above(bs1, NULL, offset,
1392 total_size1 - offset, &pnum1, NULL,
1393 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001394 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395 ret = 3;
1396 error_report("Sector allocation test failed for %s", filename1);
1397 goto out;
1398 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001399 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001400
Eric Blake033d9fc2017-10-11 22:47:16 -05001401 status2 = bdrv_block_status_above(bs2, NULL, offset,
1402 total_size2 - offset, &pnum2, NULL,
1403 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001404 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001405 ret = 3;
1406 error_report("Sector allocation test failed for %s", filename2);
1407 goto out;
1408 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001409 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001410
1411 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001412 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001413
Fam Zheng25ad8e62016-01-13 16:37:41 +08001414 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001415 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001416 ret = 1;
1417 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001418 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001419 goto out;
1420 }
1421 }
1422 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001423 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001424 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001425 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001426 int64_t pnum;
1427
Eric Blake033d9fc2017-10-11 22:47:16 -05001428 chunk = MIN(chunk, IO_BUF_SIZE);
1429 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001430 if (ret < 0) {
1431 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001432 " of %s: %s",
1433 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434 ret = 4;
1435 goto out;
1436 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001437 ret = blk_pread(blk2, offset, buf2, chunk);
1438 if (ret < 0) {
1439 error_report("Error while reading offset %" PRId64
1440 " of %s: %s",
1441 offset, filename2, strerror(-ret));
1442 ret = 4;
1443 goto out;
1444 }
1445 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1446 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001448 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001449 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001450 goto out;
1451 }
1452 }
1453 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001454 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001455 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001456 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457 filename1, buf1, quiet);
1458 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001459 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001460 filename2, buf1, quiet);
1461 }
1462 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001463 goto out;
1464 }
1465 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001466 offset += chunk;
1467 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001468 }
1469
Eric Blake033d9fc2017-10-11 22:47:16 -05001470 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001471 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001472 const char *filename_over;
1473
1474 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001475 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001476 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477 filename_over = filename1;
1478 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001479 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 filename_over = filename2;
1481 }
1482
Eric Blake033d9fc2017-10-11 22:47:16 -05001483 while (offset < progress_base) {
1484 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1485 progress_base - offset, &chunk,
1486 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487 if (ret < 0) {
1488 ret = 3;
1489 error_report("Sector allocation test failed for %s",
1490 filename_over);
1491 goto out;
1492
1493 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001494 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 chunk = MIN(chunk, IO_BUF_SIZE);
1496 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001497 filename_over, buf1, quiet);
1498 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 goto out;
1500 }
1501 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001502 offset += chunk;
1503 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 }
1505 }
1506
1507 qprintf(quiet, "Images are identical.\n");
1508 ret = 0;
1509
1510out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001511 qemu_vfree(buf1);
1512 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001513 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001514out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001515 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516out3:
1517 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001518out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 return ret;
1520}
1521
Kevin Wolf690c7302015-03-19 13:33:32 +01001522enum ImgConvertBlockStatus {
1523 BLK_DATA,
1524 BLK_ZERO,
1525 BLK_BACKING_FILE,
1526};
1527
Peter Lieven2d9187b2017-02-28 13:40:07 +01001528#define MAX_COROUTINES 16
1529
Kevin Wolf690c7302015-03-19 13:33:32 +01001530typedef struct ImgConvertState {
1531 BlockBackend **src;
1532 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001533 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001534 int64_t total_sectors;
1535 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001536 int64_t allocated_done;
1537 int64_t sector_num;
1538 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001539 enum ImgConvertBlockStatus status;
1540 int64_t sector_next_status;
1541 BlockBackend *target;
1542 bool has_zero_init;
1543 bool compressed;
1544 bool target_has_backing;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001545 bool wr_in_order;
Kevin Wolf690c7302015-03-19 13:33:32 +01001546 int min_sparse;
1547 size_t cluster_sectors;
1548 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001549 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001550 int running_coroutines;
1551 Coroutine *co[MAX_COROUTINES];
1552 int64_t wait_sector_num[MAX_COROUTINES];
1553 CoMutex lock;
1554 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001555} ImgConvertState;
1556
Peter Lieven2d9187b2017-02-28 13:40:07 +01001557static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1558 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001559{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001560 *src_cur = 0;
1561 *src_cur_offset = 0;
1562 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1563 *src_cur_offset += s->src_sectors[*src_cur];
1564 (*src_cur)++;
1565 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001566 }
1567}
1568
1569static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1570{
Eric Blake31826642017-10-11 22:47:08 -05001571 int64_t src_cur_offset;
1572 int ret, n, src_cur;
Kevin Wolf690c7302015-03-19 13:33:32 +01001573
Peter Lieven2d9187b2017-02-28 13:40:07 +01001574 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001575
1576 assert(s->total_sectors > sector_num);
1577 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1578
1579 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001580 int64_t count = n * BDRV_SECTOR_SIZE;
1581
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001582 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001583
1584 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1585 (sector_num - src_cur_offset) *
1586 BDRV_SECTOR_SIZE,
1587 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001588 } else {
Eric Blake31826642017-10-11 22:47:08 -05001589 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1590 (sector_num - src_cur_offset) *
1591 BDRV_SECTOR_SIZE,
1592 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001593 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001594 if (ret < 0) {
1595 return ret;
1596 }
Eric Blake31826642017-10-11 22:47:08 -05001597 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001598
1599 if (ret & BDRV_BLOCK_ZERO) {
1600 s->status = BLK_ZERO;
1601 } else if (ret & BDRV_BLOCK_DATA) {
1602 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001603 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001604 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001605 }
1606
1607 s->sector_next_status = sector_num + n;
1608 }
1609
1610 n = MIN(n, s->sector_next_status - sector_num);
1611 if (s->status == BLK_DATA) {
1612 n = MIN(n, s->buf_sectors);
1613 }
1614
1615 /* We need to write complete clusters for compressed images, so if an
1616 * unallocated area is shorter than that, we must consider the whole
1617 * cluster allocated. */
1618 if (s->compressed) {
1619 if (n < s->cluster_sectors) {
1620 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1621 s->status = BLK_DATA;
1622 } else {
1623 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1624 }
1625 }
1626
1627 return n;
1628}
1629
Peter Lieven2d9187b2017-02-28 13:40:07 +01001630static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1631 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001632{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001633 int n, ret;
1634 QEMUIOVector qiov;
1635 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001636
Kevin Wolf690c7302015-03-19 13:33:32 +01001637 assert(nb_sectors <= s->buf_sectors);
1638 while (nb_sectors > 0) {
1639 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001640 int src_cur;
1641 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001642
1643 /* In the case of compression with multiple source files, we can get a
1644 * nb_sectors that spreads into the next part. So we must be able to
1645 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001646 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1647 blk = s->src[src_cur];
1648 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001649
Peter Lieven2d9187b2017-02-28 13:40:07 +01001650 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1651 iov.iov_base = buf;
1652 iov.iov_len = n << BDRV_SECTOR_BITS;
1653 qemu_iovec_init_external(&qiov, &iov, 1);
1654
1655 ret = blk_co_preadv(
1656 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1657 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001658 if (ret < 0) {
1659 return ret;
1660 }
1661
1662 sector_num += n;
1663 nb_sectors -= n;
1664 buf += n * BDRV_SECTOR_SIZE;
1665 }
1666
1667 return 0;
1668}
1669
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670
1671static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1672 int nb_sectors, uint8_t *buf,
1673 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001674{
1675 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001676 QEMUIOVector qiov;
1677 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001678
1679 while (nb_sectors > 0) {
1680 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001681 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1682
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001684 case BLK_BACKING_FILE:
1685 /* If we have a backing file, leave clusters unallocated that are
1686 * unallocated in the source image, so that the backing file is
1687 * visible at the respective offset. */
1688 assert(s->target_has_backing);
1689 break;
1690
1691 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001692 /* If we're told to keep the target fully allocated (-S 0) or there
1693 * is real non-zero data, we must write it. Otherwise we can treat
1694 * it as zero sectors.
1695 * Compressed clusters need to be written as a whole, so in that
1696 * case we can only save the write if the buffer is completely
1697 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001698 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001699 (!s->compressed &&
1700 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1701 (s->compressed &&
1702 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001703 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001704 iov.iov_base = buf;
1705 iov.iov_len = n << BDRV_SECTOR_BITS;
1706 qemu_iovec_init_external(&qiov, &iov, 1);
1707
1708 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001709 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001710 if (ret < 0) {
1711 return ret;
1712 }
1713 break;
1714 }
1715 /* fall-through */
1716
1717 case BLK_ZERO:
1718 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001719 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001720 break;
1721 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001722 ret = blk_co_pwrite_zeroes(s->target,
1723 sector_num << BDRV_SECTOR_BITS,
1724 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001725 if (ret < 0) {
1726 return ret;
1727 }
1728 break;
1729 }
1730
1731 sector_num += n;
1732 nb_sectors -= n;
1733 buf += n * BDRV_SECTOR_SIZE;
1734 }
1735
1736 return 0;
1737}
1738
Peter Lieven2d9187b2017-02-28 13:40:07 +01001739static void coroutine_fn convert_co_do_copy(void *opaque)
1740{
1741 ImgConvertState *s = opaque;
1742 uint8_t *buf = NULL;
1743 int ret, i;
1744 int index = -1;
1745
1746 for (i = 0; i < s->num_coroutines; i++) {
1747 if (s->co[i] == qemu_coroutine_self()) {
1748 index = i;
1749 break;
1750 }
1751 }
1752 assert(index >= 0);
1753
1754 s->running_coroutines++;
1755 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1756
1757 while (1) {
1758 int n;
1759 int64_t sector_num;
1760 enum ImgConvertBlockStatus status;
1761
1762 qemu_co_mutex_lock(&s->lock);
1763 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1764 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001765 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001766 }
1767 n = convert_iteration_sectors(s, s->sector_num);
1768 if (n < 0) {
1769 qemu_co_mutex_unlock(&s->lock);
1770 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001771 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001772 }
1773 /* save current sector and allocation status to local variables */
1774 sector_num = s->sector_num;
1775 status = s->status;
1776 if (!s->min_sparse && s->status == BLK_ZERO) {
1777 n = MIN(n, s->buf_sectors);
1778 }
1779 /* increment global sector counter so that other coroutines can
1780 * already continue reading beyond this request */
1781 s->sector_num += n;
1782 qemu_co_mutex_unlock(&s->lock);
1783
1784 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1785 s->allocated_done += n;
1786 qemu_progress_print(100.0 * s->allocated_done /
1787 s->allocated_sectors, 0);
1788 }
1789
1790 if (status == BLK_DATA) {
1791 ret = convert_co_read(s, sector_num, n, buf);
1792 if (ret < 0) {
1793 error_report("error while reading sector %" PRId64
1794 ": %s", sector_num, strerror(-ret));
1795 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001796 }
1797 } else if (!s->min_sparse && status == BLK_ZERO) {
1798 status = BLK_DATA;
1799 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1800 }
1801
1802 if (s->wr_in_order) {
1803 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001804 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001805 s->wait_sector_num[index] = sector_num;
1806 qemu_coroutine_yield();
1807 }
1808 s->wait_sector_num[index] = -1;
1809 }
1810
Anton Nefedovb91127e2017-04-26 11:33:15 +03001811 if (s->ret == -EINPROGRESS) {
1812 ret = convert_co_write(s, sector_num, n, buf, status);
1813 if (ret < 0) {
1814 error_report("error while writing sector %" PRId64
1815 ": %s", sector_num, strerror(-ret));
1816 s->ret = ret;
1817 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001818 }
1819
1820 if (s->wr_in_order) {
1821 /* reenter the coroutine that might have waited
1822 * for this write to complete */
1823 s->wr_offs = sector_num + n;
1824 for (i = 0; i < s->num_coroutines; i++) {
1825 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1826 /*
1827 * A -> B -> A cannot occur because A has
1828 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1829 * B will never enter A during this time window.
1830 */
1831 qemu_coroutine_enter(s->co[i]);
1832 break;
1833 }
1834 }
1835 }
1836 }
1837
Peter Lieven2d9187b2017-02-28 13:40:07 +01001838 qemu_vfree(buf);
1839 s->co[index] = NULL;
1840 s->running_coroutines--;
1841 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1842 /* the convert job finished successfully */
1843 s->ret = 0;
1844 }
1845}
1846
Kevin Wolf690c7302015-03-19 13:33:32 +01001847static int convert_do_copy(ImgConvertState *s)
1848{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001849 int ret, i, n;
1850 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001851
1852 /* Check whether we have zero initialisation or can get it efficiently */
1853 s->has_zero_init = s->min_sparse && !s->target_has_backing
1854 ? bdrv_has_zero_init(blk_bs(s->target))
1855 : false;
1856
1857 if (!s->has_zero_init && !s->target_has_backing &&
1858 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1859 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001860 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001861 if (ret == 0) {
1862 s->has_zero_init = true;
1863 }
1864 }
1865
1866 /* Allocate buffer for copied data. For compressed images, only one cluster
1867 * can be copied at a time. */
1868 if (s->compressed) {
1869 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1870 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001871 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001872 }
1873 s->buf_sectors = s->cluster_sectors;
1874 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001875
Kevin Wolf690c7302015-03-19 13:33:32 +01001876 while (sector_num < s->total_sectors) {
1877 n = convert_iteration_sectors(s, sector_num);
1878 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001879 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001880 }
Max Reitzaad15de2016-03-24 23:33:57 +01001881 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1882 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001883 s->allocated_sectors += n;
1884 }
1885 sector_num += n;
1886 }
1887
1888 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001889 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001890 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001891
Peter Lieven2d9187b2017-02-28 13:40:07 +01001892 qemu_co_mutex_init(&s->lock);
1893 for (i = 0; i < s->num_coroutines; i++) {
1894 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1895 s->wait_sector_num[i] = -1;
1896 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001897 }
1898
Anton Nefedovb91127e2017-04-26 11:33:15 +03001899 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001900 main_loop_wait(false);
1901 }
1902
1903 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001904 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001905 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001906 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001907 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001908 }
1909 }
1910
Peter Lieven2d9187b2017-02-28 13:40:07 +01001911 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001912}
1913
bellardea2384d2004-08-01 21:59:26 +00001914static int img_convert(int argc, char **argv)
1915{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001916 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001917 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001918 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1919 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001920 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001921 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001922 BlockDriverState *out_bs;
1923 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001924 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001925 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001926 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001927 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001928 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001929 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08001930 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00001931
Peter Lieven9fd77f92017-04-21 11:11:55 +02001932 ImgConvertState s = (ImgConvertState) {
1933 /* Need at least 4k of zeros for sparse detection */
1934 .min_sparse = 8,
1935 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1936 .wr_in_order = true,
1937 .num_coroutines = 8,
1938 };
1939
bellardea2384d2004-08-01 21:59:26 +00001940 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001941 static const struct option long_options[] = {
1942 {"help", no_argument, 0, 'h'},
1943 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001944 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001945 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001946 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001947 {0, 0, 0, 0}
1948 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01001949 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001950 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001951 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001952 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001953 }
bellardea2384d2004-08-01 21:59:26 +00001954 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001955 case ':':
1956 missing_argument(argv[optind - 1]);
1957 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001958 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001959 unrecognized_option(argv[optind - 1]);
1960 break;
bellardea2384d2004-08-01 21:59:26 +00001961 case 'h':
1962 help();
1963 break;
1964 case 'f':
1965 fmt = optarg;
1966 break;
1967 case 'O':
1968 out_fmt = optarg;
1969 break;
thsf58c7b32008-06-05 21:53:49 +00001970 case 'B':
1971 out_baseimg = optarg;
1972 break;
bellardea2384d2004-08-01 21:59:26 +00001973 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02001974 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00001975 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001976 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001977 if (!is_valid_option_list(optarg)) {
1978 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001979 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01001980 }
1981 if (!options) {
1982 options = g_strdup(optarg);
1983 } else {
1984 char *old_options = options;
1985 options = g_strdup_printf("%s,%s", options, optarg);
1986 g_free(old_options);
1987 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02001988 break;
edison51ef6722010-09-21 19:58:41 -07001989 case 's':
1990 snapshot_name = optarg;
1991 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08001992 case 'l':
1993 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01001994 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
1995 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08001996 if (!sn_opts) {
1997 error_report("Failed in parsing snapshot param '%s'",
1998 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001999 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002000 }
2001 } else {
2002 snapshot_name = optarg;
2003 }
2004 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002005 case 'S':
2006 {
2007 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002008
2009 sval = cvtnum(optarg);
2010 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002011 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002012 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002013 }
2014
Peter Lieven9fd77f92017-04-21 11:11:55 +02002015 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002016 break;
2017 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002018 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002019 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002020 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002021 case 't':
2022 cache = optarg;
2023 break;
Max Reitz40055952014-07-22 22:58:42 +02002024 case 'T':
2025 src_cache = optarg;
2026 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002027 case 'q':
2028 quiet = true;
2029 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002030 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002031 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002032 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002033 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002034 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2035 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002036 error_report("Invalid number of coroutines. Allowed number of"
2037 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002038 goto fail_getopt;
2039 }
2040 break;
2041 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002042 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002043 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002044 case 'U':
2045 force_share = true;
2046 break;
Max Reitz3258b912017-04-26 15:46:47 +02002047 case OPTION_OBJECT: {
2048 QemuOpts *object_opts;
2049 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2050 optarg, true);
2051 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002052 goto fail_getopt;
2053 }
2054 break;
Max Reitz3258b912017-04-26 15:46:47 +02002055 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002056 case OPTION_IMAGE_OPTS:
2057 image_opts = true;
2058 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002059 case OPTION_TARGET_IMAGE_OPTS:
2060 tgt_image_opts = true;
2061 break;
bellardea2384d2004-08-01 21:59:26 +00002062 }
2063 }
ths3b46e622007-09-17 08:09:54 +00002064
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002065 if (!out_fmt && !tgt_image_opts) {
2066 out_fmt = "raw";
2067 }
2068
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002069 if (qemu_opts_foreach(&qemu_object_opts,
2070 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002071 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002072 goto fail_getopt;
2073 }
2074
Peter Lieven9fd77f92017-04-21 11:11:55 +02002075 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002076 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002077 goto fail_getopt;
2078 }
2079
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002080 if (tgt_image_opts && !skip_create) {
2081 error_report("--target-image-opts requires use of -n flag");
2082 goto fail_getopt;
2083 }
2084
Peter Lieven9fd77f92017-04-21 11:11:55 +02002085 s.src_num = argc - optind - 1;
2086 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2087
2088 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002089 if (out_fmt) {
2090 ret = print_block_option_help(out_filename, out_fmt);
2091 goto fail_getopt;
2092 } else {
2093 error_report("Option help requires a format be specified");
2094 goto fail_getopt;
2095 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002096 }
2097
2098 if (s.src_num < 1) {
2099 error_report("Must specify image file name");
2100 goto fail_getopt;
2101 }
2102
2103
Peter Lieven9fd77f92017-04-21 11:11:55 +02002104 /* ret is still -EINVAL until here */
2105 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2106 if (ret < 0) {
2107 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002108 goto fail_getopt;
2109 }
2110
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002111 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002112 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002113 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002114 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002115 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002116 qemu_progress_print(0, 100);
2117
Peter Lieven9fd77f92017-04-21 11:11:55 +02002118 s.src = g_new0(BlockBackend *, s.src_num);
2119 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002120
Peter Lieven9fd77f92017-04-21 11:11:55 +02002121 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2122 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002123 fmt, src_flags, src_writethrough, quiet,
2124 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002125 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002126 ret = -1;
2127 goto out;
2128 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002129 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2130 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002131 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002132 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002133 ret = -1;
2134 goto out;
2135 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002136 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002137 }
bellardea2384d2004-08-01 21:59:26 +00002138
Wenchao Xiaef806542013-12-04 17:10:57 +08002139 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002140 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002141 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2142 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2143 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002144 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002145 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002146 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002147 ret = -1;
2148 goto out;
2149 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002150
Peter Lieven9fd77f92017-04-21 11:11:55 +02002151 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2152 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002153 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002154 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002155 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002156 ret = -1;
2157 goto out;
edison51ef6722010-09-21 19:58:41 -07002158 }
2159
Max Reitz2e024cd2015-02-11 09:58:46 -05002160 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002161 /* Find driver and parse its options */
2162 drv = bdrv_find_format(out_fmt);
2163 if (!drv) {
2164 error_report("Unknown file format '%s'", out_fmt);
2165 ret = -1;
2166 goto out;
2167 }
2168
2169 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2170 if (!proto_drv) {
2171 error_report_err(local_err);
2172 ret = -1;
2173 goto out;
2174 }
2175
Max Reitz2e024cd2015-02-11 09:58:46 -05002176 if (!drv->create_opts) {
2177 error_report("Format driver '%s' does not support image creation",
2178 drv->format_name);
2179 ret = -1;
2180 goto out;
2181 }
Max Reitzf75613c2014-12-02 18:32:46 +01002182
Max Reitz2e024cd2015-02-11 09:58:46 -05002183 if (!proto_drv->create_opts) {
2184 error_report("Protocol driver '%s' does not support image creation",
2185 proto_drv->format_name);
2186 ret = -1;
2187 goto out;
2188 }
Max Reitzf75613c2014-12-02 18:32:46 +01002189
Max Reitz2e024cd2015-02-11 09:58:46 -05002190 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2191 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002192
Max Reitz2e024cd2015-02-11 09:58:46 -05002193 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002194 if (options) {
2195 qemu_opts_do_parse(opts, options, NULL, &local_err);
2196 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002197 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002198 ret = -1;
2199 goto out;
2200 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002201 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002202
Peter Lieven9fd77f92017-04-21 11:11:55 +02002203 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002204 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002205 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2206 if (ret < 0) {
2207 goto out;
2208 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002209 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002210
Kevin Wolfa18953f2010-10-14 15:46:04 +02002211 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002212 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002213 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002214 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002215 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002217
Max Reitz48758a82017-04-26 15:46:48 +02002218 if (s.src_num > 1 && out_baseimg) {
2219 error_report("Having a backing file for the target makes no sense when "
2220 "concatenating multiple input images");
2221 ret = -1;
2222 goto out;
2223 }
2224
Kevin Wolfefa84d42009-05-18 16:42:12 +02002225 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002227 bool encryption =
2228 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002229 const char *encryptfmt =
2230 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002231 const char *preallocation =
2232 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002233
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002234 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002235 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002236 ret = -1;
2237 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002238 }
2239
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002240 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002241 error_report("Compression and encryption not supported at "
2242 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002243 ret = -1;
2244 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002245 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002246
Chunyan Liu83d05212014-06-05 17:20:51 +08002247 if (preallocation
2248 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002249 {
2250 error_report("Compression and preallocation not supported at "
2251 "the same time");
2252 ret = -1;
2253 goto out;
2254 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002255 }
2256
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002257 if (!skip_create) {
2258 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002259 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002260 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002261 error_reportf_err(local_err, "%s: error while converting %s: ",
2262 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002263 goto out;
bellardea2384d2004-08-01 21:59:26 +00002264 }
2265 }
ths3b46e622007-09-17 08:09:54 +00002266
Peter Lieven9fd77f92017-04-21 11:11:55 +02002267 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002268 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002269 if (ret < 0) {
2270 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002271 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002272 }
2273
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002274 if (skip_create) {
2275 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2276 flags, writethrough, quiet, false);
2277 } else {
2278 /* TODO ultimately we should allow --target-image-opts
2279 * to be used even when -n is not given.
2280 * That has to wait for bdrv_create to be improved
2281 * to allow filenames in option syntax
2282 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002283 s.target = img_open_new_file(out_filename, opts, out_fmt,
2284 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002285 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002286 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002287 ret = -1;
2288 goto out;
2289 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002290 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002291
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002292 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2293 error_report("Compression not supported for this file format");
2294 ret = -1;
2295 goto out;
2296 }
2297
Eric Blake5def6b82016-06-23 16:37:19 -06002298 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002299 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2300 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002301 s.buf_sectors = MIN(32768,
2302 MAX(s.buf_sectors,
2303 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2304 out_bs->bl.pdiscard_alignment >>
2305 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002306
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002307 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002308 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002309 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002310 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002311 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002312 ret = -1;
2313 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002314 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002315 error_report("output file is smaller than input file");
2316 ret = -1;
2317 goto out;
2318 }
2319 }
2320
Peter Lieven24f833c2013-11-27 11:07:07 +01002321 ret = bdrv_get_info(out_bs, &bdi);
2322 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002323 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002324 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002325 goto out;
2326 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002327 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002328 s.compressed = s.compressed || bdi.needs_compressed_writes;
2329 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002330 }
2331
Peter Lieven9fd77f92017-04-21 11:11:55 +02002332 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002333out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002334 if (!ret) {
2335 qemu_progress_print(100, 0);
2336 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002337 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002338 qemu_opts_del(opts);
2339 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002340 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002341 blk_unref(s.target);
2342 if (s.src) {
2343 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2344 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002345 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002346 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002347 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002348 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002349fail_getopt:
2350 g_free(options);
2351
Peter Lieven9fd77f92017-04-21 11:11:55 +02002352 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002353}
2354
bellard57d1a2b2004-08-03 21:15:11 +00002355
bellardfaea38e2006-08-05 21:31:00 +00002356static void dump_snapshots(BlockDriverState *bs)
2357{
2358 QEMUSnapshotInfo *sn_tab, *sn;
2359 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002360
2361 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2362 if (nb_sns <= 0)
2363 return;
2364 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002365 bdrv_snapshot_dump(fprintf, stdout, NULL);
2366 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002367 for(i = 0; i < nb_sns; i++) {
2368 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002369 bdrv_snapshot_dump(fprintf, stdout, sn);
2370 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002371 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002372 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002373}
2374
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002375static void dump_json_image_info_list(ImageInfoList *list)
2376{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002377 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002378 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002379 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002380
2381 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2382 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002383 str = qobject_to_json_pretty(obj);
2384 assert(str != NULL);
2385 printf("%s\n", qstring_get_str(str));
2386 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002387 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002388 QDECREF(str);
2389}
2390
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002391static void dump_json_image_info(ImageInfo *info)
2392{
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002393 QString *str;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002394 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002395 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002396
2397 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2398 visit_complete(v, &obj);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002399 str = qobject_to_json_pretty(obj);
2400 assert(str != NULL);
2401 printf("%s\n", qstring_get_str(str));
2402 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002403 visit_free(v);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002404 QDECREF(str);
2405}
2406
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002407static void dump_human_image_info_list(ImageInfoList *list)
2408{
2409 ImageInfoList *elem;
2410 bool delim = false;
2411
2412 for (elem = list; elem; elem = elem->next) {
2413 if (delim) {
2414 printf("\n");
2415 }
2416 delim = true;
2417
Wenchao Xia5b917042013-05-25 11:09:45 +08002418 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002419 }
2420}
2421
2422static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2423{
2424 return strcmp(a, b) == 0;
2425}
2426
2427/**
2428 * Open an image file chain and return an ImageInfoList
2429 *
2430 * @filename: topmost image filename
2431 * @fmt: topmost image format (may be NULL to autodetect)
2432 * @chain: true - enumerate entire backing file chain
2433 * false - only topmost image file
2434 *
2435 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2436 * image file. If there was an error a message will have been printed to
2437 * stderr.
2438 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002439static ImageInfoList *collect_image_info_list(bool image_opts,
2440 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002441 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002442 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002443{
2444 ImageInfoList *head = NULL;
2445 ImageInfoList **last = &head;
2446 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002447 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002448
2449 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2450
2451 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002452 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002453 BlockDriverState *bs;
2454 ImageInfo *info;
2455 ImageInfoList *elem;
2456
2457 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2458 error_report("Backing file '%s' creates an infinite loop.",
2459 filename);
2460 goto err;
2461 }
2462 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2463
Max Reitzefaa7c42016-03-16 19:54:38 +01002464 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002465 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2466 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002467 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002468 goto err;
2469 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002470 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002471
Wenchao Xia43526ec2013-06-06 12:27:58 +08002472 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002473 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002474 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002475 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002476 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002477 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002478
2479 elem = g_new0(ImageInfoList, 1);
2480 elem->value = info;
2481 *last = elem;
2482 last = &elem->next;
2483
Markus Armbruster26f54e92014-10-07 13:59:04 +02002484 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002485
2486 filename = fmt = NULL;
2487 if (chain) {
2488 if (info->has_full_backing_filename) {
2489 filename = info->full_backing_filename;
2490 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002491 error_report("Could not determine absolute backing filename,"
2492 " but backing filename '%s' present",
2493 info->backing_filename);
2494 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002495 }
2496 if (info->has_backing_filename_format) {
2497 fmt = info->backing_filename_format;
2498 }
2499 }
2500 }
2501 g_hash_table_destroy(filenames);
2502 return head;
2503
2504err:
2505 qapi_free_ImageInfoList(head);
2506 g_hash_table_destroy(filenames);
2507 return NULL;
2508}
2509
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002510static int img_info(int argc, char **argv)
2511{
2512 int c;
2513 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002514 bool chain = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002515 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002516 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002517 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002518 bool force_share = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002519
bellardea2384d2004-08-01 21:59:26 +00002520 fmt = NULL;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002521 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002522 for(;;) {
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002523 int option_index = 0;
2524 static const struct option long_options[] = {
2525 {"help", no_argument, 0, 'h'},
2526 {"format", required_argument, 0, 'f'},
2527 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002528 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002529 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002530 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002531 {"force-share", no_argument, 0, 'U'},
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002532 {0, 0, 0, 0}
2533 };
Fam Zheng335e9932017-05-03 00:35:39 +08002534 c = getopt_long(argc, argv, ":f:hU",
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002535 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002536 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002537 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002538 }
bellardea2384d2004-08-01 21:59:26 +00002539 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002540 case ':':
2541 missing_argument(argv[optind - 1]);
2542 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002543 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002544 unrecognized_option(argv[optind - 1]);
2545 break;
bellardea2384d2004-08-01 21:59:26 +00002546 case 'h':
2547 help();
2548 break;
2549 case 'f':
2550 fmt = optarg;
2551 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002552 case 'U':
2553 force_share = true;
2554 break;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002555 case OPTION_OUTPUT:
2556 output = optarg;
2557 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002558 case OPTION_BACKING_CHAIN:
2559 chain = true;
2560 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002561 case OPTION_OBJECT: {
2562 QemuOpts *opts;
2563 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2564 optarg, true);
2565 if (!opts) {
2566 return 1;
2567 }
2568 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002569 case OPTION_IMAGE_OPTS:
2570 image_opts = true;
2571 break;
bellardea2384d2004-08-01 21:59:26 +00002572 }
2573 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002574 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002575 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002576 }
bellardea2384d2004-08-01 21:59:26 +00002577 filename = argv[optind++];
2578
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002579 if (output && !strcmp(output, "json")) {
2580 output_format = OFORMAT_JSON;
2581 } else if (output && !strcmp(output, "human")) {
2582 output_format = OFORMAT_HUMAN;
2583 } else if (output) {
2584 error_report("--output must be used with human or json as argument.");
2585 return 1;
2586 }
2587
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002588 if (qemu_opts_foreach(&qemu_object_opts,
2589 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002590 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002591 return 1;
2592 }
2593
Fam Zheng335e9932017-05-03 00:35:39 +08002594 list = collect_image_info_list(image_opts, filename, fmt, chain,
2595 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002597 return 1;
2598 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002599
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002600 switch (output_format) {
2601 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002602 dump_human_image_info_list(list);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002603 break;
2604 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002605 if (chain) {
2606 dump_json_image_info_list(list);
2607 } else {
2608 dump_json_image_info(list->value);
2609 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002610 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002611 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002612
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002613 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002614 return 0;
2615}
2616
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002617static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2618 MapEntry *next)
2619{
2620 switch (output_format) {
2621 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002622 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002623 error_report("File contains external, encrypted or compressed clusters.");
2624 exit(1);
2625 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002626 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002627 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002628 e->start, e->length,
2629 e->has_offset ? e->offset : 0,
2630 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002631 }
2632 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2633 * Modify the flags here to allow more coalescing.
2634 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002635 if (next && (!next->data || next->zero)) {
2636 next->data = false;
2637 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002638 }
2639 break;
2640 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002641 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2642 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002643 (e->start == 0 ? "[" : ",\n"),
2644 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002645 e->zero ? "true" : "false",
2646 e->data ? "true" : "false");
2647 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002648 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002649 }
2650 putchar('}');
2651
2652 if (!next) {
2653 printf("]\n");
2654 }
2655 break;
2656 }
2657}
2658
Eric Blake5e344dd2017-10-11 22:47:02 -05002659static int get_block_status(BlockDriverState *bs, int64_t offset,
2660 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002661{
Eric Blake237d78f2017-10-11 22:47:03 -05002662 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002663 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002664 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002665 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002666 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002667
2668 /* As an optimization, we could cache the current range of unallocated
2669 * clusters in each file of the chain, and avoid querying the same
2670 * range repeatedly.
2671 */
2672
2673 depth = 0;
2674 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002675 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002676 if (ret < 0) {
2677 return ret;
2678 }
Eric Blake237d78f2017-10-11 22:47:03 -05002679 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002680 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2681 break;
2682 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002683 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002684 if (bs == NULL) {
2685 ret = 0;
2686 break;
2687 }
2688
2689 depth++;
2690 }
2691
John Snow28756452016-02-05 13:12:33 -05002692 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2693
2694 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002695 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002696 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002697 .data = !!(ret & BDRV_BLOCK_DATA),
2698 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002699 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002700 .has_offset = has_offset,
2701 .depth = depth,
2702 .has_filename = file && has_offset,
2703 .filename = file && has_offset ? file->filename : NULL,
2704 };
2705
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002706 return 0;
2707}
2708
Fam Zheng16b0d552016-01-26 11:59:02 +08002709static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2710{
2711 if (curr->length == 0) {
2712 return false;
2713 }
2714 if (curr->zero != next->zero ||
2715 curr->data != next->data ||
2716 curr->depth != next->depth ||
2717 curr->has_filename != next->has_filename ||
2718 curr->has_offset != next->has_offset) {
2719 return false;
2720 }
2721 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2722 return false;
2723 }
2724 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2725 return false;
2726 }
2727 return true;
2728}
2729
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002730static int img_map(int argc, char **argv)
2731{
2732 int c;
2733 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002734 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002735 BlockDriverState *bs;
2736 const char *filename, *fmt, *output;
2737 int64_t length;
2738 MapEntry curr = { .length = 0 }, next;
2739 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002740 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002741 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002742
2743 fmt = NULL;
2744 output = NULL;
2745 for (;;) {
2746 int option_index = 0;
2747 static const struct option long_options[] = {
2748 {"help", no_argument, 0, 'h'},
2749 {"format", required_argument, 0, 'f'},
2750 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002751 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002752 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002753 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002754 {0, 0, 0, 0}
2755 };
Fam Zheng335e9932017-05-03 00:35:39 +08002756 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002757 long_options, &option_index);
2758 if (c == -1) {
2759 break;
2760 }
2761 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002762 case ':':
2763 missing_argument(argv[optind - 1]);
2764 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002765 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002766 unrecognized_option(argv[optind - 1]);
2767 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002768 case 'h':
2769 help();
2770 break;
2771 case 'f':
2772 fmt = optarg;
2773 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002774 case 'U':
2775 force_share = true;
2776 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002777 case OPTION_OUTPUT:
2778 output = optarg;
2779 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002780 case OPTION_OBJECT: {
2781 QemuOpts *opts;
2782 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2783 optarg, true);
2784 if (!opts) {
2785 return 1;
2786 }
2787 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002788 case OPTION_IMAGE_OPTS:
2789 image_opts = true;
2790 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791 }
2792 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002793 if (optind != argc - 1) {
2794 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002795 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002796 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002797
2798 if (output && !strcmp(output, "json")) {
2799 output_format = OFORMAT_JSON;
2800 } else if (output && !strcmp(output, "human")) {
2801 output_format = OFORMAT_HUMAN;
2802 } else if (output) {
2803 error_report("--output must be used with human or json as argument.");
2804 return 1;
2805 }
2806
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002807 if (qemu_opts_foreach(&qemu_object_opts,
2808 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002809 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002810 return 1;
2811 }
2812
Fam Zheng335e9932017-05-03 00:35:39 +08002813 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002814 if (!blk) {
2815 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002816 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002817 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002818
2819 if (output_format == OFORMAT_HUMAN) {
2820 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2821 }
2822
Max Reitzf1d3cd72015-02-05 13:58:18 -05002823 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002824 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002825 int64_t offset = curr.start + curr.length;
2826 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002827
2828 /* Probe up to 1 GiB at a time. */
Eric Blake5e344dd2017-10-11 22:47:02 -05002829 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2830 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002831
2832 if (ret < 0) {
2833 error_report("Could not read file metadata: %s", strerror(-ret));
2834 goto out;
2835 }
2836
Fam Zheng16b0d552016-01-26 11:59:02 +08002837 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002838 curr.length += next.length;
2839 continue;
2840 }
2841
2842 if (curr.length > 0) {
2843 dump_map_entry(output_format, &curr, &next);
2844 }
2845 curr = next;
2846 }
2847
2848 dump_map_entry(output_format, &curr, NULL);
2849
2850out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002851 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002852 return ret < 0;
2853}
2854
aliguorif7b4a942009-01-07 17:40:15 +00002855#define SNAPSHOT_LIST 1
2856#define SNAPSHOT_CREATE 2
2857#define SNAPSHOT_APPLY 3
2858#define SNAPSHOT_DELETE 4
2859
Stuart Brady153859b2009-06-07 00:42:17 +01002860static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002861{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002862 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002863 BlockDriverState *bs;
2864 QEMUSnapshotInfo sn;
2865 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002866 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002867 int action = 0;
2868 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002869 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002870 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002871 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002872 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002873
Kevin Wolfce099542016-03-15 13:01:04 +01002874 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002875 /* Parse commandline parameters */
2876 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002877 static const struct option long_options[] = {
2878 {"help", no_argument, 0, 'h'},
2879 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002880 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002881 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002882 {0, 0, 0, 0}
2883 };
Fam Zheng335e9932017-05-03 00:35:39 +08002884 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002885 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002886 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002887 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002888 }
aliguorif7b4a942009-01-07 17:40:15 +00002889 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002890 case ':':
2891 missing_argument(argv[optind - 1]);
2892 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002893 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002894 unrecognized_option(argv[optind - 1]);
2895 break;
aliguorif7b4a942009-01-07 17:40:15 +00002896 case 'h':
2897 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002898 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002899 case 'l':
2900 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002901 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002902 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002903 }
2904 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002905 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002906 break;
2907 case 'a':
2908 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002909 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002910 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002911 }
2912 action = SNAPSHOT_APPLY;
2913 snapshot_name = optarg;
2914 break;
2915 case 'c':
2916 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002917 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002918 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002919 }
2920 action = SNAPSHOT_CREATE;
2921 snapshot_name = optarg;
2922 break;
2923 case 'd':
2924 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002925 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002926 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002927 }
2928 action = SNAPSHOT_DELETE;
2929 snapshot_name = optarg;
2930 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002931 case 'q':
2932 quiet = true;
2933 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002934 case 'U':
2935 force_share = true;
2936 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002937 case OPTION_OBJECT: {
2938 QemuOpts *opts;
2939 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2940 optarg, true);
2941 if (!opts) {
2942 return 1;
2943 }
2944 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002945 case OPTION_IMAGE_OPTS:
2946 image_opts = true;
2947 break;
aliguorif7b4a942009-01-07 17:40:15 +00002948 }
2949 }
2950
Kevin Wolffc11eb22013-08-05 10:53:04 +02002951 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002952 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002953 }
aliguorif7b4a942009-01-07 17:40:15 +00002954 filename = argv[optind++];
2955
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002956 if (qemu_opts_foreach(&qemu_object_opts,
2957 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002958 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002959 return 1;
2960 }
2961
aliguorif7b4a942009-01-07 17:40:15 +00002962 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08002963 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2964 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002965 if (!blk) {
2966 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002967 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002968 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002969
2970 /* Perform the requested action */
2971 switch(action) {
2972 case SNAPSHOT_LIST:
2973 dump_snapshots(bs);
2974 break;
2975
2976 case SNAPSHOT_CREATE:
2977 memset(&sn, 0, sizeof(sn));
2978 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2979
2980 qemu_gettimeofday(&tv);
2981 sn.date_sec = tv.tv_sec;
2982 sn.date_nsec = tv.tv_usec * 1000;
2983
2984 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002985 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002986 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002987 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002988 }
aliguorif7b4a942009-01-07 17:40:15 +00002989 break;
2990
2991 case SNAPSHOT_APPLY:
2992 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002993 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002994 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00002995 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002996 }
aliguorif7b4a942009-01-07 17:40:15 +00002997 break;
2998
2999 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003000 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003001 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003002 error_reportf_err(err, "Could not delete snapshot '%s': ",
3003 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003004 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003005 }
aliguorif7b4a942009-01-07 17:40:15 +00003006 break;
3007 }
3008
3009 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003010 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003011 if (ret) {
3012 return 1;
3013 }
Stuart Brady153859b2009-06-07 00:42:17 +01003014 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003015}
3016
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003017static int img_rebase(int argc, char **argv)
3018{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003019 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003020 uint8_t *buf_old = NULL;
3021 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003022 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003023 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003024 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3025 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003026 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003027 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003028 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003029 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003030 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003031 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003032 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003033
3034 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003035 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003036 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003037 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003038 out_baseimg = NULL;
3039 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003040 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003041 static const struct option long_options[] = {
3042 {"help", no_argument, 0, 'h'},
3043 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003044 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003045 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003046 {0, 0, 0, 0}
3047 };
Fam Zheng335e9932017-05-03 00:35:39 +08003048 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003049 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003050 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003051 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003052 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003053 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003054 case ':':
3055 missing_argument(argv[optind - 1]);
3056 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003057 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003058 unrecognized_option(argv[optind - 1]);
3059 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003060 case 'h':
3061 help();
3062 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003063 case 'f':
3064 fmt = optarg;
3065 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003066 case 'F':
3067 out_basefmt = optarg;
3068 break;
3069 case 'b':
3070 out_baseimg = optarg;
3071 break;
3072 case 'u':
3073 unsafe = 1;
3074 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003075 case 'p':
3076 progress = 1;
3077 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003078 case 't':
3079 cache = optarg;
3080 break;
Max Reitz40055952014-07-22 22:58:42 +02003081 case 'T':
3082 src_cache = optarg;
3083 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003084 case 'q':
3085 quiet = true;
3086 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003087 case OPTION_OBJECT: {
3088 QemuOpts *opts;
3089 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3090 optarg, true);
3091 if (!opts) {
3092 return 1;
3093 }
3094 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003095 case OPTION_IMAGE_OPTS:
3096 image_opts = true;
3097 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003098 case 'U':
3099 force_share = true;
3100 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003101 }
3102 }
3103
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003104 if (quiet) {
3105 progress = 0;
3106 }
3107
Fam Zhengac1307a2014-04-22 13:36:11 +08003108 if (optind != argc - 1) {
3109 error_exit("Expecting one image file name");
3110 }
3111 if (!unsafe && !out_baseimg) {
3112 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003113 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003114 filename = argv[optind++];
3115
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003116 if (qemu_opts_foreach(&qemu_object_opts,
3117 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003118 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003119 return 1;
3120 }
3121
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003122 qemu_progress_init(progress, 2.0);
3123 qemu_progress_print(0, 100);
3124
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003125 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003126 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003127 if (ret < 0) {
3128 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003129 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003130 }
3131
Kevin Wolfce099542016-03-15 13:01:04 +01003132 src_flags = 0;
3133 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003134 if (ret < 0) {
3135 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003136 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003137 }
3138
Kevin Wolfce099542016-03-15 13:01:04 +01003139 /* The source files are opened read-only, don't care about WCE */
3140 assert((src_flags & BDRV_O_RDWR) == 0);
3141 (void) src_writethrough;
3142
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003143 /*
3144 * Open the images.
3145 *
3146 * Ignore the old backing file for unsafe rebase in case we want to correct
3147 * the reference to a renamed or moved backing file.
3148 */
Fam Zheng335e9932017-05-03 00:35:39 +08003149 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3150 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003151 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003152 ret = -1;
3153 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003154 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003155 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003156
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003157 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003158 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003159 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003160 ret = -1;
3161 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003162 }
3163 }
3164
3165 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003166 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003167 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003168 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003169
Max Reitz644483d2015-02-05 13:58:17 -05003170 if (bs->backing_format[0] != '\0') {
3171 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003172 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003173 }
3174
Fam Zheng335e9932017-05-03 00:35:39 +08003175 if (force_share) {
3176 if (!options) {
3177 options = qdict_new();
3178 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003179 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003180 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003181 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003182 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003183 options, src_flags, &local_err);
3184 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003185 error_reportf_err(local_err,
3186 "Could not open old backing file '%s': ",
3187 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003188 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003189 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003190 }
Max Reitz644483d2015-02-05 13:58:17 -05003191
Alex Bligha6166732012-10-16 13:46:18 +01003192 if (out_baseimg[0]) {
Fam Zheng335e9932017-05-03 00:35:39 +08003193 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003194 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003195 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003196 }
3197 if (force_share) {
3198 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003199 }
3200
Max Reitzefaa7c42016-03-16 19:54:38 +01003201 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003202 options, src_flags, &local_err);
3203 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003204 error_reportf_err(local_err,
3205 "Could not open new backing file '%s': ",
3206 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003207 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003208 goto out;
3209 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003210 }
3211 }
3212
3213 /*
3214 * Check each unallocated cluster in the COW file. If it is unallocated,
3215 * accesses go to the backing file. We must therefore compare this cluster
3216 * in the old and new backing file, and if they differ we need to copy it
3217 * from the old backing file into the COW file.
3218 *
3219 * If qemu-img crashes during this step, no harm is done. The content of
3220 * the image is the same as the original one at any time.
3221 */
3222 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003223 int64_t size;
3224 int64_t old_backing_size;
3225 int64_t new_backing_size = 0;
3226 uint64_t offset;
3227 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003228 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003229
Max Reitzf1d3cd72015-02-05 13:58:18 -05003230 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3231 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003232
Eric Blake41536282017-10-11 22:47:15 -05003233 size = blk_getlength(blk);
3234 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003235 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003236 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003237 ret = -1;
3238 goto out;
3239 }
Eric Blake41536282017-10-11 22:47:15 -05003240 old_backing_size = blk_getlength(blk_old_backing);
3241 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003242 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003243
3244 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3245 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003246 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003247 ret = -1;
3248 goto out;
3249 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003250 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003251 new_backing_size = blk_getlength(blk_new_backing);
3252 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003253 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003254 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003255 ret = -1;
3256 goto out;
3257 }
Alex Bligha6166732012-10-16 13:46:18 +01003258 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003259
Eric Blake41536282017-10-11 22:47:15 -05003260 if (size != 0) {
3261 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003262 }
3263
Eric Blake41536282017-10-11 22:47:15 -05003264 for (offset = 0; offset < size; offset += n) {
3265 /* How many bytes can we handle with the next read? */
3266 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003267
3268 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003269 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003270 if (ret < 0) {
3271 error_report("error while reading image metadata: %s",
3272 strerror(-ret));
3273 goto out;
3274 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003275 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003276 continue;
3277 }
3278
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003279 /*
3280 * Read old and new backing file and take into consideration that
3281 * backing files may be smaller than the COW image.
3282 */
Eric Blake41536282017-10-11 22:47:15 -05003283 if (offset >= old_backing_size) {
3284 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003285 } else {
Eric Blake41536282017-10-11 22:47:15 -05003286 if (offset + n > old_backing_size) {
3287 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003288 }
3289
Eric Blake41536282017-10-11 22:47:15 -05003290 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003291 if (ret < 0) {
3292 error_report("error while reading from old backing file");
3293 goto out;
3294 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003295 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003296
Eric Blake41536282017-10-11 22:47:15 -05003297 if (offset >= new_backing_size || !blk_new_backing) {
3298 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003299 } else {
Eric Blake41536282017-10-11 22:47:15 -05003300 if (offset + n > new_backing_size) {
3301 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003302 }
3303
Eric Blake41536282017-10-11 22:47:15 -05003304 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003305 if (ret < 0) {
3306 error_report("error while reading from new backing file");
3307 goto out;
3308 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003309 }
3310
3311 /* If they differ, we need to write to the COW file */
3312 uint64_t written = 0;
3313
Eric Blake41536282017-10-11 22:47:15 -05003314 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003315 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003316
Eric Blake41536282017-10-11 22:47:15 -05003317 if (compare_buffers(buf_old + written, buf_new + written,
3318 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003319 {
Eric Blake41536282017-10-11 22:47:15 -05003320 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003321 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003322 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003323 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003324 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003325 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003326 }
3327 }
3328
3329 written += pnum;
3330 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003331 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003332 }
3333 }
3334
3335 /*
3336 * Change the backing file. All clusters that are different from the old
3337 * backing file are overwritten in the COW file now, so the visible content
3338 * doesn't change when we switch the backing file.
3339 */
Alex Bligha6166732012-10-16 13:46:18 +01003340 if (out_baseimg && *out_baseimg) {
3341 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3342 } else {
3343 ret = bdrv_change_backing_file(bs, NULL, NULL);
3344 }
3345
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003346 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003347 error_report("Could not change the backing file to '%s': No "
3348 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003349 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003350 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003351 out_baseimg, strerror(-ret));
3352 }
3353
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003354 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003355 /*
3356 * TODO At this point it is possible to check if any clusters that are
3357 * allocated in the COW file are the same in the backing file. If so, they
3358 * could be dropped from the COW file. Don't do this before switching the
3359 * backing file, in case of a crash this would lead to corruption.
3360 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003361out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003362 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003363 /* Cleanup */
3364 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003365 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003366 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003367 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003368 qemu_vfree(buf_old);
3369 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003370
Markus Armbruster26f54e92014-10-07 13:59:04 +02003371 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003372 if (ret) {
3373 return 1;
3374 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003375 return 0;
3376}
3377
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003378static int img_resize(int argc, char **argv)
3379{
Markus Armbruster6750e792015-02-12 17:43:08 +01003380 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003381 int c, ret, relative;
3382 const char *filename, *fmt, *size;
Max Reitzdc5f6902017-06-13 22:20:55 +02003383 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003384 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003385 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003386 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003387 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003388
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003389 static QemuOptsList resize_options = {
3390 .name = "resize_options",
3391 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3392 .desc = {
3393 {
3394 .name = BLOCK_OPT_SIZE,
3395 .type = QEMU_OPT_SIZE,
3396 .help = "Virtual disk size"
3397 }, {
3398 /* end of list */
3399 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003400 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003401 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003402 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003403 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003404
Kevin Wolfe80fec72011-04-29 10:58:12 +02003405 /* Remove size from argv manually so that negative numbers are not treated
3406 * as options by getopt. */
3407 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003408 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003409 return 1;
3410 }
3411
3412 size = argv[--argc];
3413
3414 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003415 fmt = NULL;
3416 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003417 static const struct option long_options[] = {
3418 {"help", no_argument, 0, 'h'},
3419 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003420 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003421 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003422 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003423 {0, 0, 0, 0}
3424 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003425 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003426 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003427 if (c == -1) {
3428 break;
3429 }
3430 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003431 case ':':
3432 missing_argument(argv[optind - 1]);
3433 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003434 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003435 unrecognized_option(argv[optind - 1]);
3436 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003437 case 'h':
3438 help();
3439 break;
3440 case 'f':
3441 fmt = optarg;
3442 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003443 case 'q':
3444 quiet = true;
3445 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003446 case OPTION_OBJECT: {
3447 QemuOpts *opts;
3448 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3449 optarg, true);
3450 if (!opts) {
3451 return 1;
3452 }
3453 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003454 case OPTION_IMAGE_OPTS:
3455 image_opts = true;
3456 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003457 case OPTION_PREALLOCATION:
Marc-AndrƩ Lureauf7abe0e2017-08-24 10:46:10 +02003458 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003459 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003460 if (prealloc == PREALLOC_MODE__MAX) {
3461 error_report("Invalid preallocation mode '%s'", optarg);
3462 return 1;
3463 }
3464 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003465 case OPTION_SHRINK:
3466 shrink = true;
3467 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003468 }
3469 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003470 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003471 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003472 }
3473 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003474
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003475 if (qemu_opts_foreach(&qemu_object_opts,
3476 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003477 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003478 return 1;
3479 }
3480
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003481 /* Choose grow, shrink, or absolute resize mode */
3482 switch (size[0]) {
3483 case '+':
3484 relative = 1;
3485 size++;
3486 break;
3487 case '-':
3488 relative = -1;
3489 size++;
3490 break;
3491 default:
3492 relative = 0;
3493 break;
3494 }
3495
3496 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003497 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003498 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003499 if (err) {
3500 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003501 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003502 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003503 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003504 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003505 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3506 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003507
Max Reitzefaa7c42016-03-16 19:54:38 +01003508 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003509 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3510 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003511 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003512 ret = -1;
3513 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003514 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003515
Max Reitzdc5f6902017-06-13 22:20:55 +02003516 current_size = blk_getlength(blk);
3517 if (current_size < 0) {
3518 error_report("Failed to inquire current image length: %s",
3519 strerror(-current_size));
3520 ret = -1;
3521 goto out;
3522 }
3523
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003524 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003525 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003526 } else {
3527 total_size = n;
3528 }
3529 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003530 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003531 ret = -1;
3532 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003533 }
3534
Max Reitzdc5f6902017-06-13 22:20:55 +02003535 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3536 error_report("Preallocation can only be used for growing images");
3537 ret = -1;
3538 goto out;
3539 }
3540
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003541 if (total_size < current_size && !shrink) {
3542 warn_report("Shrinking an image will delete all data beyond the "
3543 "shrunken image's end. Before performing such an "
3544 "operation, make sure there is no important data there.");
3545
3546 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3547 error_report(
3548 "Use the --shrink option to perform a shrink operation.");
3549 ret = -1;
3550 goto out;
3551 } else {
3552 warn_report("Using the --shrink option will suppress this message. "
3553 "Note that future versions of qemu-img may refuse to "
3554 "shrink images without this option.");
3555 }
3556 }
3557
Max Reitzdc5f6902017-06-13 22:20:55 +02003558 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitzed3d2ec2017-03-28 22:51:27 +02003559 if (!ret) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003560 qprintf(quiet, "Image resized.\n");
Max Reitzed3d2ec2017-03-28 22:51:27 +02003561 } else {
3562 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003563 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003564out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003565 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003566 if (ret) {
3567 return 1;
3568 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003569 return 0;
3570}
3571
Max Reitz76a3a342014-10-27 11:12:51 +01003572static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003573 int64_t offset, int64_t total_work_size,
3574 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003575{
3576 qemu_progress_print(100.f * offset / total_work_size, 0);
3577}
3578
Max Reitz6f176b42013-09-03 10:09:50 +02003579static int img_amend(int argc, char **argv)
3580{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003581 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003582 int c, ret = 0;
3583 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003584 QemuOptsList *create_opts = NULL;
3585 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003586 const char *fmt = NULL, *filename, *cache;
3587 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003588 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003589 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003590 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003591 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003592 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003593
Max Reitzbd39e6e2014-07-22 22:58:43 +02003594 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003595 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003596 static const struct option long_options[] = {
3597 {"help", no_argument, 0, 'h'},
3598 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003599 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003600 {0, 0, 0, 0}
3601 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003602 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003603 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003604 if (c == -1) {
3605 break;
3606 }
3607
3608 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003609 case ':':
3610 missing_argument(argv[optind - 1]);
3611 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003612 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003613 unrecognized_option(argv[optind - 1]);
3614 break;
3615 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003616 help();
3617 break;
3618 case 'o':
3619 if (!is_valid_option_list(optarg)) {
3620 error_report("Invalid option list: %s", optarg);
3621 ret = -1;
3622 goto out_no_progress;
3623 }
3624 if (!options) {
3625 options = g_strdup(optarg);
3626 } else {
3627 char *old_options = options;
3628 options = g_strdup_printf("%s,%s", options, optarg);
3629 g_free(old_options);
3630 }
3631 break;
3632 case 'f':
3633 fmt = optarg;
3634 break;
3635 case 't':
3636 cache = optarg;
3637 break;
3638 case 'p':
3639 progress = true;
3640 break;
3641 case 'q':
3642 quiet = true;
3643 break;
3644 case OPTION_OBJECT:
3645 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3646 optarg, true);
3647 if (!opts) {
3648 ret = -1;
3649 goto out_no_progress;
3650 }
3651 break;
3652 case OPTION_IMAGE_OPTS:
3653 image_opts = true;
3654 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003655 }
3656 }
3657
Max Reitz6f176b42013-09-03 10:09:50 +02003658 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003659 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003660 }
3661
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003662 if (qemu_opts_foreach(&qemu_object_opts,
3663 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003664 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003665 ret = -1;
3666 goto out_no_progress;
3667 }
3668
Max Reitz76a3a342014-10-27 11:12:51 +01003669 if (quiet) {
3670 progress = false;
3671 }
3672 qemu_progress_init(progress, 1.0);
3673
Kevin Wolfa283cb62014-02-21 16:24:07 +01003674 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3675 if (fmt && has_help_option(options)) {
3676 /* If a format is explicitly specified (and possibly no filename is
3677 * given), print option help here */
3678 ret = print_block_option_help(filename, fmt);
3679 goto out;
3680 }
3681
3682 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003683 error_report("Expecting one image file name");
3684 ret = -1;
3685 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003686 }
Max Reitz6f176b42013-09-03 10:09:50 +02003687
Kevin Wolfce099542016-03-15 13:01:04 +01003688 flags = BDRV_O_RDWR;
3689 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003690 if (ret < 0) {
3691 error_report("Invalid cache option: %s", cache);
3692 goto out;
3693 }
3694
Fam Zheng335e9932017-05-03 00:35:39 +08003695 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3696 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003697 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003698 ret = -1;
3699 goto out;
3700 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003701 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003702
3703 fmt = bs->drv->format_name;
3704
Kevin Wolf626f84f2014-02-21 16:24:06 +01003705 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003706 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003707 ret = print_block_option_help(filename, fmt);
3708 goto out;
3709 }
3710
Max Reitzb2439d22014-12-02 18:32:47 +01003711 if (!bs->drv->create_opts) {
3712 error_report("Format driver '%s' does not support any options to amend",
3713 fmt);
3714 ret = -1;
3715 goto out;
3716 }
3717
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003718 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003719 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003720 qemu_opts_do_parse(opts, options, NULL, &err);
3721 if (err) {
3722 error_report_err(err);
3723 ret = -1;
3724 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003725 }
3726
Max Reitz76a3a342014-10-27 11:12:51 +01003727 /* In case the driver does not call amend_status_cb() */
3728 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003729 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003730 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003731 if (ret < 0) {
3732 error_report("Error while amending options: %s", strerror(-ret));
3733 goto out;
3734 }
3735
3736out:
Max Reitz76a3a342014-10-27 11:12:51 +01003737 qemu_progress_end();
3738
Max Reitze814dff2015-08-20 16:00:38 -07003739out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003740 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003741 qemu_opts_del(opts);
3742 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003743 g_free(options);
3744
Max Reitz6f176b42013-09-03 10:09:50 +02003745 if (ret) {
3746 return 1;
3747 }
3748 return 0;
3749}
3750
Kevin Wolfb6133b82014-08-05 14:17:13 +02003751typedef struct BenchData {
3752 BlockBackend *blk;
3753 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003754 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003755 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003756 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003757 int nrreq;
3758 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003759 int flush_interval;
3760 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003761 uint8_t *buf;
3762 QEMUIOVector *qiov;
3763
3764 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003765 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003766 uint64_t offset;
3767} BenchData;
3768
Kevin Wolf55d539c2016-06-03 13:59:41 +02003769static void bench_undrained_flush_cb(void *opaque, int ret)
3770{
3771 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003772 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003773 exit(EXIT_FAILURE);
3774 }
3775}
3776
Kevin Wolfb6133b82014-08-05 14:17:13 +02003777static void bench_cb(void *opaque, int ret)
3778{
3779 BenchData *b = opaque;
3780 BlockAIOCB *acb;
3781
3782 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003783 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003784 exit(EXIT_FAILURE);
3785 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003786
3787 if (b->in_flush) {
3788 /* Just finished a flush with drained queue: Start next requests */
3789 assert(b->in_flight == 0);
3790 b->in_flush = false;
3791 } else if (b->in_flight > 0) {
3792 int remaining = b->n - b->in_flight;
3793
Kevin Wolfb6133b82014-08-05 14:17:13 +02003794 b->n--;
3795 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003796
3797 /* Time for flush? Drain queue if requested, then flush */
3798 if (b->flush_interval && remaining % b->flush_interval == 0) {
3799 if (!b->in_flight || !b->drain_on_flush) {
3800 BlockCompletionFunc *cb;
3801
3802 if (b->drain_on_flush) {
3803 b->in_flush = true;
3804 cb = bench_cb;
3805 } else {
3806 cb = bench_undrained_flush_cb;
3807 }
3808
3809 acb = blk_aio_flush(b->blk, cb, b);
3810 if (!acb) {
3811 error_report("Failed to issue flush request");
3812 exit(EXIT_FAILURE);
3813 }
3814 }
3815 if (b->drain_on_flush) {
3816 return;
3817 }
3818 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003819 }
3820
3821 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003822 int64_t offset = b->offset;
3823 /* blk_aio_* might look for completed I/Os and kick bench_cb
3824 * again, so make sure this operation is counted by in_flight
3825 * and b->offset is ready for the next submission.
3826 */
3827 b->in_flight++;
3828 b->offset += b->step;
3829 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003830 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003831 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003832 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003833 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003834 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003835 if (!acb) {
3836 error_report("Failed to issue request");
3837 exit(EXIT_FAILURE);
3838 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003839 }
3840}
3841
3842static int img_bench(int argc, char **argv)
3843{
3844 int c, ret = 0;
3845 const char *fmt = NULL, *filename;
3846 bool quiet = false;
3847 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003848 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003849 int count = 75000;
3850 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003851 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003852 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003853 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003854 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003855 int flush_interval = 0;
3856 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003857 int64_t image_size;
3858 BlockBackend *blk = NULL;
3859 BenchData data = {};
3860 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003861 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003862 struct timeval t1, t2;
3863 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08003864 bool force_share = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003865
3866 for (;;) {
3867 static const struct option long_options[] = {
3868 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003869 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003870 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003871 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003872 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08003873 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003874 {0, 0, 0, 0}
3875 };
Fam Zheng335e9932017-05-03 00:35:39 +08003876 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003877 if (c == -1) {
3878 break;
3879 }
3880
3881 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003882 case ':':
3883 missing_argument(argv[optind - 1]);
3884 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003885 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003886 unrecognized_option(argv[optind - 1]);
3887 break;
3888 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02003889 help();
3890 break;
3891 case 'c':
3892 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003893 unsigned long res;
3894
3895 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003896 error_report("Invalid request count specified");
3897 return 1;
3898 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003899 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003900 break;
3901 }
3902 case 'd':
3903 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003904 unsigned long res;
3905
3906 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003907 error_report("Invalid queue depth specified");
3908 return 1;
3909 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003910 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003911 break;
3912 }
3913 case 'f':
3914 fmt = optarg;
3915 break;
3916 case 'n':
3917 flags |= BDRV_O_NATIVE_AIO;
3918 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003919 case 'o':
3920 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003921 offset = cvtnum(optarg);
3922 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003923 error_report("Invalid offset specified");
3924 return 1;
3925 }
3926 break;
3927 }
3928 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003929 case 'q':
3930 quiet = true;
3931 break;
3932 case 's':
3933 {
3934 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003935
Markus Armbruster606caa02017-02-21 21:14:04 +01003936 sval = cvtnum(optarg);
3937 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003938 error_report("Invalid buffer size specified");
3939 return 1;
3940 }
3941
3942 bufsize = sval;
3943 break;
3944 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003945 case 'S':
3946 {
3947 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003948
Markus Armbruster606caa02017-02-21 21:14:04 +01003949 sval = cvtnum(optarg);
3950 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003951 error_report("Invalid step size specified");
3952 return 1;
3953 }
3954
3955 step = sval;
3956 break;
3957 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003958 case 't':
3959 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3960 if (ret < 0) {
3961 error_report("Invalid cache mode");
3962 ret = -1;
3963 goto out;
3964 }
3965 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003966 case 'w':
3967 flags |= BDRV_O_RDWR;
3968 is_write = true;
3969 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003970 case 'U':
3971 force_share = true;
3972 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003973 case OPTION_PATTERN:
3974 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003975 unsigned long res;
3976
3977 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003978 error_report("Invalid pattern byte specified");
3979 return 1;
3980 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003981 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003982 break;
3983 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003984 case OPTION_FLUSH_INTERVAL:
3985 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003986 unsigned long res;
3987
3988 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02003989 error_report("Invalid flush interval specified");
3990 return 1;
3991 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003992 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003993 break;
3994 }
3995 case OPTION_NO_DRAIN:
3996 drain_on_flush = false;
3997 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003998 case OPTION_IMAGE_OPTS:
3999 image_opts = true;
4000 break;
4001 }
4002 }
4003
4004 if (optind != argc - 1) {
4005 error_exit("Expecting one image file name");
4006 }
4007 filename = argv[argc - 1];
4008
Kevin Wolf55d539c2016-06-03 13:59:41 +02004009 if (!is_write && flush_interval) {
4010 error_report("--flush-interval is only available in write tests");
4011 ret = -1;
4012 goto out;
4013 }
4014 if (flush_interval && flush_interval < depth) {
4015 error_report("Flush interval can't be smaller than depth");
4016 ret = -1;
4017 goto out;
4018 }
4019
Fam Zheng335e9932017-05-03 00:35:39 +08004020 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4021 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004022 if (!blk) {
4023 ret = -1;
4024 goto out;
4025 }
4026
4027 image_size = blk_getlength(blk);
4028 if (image_size < 0) {
4029 ret = image_size;
4030 goto out;
4031 }
4032
4033 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004034 .blk = blk,
4035 .image_size = image_size,
4036 .bufsize = bufsize,
4037 .step = step ?: bufsize,
4038 .nrreq = depth,
4039 .n = count,
4040 .offset = offset,
4041 .write = is_write,
4042 .flush_interval = flush_interval,
4043 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004044 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004045 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004046 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004047 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004048 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004049 if (flush_interval) {
4050 printf("Sending flush every %d requests\n", flush_interval);
4051 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004052
4053 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004054 memset(data.buf, pattern, data.nrreq * data.bufsize);
4055
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 data.qiov = g_new(QEMUIOVector, data.nrreq);
4057 for (i = 0; i < data.nrreq; i++) {
4058 qemu_iovec_init(&data.qiov[i], 1);
4059 qemu_iovec_add(&data.qiov[i],
4060 data.buf + i * data.bufsize, data.bufsize);
4061 }
4062
4063 gettimeofday(&t1, NULL);
4064 bench_cb(&data, 0);
4065
4066 while (data.n > 0) {
4067 main_loop_wait(false);
4068 }
4069 gettimeofday(&t2, NULL);
4070
4071 printf("Run completed in %3.3f seconds.\n",
4072 (t2.tv_sec - t1.tv_sec)
4073 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4074
4075out:
4076 qemu_vfree(data.buf);
4077 blk_unref(blk);
4078
4079 if (ret) {
4080 return 1;
4081 }
4082 return 0;
4083}
4084
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004085#define C_BS 01
4086#define C_COUNT 02
4087#define C_IF 04
4088#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004089#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004090
4091struct DdInfo {
4092 unsigned int flags;
4093 int64_t count;
4094};
4095
4096struct DdIo {
4097 int bsz; /* Block size */
4098 char *filename;
4099 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004100 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004101};
4102
4103struct DdOpts {
4104 const char *name;
4105 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4106 unsigned int flag;
4107};
4108
4109static int img_dd_bs(const char *arg,
4110 struct DdIo *in, struct DdIo *out,
4111 struct DdInfo *dd)
4112{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004113 int64_t res;
4114
Markus Armbruster606caa02017-02-21 21:14:04 +01004115 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004116
Markus Armbruster606caa02017-02-21 21:14:04 +01004117 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004118 error_report("invalid number: '%s'", arg);
4119 return 1;
4120 }
4121 in->bsz = out->bsz = res;
4122
4123 return 0;
4124}
4125
4126static int img_dd_count(const char *arg,
4127 struct DdIo *in, struct DdIo *out,
4128 struct DdInfo *dd)
4129{
Markus Armbruster606caa02017-02-21 21:14:04 +01004130 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004131
Markus Armbruster606caa02017-02-21 21:14:04 +01004132 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004133 error_report("invalid number: '%s'", arg);
4134 return 1;
4135 }
4136
4137 return 0;
4138}
4139
4140static int img_dd_if(const char *arg,
4141 struct DdIo *in, struct DdIo *out,
4142 struct DdInfo *dd)
4143{
4144 in->filename = g_strdup(arg);
4145
4146 return 0;
4147}
4148
4149static int img_dd_of(const char *arg,
4150 struct DdIo *in, struct DdIo *out,
4151 struct DdInfo *dd)
4152{
4153 out->filename = g_strdup(arg);
4154
4155 return 0;
4156}
4157
Reda Sallahif7c15532016-08-10 16:16:09 +02004158static int img_dd_skip(const char *arg,
4159 struct DdIo *in, struct DdIo *out,
4160 struct DdInfo *dd)
4161{
Markus Armbruster606caa02017-02-21 21:14:04 +01004162 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004163
Markus Armbruster606caa02017-02-21 21:14:04 +01004164 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004165 error_report("invalid number: '%s'", arg);
4166 return 1;
4167 }
4168
4169 return 0;
4170}
4171
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004172static int img_dd(int argc, char **argv)
4173{
4174 int ret = 0;
4175 char *arg = NULL;
4176 char *tmp;
4177 BlockDriver *drv = NULL, *proto_drv = NULL;
4178 BlockBackend *blk1 = NULL, *blk2 = NULL;
4179 QemuOpts *opts = NULL;
4180 QemuOptsList *create_opts = NULL;
4181 Error *local_err = NULL;
4182 bool image_opts = false;
4183 int c, i;
4184 const char *out_fmt = "raw";
4185 const char *fmt = NULL;
4186 int64_t size = 0;
4187 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004188 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004189 struct DdInfo dd = {
4190 .flags = 0,
4191 .count = 0,
4192 };
4193 struct DdIo in = {
4194 .bsz = 512, /* Block size is by default 512 bytes */
4195 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004196 .buf = NULL,
4197 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004198 };
4199 struct DdIo out = {
4200 .bsz = 512,
4201 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004202 .buf = NULL,
4203 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004204 };
4205
4206 const struct DdOpts options[] = {
4207 { "bs", img_dd_bs, C_BS },
4208 { "count", img_dd_count, C_COUNT },
4209 { "if", img_dd_if, C_IF },
4210 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004211 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004212 { NULL, NULL, 0 }
4213 };
4214 const struct option long_options[] = {
4215 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004216 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004217 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004218 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004219 { 0, 0, 0, 0 }
4220 };
4221
Fam Zheng335e9932017-05-03 00:35:39 +08004222 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004223 if (c == EOF) {
4224 break;
4225 }
4226 switch (c) {
4227 case 'O':
4228 out_fmt = optarg;
4229 break;
4230 case 'f':
4231 fmt = optarg;
4232 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004233 case ':':
4234 missing_argument(argv[optind - 1]);
4235 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004236 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004237 unrecognized_option(argv[optind - 1]);
4238 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004239 case 'h':
4240 help();
4241 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004242 case 'U':
4243 force_share = true;
4244 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004245 case OPTION_OBJECT:
4246 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004247 ret = -1;
4248 goto out;
4249 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004250 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004251 case OPTION_IMAGE_OPTS:
4252 image_opts = true;
4253 break;
4254 }
4255 }
4256
4257 for (i = optind; i < argc; i++) {
4258 int j;
4259 arg = g_strdup(argv[i]);
4260
4261 tmp = strchr(arg, '=');
4262 if (tmp == NULL) {
4263 error_report("unrecognized operand %s", arg);
4264 ret = -1;
4265 goto out;
4266 }
4267
4268 *tmp++ = '\0';
4269
4270 for (j = 0; options[j].name != NULL; j++) {
4271 if (!strcmp(arg, options[j].name)) {
4272 break;
4273 }
4274 }
4275 if (options[j].name == NULL) {
4276 error_report("unrecognized operand %s", arg);
4277 ret = -1;
4278 goto out;
4279 }
4280
4281 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4282 ret = -1;
4283 goto out;
4284 }
4285 dd.flags |= options[j].flag;
4286 g_free(arg);
4287 arg = NULL;
4288 }
4289
4290 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4291 error_report("Must specify both input and output files");
4292 ret = -1;
4293 goto out;
4294 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004295
4296 if (qemu_opts_foreach(&qemu_object_opts,
4297 user_creatable_add_opts_foreach,
4298 NULL, NULL)) {
4299 ret = -1;
4300 goto out;
4301 }
4302
Fam Zheng335e9932017-05-03 00:35:39 +08004303 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4304 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004305
4306 if (!blk1) {
4307 ret = -1;
4308 goto out;
4309 }
4310
4311 drv = bdrv_find_format(out_fmt);
4312 if (!drv) {
4313 error_report("Unknown file format");
4314 ret = -1;
4315 goto out;
4316 }
4317 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4318
4319 if (!proto_drv) {
4320 error_report_err(local_err);
4321 ret = -1;
4322 goto out;
4323 }
4324 if (!drv->create_opts) {
4325 error_report("Format driver '%s' does not support image creation",
4326 drv->format_name);
4327 ret = -1;
4328 goto out;
4329 }
4330 if (!proto_drv->create_opts) {
4331 error_report("Protocol driver '%s' does not support image creation",
4332 proto_drv->format_name);
4333 ret = -1;
4334 goto out;
4335 }
4336 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4337 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4338
4339 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4340
4341 size = blk_getlength(blk1);
4342 if (size < 0) {
4343 error_report("Failed to get size for '%s'", in.filename);
4344 ret = -1;
4345 goto out;
4346 }
4347
4348 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4349 dd.count * in.bsz < size) {
4350 size = dd.count * in.bsz;
4351 }
4352
Reda Sallahif7c15532016-08-10 16:16:09 +02004353 /* Overflow means the specified offset is beyond input image's size */
4354 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4355 size < in.bsz * in.offset)) {
4356 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4357 } else {
4358 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4359 size - in.bsz * in.offset, &error_abort);
4360 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004361
4362 ret = bdrv_create(drv, out.filename, opts, &local_err);
4363 if (ret < 0) {
4364 error_reportf_err(local_err,
4365 "%s: error while creating output image: ",
4366 out.filename);
4367 ret = -1;
4368 goto out;
4369 }
4370
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004371 /* TODO, we can't honour --image-opts for the target,
4372 * since it needs to be given in a format compatible
4373 * with the bdrv_create() call above which does not
4374 * support image-opts style.
4375 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004376 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004377 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004378
4379 if (!blk2) {
4380 ret = -1;
4381 goto out;
4382 }
4383
Reda Sallahif7c15532016-08-10 16:16:09 +02004384 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4385 size < in.offset * in.bsz)) {
4386 /* We give a warning if the skip option is bigger than the input
4387 * size and create an empty output disk image (i.e. like dd(1)).
4388 */
4389 error_report("%s: cannot skip to specified offset", in.filename);
4390 in_pos = size;
4391 } else {
4392 in_pos = in.offset * in.bsz;
4393 }
4394
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004395 in.buf = g_new(uint8_t, in.bsz);
4396
Reda Sallahif7c15532016-08-10 16:16:09 +02004397 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004398 int in_ret, out_ret;
4399
4400 if (in_pos + in.bsz > size) {
4401 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4402 } else {
4403 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4404 }
4405 if (in_ret < 0) {
4406 error_report("error while reading from input image file: %s",
4407 strerror(-in_ret));
4408 ret = -1;
4409 goto out;
4410 }
4411 in_pos += in_ret;
4412
4413 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4414
4415 if (out_ret < 0) {
4416 error_report("error while writing to output image file: %s",
4417 strerror(-out_ret));
4418 ret = -1;
4419 goto out;
4420 }
4421 out_pos += out_ret;
4422 }
4423
4424out:
4425 g_free(arg);
4426 qemu_opts_del(opts);
4427 qemu_opts_free(create_opts);
4428 blk_unref(blk1);
4429 blk_unref(blk2);
4430 g_free(in.filename);
4431 g_free(out.filename);
4432 g_free(in.buf);
4433 g_free(out.buf);
4434
4435 if (ret) {
4436 return 1;
4437 }
4438 return 0;
4439}
4440
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004441static void dump_json_block_measure_info(BlockMeasureInfo *info)
4442{
4443 QString *str;
4444 QObject *obj;
4445 Visitor *v = qobject_output_visitor_new(&obj);
4446
4447 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4448 visit_complete(v, &obj);
4449 str = qobject_to_json_pretty(obj);
4450 assert(str != NULL);
4451 printf("%s\n", qstring_get_str(str));
4452 qobject_decref(obj);
4453 visit_free(v);
4454 QDECREF(str);
4455}
4456
4457static int img_measure(int argc, char **argv)
4458{
4459 static const struct option long_options[] = {
4460 {"help", no_argument, 0, 'h'},
4461 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4462 {"object", required_argument, 0, OPTION_OBJECT},
4463 {"output", required_argument, 0, OPTION_OUTPUT},
4464 {"size", required_argument, 0, OPTION_SIZE},
4465 {"force-share", no_argument, 0, 'U'},
4466 {0, 0, 0, 0}
4467 };
4468 OutputFormat output_format = OFORMAT_HUMAN;
4469 BlockBackend *in_blk = NULL;
4470 BlockDriver *drv;
4471 const char *filename = NULL;
4472 const char *fmt = NULL;
4473 const char *out_fmt = "raw";
4474 char *options = NULL;
4475 char *snapshot_name = NULL;
4476 bool force_share = false;
4477 QemuOpts *opts = NULL;
4478 QemuOpts *object_opts = NULL;
4479 QemuOpts *sn_opts = NULL;
4480 QemuOptsList *create_opts = NULL;
4481 bool image_opts = false;
4482 uint64_t img_size = UINT64_MAX;
4483 BlockMeasureInfo *info = NULL;
4484 Error *local_err = NULL;
4485 int ret = 1;
4486 int c;
4487
4488 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4489 long_options, NULL)) != -1) {
4490 switch (c) {
4491 case '?':
4492 case 'h':
4493 help();
4494 break;
4495 case 'f':
4496 fmt = optarg;
4497 break;
4498 case 'O':
4499 out_fmt = optarg;
4500 break;
4501 case 'o':
4502 if (!is_valid_option_list(optarg)) {
4503 error_report("Invalid option list: %s", optarg);
4504 goto out;
4505 }
4506 if (!options) {
4507 options = g_strdup(optarg);
4508 } else {
4509 char *old_options = options;
4510 options = g_strdup_printf("%s,%s", options, optarg);
4511 g_free(old_options);
4512 }
4513 break;
4514 case 'l':
4515 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4516 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4517 optarg, false);
4518 if (!sn_opts) {
4519 error_report("Failed in parsing snapshot param '%s'",
4520 optarg);
4521 goto out;
4522 }
4523 } else {
4524 snapshot_name = optarg;
4525 }
4526 break;
4527 case 'U':
4528 force_share = true;
4529 break;
4530 case OPTION_OBJECT:
4531 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4532 optarg, true);
4533 if (!object_opts) {
4534 goto out;
4535 }
4536 break;
4537 case OPTION_IMAGE_OPTS:
4538 image_opts = true;
4539 break;
4540 case OPTION_OUTPUT:
4541 if (!strcmp(optarg, "json")) {
4542 output_format = OFORMAT_JSON;
4543 } else if (!strcmp(optarg, "human")) {
4544 output_format = OFORMAT_HUMAN;
4545 } else {
4546 error_report("--output must be used with human or json "
4547 "as argument.");
4548 goto out;
4549 }
4550 break;
4551 case OPTION_SIZE:
4552 {
4553 int64_t sval;
4554
4555 sval = cvtnum(optarg);
4556 if (sval < 0) {
4557 if (sval == -ERANGE) {
4558 error_report("Image size must be less than 8 EiB!");
4559 } else {
4560 error_report("Invalid image size specified! You may use "
4561 "k, M, G, T, P or E suffixes for ");
4562 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4563 "petabytes and exabytes.");
4564 }
4565 goto out;
4566 }
4567 img_size = (uint64_t)sval;
4568 }
4569 break;
4570 }
4571 }
4572
4573 if (qemu_opts_foreach(&qemu_object_opts,
4574 user_creatable_add_opts_foreach,
4575 NULL, NULL)) {
4576 goto out;
4577 }
4578
4579 if (argc - optind > 1) {
4580 error_report("At most one filename argument is allowed.");
4581 goto out;
4582 } else if (argc - optind == 1) {
4583 filename = argv[optind];
4584 }
4585
4586 if (!filename &&
4587 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4588 error_report("--object, --image-opts, -f, and -l "
4589 "require a filename argument.");
4590 goto out;
4591 }
4592 if (filename && img_size != UINT64_MAX) {
4593 error_report("--size N cannot be used together with a filename.");
4594 goto out;
4595 }
4596 if (!filename && img_size == UINT64_MAX) {
4597 error_report("Either --size N or one filename must be specified.");
4598 goto out;
4599 }
4600
4601 if (filename) {
4602 in_blk = img_open(image_opts, filename, fmt, 0,
4603 false, false, force_share);
4604 if (!in_blk) {
4605 goto out;
4606 }
4607
4608 if (sn_opts) {
4609 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4610 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4611 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4612 &local_err);
4613 } else if (snapshot_name != NULL) {
4614 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4615 snapshot_name, &local_err);
4616 }
4617 if (local_err) {
4618 error_reportf_err(local_err, "Failed to load snapshot: ");
4619 goto out;
4620 }
4621 }
4622
4623 drv = bdrv_find_format(out_fmt);
4624 if (!drv) {
4625 error_report("Unknown file format '%s'", out_fmt);
4626 goto out;
4627 }
4628 if (!drv->create_opts) {
4629 error_report("Format driver '%s' does not support image creation",
4630 drv->format_name);
4631 goto out;
4632 }
4633
4634 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4635 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4636 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4637 if (options) {
4638 qemu_opts_do_parse(opts, options, NULL, &local_err);
4639 if (local_err) {
4640 error_report_err(local_err);
4641 error_report("Invalid options for file format '%s'", out_fmt);
4642 goto out;
4643 }
4644 }
4645 if (img_size != UINT64_MAX) {
4646 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4647 }
4648
4649 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4650 if (local_err) {
4651 error_report_err(local_err);
4652 goto out;
4653 }
4654
4655 if (output_format == OFORMAT_HUMAN) {
4656 printf("required size: %" PRIu64 "\n", info->required);
4657 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4658 } else {
4659 dump_json_block_measure_info(info);
4660 }
4661
4662 ret = 0;
4663
4664out:
4665 qapi_free_BlockMeasureInfo(info);
4666 qemu_opts_del(object_opts);
4667 qemu_opts_del(opts);
4668 qemu_opts_del(sn_opts);
4669 qemu_opts_free(create_opts);
4670 g_free(options);
4671 blk_unref(in_blk);
4672 return ret;
4673}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004674
Anthony Liguoric227f092009-10-01 16:12:16 -05004675static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004676#define DEF(option, callback, arg_string) \
4677 { option, callback },
4678#include "qemu-img-cmds.h"
4679#undef DEF
4680#undef GEN_DOCS
4681 { NULL, NULL, },
4682};
4683
bellardea2384d2004-08-01 21:59:26 +00004684int main(int argc, char **argv)
4685{
Anthony Liguoric227f092009-10-01 16:12:16 -05004686 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004687 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004688 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004689 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004690 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004691 static const struct option long_options[] = {
4692 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004693 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004694 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004695 {0, 0, 0, 0}
4696 };
bellardea2384d2004-08-01 21:59:26 +00004697
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004698#ifdef CONFIG_POSIX
4699 signal(SIGPIPE, SIG_IGN);
4700#endif
4701
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004702 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004703 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004704 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004705
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004706 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004707 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004708 exit(EXIT_FAILURE);
4709 }
4710
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004711 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004712
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004713 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004714 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004715 if (argc < 2) {
4716 error_exit("Not enough arguments");
4717 }
Stuart Brady153859b2009-06-07 00:42:17 +01004718
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004719 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004720 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004721 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004722
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004723 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004724 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004725 case ':':
4726 missing_argument(argv[optind - 1]);
4727 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004728 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004729 unrecognized_option(argv[optind - 1]);
4730 return 0;
4731 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004732 help();
4733 return 0;
4734 case 'V':
4735 printf(QEMU_IMG_VERSION);
4736 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004737 case 'T':
4738 g_free(trace_file);
4739 trace_file = trace_opt_parse(optarg);
4740 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004741 }
bellardea2384d2004-08-01 21:59:26 +00004742 }
Stuart Brady153859b2009-06-07 00:42:17 +01004743
Denis V. Lunev10985132016-06-17 17:44:13 +03004744 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004745
Denis V. Lunev10985132016-06-17 17:44:13 +03004746 /* reset getopt_long scanning */
4747 argc -= optind;
4748 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004749 return 0;
4750 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004751 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004752 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004753
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004754 if (!trace_init_backends()) {
4755 exit(1);
4756 }
4757 trace_init_file(trace_file);
4758 qemu_set_log(LOG_TRACE);
4759
Denis V. Lunev10985132016-06-17 17:44:13 +03004760 /* find the command */
4761 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4762 if (!strcmp(cmdname, cmd->name)) {
4763 return cmd->handler(argc, argv);
4764 }
4765 }
Jeff Cody7db16892014-04-25 17:02:32 -04004766
Stuart Brady153859b2009-06-07 00:42:17 +01004767 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004768 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004769}