blob: c81d6ce733e7c9705e26d8eedbb7fe875873fb53 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Peter Maydell80c71a22016-01-18 18:01:42 +000024#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050025#include <getopt.h>
26
Fam Zheng67a1de02016-06-01 17:44:21 +080027#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010028#include "qapi/error.h"
BenoƮt Canetc054b3f2012-09-05 13:09:02 +020029#include "qapi-visit.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010030#include "qapi/qobject-output-visitor.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010031#include "qapi/qmp/qerror.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Fam Zheng335e9932017-05-03 00:35:39 +080033#include "qapi/qmp/qbool.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020034#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000035#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010036#include "qemu/option.h"
37#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030038#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000039#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010040#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020041#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010042#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020043#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080044#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010045#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030046#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000047
Don Slutz61979a62015-01-09 10:17:35 -050048#define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020049 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040050
Anthony Liguoric227f092009-10-01 16:12:16 -050051typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010052 const char *name;
53 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050054} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010055
Federico Simoncelli8599ea42013-01-28 06:59:47 -050056enum {
57 OPTION_OUTPUT = 256,
58 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000059 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000060 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020061 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020062 OPTION_FLUSH_INTERVAL = 261,
63 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010064 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010065 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020066 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030067 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050068};
69
70typedef enum OutputFormat {
71 OFORMAT_JSON,
72 OFORMAT_HUMAN,
73} OutputFormat;
74
Kevin Wolfe6996142016-03-15 13:03:11 +010075/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040076#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000077
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010078static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000079{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010080 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000081}
82
Fam Zhengac1307a2014-04-22 13:36:11 +080083static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
84{
85 va_list ap;
86
87 error_printf("qemu-img: ");
88
89 va_start(ap, fmt);
90 error_vprintf(fmt, ap);
91 va_end(ap);
92
93 error_printf("\nTry 'qemu-img --help' for more information\n");
94 exit(EXIT_FAILURE);
95}
96
Stefan Hajnoczic9192972017-03-17 18:45:41 +080097static void QEMU_NORETURN missing_argument(const char *option)
98{
99 error_exit("missing argument for option '%s'", option);
100}
101
102static void QEMU_NORETURN unrecognized_option(const char *option)
103{
104 error_exit("unrecognized option '%s'", option);
105}
106
blueswir1d2c639d2009-01-24 18:19:25 +0000107/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800108static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000109{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100110 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400111 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300112 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300113 "QEMU disk image utility\n"
114 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300115 " '-h', '--help' display this help and exit\n"
116 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300117 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300119 "\n"
malc3f020d72010-02-08 12:04:56 +0300120 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100121#define DEF(option, callback, arg_string) \
122 " " arg_string "\n"
123#include "qemu-img-cmds.h"
124#undef DEF
125#undef GEN_DOCS
malc3f020d72010-02-08 12:04:56 +0300126 "\n"
127 "Command parameters:\n"
128 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000129 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
130 " manual page for a description of the object properties. The most common\n"
131 " object type is a 'secret', which is used to supply passwords and/or\n"
132 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300133 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400134 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800135 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
136 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100137 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
138 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300139 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200140 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
141 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
142 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300143 " 'output_filename' is the destination disk image filename\n"
144 " 'output_fmt' is the destination format\n"
145 " 'options' is a comma separated list of format specific options in a\n"
146 " name=value format. Use -o ? for an overview of the options supported by the\n"
147 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800148 " 'snapshot_param' is param used for internal snapshot, format\n"
149 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
150 " '[ID_OR_NAME]'\n"
151 " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
152 " instead\n"
malc3f020d72010-02-08 12:04:56 +0300153 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400154 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
155 " new backing file match exactly. The image doesn't need a working\n"
156 " backing file before rebasing in this case (useful for renaming the\n"
157 " backing file). For image creation, allow creating without attempting\n"
158 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300159 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200160 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100161 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200162 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
163 " contain only zeros for qemu-img to create a sparse image during\n"
164 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
165 " unallocated or zero sectors, and the destination image will always be\n"
166 " fully allocated\n"
BenoƮt Canetc054b3f2012-09-05 13:09:02 +0200167 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100168 " '-n' skips the target volume creation (useful if the volume is created\n"
169 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300170 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200171 "Parameters to check subcommand:\n"
172 " '-r' tries to repair any inconsistencies that are found during the check.\n"
173 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
174 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200175 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200176 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100177 "Parameters to convert subcommand:\n"
178 " '-m' specifies how many coroutines work in parallel during the convert\n"
179 " process (defaults to 8)\n"
180 " '-W' allow to write to the target out of order rather than sequential\n"
181 "\n"
malc3f020d72010-02-08 12:04:56 +0300182 "Parameters to snapshot subcommand:\n"
183 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
184 " '-a' applies a snapshot (revert disk to saved state)\n"
185 " '-c' creates a snapshot\n"
186 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100187 " '-l' lists all snapshots in the given image\n"
188 "\n"
189 "Parameters to compare subcommand:\n"
190 " '-f' first image format\n"
191 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200192 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
193 "\n"
194 "Parameters to dd subcommand:\n"
195 " 'bs=BYTES' read and write up to BYTES bytes at a time "
196 "(default: 512)\n"
197 " 'count=N' copy only N input blocks\n"
198 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200199 " 'of=FILE' write to FILE\n"
200 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100201
202 printf("%s\nSupported formats:", help_msg);
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100203 bdrv_iterate_format(format_print, NULL);
Eric Blakef5048cb2017-08-03 11:33:53 -0500204 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800205 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000206}
207
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000208static QemuOptsList qemu_object_opts = {
209 .name = "object",
210 .implied_opt_name = "qom-type",
211 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
212 .desc = {
213 { }
214 },
215};
216
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000217static QemuOptsList qemu_source_opts = {
218 .name = "source",
219 .implied_opt_name = "file",
220 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
221 .desc = {
222 { }
223 },
224};
225
Stefan Weil7c30f652013-06-16 17:01:05 +0200226static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100227{
228 int ret = 0;
229 if (!quiet) {
230 va_list args;
231 va_start(args, fmt);
232 ret = vprintf(fmt, args);
233 va_end(args);
234 }
235 return ret;
236}
237
bellardea2384d2004-08-01 21:59:26 +0000238
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100239static int print_block_option_help(const char *filename, const char *fmt)
240{
241 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800242 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500243 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100244
245 /* Find driver and parse its options */
246 drv = bdrv_find_format(fmt);
247 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100248 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100249 return 1;
250 }
251
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800252 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100253 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500254 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100255 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100256 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800257 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 return 1;
259 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800260 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100261 }
262
Chunyan Liu83d05212014-06-05 17:20:51 +0800263 qemu_opts_print_help(create_opts);
264 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100265 return 0;
266}
267
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000268
Max Reitzefaa7c42016-03-16 19:54:38 +0100269static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100270 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800271 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000272{
273 QDict *options;
274 Error *local_err = NULL;
275 BlockBackend *blk;
276 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800277 if (force_share) {
278 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
279 && !qdict_get_bool(options, BDRV_OPT_FORCE_SHARE)) {
280 error_report("--force-share/-U conflicts with image options");
Fam Zhengadb998c2017-05-15 22:10:14 +0800281 QDECREF(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800282 return NULL;
283 }
Eric Blake579cf1d2017-05-15 14:54:39 -0500284 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800285 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100286 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000287 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100288 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000289 return NULL;
290 }
Kevin Wolfce099542016-03-15 13:01:04 +0100291 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000292
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000293 return blk;
294}
295
Max Reitzefaa7c42016-03-16 19:54:38 +0100296static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100297 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000298 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800299 bool writethrough, bool quiet,
300 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000301{
302 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200303 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100304
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100305 if (!options) {
306 options = qdict_new();
307 }
bellard75c23802004-08-27 21:28:58 +0000308 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500309 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000310 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100311
Fam Zheng335e9932017-05-03 00:35:39 +0800312 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500313 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800314 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100315 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500316 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100317 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000318 return NULL;
bellard75c23802004-08-27 21:28:58 +0000319 }
Kevin Wolfce099542016-03-15 13:01:04 +0100320 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100321
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200322 return blk;
bellard75c23802004-08-27 21:28:58 +0000323}
324
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000325
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100326static int img_add_key_secrets(void *opaque,
327 const char *name, const char *value,
328 Error **errp)
329{
330 QDict *options = opaque;
331
332 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600333 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100334 }
335
336 return 0;
337}
338
339static BlockBackend *img_open_new_file(const char *filename,
340 QemuOpts *create_opts,
341 const char *fmt, int flags,
342 bool writethrough, bool quiet,
343 bool force_share)
344{
345 QDict *options = NULL;
346
347 options = qdict_new();
348 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
349
350 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
351 force_share);
352}
353
354
Max Reitzefaa7c42016-03-16 19:54:38 +0100355static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000356 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100357 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800358 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000359{
360 BlockBackend *blk;
361 if (image_opts) {
362 QemuOpts *opts;
363 if (fmt) {
364 error_report("--image-opts and --format are mutually exclusive");
365 return NULL;
366 }
367 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
368 filename, true);
369 if (!opts) {
370 return NULL;
371 }
Fam Zheng335e9932017-05-03 00:35:39 +0800372 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
373 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000374 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100375 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800376 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000377 }
378 return blk;
379}
380
381
Chunyan Liu83d05212014-06-05 17:20:51 +0800382static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100383 const char *base_filename,
384 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200385{
Markus Armbruster6750e792015-02-12 17:43:08 +0100386 Error *err = NULL;
387
Kevin Wolfefa84d42009-05-18 16:42:12 +0200388 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100389 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100390 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100391 error_report("Backing file not supported for file format '%s'",
392 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100393 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900394 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200395 }
396 }
397 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100399 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100400 error_report("Backing file format not supported for file "
401 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100402 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900403 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200404 }
405 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900406 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200407}
408
Markus Armbruster606caa02017-02-21 21:14:04 +0100409static int64_t cvtnum(const char *s)
410{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100411 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100412 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100413
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100414 err = qemu_strtosz(s, NULL, &value);
415 if (err < 0) {
416 return err;
417 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100418 if (value > INT64_MAX) {
419 return -ERANGE;
420 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100421 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100422}
423
bellardea2384d2004-08-01 21:59:26 +0000424static int img_create(int argc, char **argv)
425{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200426 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100427 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000428 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000429 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000430 const char *filename;
431 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200432 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200433 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100434 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400435 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000436
bellardea2384d2004-08-01 21:59:26 +0000437 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000438 static const struct option long_options[] = {
439 {"help", no_argument, 0, 'h'},
440 {"object", required_argument, 0, OPTION_OBJECT},
441 {0, 0, 0, 0}
442 };
John Snow6e6e55f2017-07-17 20:34:22 -0400443 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000444 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100445 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000446 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100447 }
bellardea2384d2004-08-01 21:59:26 +0000448 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800449 case ':':
450 missing_argument(argv[optind - 1]);
451 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100452 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800453 unrecognized_option(argv[optind - 1]);
454 break;
bellardea2384d2004-08-01 21:59:26 +0000455 case 'h':
456 help();
457 break;
aliguori9230eaf2009-03-28 17:55:19 +0000458 case 'F':
459 base_fmt = optarg;
460 break;
bellardea2384d2004-08-01 21:59:26 +0000461 case 'b':
462 base_filename = optarg;
463 break;
464 case 'f':
465 fmt = optarg;
466 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200467 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100468 if (!is_valid_option_list(optarg)) {
469 error_report("Invalid option list: %s", optarg);
470 goto fail;
471 }
472 if (!options) {
473 options = g_strdup(optarg);
474 } else {
475 char *old_options = options;
476 options = g_strdup_printf("%s,%s", options, optarg);
477 g_free(old_options);
478 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200479 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100480 case 'q':
481 quiet = true;
482 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400483 case 'u':
484 flags |= BDRV_O_NO_BACKING;
485 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000486 case OPTION_OBJECT: {
487 QemuOpts *opts;
488 opts = qemu_opts_parse_noisily(&qemu_object_opts,
489 optarg, true);
490 if (!opts) {
491 goto fail;
492 }
493 } break;
bellardea2384d2004-08-01 21:59:26 +0000494 }
495 }
aliguori9230eaf2009-03-28 17:55:19 +0000496
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900497 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100498 filename = (optind < argc) ? argv[optind] : NULL;
499 if (options && has_help_option(options)) {
500 g_free(options);
501 return print_block_option_help(filename, fmt);
502 }
503
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100504 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800505 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100506 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100507 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900508
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000509 if (qemu_opts_foreach(&qemu_object_opts,
510 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200511 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000512 goto fail;
513 }
514
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100515 /* Get image size, if specified */
516 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100517 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100518
519 sval = cvtnum(argv[optind++]);
520 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800521 if (sval == -ERANGE) {
522 error_report("Image size must be less than 8 EiB!");
523 } else {
524 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200525 "G, T, P or E suffixes for ");
526 error_report("kilobytes, megabytes, gigabytes, terabytes, "
527 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800528 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100529 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100530 }
531 img_size = (uint64_t)sval;
532 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200533 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800534 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200535 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100536
Luiz Capitulino9b375252012-11-30 10:52:05 -0200537 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400538 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100539 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100540 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100541 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900542 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200543
Kevin Wolf77386bf2014-02-21 16:24:04 +0100544 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000545 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546
547fail:
548 g_free(options);
549 return 1;
bellardea2384d2004-08-01 21:59:26 +0000550}
551
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100552static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500553{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500554 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500555 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100556 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600557
558 visit_type_ImageCheck(v, NULL, &check, &error_abort);
559 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500560 str = qobject_to_json_pretty(obj);
561 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100562 qprintf(quiet, "%s\n", qstring_get_str(str));
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500563 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600564 visit_free(v);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 QDECREF(str);
566}
567
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100568static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500569{
570 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100571 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572 } else {
573 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100574 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
575 "Data may be corrupted, or further writes to the image "
576 "may corrupt it.\n",
577 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578 }
579
580 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100581 qprintf(quiet,
582 "\n%" PRId64 " leaked clusters were found on the image.\n"
583 "This means waste of disk space, but no harm to data.\n",
584 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585 }
586
587 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100588 qprintf(quiet,
589 "\n%" PRId64
590 " internal errors have occurred during the check.\n",
591 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500592 }
593 }
594
595 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100596 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
597 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
598 check->allocated_clusters, check->total_clusters,
599 check->allocated_clusters * 100.0 / check->total_clusters,
600 check->fragmented_clusters * 100.0 / check->allocated_clusters,
601 check->compressed_clusters * 100.0 /
602 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 }
604
605 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100606 qprintf(quiet,
607 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 }
609}
610
611static int collect_image_check(BlockDriverState *bs,
612 ImageCheck *check,
613 const char *filename,
614 const char *fmt,
615 int fix)
616{
617 int ret;
618 BdrvCheckResult result;
619
620 ret = bdrv_check(bs, &result, fix);
621 if (ret < 0) {
622 return ret;
623 }
624
625 check->filename = g_strdup(filename);
626 check->format = g_strdup(bdrv_get_format_name(bs));
627 check->check_errors = result.check_errors;
628 check->corruptions = result.corruptions;
629 check->has_corruptions = result.corruptions != 0;
630 check->leaks = result.leaks;
631 check->has_leaks = result.leaks != 0;
632 check->corruptions_fixed = result.corruptions_fixed;
633 check->has_corruptions_fixed = result.corruptions != 0;
634 check->leaks_fixed = result.leaks_fixed;
635 check->has_leaks_fixed = result.leaks != 0;
636 check->image_end_offset = result.image_end_offset;
637 check->has_image_end_offset = result.image_end_offset != 0;
638 check->total_clusters = result.bfi.total_clusters;
639 check->has_total_clusters = result.bfi.total_clusters != 0;
640 check->allocated_clusters = result.bfi.allocated_clusters;
641 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
642 check->fragmented_clusters = result.bfi.fragmented_clusters;
643 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100644 check->compressed_clusters = result.bfi.compressed_clusters;
645 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500646
647 return 0;
648}
649
Kevin Wolfe076f332010-06-29 11:43:13 +0200650/*
651 * Checks an image for consistency. Exit codes:
652 *
Max Reitzd6635c42014-06-02 22:15:21 +0200653 * 0 - Check completed, image is good
654 * 1 - Check not completed because of internal errors
655 * 2 - Check completed, image is corrupted
656 * 3 - Check completed, image has leaked clusters, but is good otherwise
657 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200658 */
aliguori15859692009-04-21 23:11:53 +0000659static int img_check(int argc, char **argv)
660{
661 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500662 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200663 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200664 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000665 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200666 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100667 int flags = BDRV_O_CHECK;
668 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200669 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100670 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000671 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800672 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000673
674 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500675 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200676 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100677
aliguori15859692009-04-21 23:11:53 +0000678 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 int option_index = 0;
680 static const struct option long_options[] = {
681 {"help", no_argument, 0, 'h'},
682 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530683 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000685 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000686 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800687 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500688 {0, 0, 0, 0}
689 };
Fam Zheng335e9932017-05-03 00:35:39 +0800690 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500691 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100692 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000693 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100694 }
aliguori15859692009-04-21 23:11:53 +0000695 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800696 case ':':
697 missing_argument(argv[optind - 1]);
698 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100699 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800700 unrecognized_option(argv[optind - 1]);
701 break;
aliguori15859692009-04-21 23:11:53 +0000702 case 'h':
703 help();
704 break;
705 case 'f':
706 fmt = optarg;
707 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200708 case 'r':
709 flags |= BDRV_O_RDWR;
710
711 if (!strcmp(optarg, "leaks")) {
712 fix = BDRV_FIX_LEAKS;
713 } else if (!strcmp(optarg, "all")) {
714 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
715 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800716 error_exit("Unknown option value for -r "
717 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200718 }
719 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500720 case OPTION_OUTPUT:
721 output = optarg;
722 break;
Max Reitz40055952014-07-22 22:58:42 +0200723 case 'T':
724 cache = optarg;
725 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100726 case 'q':
727 quiet = true;
728 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800729 case 'U':
730 force_share = true;
731 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000732 case OPTION_OBJECT: {
733 QemuOpts *opts;
734 opts = qemu_opts_parse_noisily(&qemu_object_opts,
735 optarg, true);
736 if (!opts) {
737 return 1;
738 }
739 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000740 case OPTION_IMAGE_OPTS:
741 image_opts = true;
742 break;
aliguori15859692009-04-21 23:11:53 +0000743 }
744 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200745 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800746 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100747 }
aliguori15859692009-04-21 23:11:53 +0000748 filename = argv[optind++];
749
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500750 if (output && !strcmp(output, "json")) {
751 output_format = OFORMAT_JSON;
752 } else if (output && !strcmp(output, "human")) {
753 output_format = OFORMAT_HUMAN;
754 } else if (output) {
755 error_report("--output must be used with human or json as argument.");
756 return 1;
757 }
758
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000759 if (qemu_opts_foreach(&qemu_object_opts,
760 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200761 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000762 return 1;
763 }
764
Kevin Wolfce099542016-03-15 13:01:04 +0100765 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200766 if (ret < 0) {
767 error_report("Invalid source cache option: %s", cache);
768 return 1;
769 }
770
Fam Zheng335e9932017-05-03 00:35:39 +0800771 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
772 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200773 if (!blk) {
774 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900775 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200776 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500777
778 check = g_new0(ImageCheck, 1);
779 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200780
781 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200782 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200783 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500784 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200785 }
786
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500787 if (check->corruptions_fixed || check->leaks_fixed) {
788 int corruptions_fixed, leaks_fixed;
789
790 leaks_fixed = check->leaks_fixed;
791 corruptions_fixed = check->corruptions_fixed;
792
793 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100794 qprintf(quiet,
795 "The following inconsistencies were found and repaired:\n\n"
796 " %" PRId64 " leaked clusters\n"
797 " %" PRId64 " corruptions\n\n"
798 "Double checking the fixed image now...\n",
799 check->leaks_fixed,
800 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500801 }
802
803 ret = collect_image_check(bs, check, filename, fmt, 0);
804
805 check->leaks_fixed = leaks_fixed;
806 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200807 }
808
Max Reitz832390a2014-10-23 15:29:12 +0200809 if (!ret) {
810 switch (output_format) {
811 case OFORMAT_HUMAN:
812 dump_human_image_check(check, quiet);
813 break;
814 case OFORMAT_JSON:
815 dump_json_image_check(check, quiet);
816 break;
817 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500818 }
819
820 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200821 if (ret) {
822 error_report("Check failed: %s", strerror(-ret));
823 } else {
824 error_report("Check failed");
825 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826 ret = 1;
827 goto fail;
828 }
829
830 if (check->corruptions) {
831 ret = 2;
832 } else if (check->leaks) {
833 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200834 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000836 }
837
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500838fail:
839 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200840 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500841 return ret;
aliguori15859692009-04-21 23:11:53 +0000842}
843
Max Reitzd4a32382014-10-24 15:57:37 +0200844typedef struct CommonBlockJobCBInfo {
845 BlockDriverState *bs;
846 Error **errp;
847} CommonBlockJobCBInfo;
848
849static void common_block_job_cb(void *opaque, int ret)
850{
851 CommonBlockJobCBInfo *cbi = opaque;
852
853 if (ret < 0) {
854 error_setg_errno(cbi->errp, -ret, "Block job failed");
855 }
Max Reitzd4a32382014-10-24 15:57:37 +0200856}
857
858static void run_block_job(BlockJob *job, Error **errp)
859{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200860 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800861 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200862
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200863 aio_context_acquire(aio_context);
sochin.jiang4172a002017-06-15 14:47:33 +0800864 block_job_ref(job);
Max Reitzd4a32382014-10-24 15:57:37 +0200865 do {
866 aio_poll(aio_context, true);
John Snow62547b82015-11-02 18:28:20 -0500867 qemu_progress_print(job->len ?
868 ((float)job->offset / job->len * 100.f) : 0.0f, 0);
sochin.jiang4172a002017-06-15 14:47:33 +0800869 } while (!job->ready && !job->completed);
Max Reitzd4a32382014-10-24 15:57:37 +0200870
sochin.jiang4172a002017-06-15 14:47:33 +0800871 if (!job->completed) {
872 ret = block_job_complete_sync(job, errp);
873 } else {
874 ret = job->ret;
875 }
876 block_job_unref(job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200877 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200878
sochin.jiang4172a002017-06-15 14:47:33 +0800879 /* publish completion progress only when success */
880 if (!ret) {
881 qemu_progress_print(100.f, 0);
882 }
Max Reitzd4a32382014-10-24 15:57:37 +0200883}
884
bellardea2384d2004-08-01 21:59:26 +0000885static int img_commit(int argc, char **argv)
886{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400887 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200888 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200889 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200890 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100891 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200892 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100893 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200894 Error *local_err = NULL;
895 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000896 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200897 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000898
899 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400900 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200901 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000902 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000903 static const struct option long_options[] = {
904 {"help", no_argument, 0, 'h'},
905 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000906 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000907 {0, 0, 0, 0}
908 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800909 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000910 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100911 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000912 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100913 }
bellardea2384d2004-08-01 21:59:26 +0000914 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800915 case ':':
916 missing_argument(argv[optind - 1]);
917 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100918 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800919 unrecognized_option(argv[optind - 1]);
920 break;
bellardea2384d2004-08-01 21:59:26 +0000921 case 'h':
922 help();
923 break;
924 case 'f':
925 fmt = optarg;
926 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400927 case 't':
928 cache = optarg;
929 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200930 case 'b':
931 base = optarg;
932 /* -b implies -d */
933 drop = true;
934 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200935 case 'd':
936 drop = true;
937 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200938 case 'p':
939 progress = true;
940 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100941 case 'q':
942 quiet = true;
943 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000944 case OPTION_OBJECT: {
945 QemuOpts *opts;
946 opts = qemu_opts_parse_noisily(&qemu_object_opts,
947 optarg, true);
948 if (!opts) {
949 return 1;
950 }
951 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000952 case OPTION_IMAGE_OPTS:
953 image_opts = true;
954 break;
bellardea2384d2004-08-01 21:59:26 +0000955 }
956 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200957
958 /* Progress is not shown in Quiet mode */
959 if (quiet) {
960 progress = false;
961 }
962
Kevin Wolffc11eb22013-08-05 10:53:04 +0200963 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800964 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100965 }
bellardea2384d2004-08-01 21:59:26 +0000966 filename = argv[optind++];
967
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000968 if (qemu_opts_foreach(&qemu_object_opts,
969 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200970 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000971 return 1;
972 }
973
Max Reitz9a86fe42014-10-24 15:57:38 +0200974 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100975 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400976 if (ret < 0) {
977 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100978 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400979 }
980
Fam Zheng335e9932017-05-03 00:35:39 +0800981 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
982 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200983 if (!blk) {
984 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900985 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200986 bs = blk_bs(blk);
987
Max Reitz687fa1d2014-10-24 15:57:39 +0200988 qemu_progress_init(progress, 1.f);
989 qemu_progress_print(0.f, 100);
990
Max Reitz1b22bff2014-10-24 15:57:40 +0200991 if (base) {
992 base_bs = bdrv_find_backing_image(bs, base);
993 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100994 error_setg(&local_err,
995 "Did not find '%s' in the backing chain of '%s'",
996 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200997 goto done;
998 }
999 } else {
1000 /* This is different from QMP, which by default uses the deepest file in
1001 * the backing chain (i.e., the very base); however, the traditional
1002 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001003 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001004 if (!base_bs) {
1005 error_setg(&local_err, "Image does not have a backing file");
1006 goto done;
1007 }
bellardea2384d2004-08-01 21:59:26 +00001008 }
1009
Max Reitzd4a32382014-10-24 15:57:37 +02001010 cbi = (CommonBlockJobCBInfo){
1011 .errp = &local_err,
1012 .bs = bs,
1013 };
1014
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001015 aio_context = bdrv_get_aio_context(bs);
1016 aio_context_acquire(aio_context);
John Snow47970df2016-10-27 12:06:57 -04001017 commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001018 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001019 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001020 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001021 if (local_err) {
1022 goto done;
1023 }
1024
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001025 /* When the block job completes, the BlockBackend reference will point to
1026 * the old backing file. In order to avoid that the top image is already
1027 * deleted, so we can still empty it afterwards, increment the reference
1028 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001029 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001030 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001031 }
1032
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001033 job = block_job_get("commit");
1034 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001035 if (local_err) {
1036 goto unref_backing;
1037 }
1038
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001039 if (!drop && bs->drv->bdrv_make_empty) {
1040 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001041 if (ret) {
1042 error_setg_errno(&local_err, -ret, "Could not empty %s",
1043 filename);
1044 goto unref_backing;
1045 }
1046 }
1047
1048unref_backing:
1049 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001050 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001051 }
Max Reitzd4a32382014-10-24 15:57:37 +02001052
1053done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001054 qemu_progress_end();
1055
Markus Armbruster26f54e92014-10-07 13:59:04 +02001056 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001057
1058 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001059 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001060 return 1;
1061 }
Max Reitzd4a32382014-10-24 15:57:37 +02001062
1063 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001064 return 0;
1065}
1066
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001067/*
thsf58c7b32008-06-05 21:53:49 +00001068 * Returns true iff the first sector pointed to by 'buf' contains at least
1069 * a non-NUL byte.
1070 *
1071 * 'pnum' is set to the number of sectors (including and immediately following
1072 * the first one) that are known to be in the same allocated/unallocated state.
1073 */
bellardea2384d2004-08-01 21:59:26 +00001074static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1075{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001076 bool is_zero;
1077 int i;
bellardea2384d2004-08-01 21:59:26 +00001078
1079 if (n <= 0) {
1080 *pnum = 0;
1081 return 0;
1082 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001083 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001084 for(i = 1; i < n; i++) {
1085 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001086 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001087 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001088 }
bellardea2384d2004-08-01 21:59:26 +00001089 }
1090 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001091 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001092}
1093
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001094/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001095 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1096 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1097 * breaking up write requests for only small sparse areas.
1098 */
1099static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1100 int min)
1101{
1102 int ret;
1103 int num_checked, num_used;
1104
1105 if (n < min) {
1106 min = n;
1107 }
1108
1109 ret = is_allocated_sectors(buf, n, pnum);
1110 if (!ret) {
1111 return ret;
1112 }
1113
1114 num_used = *pnum;
1115 buf += BDRV_SECTOR_SIZE * *pnum;
1116 n -= *pnum;
1117 num_checked = num_used;
1118
1119 while (n > 0) {
1120 ret = is_allocated_sectors(buf, n, pnum);
1121
1122 buf += BDRV_SECTOR_SIZE * *pnum;
1123 n -= *pnum;
1124 num_checked += *pnum;
1125 if (ret) {
1126 num_used = num_checked;
1127 } else if (*pnum >= min) {
1128 break;
1129 }
1130 }
1131
1132 *pnum = num_used;
1133 return 1;
1134}
1135
1136/*
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001137 * Compares two buffers sector by sector. Returns 0 if the first sector of both
1138 * buffers matches, non-zero otherwise.
1139 *
1140 * pnum is set to the number of sectors (including and immediately following
1141 * the first one) that are known to have the same comparison result
1142 */
1143static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
1144 int *pnum)
1145{
Radim KrčmÔř8c1ac472015-02-20 17:06:15 +01001146 bool res;
1147 int i;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001148
1149 if (n <= 0) {
1150 *pnum = 0;
1151 return 0;
1152 }
1153
1154 res = !!memcmp(buf1, buf2, 512);
1155 for(i = 1; i < n; i++) {
1156 buf1 += 512;
1157 buf2 += 512;
1158
1159 if (!!memcmp(buf1, buf2, 512) != res) {
1160 break;
1161 }
1162 }
1163
1164 *pnum = i;
1165 return res;
1166}
1167
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001168#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001169
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001170static int64_t sectors_to_bytes(int64_t sectors)
1171{
1172 return sectors << BDRV_SECTOR_BITS;
1173}
1174
1175static int64_t sectors_to_process(int64_t total, int64_t from)
1176{
1177 return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
1178}
1179
1180/*
1181 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1182 *
1183 * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
1184 * data and negative value on error.
1185 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001186 * @param blk: BlockBackend for the image
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001187 * @param sect_num: Number of first sector to check
1188 * @param sect_count: Number of sectors to check
1189 * @param filename: Name of disk file we are checking (logging purpose)
1190 * @param buffer: Allocated buffer for storing read data
1191 * @param quiet: Flag for quiet mode
1192 */
Max Reitzf1d3cd72015-02-05 13:58:18 -05001193static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001194 int sect_count, const char *filename,
1195 uint8_t *buffer, bool quiet)
1196{
1197 int pnum, ret = 0;
Eric Blake91669202016-05-06 10:26:43 -06001198 ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,
1199 sect_count << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001200 if (ret < 0) {
1201 error_report("Error while reading offset %" PRId64 " of %s: %s",
1202 sectors_to_bytes(sect_num), filename, strerror(-ret));
1203 return ret;
1204 }
1205 ret = is_allocated_sectors(buffer, sect_count, &pnum);
1206 if (ret || pnum != sect_count) {
1207 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1208 sectors_to_bytes(ret ? sect_num : sect_num + pnum));
1209 return 1;
1210 }
1211
1212 return 0;
1213}
1214
1215/*
1216 * Compares two images. Exit codes:
1217 *
1218 * 0 - Images are identical
1219 * 1 - Images differ
1220 * >1 - Error occurred
1221 */
1222static int img_compare(int argc, char **argv)
1223{
Max Reitz40055952014-07-22 22:58:42 +02001224 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001225 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001226 BlockDriverState *bs1, *bs2;
1227 int64_t total_sectors1, total_sectors2;
1228 uint8_t *buf1 = NULL, *buf2 = NULL;
1229 int pnum1, pnum2;
1230 int allocated1, allocated2;
1231 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1232 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001233 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001234 bool writethrough;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001235 int64_t total_sectors;
1236 int64_t sector_num = 0;
1237 int64_t nb_sectors;
1238 int c, pnum;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001239 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001240 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001241 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242
Max Reitz40055952014-07-22 22:58:42 +02001243 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001245 static const struct option long_options[] = {
1246 {"help", no_argument, 0, 'h'},
1247 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001248 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001249 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001250 {0, 0, 0, 0}
1251 };
Fam Zheng335e9932017-05-03 00:35:39 +08001252 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001253 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001254 if (c == -1) {
1255 break;
1256 }
1257 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001258 case ':':
1259 missing_argument(argv[optind - 1]);
1260 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001262 unrecognized_option(argv[optind - 1]);
1263 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001264 case 'h':
1265 help();
1266 break;
1267 case 'f':
1268 fmt1 = optarg;
1269 break;
1270 case 'F':
1271 fmt2 = optarg;
1272 break;
Max Reitz40055952014-07-22 22:58:42 +02001273 case 'T':
1274 cache = optarg;
1275 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 case 'p':
1277 progress = true;
1278 break;
1279 case 'q':
1280 quiet = true;
1281 break;
1282 case 's':
1283 strict = true;
1284 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001285 case 'U':
1286 force_share = true;
1287 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001288 case OPTION_OBJECT: {
1289 QemuOpts *opts;
1290 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1291 optarg, true);
1292 if (!opts) {
1293 ret = 2;
1294 goto out4;
1295 }
1296 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001297 case OPTION_IMAGE_OPTS:
1298 image_opts = true;
1299 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001300 }
1301 }
1302
1303 /* Progress is not shown in Quiet mode */
1304 if (quiet) {
1305 progress = false;
1306 }
1307
1308
Kevin Wolffc11eb22013-08-05 10:53:04 +02001309 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001310 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 }
1312 filename1 = argv[optind++];
1313 filename2 = argv[optind++];
1314
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001315 if (qemu_opts_foreach(&qemu_object_opts,
1316 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001317 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001318 ret = 2;
1319 goto out4;
1320 }
1321
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001322 /* Initialize before goto out */
1323 qemu_progress_init(progress, 2.0);
1324
Kevin Wolfce099542016-03-15 13:01:04 +01001325 flags = 0;
1326 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001327 if (ret < 0) {
1328 error_report("Invalid source cache option: %s", cache);
1329 ret = 2;
1330 goto out3;
1331 }
1332
Fam Zheng335e9932017-05-03 00:35:39 +08001333 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1334 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001335 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001336 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001337 goto out3;
1338 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001339
Fam Zheng335e9932017-05-03 00:35:39 +08001340 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1341 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001342 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001343 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001344 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001346 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001347 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348
Max Reitzf1d3cd72015-02-05 13:58:18 -05001349 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1350 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
1351 total_sectors1 = blk_nb_sectors(blk1);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001352 if (total_sectors1 < 0) {
1353 error_report("Can't get size of %s: %s",
1354 filename1, strerror(-total_sectors1));
1355 ret = 4;
1356 goto out;
1357 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05001358 total_sectors2 = blk_nb_sectors(blk2);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001359 if (total_sectors2 < 0) {
1360 error_report("Can't get size of %s: %s",
1361 filename2, strerror(-total_sectors2));
1362 ret = 4;
1363 goto out;
1364 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001365 total_sectors = MIN(total_sectors1, total_sectors2);
1366 progress_base = MAX(total_sectors1, total_sectors2);
1367
1368 qemu_progress_print(0, 100);
1369
1370 if (strict && total_sectors1 != total_sectors2) {
1371 ret = 1;
1372 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1373 goto out;
1374 }
1375
1376 for (;;) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001377 int64_t status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001378
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001379 nb_sectors = sectors_to_process(total_sectors, sector_num);
1380 if (nb_sectors <= 0) {
1381 break;
1382 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001383 status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,
1384 total_sectors1 - sector_num,
Eric Blake298a1662017-10-11 22:46:57 -05001385 &pnum1, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001386 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001387 ret = 3;
1388 error_report("Sector allocation test failed for %s", filename1);
1389 goto out;
1390 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001391 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392
Fam Zheng25ad8e62016-01-13 16:37:41 +08001393 status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,
1394 total_sectors2 - sector_num,
Eric Blake298a1662017-10-11 22:46:57 -05001395 &pnum2, NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001396 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001397 ret = 3;
1398 error_report("Sector allocation test failed for %s", filename2);
1399 goto out;
1400 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001401 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
1402 if (pnum1) {
1403 nb_sectors = MIN(nb_sectors, pnum1);
1404 }
1405 if (pnum2) {
1406 nb_sectors = MIN(nb_sectors, pnum2);
1407 }
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001408
Fam Zheng25ad8e62016-01-13 16:37:41 +08001409 if (strict) {
1410 if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=
1411 (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {
1412 ret = 1;
1413 qprintf(quiet, "Strict mode: Offset %" PRId64
1414 " block status mismatch!\n",
1415 sectors_to_bytes(sector_num));
1416 goto out;
1417 }
1418 }
1419 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
1420 nb_sectors = MIN(pnum1, pnum2);
1421 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001422 if (allocated1) {
Eric Blake91669202016-05-06 10:26:43 -06001423 ret = blk_pread(blk1, sector_num << BDRV_SECTOR_BITS, buf1,
1424 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001425 if (ret < 0) {
1426 error_report("Error while reading offset %" PRId64 " of %s:"
1427 " %s", sectors_to_bytes(sector_num), filename1,
1428 strerror(-ret));
1429 ret = 4;
1430 goto out;
1431 }
Eric Blake91669202016-05-06 10:26:43 -06001432 ret = blk_pread(blk2, sector_num << BDRV_SECTOR_BITS, buf2,
1433 nb_sectors << BDRV_SECTOR_BITS);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434 if (ret < 0) {
1435 error_report("Error while reading offset %" PRId64
1436 " of %s: %s", sectors_to_bytes(sector_num),
1437 filename2, strerror(-ret));
1438 ret = 4;
1439 goto out;
1440 }
1441 ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
1442 if (ret || pnum != nb_sectors) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001443 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
1444 sectors_to_bytes(
1445 ret ? sector_num : sector_num + pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001446 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 goto out;
1448 }
1449 }
1450 } else {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451
1452 if (allocated1) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001453 ret = check_empty_sectors(blk1, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001454 filename1, buf1, quiet);
1455 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001456 ret = check_empty_sectors(blk2, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457 filename2, buf1, quiet);
1458 }
1459 if (ret) {
1460 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001461 error_report("Error while reading offset %" PRId64 ": %s",
1462 sectors_to_bytes(sector_num), strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001463 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001464 }
1465 goto out;
1466 }
1467 }
1468 sector_num += nb_sectors;
1469 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1470 }
1471
1472 if (total_sectors1 != total_sectors2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001473 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 int64_t total_sectors_over;
1475 const char *filename_over;
1476
1477 qprintf(quiet, "Warning: Image size mismatch!\n");
1478 if (total_sectors1 > total_sectors2) {
1479 total_sectors_over = total_sectors1;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001480 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 filename_over = filename1;
1482 } else {
1483 total_sectors_over = total_sectors2;
Max Reitzf1d3cd72015-02-05 13:58:18 -05001484 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001485 filename_over = filename2;
1486 }
1487
1488 for (;;) {
Eric Blake51b0a482017-07-07 07:44:59 -05001489 int64_t count;
1490
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 nb_sectors = sectors_to_process(total_sectors_over, sector_num);
1492 if (nb_sectors <= 0) {
1493 break;
1494 }
Eric Blake51b0a482017-07-07 07:44:59 -05001495 ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL,
1496 sector_num * BDRV_SECTOR_SIZE,
1497 nb_sectors * BDRV_SECTOR_SIZE,
1498 &count);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 if (ret < 0) {
1500 ret = 3;
1501 error_report("Sector allocation test failed for %s",
1502 filename_over);
1503 goto out;
1504
1505 }
Eric Blake51b0a482017-07-07 07:44:59 -05001506 /* TODO relax this once bdrv_is_allocated_above does not enforce
1507 * sector alignment */
1508 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1509 nb_sectors = count >> BDRV_SECTOR_BITS;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 if (ret) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001511 ret = check_empty_sectors(blk_over, sector_num, nb_sectors,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 filename_over, buf1, quiet);
1513 if (ret) {
1514 if (ret < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001515 error_report("Error while reading offset %" PRId64
1516 " of %s: %s", sectors_to_bytes(sector_num),
1517 filename_over, strerror(-ret));
Fam Zheng36452f12013-11-13 20:26:49 +08001518 ret = 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 }
1520 goto out;
1521 }
1522 }
1523 sector_num += nb_sectors;
1524 qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
1525 }
1526 }
1527
1528 qprintf(quiet, "Images are identical.\n");
1529 ret = 0;
1530
1531out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 qemu_vfree(buf1);
1533 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001534 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001536 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537out3:
1538 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001539out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 return ret;
1541}
1542
Kevin Wolf690c7302015-03-19 13:33:32 +01001543enum ImgConvertBlockStatus {
1544 BLK_DATA,
1545 BLK_ZERO,
1546 BLK_BACKING_FILE,
1547};
1548
Peter Lieven2d9187b2017-02-28 13:40:07 +01001549#define MAX_COROUTINES 16
1550
Kevin Wolf690c7302015-03-19 13:33:32 +01001551typedef struct ImgConvertState {
1552 BlockBackend **src;
1553 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001554 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001555 int64_t total_sectors;
1556 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001557 int64_t allocated_done;
1558 int64_t sector_num;
1559 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001560 enum ImgConvertBlockStatus status;
1561 int64_t sector_next_status;
1562 BlockBackend *target;
1563 bool has_zero_init;
1564 bool compressed;
1565 bool target_has_backing;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001566 bool wr_in_order;
Kevin Wolf690c7302015-03-19 13:33:32 +01001567 int min_sparse;
1568 size_t cluster_sectors;
1569 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001570 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001571 int running_coroutines;
1572 Coroutine *co[MAX_COROUTINES];
1573 int64_t wait_sector_num[MAX_COROUTINES];
1574 CoMutex lock;
1575 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001576} ImgConvertState;
1577
Peter Lieven2d9187b2017-02-28 13:40:07 +01001578static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1579 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001580{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001581 *src_cur = 0;
1582 *src_cur_offset = 0;
1583 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1584 *src_cur_offset += s->src_sectors[*src_cur];
1585 (*src_cur)++;
1586 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001587 }
1588}
1589
1590static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1591{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001592 int64_t ret, src_cur_offset;
1593 int n, src_cur;
Kevin Wolf690c7302015-03-19 13:33:32 +01001594
Peter Lieven2d9187b2017-02-28 13:40:07 +01001595 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001596
1597 assert(s->total_sectors > sector_num);
1598 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1599
1600 if (s->sector_next_status <= sector_num) {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001601 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001602 int64_t count = n * BDRV_SECTOR_SIZE;
1603
1604 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1605 (sector_num - src_cur_offset) *
1606 BDRV_SECTOR_SIZE,
1607 count, &count, NULL, NULL);
1608 assert(ret < 0 || QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
1609 n = count >> BDRV_SECTOR_BITS;
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001610 } else {
1611 ret = bdrv_get_block_status_above(blk_bs(s->src[src_cur]), NULL,
1612 sector_num - src_cur_offset,
Eric Blake298a1662017-10-11 22:46:57 -05001613 n, &n, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001614 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001615 if (ret < 0) {
1616 return ret;
1617 }
1618
1619 if (ret & BDRV_BLOCK_ZERO) {
1620 s->status = BLK_ZERO;
1621 } else if (ret & BDRV_BLOCK_DATA) {
1622 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001623 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001624 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001625 }
1626
1627 s->sector_next_status = sector_num + n;
1628 }
1629
1630 n = MIN(n, s->sector_next_status - sector_num);
1631 if (s->status == BLK_DATA) {
1632 n = MIN(n, s->buf_sectors);
1633 }
1634
1635 /* We need to write complete clusters for compressed images, so if an
1636 * unallocated area is shorter than that, we must consider the whole
1637 * cluster allocated. */
1638 if (s->compressed) {
1639 if (n < s->cluster_sectors) {
1640 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1641 s->status = BLK_DATA;
1642 } else {
1643 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1644 }
1645 }
1646
1647 return n;
1648}
1649
Peter Lieven2d9187b2017-02-28 13:40:07 +01001650static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1651 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001652{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001653 int n, ret;
1654 QEMUIOVector qiov;
1655 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001656
Kevin Wolf690c7302015-03-19 13:33:32 +01001657 assert(nb_sectors <= s->buf_sectors);
1658 while (nb_sectors > 0) {
1659 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001660 int src_cur;
1661 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001662
1663 /* In the case of compression with multiple source files, we can get a
1664 * nb_sectors that spreads into the next part. So we must be able to
1665 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001666 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1667 blk = s->src[src_cur];
1668 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001669
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1671 iov.iov_base = buf;
1672 iov.iov_len = n << BDRV_SECTOR_BITS;
1673 qemu_iovec_init_external(&qiov, &iov, 1);
1674
1675 ret = blk_co_preadv(
1676 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1677 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001678 if (ret < 0) {
1679 return ret;
1680 }
1681
1682 sector_num += n;
1683 nb_sectors -= n;
1684 buf += n * BDRV_SECTOR_SIZE;
1685 }
1686
1687 return 0;
1688}
1689
Peter Lieven2d9187b2017-02-28 13:40:07 +01001690
1691static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1692 int nb_sectors, uint8_t *buf,
1693 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001694{
1695 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001696 QEMUIOVector qiov;
1697 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001698
1699 while (nb_sectors > 0) {
1700 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001701 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1702
Peter Lieven2d9187b2017-02-28 13:40:07 +01001703 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001704 case BLK_BACKING_FILE:
1705 /* If we have a backing file, leave clusters unallocated that are
1706 * unallocated in the source image, so that the backing file is
1707 * visible at the respective offset. */
1708 assert(s->target_has_backing);
1709 break;
1710
1711 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001712 /* If we're told to keep the target fully allocated (-S 0) or there
1713 * is real non-zero data, we must write it. Otherwise we can treat
1714 * it as zero sectors.
1715 * Compressed clusters need to be written as a whole, so in that
1716 * case we can only save the write if the buffer is completely
1717 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001718 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001719 (!s->compressed &&
1720 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1721 (s->compressed &&
1722 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001723 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001724 iov.iov_base = buf;
1725 iov.iov_len = n << BDRV_SECTOR_BITS;
1726 qemu_iovec_init_external(&qiov, &iov, 1);
1727
1728 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001729 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001730 if (ret < 0) {
1731 return ret;
1732 }
1733 break;
1734 }
1735 /* fall-through */
1736
1737 case BLK_ZERO:
1738 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001739 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001740 break;
1741 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001742 ret = blk_co_pwrite_zeroes(s->target,
1743 sector_num << BDRV_SECTOR_BITS,
1744 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001745 if (ret < 0) {
1746 return ret;
1747 }
1748 break;
1749 }
1750
1751 sector_num += n;
1752 nb_sectors -= n;
1753 buf += n * BDRV_SECTOR_SIZE;
1754 }
1755
1756 return 0;
1757}
1758
Peter Lieven2d9187b2017-02-28 13:40:07 +01001759static void coroutine_fn convert_co_do_copy(void *opaque)
1760{
1761 ImgConvertState *s = opaque;
1762 uint8_t *buf = NULL;
1763 int ret, i;
1764 int index = -1;
1765
1766 for (i = 0; i < s->num_coroutines; i++) {
1767 if (s->co[i] == qemu_coroutine_self()) {
1768 index = i;
1769 break;
1770 }
1771 }
1772 assert(index >= 0);
1773
1774 s->running_coroutines++;
1775 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1776
1777 while (1) {
1778 int n;
1779 int64_t sector_num;
1780 enum ImgConvertBlockStatus status;
1781
1782 qemu_co_mutex_lock(&s->lock);
1783 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1784 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001785 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001786 }
1787 n = convert_iteration_sectors(s, s->sector_num);
1788 if (n < 0) {
1789 qemu_co_mutex_unlock(&s->lock);
1790 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001791 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001792 }
1793 /* save current sector and allocation status to local variables */
1794 sector_num = s->sector_num;
1795 status = s->status;
1796 if (!s->min_sparse && s->status == BLK_ZERO) {
1797 n = MIN(n, s->buf_sectors);
1798 }
1799 /* increment global sector counter so that other coroutines can
1800 * already continue reading beyond this request */
1801 s->sector_num += n;
1802 qemu_co_mutex_unlock(&s->lock);
1803
1804 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1805 s->allocated_done += n;
1806 qemu_progress_print(100.0 * s->allocated_done /
1807 s->allocated_sectors, 0);
1808 }
1809
1810 if (status == BLK_DATA) {
1811 ret = convert_co_read(s, sector_num, n, buf);
1812 if (ret < 0) {
1813 error_report("error while reading sector %" PRId64
1814 ": %s", sector_num, strerror(-ret));
1815 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001816 }
1817 } else if (!s->min_sparse && status == BLK_ZERO) {
1818 status = BLK_DATA;
1819 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1820 }
1821
1822 if (s->wr_in_order) {
1823 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001824 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001825 s->wait_sector_num[index] = sector_num;
1826 qemu_coroutine_yield();
1827 }
1828 s->wait_sector_num[index] = -1;
1829 }
1830
Anton Nefedovb91127e2017-04-26 11:33:15 +03001831 if (s->ret == -EINPROGRESS) {
1832 ret = convert_co_write(s, sector_num, n, buf, status);
1833 if (ret < 0) {
1834 error_report("error while writing sector %" PRId64
1835 ": %s", sector_num, strerror(-ret));
1836 s->ret = ret;
1837 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001838 }
1839
1840 if (s->wr_in_order) {
1841 /* reenter the coroutine that might have waited
1842 * for this write to complete */
1843 s->wr_offs = sector_num + n;
1844 for (i = 0; i < s->num_coroutines; i++) {
1845 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1846 /*
1847 * A -> B -> A cannot occur because A has
1848 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1849 * B will never enter A during this time window.
1850 */
1851 qemu_coroutine_enter(s->co[i]);
1852 break;
1853 }
1854 }
1855 }
1856 }
1857
Peter Lieven2d9187b2017-02-28 13:40:07 +01001858 qemu_vfree(buf);
1859 s->co[index] = NULL;
1860 s->running_coroutines--;
1861 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1862 /* the convert job finished successfully */
1863 s->ret = 0;
1864 }
1865}
1866
Kevin Wolf690c7302015-03-19 13:33:32 +01001867static int convert_do_copy(ImgConvertState *s)
1868{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001869 int ret, i, n;
1870 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001871
1872 /* Check whether we have zero initialisation or can get it efficiently */
1873 s->has_zero_init = s->min_sparse && !s->target_has_backing
1874 ? bdrv_has_zero_init(blk_bs(s->target))
1875 : false;
1876
1877 if (!s->has_zero_init && !s->target_has_backing &&
1878 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1879 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001880 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001881 if (ret == 0) {
1882 s->has_zero_init = true;
1883 }
1884 }
1885
1886 /* Allocate buffer for copied data. For compressed images, only one cluster
1887 * can be copied at a time. */
1888 if (s->compressed) {
1889 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1890 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001891 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001892 }
1893 s->buf_sectors = s->cluster_sectors;
1894 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001895
Kevin Wolf690c7302015-03-19 13:33:32 +01001896 while (sector_num < s->total_sectors) {
1897 n = convert_iteration_sectors(s, sector_num);
1898 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001899 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001900 }
Max Reitzaad15de2016-03-24 23:33:57 +01001901 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1902 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001903 s->allocated_sectors += n;
1904 }
1905 sector_num += n;
1906 }
1907
1908 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001909 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001910 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001911
Peter Lieven2d9187b2017-02-28 13:40:07 +01001912 qemu_co_mutex_init(&s->lock);
1913 for (i = 0; i < s->num_coroutines; i++) {
1914 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1915 s->wait_sector_num[i] = -1;
1916 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001917 }
1918
Anton Nefedovb91127e2017-04-26 11:33:15 +03001919 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001920 main_loop_wait(false);
1921 }
1922
1923 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001924 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001925 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001926 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001927 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001928 }
1929 }
1930
Peter Lieven2d9187b2017-02-28 13:40:07 +01001931 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001932}
1933
bellardea2384d2004-08-01 21:59:26 +00001934static int img_convert(int argc, char **argv)
1935{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001936 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001937 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001938 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1939 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001940 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001941 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001942 BlockDriverState *out_bs;
1943 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001944 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001945 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001946 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001947 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001948 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001949 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08001950 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00001951
Peter Lieven9fd77f92017-04-21 11:11:55 +02001952 ImgConvertState s = (ImgConvertState) {
1953 /* Need at least 4k of zeros for sparse detection */
1954 .min_sparse = 8,
1955 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
1956 .wr_in_order = true,
1957 .num_coroutines = 8,
1958 };
1959
bellardea2384d2004-08-01 21:59:26 +00001960 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001961 static const struct option long_options[] = {
1962 {"help", no_argument, 0, 'h'},
1963 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001964 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001965 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001966 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001967 {0, 0, 0, 0}
1968 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01001969 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001970 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001971 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001972 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001973 }
bellardea2384d2004-08-01 21:59:26 +00001974 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001975 case ':':
1976 missing_argument(argv[optind - 1]);
1977 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001978 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001979 unrecognized_option(argv[optind - 1]);
1980 break;
bellardea2384d2004-08-01 21:59:26 +00001981 case 'h':
1982 help();
1983 break;
1984 case 'f':
1985 fmt = optarg;
1986 break;
1987 case 'O':
1988 out_fmt = optarg;
1989 break;
thsf58c7b32008-06-05 21:53:49 +00001990 case 'B':
1991 out_baseimg = optarg;
1992 break;
bellardea2384d2004-08-01 21:59:26 +00001993 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02001994 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00001995 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001996 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01001997 if (!is_valid_option_list(optarg)) {
1998 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01001999 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002000 }
2001 if (!options) {
2002 options = g_strdup(optarg);
2003 } else {
2004 char *old_options = options;
2005 options = g_strdup_printf("%s,%s", options, optarg);
2006 g_free(old_options);
2007 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002008 break;
edison51ef6722010-09-21 19:58:41 -07002009 case 's':
2010 snapshot_name = optarg;
2011 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002012 case 'l':
2013 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002014 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2015 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002016 if (!sn_opts) {
2017 error_report("Failed in parsing snapshot param '%s'",
2018 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002019 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002020 }
2021 } else {
2022 snapshot_name = optarg;
2023 }
2024 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002025 case 'S':
2026 {
2027 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002028
2029 sval = cvtnum(optarg);
2030 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002031 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002032 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002033 }
2034
Peter Lieven9fd77f92017-04-21 11:11:55 +02002035 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002036 break;
2037 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002038 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002039 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002040 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002041 case 't':
2042 cache = optarg;
2043 break;
Max Reitz40055952014-07-22 22:58:42 +02002044 case 'T':
2045 src_cache = optarg;
2046 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002047 case 'q':
2048 quiet = true;
2049 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002050 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002051 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002052 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002053 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002054 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2055 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002056 error_report("Invalid number of coroutines. Allowed number of"
2057 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002058 goto fail_getopt;
2059 }
2060 break;
2061 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002062 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002063 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002064 case 'U':
2065 force_share = true;
2066 break;
Max Reitz3258b912017-04-26 15:46:47 +02002067 case OPTION_OBJECT: {
2068 QemuOpts *object_opts;
2069 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2070 optarg, true);
2071 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002072 goto fail_getopt;
2073 }
2074 break;
Max Reitz3258b912017-04-26 15:46:47 +02002075 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002076 case OPTION_IMAGE_OPTS:
2077 image_opts = true;
2078 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002079 case OPTION_TARGET_IMAGE_OPTS:
2080 tgt_image_opts = true;
2081 break;
bellardea2384d2004-08-01 21:59:26 +00002082 }
2083 }
ths3b46e622007-09-17 08:09:54 +00002084
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002085 if (!out_fmt && !tgt_image_opts) {
2086 out_fmt = "raw";
2087 }
2088
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002089 if (qemu_opts_foreach(&qemu_object_opts,
2090 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002091 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002092 goto fail_getopt;
2093 }
2094
Peter Lieven9fd77f92017-04-21 11:11:55 +02002095 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002096 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002097 goto fail_getopt;
2098 }
2099
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002100 if (tgt_image_opts && !skip_create) {
2101 error_report("--target-image-opts requires use of -n flag");
2102 goto fail_getopt;
2103 }
2104
Peter Lieven9fd77f92017-04-21 11:11:55 +02002105 s.src_num = argc - optind - 1;
2106 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2107
2108 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002109 if (out_fmt) {
2110 ret = print_block_option_help(out_filename, out_fmt);
2111 goto fail_getopt;
2112 } else {
2113 error_report("Option help requires a format be specified");
2114 goto fail_getopt;
2115 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002116 }
2117
2118 if (s.src_num < 1) {
2119 error_report("Must specify image file name");
2120 goto fail_getopt;
2121 }
2122
2123
Peter Lieven9fd77f92017-04-21 11:11:55 +02002124 /* ret is still -EINVAL until here */
2125 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2126 if (ret < 0) {
2127 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 goto fail_getopt;
2129 }
2130
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002131 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002132 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002133 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002134 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002135 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002136 qemu_progress_print(0, 100);
2137
Peter Lieven9fd77f92017-04-21 11:11:55 +02002138 s.src = g_new0(BlockBackend *, s.src_num);
2139 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002140
Peter Lieven9fd77f92017-04-21 11:11:55 +02002141 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2142 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002143 fmt, src_flags, src_writethrough, quiet,
2144 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002145 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002146 ret = -1;
2147 goto out;
2148 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002149 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2150 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002151 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002152 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002153 ret = -1;
2154 goto out;
2155 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002156 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002157 }
bellardea2384d2004-08-01 21:59:26 +00002158
Wenchao Xiaef806542013-12-04 17:10:57 +08002159 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002160 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002161 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2162 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2163 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002164 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002165 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002166 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002167 ret = -1;
2168 goto out;
2169 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002170
Peter Lieven9fd77f92017-04-21 11:11:55 +02002171 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2172 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002173 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002174 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002175 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002176 ret = -1;
2177 goto out;
edison51ef6722010-09-21 19:58:41 -07002178 }
2179
Max Reitz2e024cd2015-02-11 09:58:46 -05002180 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002181 /* Find driver and parse its options */
2182 drv = bdrv_find_format(out_fmt);
2183 if (!drv) {
2184 error_report("Unknown file format '%s'", out_fmt);
2185 ret = -1;
2186 goto out;
2187 }
2188
2189 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2190 if (!proto_drv) {
2191 error_report_err(local_err);
2192 ret = -1;
2193 goto out;
2194 }
2195
Max Reitz2e024cd2015-02-11 09:58:46 -05002196 if (!drv->create_opts) {
2197 error_report("Format driver '%s' does not support image creation",
2198 drv->format_name);
2199 ret = -1;
2200 goto out;
2201 }
Max Reitzf75613c2014-12-02 18:32:46 +01002202
Max Reitz2e024cd2015-02-11 09:58:46 -05002203 if (!proto_drv->create_opts) {
2204 error_report("Protocol driver '%s' does not support image creation",
2205 proto_drv->format_name);
2206 ret = -1;
2207 goto out;
2208 }
Max Reitzf75613c2014-12-02 18:32:46 +01002209
Max Reitz2e024cd2015-02-11 09:58:46 -05002210 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2211 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002212
Max Reitz2e024cd2015-02-11 09:58:46 -05002213 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002214 if (options) {
2215 qemu_opts_do_parse(opts, options, NULL, &local_err);
2216 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002217 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002218 ret = -1;
2219 goto out;
2220 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002221 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002222
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002224 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002225 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2226 if (ret < 0) {
2227 goto out;
2228 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002229 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002230
Kevin Wolfa18953f2010-10-14 15:46:04 +02002231 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002232 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002233 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002234 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002235 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002236 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002237
Max Reitz48758a82017-04-26 15:46:48 +02002238 if (s.src_num > 1 && out_baseimg) {
2239 error_report("Having a backing file for the target makes no sense when "
2240 "concatenating multiple input images");
2241 ret = -1;
2242 goto out;
2243 }
2244
Kevin Wolfefa84d42009-05-18 16:42:12 +02002245 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002246 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002247 bool encryption =
2248 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002249 const char *encryptfmt =
2250 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002251 const char *preallocation =
2252 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002253
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002254 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002255 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002256 ret = -1;
2257 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002258 }
2259
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002260 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002261 error_report("Compression and encryption not supported at "
2262 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002263 ret = -1;
2264 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002265 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002266
Chunyan Liu83d05212014-06-05 17:20:51 +08002267 if (preallocation
2268 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002269 {
2270 error_report("Compression and preallocation not supported at "
2271 "the same time");
2272 ret = -1;
2273 goto out;
2274 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002275 }
2276
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002277 if (!skip_create) {
2278 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002279 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002280 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002281 error_reportf_err(local_err, "%s: error while converting %s: ",
2282 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002283 goto out;
bellardea2384d2004-08-01 21:59:26 +00002284 }
2285 }
ths3b46e622007-09-17 08:09:54 +00002286
Peter Lieven9fd77f92017-04-21 11:11:55 +02002287 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002288 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002289 if (ret < 0) {
2290 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002291 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002292 }
2293
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002294 if (skip_create) {
2295 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2296 flags, writethrough, quiet, false);
2297 } else {
2298 /* TODO ultimately we should allow --target-image-opts
2299 * to be used even when -n is not given.
2300 * That has to wait for bdrv_create to be improved
2301 * to allow filenames in option syntax
2302 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002303 s.target = img_open_new_file(out_filename, opts, out_fmt,
2304 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002305 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002306 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002307 ret = -1;
2308 goto out;
2309 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002310 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002311
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002312 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2313 error_report("Compression not supported for this file format");
2314 ret = -1;
2315 goto out;
2316 }
2317
Eric Blake5def6b82016-06-23 16:37:19 -06002318 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002319 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2320 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002321 s.buf_sectors = MIN(32768,
2322 MAX(s.buf_sectors,
2323 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2324 out_bs->bl.pdiscard_alignment >>
2325 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002326
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002327 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002328 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002329 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002330 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002331 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002332 ret = -1;
2333 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002334 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002335 error_report("output file is smaller than input file");
2336 ret = -1;
2337 goto out;
2338 }
2339 }
2340
Peter Lieven24f833c2013-11-27 11:07:07 +01002341 ret = bdrv_get_info(out_bs, &bdi);
2342 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002343 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002344 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002345 goto out;
2346 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002347 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002348 s.compressed = s.compressed || bdi.needs_compressed_writes;
2349 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002350 }
2351
Peter Lieven9fd77f92017-04-21 11:11:55 +02002352 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002353out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002354 if (!ret) {
2355 qemu_progress_print(100, 0);
2356 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002357 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002358 qemu_opts_del(opts);
2359 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002360 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002361 blk_unref(s.target);
2362 if (s.src) {
2363 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2364 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002365 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002366 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002367 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002368 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002369fail_getopt:
2370 g_free(options);
2371
Peter Lieven9fd77f92017-04-21 11:11:55 +02002372 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002373}
2374
bellard57d1a2b2004-08-03 21:15:11 +00002375
bellardfaea38e2006-08-05 21:31:00 +00002376static void dump_snapshots(BlockDriverState *bs)
2377{
2378 QEMUSnapshotInfo *sn_tab, *sn;
2379 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002380
2381 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2382 if (nb_sns <= 0)
2383 return;
2384 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002385 bdrv_snapshot_dump(fprintf, stdout, NULL);
2386 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002387 for(i = 0; i < nb_sns; i++) {
2388 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002389 bdrv_snapshot_dump(fprintf, stdout, sn);
2390 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002391 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002392 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002393}
2394
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002395static void dump_json_image_info_list(ImageInfoList *list)
2396{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002397 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002398 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002399 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002400
2401 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2402 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002403 str = qobject_to_json_pretty(obj);
2404 assert(str != NULL);
2405 printf("%s\n", qstring_get_str(str));
2406 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002407 visit_free(v);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002408 QDECREF(str);
2409}
2410
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002411static void dump_json_image_info(ImageInfo *info)
2412{
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002413 QString *str;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002414 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002415 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002416
2417 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2418 visit_complete(v, &obj);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002419 str = qobject_to_json_pretty(obj);
2420 assert(str != NULL);
2421 printf("%s\n", qstring_get_str(str));
2422 qobject_decref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002423 visit_free(v);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002424 QDECREF(str);
2425}
2426
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002427static void dump_human_image_info_list(ImageInfoList *list)
2428{
2429 ImageInfoList *elem;
2430 bool delim = false;
2431
2432 for (elem = list; elem; elem = elem->next) {
2433 if (delim) {
2434 printf("\n");
2435 }
2436 delim = true;
2437
Wenchao Xia5b917042013-05-25 11:09:45 +08002438 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002439 }
2440}
2441
2442static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2443{
2444 return strcmp(a, b) == 0;
2445}
2446
2447/**
2448 * Open an image file chain and return an ImageInfoList
2449 *
2450 * @filename: topmost image filename
2451 * @fmt: topmost image format (may be NULL to autodetect)
2452 * @chain: true - enumerate entire backing file chain
2453 * false - only topmost image file
2454 *
2455 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2456 * image file. If there was an error a message will have been printed to
2457 * stderr.
2458 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002459static ImageInfoList *collect_image_info_list(bool image_opts,
2460 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002461 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002462 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002463{
2464 ImageInfoList *head = NULL;
2465 ImageInfoList **last = &head;
2466 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002467 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002468
2469 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2470
2471 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002472 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002473 BlockDriverState *bs;
2474 ImageInfo *info;
2475 ImageInfoList *elem;
2476
2477 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2478 error_report("Backing file '%s' creates an infinite loop.",
2479 filename);
2480 goto err;
2481 }
2482 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2483
Max Reitzefaa7c42016-03-16 19:54:38 +01002484 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002485 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2486 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002487 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002488 goto err;
2489 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002490 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002491
Wenchao Xia43526ec2013-06-06 12:27:58 +08002492 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002493 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002494 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002495 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002496 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002497 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002498
2499 elem = g_new0(ImageInfoList, 1);
2500 elem->value = info;
2501 *last = elem;
2502 last = &elem->next;
2503
Markus Armbruster26f54e92014-10-07 13:59:04 +02002504 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505
2506 filename = fmt = NULL;
2507 if (chain) {
2508 if (info->has_full_backing_filename) {
2509 filename = info->full_backing_filename;
2510 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002511 error_report("Could not determine absolute backing filename,"
2512 " but backing filename '%s' present",
2513 info->backing_filename);
2514 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002515 }
2516 if (info->has_backing_filename_format) {
2517 fmt = info->backing_filename_format;
2518 }
2519 }
2520 }
2521 g_hash_table_destroy(filenames);
2522 return head;
2523
2524err:
2525 qapi_free_ImageInfoList(head);
2526 g_hash_table_destroy(filenames);
2527 return NULL;
2528}
2529
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002530static int img_info(int argc, char **argv)
2531{
2532 int c;
2533 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002534 bool chain = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002535 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002536 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002537 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002538 bool force_share = false;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002539
bellardea2384d2004-08-01 21:59:26 +00002540 fmt = NULL;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002541 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002542 for(;;) {
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002543 int option_index = 0;
2544 static const struct option long_options[] = {
2545 {"help", no_argument, 0, 'h'},
2546 {"format", required_argument, 0, 'f'},
2547 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002548 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002549 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002550 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002551 {"force-share", no_argument, 0, 'U'},
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002552 {0, 0, 0, 0}
2553 };
Fam Zheng335e9932017-05-03 00:35:39 +08002554 c = getopt_long(argc, argv, ":f:hU",
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002555 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002556 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002557 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002558 }
bellardea2384d2004-08-01 21:59:26 +00002559 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002560 case ':':
2561 missing_argument(argv[optind - 1]);
2562 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002563 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002564 unrecognized_option(argv[optind - 1]);
2565 break;
bellardea2384d2004-08-01 21:59:26 +00002566 case 'h':
2567 help();
2568 break;
2569 case 'f':
2570 fmt = optarg;
2571 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002572 case 'U':
2573 force_share = true;
2574 break;
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002575 case OPTION_OUTPUT:
2576 output = optarg;
2577 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002578 case OPTION_BACKING_CHAIN:
2579 chain = true;
2580 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002581 case OPTION_OBJECT: {
2582 QemuOpts *opts;
2583 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2584 optarg, true);
2585 if (!opts) {
2586 return 1;
2587 }
2588 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002589 case OPTION_IMAGE_OPTS:
2590 image_opts = true;
2591 break;
bellardea2384d2004-08-01 21:59:26 +00002592 }
2593 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002594 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002595 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002596 }
bellardea2384d2004-08-01 21:59:26 +00002597 filename = argv[optind++];
2598
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002599 if (output && !strcmp(output, "json")) {
2600 output_format = OFORMAT_JSON;
2601 } else if (output && !strcmp(output, "human")) {
2602 output_format = OFORMAT_HUMAN;
2603 } else if (output) {
2604 error_report("--output must be used with human or json as argument.");
2605 return 1;
2606 }
2607
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002608 if (qemu_opts_foreach(&qemu_object_opts,
2609 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002610 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002611 return 1;
2612 }
2613
Fam Zheng335e9932017-05-03 00:35:39 +08002614 list = collect_image_info_list(image_opts, filename, fmt, chain,
2615 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002616 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002617 return 1;
2618 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002619
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002620 switch (output_format) {
2621 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002622 dump_human_image_info_list(list);
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002623 break;
2624 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002625 if (chain) {
2626 dump_json_image_info_list(list);
2627 } else {
2628 dump_json_image_info(list->value);
2629 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002630 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002631 }
BenoƮt Canetc054b3f2012-09-05 13:09:02 +02002632
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002633 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002634 return 0;
2635}
2636
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002637static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2638 MapEntry *next)
2639{
2640 switch (output_format) {
2641 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002642 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002643 error_report("File contains external, encrypted or compressed clusters.");
2644 exit(1);
2645 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002646 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002647 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002648 e->start, e->length,
2649 e->has_offset ? e->offset : 0,
2650 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002651 }
2652 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2653 * Modify the flags here to allow more coalescing.
2654 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002655 if (next && (!next->data || next->zero)) {
2656 next->data = false;
2657 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002658 }
2659 break;
2660 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002661 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2662 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002663 (e->start == 0 ? "[" : ",\n"),
2664 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002665 e->zero ? "true" : "false",
2666 e->data ? "true" : "false");
2667 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002668 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002669 }
2670 putchar('}');
2671
2672 if (!next) {
2673 printf("]\n");
2674 }
2675 break;
2676 }
2677}
2678
Eric Blake5e344dd2017-10-11 22:47:02 -05002679static int get_block_status(BlockDriverState *bs, int64_t offset,
2680 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002681{
Eric Blake237d78f2017-10-11 22:47:03 -05002682 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002683 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002684 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002685 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002686 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002687
2688 /* As an optimization, we could cache the current range of unallocated
2689 * clusters in each file of the chain, and avoid querying the same
2690 * range repeatedly.
2691 */
2692
2693 depth = 0;
2694 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002695 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002696 if (ret < 0) {
2697 return ret;
2698 }
Eric Blake237d78f2017-10-11 22:47:03 -05002699 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002700 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2701 break;
2702 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002703 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002704 if (bs == NULL) {
2705 ret = 0;
2706 break;
2707 }
2708
2709 depth++;
2710 }
2711
John Snow28756452016-02-05 13:12:33 -05002712 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2713
2714 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002715 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002716 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002717 .data = !!(ret & BDRV_BLOCK_DATA),
2718 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002719 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002720 .has_offset = has_offset,
2721 .depth = depth,
2722 .has_filename = file && has_offset,
2723 .filename = file && has_offset ? file->filename : NULL,
2724 };
2725
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002726 return 0;
2727}
2728
Fam Zheng16b0d552016-01-26 11:59:02 +08002729static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2730{
2731 if (curr->length == 0) {
2732 return false;
2733 }
2734 if (curr->zero != next->zero ||
2735 curr->data != next->data ||
2736 curr->depth != next->depth ||
2737 curr->has_filename != next->has_filename ||
2738 curr->has_offset != next->has_offset) {
2739 return false;
2740 }
2741 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2742 return false;
2743 }
2744 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2745 return false;
2746 }
2747 return true;
2748}
2749
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002750static int img_map(int argc, char **argv)
2751{
2752 int c;
2753 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002754 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002755 BlockDriverState *bs;
2756 const char *filename, *fmt, *output;
2757 int64_t length;
2758 MapEntry curr = { .length = 0 }, next;
2759 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002760 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002761 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002762
2763 fmt = NULL;
2764 output = NULL;
2765 for (;;) {
2766 int option_index = 0;
2767 static const struct option long_options[] = {
2768 {"help", no_argument, 0, 'h'},
2769 {"format", required_argument, 0, 'f'},
2770 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002771 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002772 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002773 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002774 {0, 0, 0, 0}
2775 };
Fam Zheng335e9932017-05-03 00:35:39 +08002776 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002777 long_options, &option_index);
2778 if (c == -1) {
2779 break;
2780 }
2781 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002782 case ':':
2783 missing_argument(argv[optind - 1]);
2784 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002785 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002786 unrecognized_option(argv[optind - 1]);
2787 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002788 case 'h':
2789 help();
2790 break;
2791 case 'f':
2792 fmt = optarg;
2793 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002794 case 'U':
2795 force_share = true;
2796 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002797 case OPTION_OUTPUT:
2798 output = optarg;
2799 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002800 case OPTION_OBJECT: {
2801 QemuOpts *opts;
2802 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2803 optarg, true);
2804 if (!opts) {
2805 return 1;
2806 }
2807 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002808 case OPTION_IMAGE_OPTS:
2809 image_opts = true;
2810 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002811 }
2812 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002813 if (optind != argc - 1) {
2814 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002815 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002816 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002817
2818 if (output && !strcmp(output, "json")) {
2819 output_format = OFORMAT_JSON;
2820 } else if (output && !strcmp(output, "human")) {
2821 output_format = OFORMAT_HUMAN;
2822 } else if (output) {
2823 error_report("--output must be used with human or json as argument.");
2824 return 1;
2825 }
2826
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002827 if (qemu_opts_foreach(&qemu_object_opts,
2828 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002829 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002830 return 1;
2831 }
2832
Fam Zheng335e9932017-05-03 00:35:39 +08002833 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002834 if (!blk) {
2835 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002836 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002837 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002838
2839 if (output_format == OFORMAT_HUMAN) {
2840 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2841 }
2842
Max Reitzf1d3cd72015-02-05 13:58:18 -05002843 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002844 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002845 int64_t offset = curr.start + curr.length;
2846 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002847
2848 /* Probe up to 1 GiB at a time. */
Eric Blake5e344dd2017-10-11 22:47:02 -05002849 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2850 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002851
2852 if (ret < 0) {
2853 error_report("Could not read file metadata: %s", strerror(-ret));
2854 goto out;
2855 }
2856
Fam Zheng16b0d552016-01-26 11:59:02 +08002857 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858 curr.length += next.length;
2859 continue;
2860 }
2861
2862 if (curr.length > 0) {
2863 dump_map_entry(output_format, &curr, &next);
2864 }
2865 curr = next;
2866 }
2867
2868 dump_map_entry(output_format, &curr, NULL);
2869
2870out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002871 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002872 return ret < 0;
2873}
2874
aliguorif7b4a942009-01-07 17:40:15 +00002875#define SNAPSHOT_LIST 1
2876#define SNAPSHOT_CREATE 2
2877#define SNAPSHOT_APPLY 3
2878#define SNAPSHOT_DELETE 4
2879
Stuart Brady153859b2009-06-07 00:42:17 +01002880static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002881{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002882 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002883 BlockDriverState *bs;
2884 QEMUSnapshotInfo sn;
2885 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002886 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002887 int action = 0;
2888 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002889 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002890 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002891 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002892 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002893
Kevin Wolfce099542016-03-15 13:01:04 +01002894 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002895 /* Parse commandline parameters */
2896 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002897 static const struct option long_options[] = {
2898 {"help", no_argument, 0, 'h'},
2899 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002900 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002901 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002902 {0, 0, 0, 0}
2903 };
Fam Zheng335e9932017-05-03 00:35:39 +08002904 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002905 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002906 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002907 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002908 }
aliguorif7b4a942009-01-07 17:40:15 +00002909 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002910 case ':':
2911 missing_argument(argv[optind - 1]);
2912 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002913 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002914 unrecognized_option(argv[optind - 1]);
2915 break;
aliguorif7b4a942009-01-07 17:40:15 +00002916 case 'h':
2917 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002918 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002919 case 'l':
2920 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002921 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002922 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002923 }
2924 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002925 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002926 break;
2927 case 'a':
2928 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002929 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002930 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002931 }
2932 action = SNAPSHOT_APPLY;
2933 snapshot_name = optarg;
2934 break;
2935 case 'c':
2936 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002937 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002938 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002939 }
2940 action = SNAPSHOT_CREATE;
2941 snapshot_name = optarg;
2942 break;
2943 case 'd':
2944 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002945 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002946 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002947 }
2948 action = SNAPSHOT_DELETE;
2949 snapshot_name = optarg;
2950 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002951 case 'q':
2952 quiet = true;
2953 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002954 case 'U':
2955 force_share = true;
2956 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002957 case OPTION_OBJECT: {
2958 QemuOpts *opts;
2959 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2960 optarg, true);
2961 if (!opts) {
2962 return 1;
2963 }
2964 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002965 case OPTION_IMAGE_OPTS:
2966 image_opts = true;
2967 break;
aliguorif7b4a942009-01-07 17:40:15 +00002968 }
2969 }
2970
Kevin Wolffc11eb22013-08-05 10:53:04 +02002971 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002972 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002973 }
aliguorif7b4a942009-01-07 17:40:15 +00002974 filename = argv[optind++];
2975
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002976 if (qemu_opts_foreach(&qemu_object_opts,
2977 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002978 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002979 return 1;
2980 }
2981
aliguorif7b4a942009-01-07 17:40:15 +00002982 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08002983 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
2984 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002985 if (!blk) {
2986 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002987 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002988 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00002989
2990 /* Perform the requested action */
2991 switch(action) {
2992 case SNAPSHOT_LIST:
2993 dump_snapshots(bs);
2994 break;
2995
2996 case SNAPSHOT_CREATE:
2997 memset(&sn, 0, sizeof(sn));
2998 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
2999
3000 qemu_gettimeofday(&tv);
3001 sn.date_sec = tv.tv_sec;
3002 sn.date_nsec = tv.tv_usec * 1000;
3003
3004 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003005 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003006 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003007 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003008 }
aliguorif7b4a942009-01-07 17:40:15 +00003009 break;
3010
3011 case SNAPSHOT_APPLY:
3012 ret = bdrv_snapshot_goto(bs, snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003013 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003014 error_report("Could not apply snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003015 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003016 }
aliguorif7b4a942009-01-07 17:40:15 +00003017 break;
3018
3019 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003020 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003021 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003022 error_reportf_err(err, "Could not delete snapshot '%s': ",
3023 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003024 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003025 }
aliguorif7b4a942009-01-07 17:40:15 +00003026 break;
3027 }
3028
3029 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003030 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003031 if (ret) {
3032 return 1;
3033 }
Stuart Brady153859b2009-06-07 00:42:17 +01003034 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003035}
3036
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003037static int img_rebase(int argc, char **argv)
3038{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003039 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003040 uint8_t *buf_old = NULL;
3041 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003042 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003043 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003044 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3045 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003046 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003047 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003048 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003049 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003050 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003051 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003052 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003053
3054 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003055 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003056 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003057 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003058 out_baseimg = NULL;
3059 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003060 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003061 static const struct option long_options[] = {
3062 {"help", no_argument, 0, 'h'},
3063 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003064 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003065 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003066 {0, 0, 0, 0}
3067 };
Fam Zheng335e9932017-05-03 00:35:39 +08003068 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003069 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003070 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003071 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003072 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003073 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003074 case ':':
3075 missing_argument(argv[optind - 1]);
3076 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003077 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003078 unrecognized_option(argv[optind - 1]);
3079 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003080 case 'h':
3081 help();
3082 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003083 case 'f':
3084 fmt = optarg;
3085 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003086 case 'F':
3087 out_basefmt = optarg;
3088 break;
3089 case 'b':
3090 out_baseimg = optarg;
3091 break;
3092 case 'u':
3093 unsafe = 1;
3094 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003095 case 'p':
3096 progress = 1;
3097 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003098 case 't':
3099 cache = optarg;
3100 break;
Max Reitz40055952014-07-22 22:58:42 +02003101 case 'T':
3102 src_cache = optarg;
3103 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003104 case 'q':
3105 quiet = true;
3106 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003107 case OPTION_OBJECT: {
3108 QemuOpts *opts;
3109 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3110 optarg, true);
3111 if (!opts) {
3112 return 1;
3113 }
3114 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003115 case OPTION_IMAGE_OPTS:
3116 image_opts = true;
3117 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003118 case 'U':
3119 force_share = true;
3120 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003121 }
3122 }
3123
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003124 if (quiet) {
3125 progress = 0;
3126 }
3127
Fam Zhengac1307a2014-04-22 13:36:11 +08003128 if (optind != argc - 1) {
3129 error_exit("Expecting one image file name");
3130 }
3131 if (!unsafe && !out_baseimg) {
3132 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003133 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003134 filename = argv[optind++];
3135
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003136 if (qemu_opts_foreach(&qemu_object_opts,
3137 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003138 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003139 return 1;
3140 }
3141
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003142 qemu_progress_init(progress, 2.0);
3143 qemu_progress_print(0, 100);
3144
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003145 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003146 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003147 if (ret < 0) {
3148 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003149 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003150 }
3151
Kevin Wolfce099542016-03-15 13:01:04 +01003152 src_flags = 0;
3153 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003154 if (ret < 0) {
3155 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003156 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003157 }
3158
Kevin Wolfce099542016-03-15 13:01:04 +01003159 /* The source files are opened read-only, don't care about WCE */
3160 assert((src_flags & BDRV_O_RDWR) == 0);
3161 (void) src_writethrough;
3162
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003163 /*
3164 * Open the images.
3165 *
3166 * Ignore the old backing file for unsafe rebase in case we want to correct
3167 * the reference to a renamed or moved backing file.
3168 */
Fam Zheng335e9932017-05-03 00:35:39 +08003169 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3170 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003171 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003172 ret = -1;
3173 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003174 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003175 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003176
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003177 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003178 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003179 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003180 ret = -1;
3181 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003182 }
3183 }
3184
3185 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003186 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003187 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003188 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003189
Max Reitz644483d2015-02-05 13:58:17 -05003190 if (bs->backing_format[0] != '\0') {
3191 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003192 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003193 }
3194
Fam Zheng335e9932017-05-03 00:35:39 +08003195 if (force_share) {
3196 if (!options) {
3197 options = qdict_new();
3198 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003199 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003200 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003201 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003202 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003203 options, src_flags, &local_err);
3204 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003205 error_reportf_err(local_err,
3206 "Could not open old backing file '%s': ",
3207 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003208 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003209 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003210 }
Max Reitz644483d2015-02-05 13:58:17 -05003211
Alex Bligha6166732012-10-16 13:46:18 +01003212 if (out_baseimg[0]) {
Fam Zheng335e9932017-05-03 00:35:39 +08003213 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003214 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003215 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003216 }
3217 if (force_share) {
3218 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003219 }
3220
Max Reitzefaa7c42016-03-16 19:54:38 +01003221 blk_new_backing = blk_new_open(out_baseimg, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003222 options, src_flags, &local_err);
3223 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003224 error_reportf_err(local_err,
3225 "Could not open new backing file '%s': ",
3226 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003227 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003228 goto out;
3229 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003230 }
3231 }
3232
3233 /*
3234 * Check each unallocated cluster in the COW file. If it is unallocated,
3235 * accesses go to the backing file. We must therefore compare this cluster
3236 * in the old and new backing file, and if they differ we need to copy it
3237 * from the old backing file into the COW file.
3238 *
3239 * If qemu-img crashes during this step, no harm is done. The content of
3240 * the image is the same as the original one at any time.
3241 */
3242 if (!unsafe) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003243 int64_t num_sectors;
3244 int64_t old_backing_num_sectors;
3245 int64_t new_backing_num_sectors = 0;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003246 uint64_t sector;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003247 int n;
Eric Blaked6a644b2017-07-07 07:44:57 -05003248 int64_t count;
Kevin Wolf1f710492012-10-12 14:29:18 +02003249 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003250
Max Reitzf1d3cd72015-02-05 13:58:18 -05003251 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3252 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003253
Max Reitzf1d3cd72015-02-05 13:58:18 -05003254 num_sectors = blk_nb_sectors(blk);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003255 if (num_sectors < 0) {
3256 error_report("Could not get size of '%s': %s",
3257 filename, strerror(-num_sectors));
3258 ret = -1;
3259 goto out;
3260 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003261 old_backing_num_sectors = blk_nb_sectors(blk_old_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003262 if (old_backing_num_sectors < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003263 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003264
3265 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3266 error_report("Could not get size of '%s': %s",
3267 backing_name, strerror(-old_backing_num_sectors));
3268 ret = -1;
3269 goto out;
3270 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003271 if (blk_new_backing) {
3272 new_backing_num_sectors = blk_nb_sectors(blk_new_backing);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003273 if (new_backing_num_sectors < 0) {
3274 error_report("Could not get size of '%s': %s",
3275 out_baseimg, strerror(-new_backing_num_sectors));
3276 ret = -1;
3277 goto out;
3278 }
Alex Bligha6166732012-10-16 13:46:18 +01003279 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003280
Kevin Wolf1f710492012-10-12 14:29:18 +02003281 if (num_sectors != 0) {
3282 local_progress = (float)100 /
3283 (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
3284 }
3285
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003286 for (sector = 0; sector < num_sectors; sector += n) {
3287
3288 /* How many sectors can we handle with the next read? */
3289 if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
3290 n = (IO_BUF_SIZE / 512);
3291 } else {
3292 n = num_sectors - sector;
3293 }
3294
3295 /* If the cluster is allocated, we don't need to take action */
Eric Blaked6a644b2017-07-07 07:44:57 -05003296 ret = bdrv_is_allocated(bs, sector << BDRV_SECTOR_BITS,
3297 n << BDRV_SECTOR_BITS, &count);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003298 if (ret < 0) {
3299 error_report("error while reading image metadata: %s",
3300 strerror(-ret));
3301 goto out;
3302 }
Eric Blaked6a644b2017-07-07 07:44:57 -05003303 /* TODO relax this once bdrv_is_allocated does not enforce
3304 * sector alignment */
3305 assert(QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE));
3306 n = count >> BDRV_SECTOR_BITS;
Kevin Wolfcc60e322010-04-29 14:47:48 +02003307 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003308 continue;
3309 }
3310
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003311 /*
3312 * Read old and new backing file and take into consideration that
3313 * backing files may be smaller than the COW image.
3314 */
3315 if (sector >= old_backing_num_sectors) {
3316 memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
3317 } else {
3318 if (sector + n > old_backing_num_sectors) {
3319 n = old_backing_num_sectors - sector;
3320 }
3321
Eric Blake91669202016-05-06 10:26:43 -06003322 ret = blk_pread(blk_old_backing, sector << BDRV_SECTOR_BITS,
3323 buf_old, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003324 if (ret < 0) {
3325 error_report("error while reading from old backing file");
3326 goto out;
3327 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003328 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003329
Max Reitzf1d3cd72015-02-05 13:58:18 -05003330 if (sector >= new_backing_num_sectors || !blk_new_backing) {
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003331 memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
3332 } else {
3333 if (sector + n > new_backing_num_sectors) {
3334 n = new_backing_num_sectors - sector;
3335 }
3336
Eric Blake91669202016-05-06 10:26:43 -06003337 ret = blk_pread(blk_new_backing, sector << BDRV_SECTOR_BITS,
3338 buf_new, n << BDRV_SECTOR_BITS);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003339 if (ret < 0) {
3340 error_report("error while reading from new backing file");
3341 goto out;
3342 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003343 }
3344
3345 /* If they differ, we need to write to the COW file */
3346 uint64_t written = 0;
3347
3348 while (written < n) {
3349 int pnum;
3350
3351 if (compare_sectors(buf_old + written * 512,
Kevin Wolf60b1bd42010-02-17 12:32:59 +01003352 buf_new + written * 512, n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003353 {
Eric Blake91669202016-05-06 10:26:43 -06003354 ret = blk_pwrite(blk,
3355 (sector + written) << BDRV_SECTOR_BITS,
3356 buf_old + written * 512,
3357 pnum << BDRV_SECTOR_BITS, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003358 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003359 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003360 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003361 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003362 }
3363 }
3364
3365 written += pnum;
3366 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003367 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003368 }
3369 }
3370
3371 /*
3372 * Change the backing file. All clusters that are different from the old
3373 * backing file are overwritten in the COW file now, so the visible content
3374 * doesn't change when we switch the backing file.
3375 */
Alex Bligha6166732012-10-16 13:46:18 +01003376 if (out_baseimg && *out_baseimg) {
3377 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3378 } else {
3379 ret = bdrv_change_backing_file(bs, NULL, NULL);
3380 }
3381
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003382 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003383 error_report("Could not change the backing file to '%s': No "
3384 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003385 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003386 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003387 out_baseimg, strerror(-ret));
3388 }
3389
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003390 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003391 /*
3392 * TODO At this point it is possible to check if any clusters that are
3393 * allocated in the COW file are the same in the backing file. If so, they
3394 * could be dropped from the COW file. Don't do this before switching the
3395 * backing file, in case of a crash this would lead to corruption.
3396 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003397out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003398 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003399 /* Cleanup */
3400 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003401 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003402 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003403 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003404 qemu_vfree(buf_old);
3405 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003406
Markus Armbruster26f54e92014-10-07 13:59:04 +02003407 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003408 if (ret) {
3409 return 1;
3410 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003411 return 0;
3412}
3413
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003414static int img_resize(int argc, char **argv)
3415{
Markus Armbruster6750e792015-02-12 17:43:08 +01003416 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003417 int c, ret, relative;
3418 const char *filename, *fmt, *size;
Max Reitzdc5f6902017-06-13 22:20:55 +02003419 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003420 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003421 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003422 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003423 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003424
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003425 static QemuOptsList resize_options = {
3426 .name = "resize_options",
3427 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3428 .desc = {
3429 {
3430 .name = BLOCK_OPT_SIZE,
3431 .type = QEMU_OPT_SIZE,
3432 .help = "Virtual disk size"
3433 }, {
3434 /* end of list */
3435 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003436 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003437 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003438 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003439 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003440
Kevin Wolfe80fec72011-04-29 10:58:12 +02003441 /* Remove size from argv manually so that negative numbers are not treated
3442 * as options by getopt. */
3443 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003444 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003445 return 1;
3446 }
3447
3448 size = argv[--argc];
3449
3450 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003451 fmt = NULL;
3452 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003453 static const struct option long_options[] = {
3454 {"help", no_argument, 0, 'h'},
3455 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003456 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003457 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003458 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003459 {0, 0, 0, 0}
3460 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003461 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003462 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003463 if (c == -1) {
3464 break;
3465 }
3466 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003467 case ':':
3468 missing_argument(argv[optind - 1]);
3469 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003470 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003471 unrecognized_option(argv[optind - 1]);
3472 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003473 case 'h':
3474 help();
3475 break;
3476 case 'f':
3477 fmt = optarg;
3478 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003479 case 'q':
3480 quiet = true;
3481 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003482 case OPTION_OBJECT: {
3483 QemuOpts *opts;
3484 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3485 optarg, true);
3486 if (!opts) {
3487 return 1;
3488 }
3489 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003490 case OPTION_IMAGE_OPTS:
3491 image_opts = true;
3492 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003493 case OPTION_PREALLOCATION:
Marc-AndrƩ Lureauf7abe0e2017-08-24 10:46:10 +02003494 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003495 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003496 if (prealloc == PREALLOC_MODE__MAX) {
3497 error_report("Invalid preallocation mode '%s'", optarg);
3498 return 1;
3499 }
3500 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003501 case OPTION_SHRINK:
3502 shrink = true;
3503 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003504 }
3505 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003506 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003507 error_exit("Expecting one image file name");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003508 }
3509 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003510
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003511 if (qemu_opts_foreach(&qemu_object_opts,
3512 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003513 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003514 return 1;
3515 }
3516
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003517 /* Choose grow, shrink, or absolute resize mode */
3518 switch (size[0]) {
3519 case '+':
3520 relative = 1;
3521 size++;
3522 break;
3523 case '-':
3524 relative = -1;
3525 size++;
3526 break;
3527 default:
3528 relative = 0;
3529 break;
3530 }
3531
3532 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003533 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003534 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003535 if (err) {
3536 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003537 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003538 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003539 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003540 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003541 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3542 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003543
Max Reitzefaa7c42016-03-16 19:54:38 +01003544 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003545 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3546 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003547 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003548 ret = -1;
3549 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003550 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003551
Max Reitzdc5f6902017-06-13 22:20:55 +02003552 current_size = blk_getlength(blk);
3553 if (current_size < 0) {
3554 error_report("Failed to inquire current image length: %s",
3555 strerror(-current_size));
3556 ret = -1;
3557 goto out;
3558 }
3559
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003560 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003561 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003562 } else {
3563 total_size = n;
3564 }
3565 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003566 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003567 ret = -1;
3568 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003569 }
3570
Max Reitzdc5f6902017-06-13 22:20:55 +02003571 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3572 error_report("Preallocation can only be used for growing images");
3573 ret = -1;
3574 goto out;
3575 }
3576
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003577 if (total_size < current_size && !shrink) {
3578 warn_report("Shrinking an image will delete all data beyond the "
3579 "shrunken image's end. Before performing such an "
3580 "operation, make sure there is no important data there.");
3581
3582 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3583 error_report(
3584 "Use the --shrink option to perform a shrink operation.");
3585 ret = -1;
3586 goto out;
3587 } else {
3588 warn_report("Using the --shrink option will suppress this message. "
3589 "Note that future versions of qemu-img may refuse to "
3590 "shrink images without this option.");
3591 }
3592 }
3593
Max Reitzdc5f6902017-06-13 22:20:55 +02003594 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitzed3d2ec2017-03-28 22:51:27 +02003595 if (!ret) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003596 qprintf(quiet, "Image resized.\n");
Max Reitzed3d2ec2017-03-28 22:51:27 +02003597 } else {
3598 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003599 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003600out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003601 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003602 if (ret) {
3603 return 1;
3604 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003605 return 0;
3606}
3607
Max Reitz76a3a342014-10-27 11:12:51 +01003608static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003609 int64_t offset, int64_t total_work_size,
3610 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003611{
3612 qemu_progress_print(100.f * offset / total_work_size, 0);
3613}
3614
Max Reitz6f176b42013-09-03 10:09:50 +02003615static int img_amend(int argc, char **argv)
3616{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003617 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003618 int c, ret = 0;
3619 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003620 QemuOptsList *create_opts = NULL;
3621 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003622 const char *fmt = NULL, *filename, *cache;
3623 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003624 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003625 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003626 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003627 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003628 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003629
Max Reitzbd39e6e2014-07-22 22:58:43 +02003630 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003631 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003632 static const struct option long_options[] = {
3633 {"help", no_argument, 0, 'h'},
3634 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003635 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003636 {0, 0, 0, 0}
3637 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003638 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003639 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003640 if (c == -1) {
3641 break;
3642 }
3643
3644 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003645 case ':':
3646 missing_argument(argv[optind - 1]);
3647 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003648 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003649 unrecognized_option(argv[optind - 1]);
3650 break;
3651 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003652 help();
3653 break;
3654 case 'o':
3655 if (!is_valid_option_list(optarg)) {
3656 error_report("Invalid option list: %s", optarg);
3657 ret = -1;
3658 goto out_no_progress;
3659 }
3660 if (!options) {
3661 options = g_strdup(optarg);
3662 } else {
3663 char *old_options = options;
3664 options = g_strdup_printf("%s,%s", options, optarg);
3665 g_free(old_options);
3666 }
3667 break;
3668 case 'f':
3669 fmt = optarg;
3670 break;
3671 case 't':
3672 cache = optarg;
3673 break;
3674 case 'p':
3675 progress = true;
3676 break;
3677 case 'q':
3678 quiet = true;
3679 break;
3680 case OPTION_OBJECT:
3681 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3682 optarg, true);
3683 if (!opts) {
3684 ret = -1;
3685 goto out_no_progress;
3686 }
3687 break;
3688 case OPTION_IMAGE_OPTS:
3689 image_opts = true;
3690 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003691 }
3692 }
3693
Max Reitz6f176b42013-09-03 10:09:50 +02003694 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003695 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003696 }
3697
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003698 if (qemu_opts_foreach(&qemu_object_opts,
3699 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003700 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003701 ret = -1;
3702 goto out_no_progress;
3703 }
3704
Max Reitz76a3a342014-10-27 11:12:51 +01003705 if (quiet) {
3706 progress = false;
3707 }
3708 qemu_progress_init(progress, 1.0);
3709
Kevin Wolfa283cb62014-02-21 16:24:07 +01003710 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3711 if (fmt && has_help_option(options)) {
3712 /* If a format is explicitly specified (and possibly no filename is
3713 * given), print option help here */
3714 ret = print_block_option_help(filename, fmt);
3715 goto out;
3716 }
3717
3718 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003719 error_report("Expecting one image file name");
3720 ret = -1;
3721 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003722 }
Max Reitz6f176b42013-09-03 10:09:50 +02003723
Kevin Wolfce099542016-03-15 13:01:04 +01003724 flags = BDRV_O_RDWR;
3725 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003726 if (ret < 0) {
3727 error_report("Invalid cache option: %s", cache);
3728 goto out;
3729 }
3730
Fam Zheng335e9932017-05-03 00:35:39 +08003731 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3732 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003733 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003734 ret = -1;
3735 goto out;
3736 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003737 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003738
3739 fmt = bs->drv->format_name;
3740
Kevin Wolf626f84f2014-02-21 16:24:06 +01003741 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003742 /* If the format was auto-detected, print option help here */
Max Reitz6f176b42013-09-03 10:09:50 +02003743 ret = print_block_option_help(filename, fmt);
3744 goto out;
3745 }
3746
Max Reitzb2439d22014-12-02 18:32:47 +01003747 if (!bs->drv->create_opts) {
3748 error_report("Format driver '%s' does not support any options to amend",
3749 fmt);
3750 ret = -1;
3751 goto out;
3752 }
3753
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003754 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003755 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003756 qemu_opts_do_parse(opts, options, NULL, &err);
3757 if (err) {
3758 error_report_err(err);
3759 ret = -1;
3760 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003761 }
3762
Max Reitz76a3a342014-10-27 11:12:51 +01003763 /* In case the driver does not call amend_status_cb() */
3764 qemu_progress_print(0.f, 0);
Max Reitz8b139762015-07-27 17:51:32 +02003765 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
Max Reitz76a3a342014-10-27 11:12:51 +01003766 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003767 if (ret < 0) {
3768 error_report("Error while amending options: %s", strerror(-ret));
3769 goto out;
3770 }
3771
3772out:
Max Reitz76a3a342014-10-27 11:12:51 +01003773 qemu_progress_end();
3774
Max Reitze814dff2015-08-20 16:00:38 -07003775out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003776 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003777 qemu_opts_del(opts);
3778 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003779 g_free(options);
3780
Max Reitz6f176b42013-09-03 10:09:50 +02003781 if (ret) {
3782 return 1;
3783 }
3784 return 0;
3785}
3786
Kevin Wolfb6133b82014-08-05 14:17:13 +02003787typedef struct BenchData {
3788 BlockBackend *blk;
3789 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003790 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003791 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003792 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003793 int nrreq;
3794 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003795 int flush_interval;
3796 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003797 uint8_t *buf;
3798 QEMUIOVector *qiov;
3799
3800 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003801 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003802 uint64_t offset;
3803} BenchData;
3804
Kevin Wolf55d539c2016-06-03 13:59:41 +02003805static void bench_undrained_flush_cb(void *opaque, int ret)
3806{
3807 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003808 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003809 exit(EXIT_FAILURE);
3810 }
3811}
3812
Kevin Wolfb6133b82014-08-05 14:17:13 +02003813static void bench_cb(void *opaque, int ret)
3814{
3815 BenchData *b = opaque;
3816 BlockAIOCB *acb;
3817
3818 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003819 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003820 exit(EXIT_FAILURE);
3821 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003822
3823 if (b->in_flush) {
3824 /* Just finished a flush with drained queue: Start next requests */
3825 assert(b->in_flight == 0);
3826 b->in_flush = false;
3827 } else if (b->in_flight > 0) {
3828 int remaining = b->n - b->in_flight;
3829
Kevin Wolfb6133b82014-08-05 14:17:13 +02003830 b->n--;
3831 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003832
3833 /* Time for flush? Drain queue if requested, then flush */
3834 if (b->flush_interval && remaining % b->flush_interval == 0) {
3835 if (!b->in_flight || !b->drain_on_flush) {
3836 BlockCompletionFunc *cb;
3837
3838 if (b->drain_on_flush) {
3839 b->in_flush = true;
3840 cb = bench_cb;
3841 } else {
3842 cb = bench_undrained_flush_cb;
3843 }
3844
3845 acb = blk_aio_flush(b->blk, cb, b);
3846 if (!acb) {
3847 error_report("Failed to issue flush request");
3848 exit(EXIT_FAILURE);
3849 }
3850 }
3851 if (b->drain_on_flush) {
3852 return;
3853 }
3854 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003855 }
3856
3857 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003858 int64_t offset = b->offset;
3859 /* blk_aio_* might look for completed I/Os and kick bench_cb
3860 * again, so make sure this operation is counted by in_flight
3861 * and b->offset is ready for the next submission.
3862 */
3863 b->in_flight++;
3864 b->offset += b->step;
3865 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003866 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003867 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003868 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003869 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003870 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003871 if (!acb) {
3872 error_report("Failed to issue request");
3873 exit(EXIT_FAILURE);
3874 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003875 }
3876}
3877
3878static int img_bench(int argc, char **argv)
3879{
3880 int c, ret = 0;
3881 const char *fmt = NULL, *filename;
3882 bool quiet = false;
3883 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003884 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003885 int count = 75000;
3886 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003887 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003888 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003889 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003890 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003891 int flush_interval = 0;
3892 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003893 int64_t image_size;
3894 BlockBackend *blk = NULL;
3895 BenchData data = {};
3896 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02003897 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003898 struct timeval t1, t2;
3899 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08003900 bool force_share = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003901
3902 for (;;) {
3903 static const struct option long_options[] = {
3904 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003905 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003906 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003907 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02003908 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08003909 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02003910 {0, 0, 0, 0}
3911 };
Fam Zheng335e9932017-05-03 00:35:39 +08003912 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02003913 if (c == -1) {
3914 break;
3915 }
3916
3917 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003918 case ':':
3919 missing_argument(argv[optind - 1]);
3920 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003921 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003922 unrecognized_option(argv[optind - 1]);
3923 break;
3924 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02003925 help();
3926 break;
3927 case 'c':
3928 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003929 unsigned long res;
3930
3931 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003932 error_report("Invalid request count specified");
3933 return 1;
3934 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003935 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003936 break;
3937 }
3938 case 'd':
3939 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00003940 unsigned long res;
3941
3942 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003943 error_report("Invalid queue depth specified");
3944 return 1;
3945 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00003946 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003947 break;
3948 }
3949 case 'f':
3950 fmt = optarg;
3951 break;
3952 case 'n':
3953 flags |= BDRV_O_NATIVE_AIO;
3954 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02003955 case 'o':
3956 {
Markus Armbruster606caa02017-02-21 21:14:04 +01003957 offset = cvtnum(optarg);
3958 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02003959 error_report("Invalid offset specified");
3960 return 1;
3961 }
3962 break;
3963 }
3964 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003965 case 'q':
3966 quiet = true;
3967 break;
3968 case 's':
3969 {
3970 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003971
Markus Armbruster606caa02017-02-21 21:14:04 +01003972 sval = cvtnum(optarg);
3973 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02003974 error_report("Invalid buffer size specified");
3975 return 1;
3976 }
3977
3978 bufsize = sval;
3979 break;
3980 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02003981 case 'S':
3982 {
3983 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003984
Markus Armbruster606caa02017-02-21 21:14:04 +01003985 sval = cvtnum(optarg);
3986 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02003987 error_report("Invalid step size specified");
3988 return 1;
3989 }
3990
3991 step = sval;
3992 break;
3993 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003994 case 't':
3995 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
3996 if (ret < 0) {
3997 error_report("Invalid cache mode");
3998 ret = -1;
3999 goto out;
4000 }
4001 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004002 case 'w':
4003 flags |= BDRV_O_RDWR;
4004 is_write = true;
4005 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004006 case 'U':
4007 force_share = true;
4008 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004009 case OPTION_PATTERN:
4010 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004011 unsigned long res;
4012
4013 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004014 error_report("Invalid pattern byte specified");
4015 return 1;
4016 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004017 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004018 break;
4019 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004020 case OPTION_FLUSH_INTERVAL:
4021 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004022 unsigned long res;
4023
4024 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004025 error_report("Invalid flush interval specified");
4026 return 1;
4027 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004028 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004029 break;
4030 }
4031 case OPTION_NO_DRAIN:
4032 drain_on_flush = false;
4033 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004034 case OPTION_IMAGE_OPTS:
4035 image_opts = true;
4036 break;
4037 }
4038 }
4039
4040 if (optind != argc - 1) {
4041 error_exit("Expecting one image file name");
4042 }
4043 filename = argv[argc - 1];
4044
Kevin Wolf55d539c2016-06-03 13:59:41 +02004045 if (!is_write && flush_interval) {
4046 error_report("--flush-interval is only available in write tests");
4047 ret = -1;
4048 goto out;
4049 }
4050 if (flush_interval && flush_interval < depth) {
4051 error_report("Flush interval can't be smaller than depth");
4052 ret = -1;
4053 goto out;
4054 }
4055
Fam Zheng335e9932017-05-03 00:35:39 +08004056 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4057 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004058 if (!blk) {
4059 ret = -1;
4060 goto out;
4061 }
4062
4063 image_size = blk_getlength(blk);
4064 if (image_size < 0) {
4065 ret = image_size;
4066 goto out;
4067 }
4068
4069 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004070 .blk = blk,
4071 .image_size = image_size,
4072 .bufsize = bufsize,
4073 .step = step ?: bufsize,
4074 .nrreq = depth,
4075 .n = count,
4076 .offset = offset,
4077 .write = is_write,
4078 .flush_interval = flush_interval,
4079 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004080 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004081 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004082 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004083 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004084 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004085 if (flush_interval) {
4086 printf("Sending flush every %d requests\n", flush_interval);
4087 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004088
4089 data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004090 memset(data.buf, pattern, data.nrreq * data.bufsize);
4091
Kevin Wolfb6133b82014-08-05 14:17:13 +02004092 data.qiov = g_new(QEMUIOVector, data.nrreq);
4093 for (i = 0; i < data.nrreq; i++) {
4094 qemu_iovec_init(&data.qiov[i], 1);
4095 qemu_iovec_add(&data.qiov[i],
4096 data.buf + i * data.bufsize, data.bufsize);
4097 }
4098
4099 gettimeofday(&t1, NULL);
4100 bench_cb(&data, 0);
4101
4102 while (data.n > 0) {
4103 main_loop_wait(false);
4104 }
4105 gettimeofday(&t2, NULL);
4106
4107 printf("Run completed in %3.3f seconds.\n",
4108 (t2.tv_sec - t1.tv_sec)
4109 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4110
4111out:
4112 qemu_vfree(data.buf);
4113 blk_unref(blk);
4114
4115 if (ret) {
4116 return 1;
4117 }
4118 return 0;
4119}
4120
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004121#define C_BS 01
4122#define C_COUNT 02
4123#define C_IF 04
4124#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004125#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004126
4127struct DdInfo {
4128 unsigned int flags;
4129 int64_t count;
4130};
4131
4132struct DdIo {
4133 int bsz; /* Block size */
4134 char *filename;
4135 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004136 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004137};
4138
4139struct DdOpts {
4140 const char *name;
4141 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4142 unsigned int flag;
4143};
4144
4145static int img_dd_bs(const char *arg,
4146 struct DdIo *in, struct DdIo *out,
4147 struct DdInfo *dd)
4148{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004149 int64_t res;
4150
Markus Armbruster606caa02017-02-21 21:14:04 +01004151 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004152
Markus Armbruster606caa02017-02-21 21:14:04 +01004153 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004154 error_report("invalid number: '%s'", arg);
4155 return 1;
4156 }
4157 in->bsz = out->bsz = res;
4158
4159 return 0;
4160}
4161
4162static int img_dd_count(const char *arg,
4163 struct DdIo *in, struct DdIo *out,
4164 struct DdInfo *dd)
4165{
Markus Armbruster606caa02017-02-21 21:14:04 +01004166 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004167
Markus Armbruster606caa02017-02-21 21:14:04 +01004168 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004169 error_report("invalid number: '%s'", arg);
4170 return 1;
4171 }
4172
4173 return 0;
4174}
4175
4176static int img_dd_if(const char *arg,
4177 struct DdIo *in, struct DdIo *out,
4178 struct DdInfo *dd)
4179{
4180 in->filename = g_strdup(arg);
4181
4182 return 0;
4183}
4184
4185static int img_dd_of(const char *arg,
4186 struct DdIo *in, struct DdIo *out,
4187 struct DdInfo *dd)
4188{
4189 out->filename = g_strdup(arg);
4190
4191 return 0;
4192}
4193
Reda Sallahif7c15532016-08-10 16:16:09 +02004194static int img_dd_skip(const char *arg,
4195 struct DdIo *in, struct DdIo *out,
4196 struct DdInfo *dd)
4197{
Markus Armbruster606caa02017-02-21 21:14:04 +01004198 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004199
Markus Armbruster606caa02017-02-21 21:14:04 +01004200 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004201 error_report("invalid number: '%s'", arg);
4202 return 1;
4203 }
4204
4205 return 0;
4206}
4207
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004208static int img_dd(int argc, char **argv)
4209{
4210 int ret = 0;
4211 char *arg = NULL;
4212 char *tmp;
4213 BlockDriver *drv = NULL, *proto_drv = NULL;
4214 BlockBackend *blk1 = NULL, *blk2 = NULL;
4215 QemuOpts *opts = NULL;
4216 QemuOptsList *create_opts = NULL;
4217 Error *local_err = NULL;
4218 bool image_opts = false;
4219 int c, i;
4220 const char *out_fmt = "raw";
4221 const char *fmt = NULL;
4222 int64_t size = 0;
4223 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004224 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004225 struct DdInfo dd = {
4226 .flags = 0,
4227 .count = 0,
4228 };
4229 struct DdIo in = {
4230 .bsz = 512, /* Block size is by default 512 bytes */
4231 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004232 .buf = NULL,
4233 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004234 };
4235 struct DdIo out = {
4236 .bsz = 512,
4237 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004238 .buf = NULL,
4239 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004240 };
4241
4242 const struct DdOpts options[] = {
4243 { "bs", img_dd_bs, C_BS },
4244 { "count", img_dd_count, C_COUNT },
4245 { "if", img_dd_if, C_IF },
4246 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004247 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004248 { NULL, NULL, 0 }
4249 };
4250 const struct option long_options[] = {
4251 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004252 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004253 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004254 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004255 { 0, 0, 0, 0 }
4256 };
4257
Fam Zheng335e9932017-05-03 00:35:39 +08004258 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004259 if (c == EOF) {
4260 break;
4261 }
4262 switch (c) {
4263 case 'O':
4264 out_fmt = optarg;
4265 break;
4266 case 'f':
4267 fmt = optarg;
4268 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004269 case ':':
4270 missing_argument(argv[optind - 1]);
4271 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004272 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004273 unrecognized_option(argv[optind - 1]);
4274 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004275 case 'h':
4276 help();
4277 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004278 case 'U':
4279 force_share = true;
4280 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004281 case OPTION_OBJECT:
4282 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004283 ret = -1;
4284 goto out;
4285 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004286 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004287 case OPTION_IMAGE_OPTS:
4288 image_opts = true;
4289 break;
4290 }
4291 }
4292
4293 for (i = optind; i < argc; i++) {
4294 int j;
4295 arg = g_strdup(argv[i]);
4296
4297 tmp = strchr(arg, '=');
4298 if (tmp == NULL) {
4299 error_report("unrecognized operand %s", arg);
4300 ret = -1;
4301 goto out;
4302 }
4303
4304 *tmp++ = '\0';
4305
4306 for (j = 0; options[j].name != NULL; j++) {
4307 if (!strcmp(arg, options[j].name)) {
4308 break;
4309 }
4310 }
4311 if (options[j].name == NULL) {
4312 error_report("unrecognized operand %s", arg);
4313 ret = -1;
4314 goto out;
4315 }
4316
4317 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4318 ret = -1;
4319 goto out;
4320 }
4321 dd.flags |= options[j].flag;
4322 g_free(arg);
4323 arg = NULL;
4324 }
4325
4326 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4327 error_report("Must specify both input and output files");
4328 ret = -1;
4329 goto out;
4330 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004331
4332 if (qemu_opts_foreach(&qemu_object_opts,
4333 user_creatable_add_opts_foreach,
4334 NULL, NULL)) {
4335 ret = -1;
4336 goto out;
4337 }
4338
Fam Zheng335e9932017-05-03 00:35:39 +08004339 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4340 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004341
4342 if (!blk1) {
4343 ret = -1;
4344 goto out;
4345 }
4346
4347 drv = bdrv_find_format(out_fmt);
4348 if (!drv) {
4349 error_report("Unknown file format");
4350 ret = -1;
4351 goto out;
4352 }
4353 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4354
4355 if (!proto_drv) {
4356 error_report_err(local_err);
4357 ret = -1;
4358 goto out;
4359 }
4360 if (!drv->create_opts) {
4361 error_report("Format driver '%s' does not support image creation",
4362 drv->format_name);
4363 ret = -1;
4364 goto out;
4365 }
4366 if (!proto_drv->create_opts) {
4367 error_report("Protocol driver '%s' does not support image creation",
4368 proto_drv->format_name);
4369 ret = -1;
4370 goto out;
4371 }
4372 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4373 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4374
4375 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4376
4377 size = blk_getlength(blk1);
4378 if (size < 0) {
4379 error_report("Failed to get size for '%s'", in.filename);
4380 ret = -1;
4381 goto out;
4382 }
4383
4384 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4385 dd.count * in.bsz < size) {
4386 size = dd.count * in.bsz;
4387 }
4388
Reda Sallahif7c15532016-08-10 16:16:09 +02004389 /* Overflow means the specified offset is beyond input image's size */
4390 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4391 size < in.bsz * in.offset)) {
4392 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4393 } else {
4394 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4395 size - in.bsz * in.offset, &error_abort);
4396 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004397
4398 ret = bdrv_create(drv, out.filename, opts, &local_err);
4399 if (ret < 0) {
4400 error_reportf_err(local_err,
4401 "%s: error while creating output image: ",
4402 out.filename);
4403 ret = -1;
4404 goto out;
4405 }
4406
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004407 /* TODO, we can't honour --image-opts for the target,
4408 * since it needs to be given in a format compatible
4409 * with the bdrv_create() call above which does not
4410 * support image-opts style.
4411 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004412 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004413 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004414
4415 if (!blk2) {
4416 ret = -1;
4417 goto out;
4418 }
4419
Reda Sallahif7c15532016-08-10 16:16:09 +02004420 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4421 size < in.offset * in.bsz)) {
4422 /* We give a warning if the skip option is bigger than the input
4423 * size and create an empty output disk image (i.e. like dd(1)).
4424 */
4425 error_report("%s: cannot skip to specified offset", in.filename);
4426 in_pos = size;
4427 } else {
4428 in_pos = in.offset * in.bsz;
4429 }
4430
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004431 in.buf = g_new(uint8_t, in.bsz);
4432
Reda Sallahif7c15532016-08-10 16:16:09 +02004433 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004434 int in_ret, out_ret;
4435
4436 if (in_pos + in.bsz > size) {
4437 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4438 } else {
4439 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4440 }
4441 if (in_ret < 0) {
4442 error_report("error while reading from input image file: %s",
4443 strerror(-in_ret));
4444 ret = -1;
4445 goto out;
4446 }
4447 in_pos += in_ret;
4448
4449 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4450
4451 if (out_ret < 0) {
4452 error_report("error while writing to output image file: %s",
4453 strerror(-out_ret));
4454 ret = -1;
4455 goto out;
4456 }
4457 out_pos += out_ret;
4458 }
4459
4460out:
4461 g_free(arg);
4462 qemu_opts_del(opts);
4463 qemu_opts_free(create_opts);
4464 blk_unref(blk1);
4465 blk_unref(blk2);
4466 g_free(in.filename);
4467 g_free(out.filename);
4468 g_free(in.buf);
4469 g_free(out.buf);
4470
4471 if (ret) {
4472 return 1;
4473 }
4474 return 0;
4475}
4476
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004477static void dump_json_block_measure_info(BlockMeasureInfo *info)
4478{
4479 QString *str;
4480 QObject *obj;
4481 Visitor *v = qobject_output_visitor_new(&obj);
4482
4483 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4484 visit_complete(v, &obj);
4485 str = qobject_to_json_pretty(obj);
4486 assert(str != NULL);
4487 printf("%s\n", qstring_get_str(str));
4488 qobject_decref(obj);
4489 visit_free(v);
4490 QDECREF(str);
4491}
4492
4493static int img_measure(int argc, char **argv)
4494{
4495 static const struct option long_options[] = {
4496 {"help", no_argument, 0, 'h'},
4497 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4498 {"object", required_argument, 0, OPTION_OBJECT},
4499 {"output", required_argument, 0, OPTION_OUTPUT},
4500 {"size", required_argument, 0, OPTION_SIZE},
4501 {"force-share", no_argument, 0, 'U'},
4502 {0, 0, 0, 0}
4503 };
4504 OutputFormat output_format = OFORMAT_HUMAN;
4505 BlockBackend *in_blk = NULL;
4506 BlockDriver *drv;
4507 const char *filename = NULL;
4508 const char *fmt = NULL;
4509 const char *out_fmt = "raw";
4510 char *options = NULL;
4511 char *snapshot_name = NULL;
4512 bool force_share = false;
4513 QemuOpts *opts = NULL;
4514 QemuOpts *object_opts = NULL;
4515 QemuOpts *sn_opts = NULL;
4516 QemuOptsList *create_opts = NULL;
4517 bool image_opts = false;
4518 uint64_t img_size = UINT64_MAX;
4519 BlockMeasureInfo *info = NULL;
4520 Error *local_err = NULL;
4521 int ret = 1;
4522 int c;
4523
4524 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4525 long_options, NULL)) != -1) {
4526 switch (c) {
4527 case '?':
4528 case 'h':
4529 help();
4530 break;
4531 case 'f':
4532 fmt = optarg;
4533 break;
4534 case 'O':
4535 out_fmt = optarg;
4536 break;
4537 case 'o':
4538 if (!is_valid_option_list(optarg)) {
4539 error_report("Invalid option list: %s", optarg);
4540 goto out;
4541 }
4542 if (!options) {
4543 options = g_strdup(optarg);
4544 } else {
4545 char *old_options = options;
4546 options = g_strdup_printf("%s,%s", options, optarg);
4547 g_free(old_options);
4548 }
4549 break;
4550 case 'l':
4551 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4552 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4553 optarg, false);
4554 if (!sn_opts) {
4555 error_report("Failed in parsing snapshot param '%s'",
4556 optarg);
4557 goto out;
4558 }
4559 } else {
4560 snapshot_name = optarg;
4561 }
4562 break;
4563 case 'U':
4564 force_share = true;
4565 break;
4566 case OPTION_OBJECT:
4567 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4568 optarg, true);
4569 if (!object_opts) {
4570 goto out;
4571 }
4572 break;
4573 case OPTION_IMAGE_OPTS:
4574 image_opts = true;
4575 break;
4576 case OPTION_OUTPUT:
4577 if (!strcmp(optarg, "json")) {
4578 output_format = OFORMAT_JSON;
4579 } else if (!strcmp(optarg, "human")) {
4580 output_format = OFORMAT_HUMAN;
4581 } else {
4582 error_report("--output must be used with human or json "
4583 "as argument.");
4584 goto out;
4585 }
4586 break;
4587 case OPTION_SIZE:
4588 {
4589 int64_t sval;
4590
4591 sval = cvtnum(optarg);
4592 if (sval < 0) {
4593 if (sval == -ERANGE) {
4594 error_report("Image size must be less than 8 EiB!");
4595 } else {
4596 error_report("Invalid image size specified! You may use "
4597 "k, M, G, T, P or E suffixes for ");
4598 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4599 "petabytes and exabytes.");
4600 }
4601 goto out;
4602 }
4603 img_size = (uint64_t)sval;
4604 }
4605 break;
4606 }
4607 }
4608
4609 if (qemu_opts_foreach(&qemu_object_opts,
4610 user_creatable_add_opts_foreach,
4611 NULL, NULL)) {
4612 goto out;
4613 }
4614
4615 if (argc - optind > 1) {
4616 error_report("At most one filename argument is allowed.");
4617 goto out;
4618 } else if (argc - optind == 1) {
4619 filename = argv[optind];
4620 }
4621
4622 if (!filename &&
4623 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4624 error_report("--object, --image-opts, -f, and -l "
4625 "require a filename argument.");
4626 goto out;
4627 }
4628 if (filename && img_size != UINT64_MAX) {
4629 error_report("--size N cannot be used together with a filename.");
4630 goto out;
4631 }
4632 if (!filename && img_size == UINT64_MAX) {
4633 error_report("Either --size N or one filename must be specified.");
4634 goto out;
4635 }
4636
4637 if (filename) {
4638 in_blk = img_open(image_opts, filename, fmt, 0,
4639 false, false, force_share);
4640 if (!in_blk) {
4641 goto out;
4642 }
4643
4644 if (sn_opts) {
4645 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4646 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4647 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4648 &local_err);
4649 } else if (snapshot_name != NULL) {
4650 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4651 snapshot_name, &local_err);
4652 }
4653 if (local_err) {
4654 error_reportf_err(local_err, "Failed to load snapshot: ");
4655 goto out;
4656 }
4657 }
4658
4659 drv = bdrv_find_format(out_fmt);
4660 if (!drv) {
4661 error_report("Unknown file format '%s'", out_fmt);
4662 goto out;
4663 }
4664 if (!drv->create_opts) {
4665 error_report("Format driver '%s' does not support image creation",
4666 drv->format_name);
4667 goto out;
4668 }
4669
4670 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4671 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4672 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4673 if (options) {
4674 qemu_opts_do_parse(opts, options, NULL, &local_err);
4675 if (local_err) {
4676 error_report_err(local_err);
4677 error_report("Invalid options for file format '%s'", out_fmt);
4678 goto out;
4679 }
4680 }
4681 if (img_size != UINT64_MAX) {
4682 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4683 }
4684
4685 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4686 if (local_err) {
4687 error_report_err(local_err);
4688 goto out;
4689 }
4690
4691 if (output_format == OFORMAT_HUMAN) {
4692 printf("required size: %" PRIu64 "\n", info->required);
4693 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4694 } else {
4695 dump_json_block_measure_info(info);
4696 }
4697
4698 ret = 0;
4699
4700out:
4701 qapi_free_BlockMeasureInfo(info);
4702 qemu_opts_del(object_opts);
4703 qemu_opts_del(opts);
4704 qemu_opts_del(sn_opts);
4705 qemu_opts_free(create_opts);
4706 g_free(options);
4707 blk_unref(in_blk);
4708 return ret;
4709}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004710
Anthony Liguoric227f092009-10-01 16:12:16 -05004711static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004712#define DEF(option, callback, arg_string) \
4713 { option, callback },
4714#include "qemu-img-cmds.h"
4715#undef DEF
4716#undef GEN_DOCS
4717 { NULL, NULL, },
4718};
4719
bellardea2384d2004-08-01 21:59:26 +00004720int main(int argc, char **argv)
4721{
Anthony Liguoric227f092009-10-01 16:12:16 -05004722 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004723 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004724 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004725 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004726 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004727 static const struct option long_options[] = {
4728 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004729 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004730 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004731 {0, 0, 0, 0}
4732 };
bellardea2384d2004-08-01 21:59:26 +00004733
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004734#ifdef CONFIG_POSIX
4735 signal(SIGPIPE, SIG_IGN);
4736#endif
4737
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004738 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004739 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004740 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004741
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004742 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004743 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004744 exit(EXIT_FAILURE);
4745 }
4746
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004747 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004748
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004749 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004750 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004751 if (argc < 2) {
4752 error_exit("Not enough arguments");
4753 }
Stuart Brady153859b2009-06-07 00:42:17 +01004754
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004755 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004756 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004757 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004758
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004759 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004760 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004761 case ':':
4762 missing_argument(argv[optind - 1]);
4763 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004764 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004765 unrecognized_option(argv[optind - 1]);
4766 return 0;
4767 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004768 help();
4769 return 0;
4770 case 'V':
4771 printf(QEMU_IMG_VERSION);
4772 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004773 case 'T':
4774 g_free(trace_file);
4775 trace_file = trace_opt_parse(optarg);
4776 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004777 }
bellardea2384d2004-08-01 21:59:26 +00004778 }
Stuart Brady153859b2009-06-07 00:42:17 +01004779
Denis V. Lunev10985132016-06-17 17:44:13 +03004780 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004781
Denis V. Lunev10985132016-06-17 17:44:13 +03004782 /* reset getopt_long scanning */
4783 argc -= optind;
4784 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004785 return 0;
4786 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004787 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004788 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004789
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004790 if (!trace_init_backends()) {
4791 exit(1);
4792 }
4793 trace_init_file(trace_file);
4794 qemu_set_log(LOG_TRACE);
4795
Denis V. Lunev10985132016-06-17 17:44:13 +03004796 /* find the command */
4797 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4798 if (!strcmp(cmdname, cmd->name)) {
4799 return cmd->handler(argc, argv);
4800 }
4801 }
Jeff Cody7db16892014-04-25 17:02:32 -04004802
Stuart Brady153859b2009-06-07 00:42:17 +01004803 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004804 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004805}