blob: ae4acb655b9f68f4aa7d21a43e4d9e33b62ebb6f [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 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Fam Zheng67a1de02016-06-01 17:44:21 +080028#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010029#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010030#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010031#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010032#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010033#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010034#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020035#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000036#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010037#include "qemu/option.h"
38#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030039#include "qemu/log.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000040#include "qom/object_interfaces.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010041#include "sysemu/sysemu.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020042#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010043#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020044#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080045#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010046#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030047#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000048
Thomas Huth7e563bf2018-02-15 12:06:47 +010049#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020050 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040051
Anthony Liguoric227f092009-10-01 16:12:16 -050052typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010053 const char *name;
54 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050055} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010056
Federico Simoncelli8599ea42013-01-28 06:59:47 -050057enum {
58 OPTION_OUTPUT = 256,
59 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000060 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000061 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020062 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020063 OPTION_FLUSH_INTERVAL = 261,
64 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010065 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010066 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020067 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030068 OPTION_SHRINK = 266,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050069};
70
71typedef enum OutputFormat {
72 OFORMAT_JSON,
73 OFORMAT_HUMAN,
74} OutputFormat;
75
Kevin Wolfe6996142016-03-15 13:03:11 +010076/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040077#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000078
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010079static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000080{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010081 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000082}
83
Fam Zhengac1307a2014-04-22 13:36:11 +080084static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
85{
86 va_list ap;
87
88 error_printf("qemu-img: ");
89
90 va_start(ap, fmt);
91 error_vprintf(fmt, ap);
92 va_end(ap);
93
94 error_printf("\nTry 'qemu-img --help' for more information\n");
95 exit(EXIT_FAILURE);
96}
97
Stefan Hajnoczic9192972017-03-17 18:45:41 +080098static void QEMU_NORETURN missing_argument(const char *option)
99{
100 error_exit("missing argument for option '%s'", option);
101}
102
103static void QEMU_NORETURN unrecognized_option(const char *option)
104{
105 error_exit("unrecognized option '%s'", option);
106}
107
blueswir1d2c639d2009-01-24 18:19:25 +0000108/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800109static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000110{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100111 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400112 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300113 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300114 "QEMU disk image utility\n"
115 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300116 " '-h', '--help' display this help and exit\n"
117 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300118 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
119 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300120 "\n"
malc3f020d72010-02-08 12:04:56 +0300121 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100122#define DEF(option, callback, arg_string) \
123 " " arg_string "\n"
124#include "qemu-img-cmds.h"
125#undef DEF
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
Max Reitzd402b6a2018-05-09 23:00:21 +0200252 if (!drv->create_opts) {
253 error_report("Format driver '%s' does not support image creation", fmt);
254 return 1;
255 }
256
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800257 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100258 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500259 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100260 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100261 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800262 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100263 return 1;
264 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200265 if (!proto_drv->create_opts) {
266 error_report("Protocal driver '%s' does not support image creation",
267 proto_drv->format_name);
268 return 1;
269 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800270 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100271 }
272
Max Reitz7f3fb002018-05-09 23:00:19 +0200273 printf("Supported options:\n");
Chunyan Liu83d05212014-06-05 17:20:51 +0800274 qemu_opts_print_help(create_opts);
275 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100276 return 0;
277}
278
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000279
Max Reitzefaa7c42016-03-16 19:54:38 +0100280static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100281 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800282 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000283{
284 QDict *options;
285 Error *local_err = NULL;
286 BlockBackend *blk;
287 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800288 if (force_share) {
289 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200290 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800291 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200292 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800293 return NULL;
294 }
Max Reitz4615f872018-05-02 22:20:50 +0200295 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800296 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100297 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000298 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100299 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000300 return NULL;
301 }
Kevin Wolfce099542016-03-15 13:01:04 +0100302 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000303
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000304 return blk;
305}
306
Max Reitzefaa7c42016-03-16 19:54:38 +0100307static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100308 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000309 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800310 bool writethrough, bool quiet,
311 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312{
313 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200314 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100315
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100316 if (!options) {
317 options = qdict_new();
318 }
bellard75c23802004-08-27 21:28:58 +0000319 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500320 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000321 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100322
Fam Zheng335e9932017-05-03 00:35:39 +0800323 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500324 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800325 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100326 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500327 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100328 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000329 return NULL;
bellard75c23802004-08-27 21:28:58 +0000330 }
Kevin Wolfce099542016-03-15 13:01:04 +0100331 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100332
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200333 return blk;
bellard75c23802004-08-27 21:28:58 +0000334}
335
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000336
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100337static int img_add_key_secrets(void *opaque,
338 const char *name, const char *value,
339 Error **errp)
340{
341 QDict *options = opaque;
342
343 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600344 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100345 }
346
347 return 0;
348}
349
350static BlockBackend *img_open_new_file(const char *filename,
351 QemuOpts *create_opts,
352 const char *fmt, int flags,
353 bool writethrough, bool quiet,
354 bool force_share)
355{
356 QDict *options = NULL;
357
358 options = qdict_new();
359 qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
360
361 return img_open_file(filename, options, fmt, flags, writethrough, quiet,
362 force_share);
363}
364
365
Max Reitzefaa7c42016-03-16 19:54:38 +0100366static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000367 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100368 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800369 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000370{
371 BlockBackend *blk;
372 if (image_opts) {
373 QemuOpts *opts;
374 if (fmt) {
375 error_report("--image-opts and --format are mutually exclusive");
376 return NULL;
377 }
378 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
379 filename, true);
380 if (!opts) {
381 return NULL;
382 }
Fam Zheng335e9932017-05-03 00:35:39 +0800383 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
384 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000385 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100386 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800387 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000388 }
389 return blk;
390}
391
392
Chunyan Liu83d05212014-06-05 17:20:51 +0800393static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100394 const char *base_filename,
395 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200396{
Markus Armbruster6750e792015-02-12 17:43:08 +0100397 Error *err = NULL;
398
Kevin Wolfefa84d42009-05-18 16:42:12 +0200399 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100400 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100401 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100402 error_report("Backing file not supported for file format '%s'",
403 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100404 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900405 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200406 }
407 }
408 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100409 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100410 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100411 error_report("Backing file format not supported for file "
412 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100413 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900414 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200415 }
416 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900417 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200418}
419
Markus Armbruster606caa02017-02-21 21:14:04 +0100420static int64_t cvtnum(const char *s)
421{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100422 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100423 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100424
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100425 err = qemu_strtosz(s, NULL, &value);
426 if (err < 0) {
427 return err;
428 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100429 if (value > INT64_MAX) {
430 return -ERANGE;
431 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100432 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100433}
434
bellardea2384d2004-08-01 21:59:26 +0000435static int img_create(int argc, char **argv)
436{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200437 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100438 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000439 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000440 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000441 const char *filename;
442 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200443 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200444 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100445 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400446 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000447
bellardea2384d2004-08-01 21:59:26 +0000448 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000449 static const struct option long_options[] = {
450 {"help", no_argument, 0, 'h'},
451 {"object", required_argument, 0, OPTION_OBJECT},
452 {0, 0, 0, 0}
453 };
John Snow6e6e55f2017-07-17 20:34:22 -0400454 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000455 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100456 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000457 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100458 }
bellardea2384d2004-08-01 21:59:26 +0000459 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800460 case ':':
461 missing_argument(argv[optind - 1]);
462 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100463 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800464 unrecognized_option(argv[optind - 1]);
465 break;
bellardea2384d2004-08-01 21:59:26 +0000466 case 'h':
467 help();
468 break;
aliguori9230eaf2009-03-28 17:55:19 +0000469 case 'F':
470 base_fmt = optarg;
471 break;
bellardea2384d2004-08-01 21:59:26 +0000472 case 'b':
473 base_filename = optarg;
474 break;
475 case 'f':
476 fmt = optarg;
477 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200478 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100479 if (!is_valid_option_list(optarg)) {
480 error_report("Invalid option list: %s", optarg);
481 goto fail;
482 }
483 if (!options) {
484 options = g_strdup(optarg);
485 } else {
486 char *old_options = options;
487 options = g_strdup_printf("%s,%s", options, optarg);
488 g_free(old_options);
489 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200490 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100491 case 'q':
492 quiet = true;
493 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400494 case 'u':
495 flags |= BDRV_O_NO_BACKING;
496 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000497 case OPTION_OBJECT: {
498 QemuOpts *opts;
499 opts = qemu_opts_parse_noisily(&qemu_object_opts,
500 optarg, true);
501 if (!opts) {
502 goto fail;
503 }
504 } break;
bellardea2384d2004-08-01 21:59:26 +0000505 }
506 }
aliguori9230eaf2009-03-28 17:55:19 +0000507
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900508 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100509 filename = (optind < argc) ? argv[optind] : NULL;
510 if (options && has_help_option(options)) {
511 g_free(options);
512 return print_block_option_help(filename, fmt);
513 }
514
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100515 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800516 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100517 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100518 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900519
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000520 if (qemu_opts_foreach(&qemu_object_opts,
521 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200522 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000523 goto fail;
524 }
525
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100526 /* Get image size, if specified */
527 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100528 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100529
530 sval = cvtnum(argv[optind++]);
531 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800532 if (sval == -ERANGE) {
533 error_report("Image size must be less than 8 EiB!");
534 } else {
535 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200536 "G, T, P or E suffixes for ");
537 error_report("kilobytes, megabytes, gigabytes, terabytes, "
538 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800539 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100540 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100541 }
542 img_size = (uint64_t)sval;
543 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200544 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800545 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200546 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100547
Luiz Capitulino9b375252012-11-30 10:52:05 -0200548 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400549 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100550 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100551 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100552 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900553 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200554
Kevin Wolf77386bf2014-02-21 16:24:04 +0100555 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000556 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100557
558fail:
559 g_free(options);
560 return 1;
bellardea2384d2004-08-01 21:59:26 +0000561}
562
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100563static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500564{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500566 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100567 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600568
569 visit_type_ImageCheck(v, NULL, &check, &error_abort);
570 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571 str = qobject_to_json_pretty(obj);
572 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100573 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200574 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600575 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200576 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577}
578
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100579static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500580{
581 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100582 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500583 } else {
584 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100585 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
586 "Data may be corrupted, or further writes to the image "
587 "may corrupt it.\n",
588 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500589 }
590
591 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100592 qprintf(quiet,
593 "\n%" PRId64 " leaked clusters were found on the image.\n"
594 "This means waste of disk space, but no harm to data.\n",
595 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500596 }
597
598 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100599 qprintf(quiet,
600 "\n%" PRId64
601 " internal errors have occurred during the check.\n",
602 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 }
604 }
605
606 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100607 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
608 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
609 check->allocated_clusters, check->total_clusters,
610 check->allocated_clusters * 100.0 / check->total_clusters,
611 check->fragmented_clusters * 100.0 / check->allocated_clusters,
612 check->compressed_clusters * 100.0 /
613 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500614 }
615
616 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100617 qprintf(quiet,
618 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500619 }
620}
621
622static int collect_image_check(BlockDriverState *bs,
623 ImageCheck *check,
624 const char *filename,
625 const char *fmt,
626 int fix)
627{
628 int ret;
629 BdrvCheckResult result;
630
631 ret = bdrv_check(bs, &result, fix);
632 if (ret < 0) {
633 return ret;
634 }
635
636 check->filename = g_strdup(filename);
637 check->format = g_strdup(bdrv_get_format_name(bs));
638 check->check_errors = result.check_errors;
639 check->corruptions = result.corruptions;
640 check->has_corruptions = result.corruptions != 0;
641 check->leaks = result.leaks;
642 check->has_leaks = result.leaks != 0;
643 check->corruptions_fixed = result.corruptions_fixed;
644 check->has_corruptions_fixed = result.corruptions != 0;
645 check->leaks_fixed = result.leaks_fixed;
646 check->has_leaks_fixed = result.leaks != 0;
647 check->image_end_offset = result.image_end_offset;
648 check->has_image_end_offset = result.image_end_offset != 0;
649 check->total_clusters = result.bfi.total_clusters;
650 check->has_total_clusters = result.bfi.total_clusters != 0;
651 check->allocated_clusters = result.bfi.allocated_clusters;
652 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
653 check->fragmented_clusters = result.bfi.fragmented_clusters;
654 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100655 check->compressed_clusters = result.bfi.compressed_clusters;
656 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500657
658 return 0;
659}
660
Kevin Wolfe076f332010-06-29 11:43:13 +0200661/*
662 * Checks an image for consistency. Exit codes:
663 *
Max Reitzd6635c42014-06-02 22:15:21 +0200664 * 0 - Check completed, image is good
665 * 1 - Check not completed because of internal errors
666 * 2 - Check completed, image is corrupted
667 * 3 - Check completed, image has leaked clusters, but is good otherwise
668 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200669 */
aliguori15859692009-04-21 23:11:53 +0000670static int img_check(int argc, char **argv)
671{
672 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500673 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200674 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200675 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000676 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200677 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100678 int flags = BDRV_O_CHECK;
679 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200680 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100681 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000682 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800683 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000684
685 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200687 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100688
aliguori15859692009-04-21 23:11:53 +0000689 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500690 int option_index = 0;
691 static const struct option long_options[] = {
692 {"help", no_argument, 0, 'h'},
693 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530694 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500695 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000696 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000697 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800698 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500699 {0, 0, 0, 0}
700 };
Fam Zheng335e9932017-05-03 00:35:39 +0800701 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500702 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100703 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000704 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100705 }
aliguori15859692009-04-21 23:11:53 +0000706 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800707 case ':':
708 missing_argument(argv[optind - 1]);
709 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100710 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800711 unrecognized_option(argv[optind - 1]);
712 break;
aliguori15859692009-04-21 23:11:53 +0000713 case 'h':
714 help();
715 break;
716 case 'f':
717 fmt = optarg;
718 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200719 case 'r':
720 flags |= BDRV_O_RDWR;
721
722 if (!strcmp(optarg, "leaks")) {
723 fix = BDRV_FIX_LEAKS;
724 } else if (!strcmp(optarg, "all")) {
725 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
726 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800727 error_exit("Unknown option value for -r "
728 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200729 }
730 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500731 case OPTION_OUTPUT:
732 output = optarg;
733 break;
Max Reitz40055952014-07-22 22:58:42 +0200734 case 'T':
735 cache = optarg;
736 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100737 case 'q':
738 quiet = true;
739 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800740 case 'U':
741 force_share = true;
742 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000743 case OPTION_OBJECT: {
744 QemuOpts *opts;
745 opts = qemu_opts_parse_noisily(&qemu_object_opts,
746 optarg, true);
747 if (!opts) {
748 return 1;
749 }
750 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000751 case OPTION_IMAGE_OPTS:
752 image_opts = true;
753 break;
aliguori15859692009-04-21 23:11:53 +0000754 }
755 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200756 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800757 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100758 }
aliguori15859692009-04-21 23:11:53 +0000759 filename = argv[optind++];
760
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500761 if (output && !strcmp(output, "json")) {
762 output_format = OFORMAT_JSON;
763 } else if (output && !strcmp(output, "human")) {
764 output_format = OFORMAT_HUMAN;
765 } else if (output) {
766 error_report("--output must be used with human or json as argument.");
767 return 1;
768 }
769
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000770 if (qemu_opts_foreach(&qemu_object_opts,
771 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200772 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000773 return 1;
774 }
775
Kevin Wolfce099542016-03-15 13:01:04 +0100776 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200777 if (ret < 0) {
778 error_report("Invalid source cache option: %s", cache);
779 return 1;
780 }
781
Fam Zheng335e9932017-05-03 00:35:39 +0800782 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
783 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200784 if (!blk) {
785 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900786 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200787 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500788
789 check = g_new0(ImageCheck, 1);
790 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200791
792 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200793 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200794 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200796 }
797
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500798 if (check->corruptions_fixed || check->leaks_fixed) {
799 int corruptions_fixed, leaks_fixed;
800
801 leaks_fixed = check->leaks_fixed;
802 corruptions_fixed = check->corruptions_fixed;
803
804 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100805 qprintf(quiet,
806 "The following inconsistencies were found and repaired:\n\n"
807 " %" PRId64 " leaked clusters\n"
808 " %" PRId64 " corruptions\n\n"
809 "Double checking the fixed image now...\n",
810 check->leaks_fixed,
811 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500812 }
813
814 ret = collect_image_check(bs, check, filename, fmt, 0);
815
816 check->leaks_fixed = leaks_fixed;
817 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200818 }
819
Max Reitz832390a2014-10-23 15:29:12 +0200820 if (!ret) {
821 switch (output_format) {
822 case OFORMAT_HUMAN:
823 dump_human_image_check(check, quiet);
824 break;
825 case OFORMAT_JSON:
826 dump_json_image_check(check, quiet);
827 break;
828 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500829 }
830
831 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200832 if (ret) {
833 error_report("Check failed: %s", strerror(-ret));
834 } else {
835 error_report("Check failed");
836 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500837 ret = 1;
838 goto fail;
839 }
840
841 if (check->corruptions) {
842 ret = 2;
843 } else if (check->leaks) {
844 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200845 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500846 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000847 }
848
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500849fail:
850 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200851 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500852 return ret;
aliguori15859692009-04-21 23:11:53 +0000853}
854
Max Reitzd4a32382014-10-24 15:57:37 +0200855typedef struct CommonBlockJobCBInfo {
856 BlockDriverState *bs;
857 Error **errp;
858} CommonBlockJobCBInfo;
859
860static void common_block_job_cb(void *opaque, int ret)
861{
862 CommonBlockJobCBInfo *cbi = opaque;
863
864 if (ret < 0) {
865 error_setg_errno(cbi->errp, -ret, "Block job failed");
866 }
Max Reitzd4a32382014-10-24 15:57:37 +0200867}
868
869static void run_block_job(BlockJob *job, Error **errp)
870{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200871 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800872 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200873
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200874 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200875 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200876 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200877 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200878 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200879 if (job->job.progress_total) {
880 progress = (float)job->job.progress_current /
881 job->job.progress_total * 100.f;
882 }
883 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200884 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200885
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200886 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200887 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800888 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200889 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800890 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200891 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200892 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200893
sochin.jiang4172a002017-06-15 14:47:33 +0800894 /* publish completion progress only when success */
895 if (!ret) {
896 qemu_progress_print(100.f, 0);
897 }
Max Reitzd4a32382014-10-24 15:57:37 +0200898}
899
bellardea2384d2004-08-01 21:59:26 +0000900static int img_commit(int argc, char **argv)
901{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400902 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200903 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200904 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200905 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100906 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200907 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100908 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200909 Error *local_err = NULL;
910 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000911 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200912 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000913
914 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400915 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200916 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000917 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000918 static const struct option long_options[] = {
919 {"help", no_argument, 0, 'h'},
920 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000921 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000922 {0, 0, 0, 0}
923 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800924 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000925 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100926 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000927 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100928 }
bellardea2384d2004-08-01 21:59:26 +0000929 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800930 case ':':
931 missing_argument(argv[optind - 1]);
932 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100933 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800934 unrecognized_option(argv[optind - 1]);
935 break;
bellardea2384d2004-08-01 21:59:26 +0000936 case 'h':
937 help();
938 break;
939 case 'f':
940 fmt = optarg;
941 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400942 case 't':
943 cache = optarg;
944 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200945 case 'b':
946 base = optarg;
947 /* -b implies -d */
948 drop = true;
949 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200950 case 'd':
951 drop = true;
952 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200953 case 'p':
954 progress = true;
955 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100956 case 'q':
957 quiet = true;
958 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000959 case OPTION_OBJECT: {
960 QemuOpts *opts;
961 opts = qemu_opts_parse_noisily(&qemu_object_opts,
962 optarg, true);
963 if (!opts) {
964 return 1;
965 }
966 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000967 case OPTION_IMAGE_OPTS:
968 image_opts = true;
969 break;
bellardea2384d2004-08-01 21:59:26 +0000970 }
971 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200972
973 /* Progress is not shown in Quiet mode */
974 if (quiet) {
975 progress = false;
976 }
977
Kevin Wolffc11eb22013-08-05 10:53:04 +0200978 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800979 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100980 }
bellardea2384d2004-08-01 21:59:26 +0000981 filename = argv[optind++];
982
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000983 if (qemu_opts_foreach(&qemu_object_opts,
984 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +0200985 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000986 return 1;
987 }
988
Max Reitz9a86fe42014-10-24 15:57:38 +0200989 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100990 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400991 if (ret < 0) {
992 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100993 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400994 }
995
Fam Zheng335e9932017-05-03 00:35:39 +0800996 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
997 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200998 if (!blk) {
999 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001000 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001001 bs = blk_bs(blk);
1002
Max Reitz687fa1d2014-10-24 15:57:39 +02001003 qemu_progress_init(progress, 1.f);
1004 qemu_progress_print(0.f, 100);
1005
Max Reitz1b22bff2014-10-24 15:57:40 +02001006 if (base) {
1007 base_bs = bdrv_find_backing_image(bs, base);
1008 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001009 error_setg(&local_err,
1010 "Did not find '%s' in the backing chain of '%s'",
1011 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001012 goto done;
1013 }
1014 } else {
1015 /* This is different from QMP, which by default uses the deepest file in
1016 * the backing chain (i.e., the very base); however, the traditional
1017 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001018 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001019 if (!base_bs) {
1020 error_setg(&local_err, "Image does not have a backing file");
1021 goto done;
1022 }
bellardea2384d2004-08-01 21:59:26 +00001023 }
1024
Max Reitzd4a32382014-10-24 15:57:37 +02001025 cbi = (CommonBlockJobCBInfo){
1026 .errp = &local_err,
1027 .bs = bs,
1028 };
1029
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001030 aio_context = bdrv_get_aio_context(bs);
1031 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001032 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001033 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001034 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001035 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001036 if (local_err) {
1037 goto done;
1038 }
1039
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001040 /* When the block job completes, the BlockBackend reference will point to
1041 * the old backing file. In order to avoid that the top image is already
1042 * deleted, so we can still empty it afterwards, increment the reference
1043 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001044 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001045 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001046 }
1047
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001048 job = block_job_get("commit");
1049 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001050 if (local_err) {
1051 goto unref_backing;
1052 }
1053
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001054 if (!drop && bs->drv->bdrv_make_empty) {
1055 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001056 if (ret) {
1057 error_setg_errno(&local_err, -ret, "Could not empty %s",
1058 filename);
1059 goto unref_backing;
1060 }
1061 }
1062
1063unref_backing:
1064 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001065 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001066 }
Max Reitzd4a32382014-10-24 15:57:37 +02001067
1068done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001069 qemu_progress_end();
1070
Markus Armbruster26f54e92014-10-07 13:59:04 +02001071 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001072
1073 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001074 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001075 return 1;
1076 }
Max Reitzd4a32382014-10-24 15:57:37 +02001077
1078 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001079 return 0;
1080}
1081
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001082/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001083 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1084 * of the first sector boundary within buf where the sector contains a
1085 * non-zero byte. This function is robust to a buffer that is not
1086 * sector-aligned.
1087 */
1088static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1089{
1090 int64_t i;
1091 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1092
1093 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1094 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1095 return i;
1096 }
1097 }
1098 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1099 return i;
1100 }
1101 return -1;
1102}
1103
1104/*
thsf58c7b32008-06-05 21:53:49 +00001105 * Returns true iff the first sector pointed to by 'buf' contains at least
1106 * a non-NUL byte.
1107 *
1108 * 'pnum' is set to the number of sectors (including and immediately following
1109 * the first one) that are known to be in the same allocated/unallocated state.
1110 */
bellardea2384d2004-08-01 21:59:26 +00001111static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
1112{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001113 bool is_zero;
1114 int i;
bellardea2384d2004-08-01 21:59:26 +00001115
1116 if (n <= 0) {
1117 *pnum = 0;
1118 return 0;
1119 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001120 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001121 for(i = 1; i < n; i++) {
1122 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001123 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001124 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001125 }
bellardea2384d2004-08-01 21:59:26 +00001126 }
1127 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001128 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001129}
1130
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001131/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001132 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1133 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1134 * breaking up write requests for only small sparse areas.
1135 */
1136static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
1137 int min)
1138{
1139 int ret;
1140 int num_checked, num_used;
1141
1142 if (n < min) {
1143 min = n;
1144 }
1145
1146 ret = is_allocated_sectors(buf, n, pnum);
1147 if (!ret) {
1148 return ret;
1149 }
1150
1151 num_used = *pnum;
1152 buf += BDRV_SECTOR_SIZE * *pnum;
1153 n -= *pnum;
1154 num_checked = num_used;
1155
1156 while (n > 0) {
1157 ret = is_allocated_sectors(buf, n, pnum);
1158
1159 buf += BDRV_SECTOR_SIZE * *pnum;
1160 n -= *pnum;
1161 num_checked += *pnum;
1162 if (ret) {
1163 num_used = num_checked;
1164 } else if (*pnum >= min) {
1165 break;
1166 }
1167 }
1168
1169 *pnum = num_used;
1170 return 1;
1171}
1172
1173/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001174 * Compares two buffers sector by sector. Returns 0 if the first
1175 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001176 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001177 * pnum is set to the sector-aligned size of the buffer prefix that
1178 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001179 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001180static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1181 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001182{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001183 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001184 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001185
Eric Blakedc61cd32017-10-11 22:47:14 -05001186 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001187
Eric Blakedc61cd32017-10-11 22:47:14 -05001188 res = !!memcmp(buf1, buf2, i);
1189 while (i < bytes) {
1190 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001191
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001193 break;
1194 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001195 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001196 }
1197
1198 *pnum = i;
1199 return res;
1200}
1201
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001202#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001203
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001204/*
1205 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1206 *
Eric Blake0608e402017-10-11 22:47:12 -05001207 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1208 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1209 * failure), and 4 on error (the exit status for read errors), after emitting
1210 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001211 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001212 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001213 * @param offset: Starting offset to check
1214 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001215 * @param filename: Name of disk file we are checking (logging purpose)
1216 * @param buffer: Allocated buffer for storing read data
1217 * @param quiet: Flag for quiet mode
1218 */
Eric Blakec41508e2017-10-11 22:47:13 -05001219static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1220 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 uint8_t *buffer, bool quiet)
1222{
Eric Blakedebb38a2017-10-11 22:47:11 -05001223 int ret = 0;
1224 int64_t idx;
1225
Eric Blakec41508e2017-10-11 22:47:13 -05001226 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001227 if (ret < 0) {
1228 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001229 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001230 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001231 }
Eric Blakec41508e2017-10-11 22:47:13 -05001232 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001233 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001235 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001236 return 1;
1237 }
1238
1239 return 0;
1240}
1241
1242/*
1243 * Compares two images. Exit codes:
1244 *
1245 * 0 - Images are identical
1246 * 1 - Images differ
1247 * >1 - Error occurred
1248 */
1249static int img_compare(int argc, char **argv)
1250{
Max Reitz40055952014-07-22 22:58:42 +02001251 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001252 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001253 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001254 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001255 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001256 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001257 int allocated1, allocated2;
1258 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1259 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001260 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001261 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001262 int64_t total_size;
1263 int64_t offset = 0;
1264 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001265 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001266 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001267 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001268 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001269
Max Reitz40055952014-07-22 22:58:42 +02001270 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001271 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001272 static const struct option long_options[] = {
1273 {"help", no_argument, 0, 'h'},
1274 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001275 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001276 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001277 {0, 0, 0, 0}
1278 };
Fam Zheng335e9932017-05-03 00:35:39 +08001279 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001280 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001281 if (c == -1) {
1282 break;
1283 }
1284 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001285 case ':':
1286 missing_argument(argv[optind - 1]);
1287 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001289 unrecognized_option(argv[optind - 1]);
1290 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001291 case 'h':
1292 help();
1293 break;
1294 case 'f':
1295 fmt1 = optarg;
1296 break;
1297 case 'F':
1298 fmt2 = optarg;
1299 break;
Max Reitz40055952014-07-22 22:58:42 +02001300 case 'T':
1301 cache = optarg;
1302 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001303 case 'p':
1304 progress = true;
1305 break;
1306 case 'q':
1307 quiet = true;
1308 break;
1309 case 's':
1310 strict = true;
1311 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001312 case 'U':
1313 force_share = true;
1314 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001315 case OPTION_OBJECT: {
1316 QemuOpts *opts;
1317 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1318 optarg, true);
1319 if (!opts) {
1320 ret = 2;
1321 goto out4;
1322 }
1323 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001324 case OPTION_IMAGE_OPTS:
1325 image_opts = true;
1326 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001327 }
1328 }
1329
1330 /* Progress is not shown in Quiet mode */
1331 if (quiet) {
1332 progress = false;
1333 }
1334
1335
Kevin Wolffc11eb22013-08-05 10:53:04 +02001336 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001337 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001338 }
1339 filename1 = argv[optind++];
1340 filename2 = argv[optind++];
1341
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001342 if (qemu_opts_foreach(&qemu_object_opts,
1343 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02001344 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001345 ret = 2;
1346 goto out4;
1347 }
1348
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001349 /* Initialize before goto out */
1350 qemu_progress_init(progress, 2.0);
1351
Kevin Wolfce099542016-03-15 13:01:04 +01001352 flags = 0;
1353 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001354 if (ret < 0) {
1355 error_report("Invalid source cache option: %s", cache);
1356 ret = 2;
1357 goto out3;
1358 }
1359
Fam Zheng335e9932017-05-03 00:35:39 +08001360 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1361 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001362 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001363 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001364 goto out3;
1365 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001366
Fam Zheng335e9932017-05-03 00:35:39 +08001367 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1368 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001369 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001370 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001371 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001372 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001373 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001374 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001375
Max Reitzf1d3cd72015-02-05 13:58:18 -05001376 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1377 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001378 total_size1 = blk_getlength(blk1);
1379 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001380 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001381 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001382 ret = 4;
1383 goto out;
1384 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001385 total_size2 = blk_getlength(blk2);
1386 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001387 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001388 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001389 ret = 4;
1390 goto out;
1391 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001392 total_size = MIN(total_size1, total_size2);
1393 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394
1395 qemu_progress_print(0, 100);
1396
Eric Blake033d9fc2017-10-11 22:47:16 -05001397 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001398 ret = 1;
1399 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1400 goto out;
1401 }
1402
Eric Blake033d9fc2017-10-11 22:47:16 -05001403 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001404 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001405
Eric Blake033d9fc2017-10-11 22:47:16 -05001406 status1 = bdrv_block_status_above(bs1, NULL, offset,
1407 total_size1 - offset, &pnum1, NULL,
1408 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001409 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001410 ret = 3;
1411 error_report("Sector allocation test failed for %s", filename1);
1412 goto out;
1413 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001414 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415
Eric Blake033d9fc2017-10-11 22:47:16 -05001416 status2 = bdrv_block_status_above(bs2, NULL, offset,
1417 total_size2 - offset, &pnum2, NULL,
1418 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001419 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001420 ret = 3;
1421 error_report("Sector allocation test failed for %s", filename2);
1422 goto out;
1423 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001424 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001425
1426 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001427 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428
Fam Zheng25ad8e62016-01-13 16:37:41 +08001429 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001430 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001431 ret = 1;
1432 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001433 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001434 goto out;
1435 }
1436 }
1437 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001438 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001439 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001440 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001441 int64_t pnum;
1442
Eric Blake033d9fc2017-10-11 22:47:16 -05001443 chunk = MIN(chunk, IO_BUF_SIZE);
1444 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001445 if (ret < 0) {
1446 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001447 " of %s: %s",
1448 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449 ret = 4;
1450 goto out;
1451 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001452 ret = blk_pread(blk2, offset, buf2, chunk);
1453 if (ret < 0) {
1454 error_report("Error while reading offset %" PRId64
1455 " of %s: %s",
1456 offset, filename2, strerror(-ret));
1457 ret = 4;
1458 goto out;
1459 }
1460 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1461 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001462 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001463 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001464 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001465 goto out;
1466 }
1467 }
1468 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001469 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001471 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001472 filename1, buf1, quiet);
1473 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001474 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001475 filename2, buf1, quiet);
1476 }
1477 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 goto out;
1479 }
1480 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 offset += chunk;
1482 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 }
1484
Eric Blake033d9fc2017-10-11 22:47:16 -05001485 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001486 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487 const char *filename_over;
1488
1489 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001491 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001492 filename_over = filename1;
1493 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001494 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001495 filename_over = filename2;
1496 }
1497
Eric Blake033d9fc2017-10-11 22:47:16 -05001498 while (offset < progress_base) {
1499 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1500 progress_base - offset, &chunk,
1501 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 if (ret < 0) {
1503 ret = 3;
1504 error_report("Sector allocation test failed for %s",
1505 filename_over);
1506 goto out;
1507
1508 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001509 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001510 chunk = MIN(chunk, IO_BUF_SIZE);
1511 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 filename_over, buf1, quiet);
1513 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001514 goto out;
1515 }
1516 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001517 offset += chunk;
1518 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 }
1520 }
1521
1522 qprintf(quiet, "Images are identical.\n");
1523 ret = 0;
1524
1525out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001526 qemu_vfree(buf1);
1527 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001528 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001529out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001530 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001531out3:
1532 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001533out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534 return ret;
1535}
1536
Kevin Wolf690c7302015-03-19 13:33:32 +01001537enum ImgConvertBlockStatus {
1538 BLK_DATA,
1539 BLK_ZERO,
1540 BLK_BACKING_FILE,
1541};
1542
Peter Lieven2d9187b2017-02-28 13:40:07 +01001543#define MAX_COROUTINES 16
1544
Kevin Wolf690c7302015-03-19 13:33:32 +01001545typedef struct ImgConvertState {
1546 BlockBackend **src;
1547 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001548 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001549 int64_t total_sectors;
1550 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001551 int64_t allocated_done;
1552 int64_t sector_num;
1553 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001554 enum ImgConvertBlockStatus status;
1555 int64_t sector_next_status;
1556 BlockBackend *target;
1557 bool has_zero_init;
1558 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001559 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001560 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001561 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001562 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001563 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001564 int min_sparse;
1565 size_t cluster_sectors;
1566 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001567 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568 int running_coroutines;
1569 Coroutine *co[MAX_COROUTINES];
1570 int64_t wait_sector_num[MAX_COROUTINES];
1571 CoMutex lock;
1572 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001573} ImgConvertState;
1574
Peter Lieven2d9187b2017-02-28 13:40:07 +01001575static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1576 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001577{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001578 *src_cur = 0;
1579 *src_cur_offset = 0;
1580 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1581 *src_cur_offset += s->src_sectors[*src_cur];
1582 (*src_cur)++;
1583 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001584 }
1585}
1586
1587static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1588{
Eric Blake31826642017-10-11 22:47:08 -05001589 int64_t src_cur_offset;
1590 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001591 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001592
Peter Lieven2d9187b2017-02-28 13:40:07 +01001593 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001594
1595 assert(s->total_sectors > sector_num);
1596 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1597
Max Reitz351c8ef2018-05-01 18:57:49 +02001598 if (s->target_backing_sectors >= 0) {
1599 if (sector_num >= s->target_backing_sectors) {
1600 post_backing_zero = s->unallocated_blocks_are_zero;
1601 } else if (sector_num + n > s->target_backing_sectors) {
1602 /* Split requests around target_backing_sectors (because
1603 * starting from there, zeros are handled differently) */
1604 n = s->target_backing_sectors - sector_num;
1605 }
1606 }
1607
Kevin Wolf690c7302015-03-19 13:33:32 +01001608 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001609 int64_t count = n * BDRV_SECTOR_SIZE;
1610
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001611 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001612
1613 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1614 (sector_num - src_cur_offset) *
1615 BDRV_SECTOR_SIZE,
1616 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001617 } else {
Eric Blake31826642017-10-11 22:47:08 -05001618 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1619 (sector_num - src_cur_offset) *
1620 BDRV_SECTOR_SIZE,
1621 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001622 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001623 if (ret < 0) {
1624 return ret;
1625 }
Eric Blake31826642017-10-11 22:47:08 -05001626 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001627
1628 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001629 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 } else if (ret & BDRV_BLOCK_DATA) {
1631 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001632 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001633 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001634 }
1635
1636 s->sector_next_status = sector_num + n;
1637 }
1638
1639 n = MIN(n, s->sector_next_status - sector_num);
1640 if (s->status == BLK_DATA) {
1641 n = MIN(n, s->buf_sectors);
1642 }
1643
1644 /* We need to write complete clusters for compressed images, so if an
1645 * unallocated area is shorter than that, we must consider the whole
1646 * cluster allocated. */
1647 if (s->compressed) {
1648 if (n < s->cluster_sectors) {
1649 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1650 s->status = BLK_DATA;
1651 } else {
1652 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1653 }
1654 }
1655
1656 return n;
1657}
1658
Peter Lieven2d9187b2017-02-28 13:40:07 +01001659static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1660 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001661{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001662 int n, ret;
1663 QEMUIOVector qiov;
1664 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001665
Kevin Wolf690c7302015-03-19 13:33:32 +01001666 assert(nb_sectors <= s->buf_sectors);
1667 while (nb_sectors > 0) {
1668 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001669 int src_cur;
1670 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001671
1672 /* In the case of compression with multiple source files, we can get a
1673 * nb_sectors that spreads into the next part. So we must be able to
1674 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001675 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1676 blk = s->src[src_cur];
1677 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001678
Peter Lieven2d9187b2017-02-28 13:40:07 +01001679 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1680 iov.iov_base = buf;
1681 iov.iov_len = n << BDRV_SECTOR_BITS;
1682 qemu_iovec_init_external(&qiov, &iov, 1);
1683
1684 ret = blk_co_preadv(
1685 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1686 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001687 if (ret < 0) {
1688 return ret;
1689 }
1690
1691 sector_num += n;
1692 nb_sectors -= n;
1693 buf += n * BDRV_SECTOR_SIZE;
1694 }
1695
1696 return 0;
1697}
1698
Peter Lieven2d9187b2017-02-28 13:40:07 +01001699
1700static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1701 int nb_sectors, uint8_t *buf,
1702 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001703{
1704 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001705 QEMUIOVector qiov;
1706 struct iovec iov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001707
1708 while (nb_sectors > 0) {
1709 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001710 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1711
Peter Lieven2d9187b2017-02-28 13:40:07 +01001712 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001713 case BLK_BACKING_FILE:
1714 /* If we have a backing file, leave clusters unallocated that are
1715 * unallocated in the source image, so that the backing file is
1716 * visible at the respective offset. */
1717 assert(s->target_has_backing);
1718 break;
1719
1720 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001721 /* If we're told to keep the target fully allocated (-S 0) or there
1722 * is real non-zero data, we must write it. Otherwise we can treat
1723 * it as zero sectors.
1724 * Compressed clusters need to be written as a whole, so in that
1725 * case we can only save the write if the buffer is completely
1726 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001727 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001728 (!s->compressed &&
1729 is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
1730 (s->compressed &&
1731 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001732 {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001733 iov.iov_base = buf;
1734 iov.iov_len = n << BDRV_SECTOR_BITS;
1735 qemu_iovec_init_external(&qiov, &iov, 1);
1736
1737 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001738 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001739 if (ret < 0) {
1740 return ret;
1741 }
1742 break;
1743 }
1744 /* fall-through */
1745
1746 case BLK_ZERO:
1747 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001748 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 break;
1750 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001751 ret = blk_co_pwrite_zeroes(s->target,
1752 sector_num << BDRV_SECTOR_BITS,
1753 n << BDRV_SECTOR_BITS, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001754 if (ret < 0) {
1755 return ret;
1756 }
1757 break;
1758 }
1759
1760 sector_num += n;
1761 nb_sectors -= n;
1762 buf += n * BDRV_SECTOR_SIZE;
1763 }
1764
1765 return 0;
1766}
1767
Fam Zhengee5306d2018-06-01 17:26:48 +08001768static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1769 int nb_sectors)
1770{
1771 int n, ret;
1772
1773 while (nb_sectors > 0) {
1774 BlockBackend *blk;
1775 int src_cur;
1776 int64_t bs_sectors, src_cur_offset;
1777 int64_t offset;
1778
1779 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1780 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1781 blk = s->src[src_cur];
1782 bs_sectors = s->src_sectors[src_cur];
1783
1784 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1785
1786 ret = blk_co_copy_range(blk, offset, s->target,
1787 sector_num << BDRV_SECTOR_BITS,
1788 n << BDRV_SECTOR_BITS, 0);
1789 if (ret < 0) {
1790 return ret;
1791 }
1792
1793 sector_num += n;
1794 nb_sectors -= n;
1795 }
1796 return 0;
1797}
1798
Peter Lieven2d9187b2017-02-28 13:40:07 +01001799static void coroutine_fn convert_co_do_copy(void *opaque)
1800{
1801 ImgConvertState *s = opaque;
1802 uint8_t *buf = NULL;
1803 int ret, i;
1804 int index = -1;
1805
1806 for (i = 0; i < s->num_coroutines; i++) {
1807 if (s->co[i] == qemu_coroutine_self()) {
1808 index = i;
1809 break;
1810 }
1811 }
1812 assert(index >= 0);
1813
1814 s->running_coroutines++;
1815 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1816
1817 while (1) {
1818 int n;
1819 int64_t sector_num;
1820 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001821 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001822
1823 qemu_co_mutex_lock(&s->lock);
1824 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1825 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001826 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001827 }
1828 n = convert_iteration_sectors(s, s->sector_num);
1829 if (n < 0) {
1830 qemu_co_mutex_unlock(&s->lock);
1831 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001832 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001833 }
1834 /* save current sector and allocation status to local variables */
1835 sector_num = s->sector_num;
1836 status = s->status;
1837 if (!s->min_sparse && s->status == BLK_ZERO) {
1838 n = MIN(n, s->buf_sectors);
1839 }
1840 /* increment global sector counter so that other coroutines can
1841 * already continue reading beyond this request */
1842 s->sector_num += n;
1843 qemu_co_mutex_unlock(&s->lock);
1844
1845 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1846 s->allocated_done += n;
1847 qemu_progress_print(100.0 * s->allocated_done /
1848 s->allocated_sectors, 0);
1849 }
1850
Fam Zhengee5306d2018-06-01 17:26:48 +08001851retry:
1852 copy_range = s->copy_range && s->status == BLK_DATA;
1853 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001854 ret = convert_co_read(s, sector_num, n, buf);
1855 if (ret < 0) {
1856 error_report("error while reading sector %" PRId64
1857 ": %s", sector_num, strerror(-ret));
1858 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001859 }
1860 } else if (!s->min_sparse && status == BLK_ZERO) {
1861 status = BLK_DATA;
1862 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1863 }
1864
1865 if (s->wr_in_order) {
1866 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001867 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001868 s->wait_sector_num[index] = sector_num;
1869 qemu_coroutine_yield();
1870 }
1871 s->wait_sector_num[index] = -1;
1872 }
1873
Anton Nefedovb91127e2017-04-26 11:33:15 +03001874 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001875 if (copy_range) {
1876 ret = convert_co_copy_range(s, sector_num, n);
1877 if (ret) {
1878 s->copy_range = false;
1879 goto retry;
1880 }
1881 } else {
1882 ret = convert_co_write(s, sector_num, n, buf, status);
1883 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001884 if (ret < 0) {
1885 error_report("error while writing sector %" PRId64
1886 ": %s", sector_num, strerror(-ret));
1887 s->ret = ret;
1888 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001889 }
1890
1891 if (s->wr_in_order) {
1892 /* reenter the coroutine that might have waited
1893 * for this write to complete */
1894 s->wr_offs = sector_num + n;
1895 for (i = 0; i < s->num_coroutines; i++) {
1896 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1897 /*
1898 * A -> B -> A cannot occur because A has
1899 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1900 * B will never enter A during this time window.
1901 */
1902 qemu_coroutine_enter(s->co[i]);
1903 break;
1904 }
1905 }
1906 }
1907 }
1908
Peter Lieven2d9187b2017-02-28 13:40:07 +01001909 qemu_vfree(buf);
1910 s->co[index] = NULL;
1911 s->running_coroutines--;
1912 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1913 /* the convert job finished successfully */
1914 s->ret = 0;
1915 }
1916}
1917
Kevin Wolf690c7302015-03-19 13:33:32 +01001918static int convert_do_copy(ImgConvertState *s)
1919{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001920 int ret, i, n;
1921 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001922
1923 /* Check whether we have zero initialisation or can get it efficiently */
1924 s->has_zero_init = s->min_sparse && !s->target_has_backing
1925 ? bdrv_has_zero_init(blk_bs(s->target))
1926 : false;
1927
1928 if (!s->has_zero_init && !s->target_has_backing &&
1929 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1930 {
Kevin Wolf720ff282016-06-16 15:13:15 +02001931 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001932 if (ret == 0) {
1933 s->has_zero_init = true;
1934 }
1935 }
1936
1937 /* Allocate buffer for copied data. For compressed images, only one cluster
1938 * can be copied at a time. */
1939 if (s->compressed) {
1940 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1941 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001942 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001943 }
1944 s->buf_sectors = s->cluster_sectors;
1945 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001946
Kevin Wolf690c7302015-03-19 13:33:32 +01001947 while (sector_num < s->total_sectors) {
1948 n = convert_iteration_sectors(s, sector_num);
1949 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001950 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001951 }
Max Reitzaad15de2016-03-24 23:33:57 +01001952 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1953 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001954 s->allocated_sectors += n;
1955 }
1956 sector_num += n;
1957 }
1958
1959 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001960 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001961 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001962
Peter Lieven2d9187b2017-02-28 13:40:07 +01001963 qemu_co_mutex_init(&s->lock);
1964 for (i = 0; i < s->num_coroutines; i++) {
1965 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1966 s->wait_sector_num[i] = -1;
1967 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001968 }
1969
Anton Nefedovb91127e2017-04-26 11:33:15 +03001970 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001971 main_loop_wait(false);
1972 }
1973
1974 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001975 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001976 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001977 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001978 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001979 }
1980 }
1981
Peter Lieven2d9187b2017-02-28 13:40:07 +01001982 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001983}
1984
bellardea2384d2004-08-01 21:59:26 +00001985static int img_convert(int argc, char **argv)
1986{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001987 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001988 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001989 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1990 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001991 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001992 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001993 BlockDriverState *out_bs;
1994 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08001995 QemuOptsList *create_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02001996 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02001997 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001998 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001999 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002000 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002001 bool force_share = false;
bellardea2384d2004-08-01 21:59:26 +00002002
Peter Lieven9fd77f92017-04-21 11:11:55 +02002003 ImgConvertState s = (ImgConvertState) {
2004 /* Need at least 4k of zeros for sparse detection */
2005 .min_sparse = 8,
Fam Zhengee5306d2018-06-01 17:26:48 +08002006 .copy_range = true,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002007 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2008 .wr_in_order = true,
2009 .num_coroutines = 8,
2010 };
2011
bellardea2384d2004-08-01 21:59:26 +00002012 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002013 static const struct option long_options[] = {
2014 {"help", no_argument, 0, 'h'},
2015 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002016 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002017 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002018 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002019 {0, 0, 0, 0}
2020 };
Daniel P. Berrange6b4df542017-07-04 13:30:09 +01002021 c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002022 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002023 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002024 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002025 }
bellardea2384d2004-08-01 21:59:26 +00002026 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002027 case ':':
2028 missing_argument(argv[optind - 1]);
2029 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002030 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002031 unrecognized_option(argv[optind - 1]);
2032 break;
bellardea2384d2004-08-01 21:59:26 +00002033 case 'h':
2034 help();
2035 break;
2036 case 'f':
2037 fmt = optarg;
2038 break;
2039 case 'O':
2040 out_fmt = optarg;
2041 break;
thsf58c7b32008-06-05 21:53:49 +00002042 case 'B':
2043 out_baseimg = optarg;
2044 break;
bellardea2384d2004-08-01 21:59:26 +00002045 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002046 s.compressed = true;
Fam Zhengee5306d2018-06-01 17:26:48 +08002047 s.copy_range = false;
bellardea2384d2004-08-01 21:59:26 +00002048 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002049 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002050 if (!is_valid_option_list(optarg)) {
2051 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002052 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002053 }
2054 if (!options) {
2055 options = g_strdup(optarg);
2056 } else {
2057 char *old_options = options;
2058 options = g_strdup_printf("%s,%s", options, optarg);
2059 g_free(old_options);
2060 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002061 break;
edison51ef6722010-09-21 19:58:41 -07002062 case 's':
2063 snapshot_name = optarg;
2064 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002065 case 'l':
2066 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002067 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2068 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002069 if (!sn_opts) {
2070 error_report("Failed in parsing snapshot param '%s'",
2071 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002072 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002073 }
2074 } else {
2075 snapshot_name = optarg;
2076 }
2077 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002078 case 'S':
2079 {
2080 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002081
2082 sval = cvtnum(optarg);
2083 if (sval < 0) {
Kevin Wolfa22f1232011-08-26 15:27:13 +02002084 error_report("Invalid minimum zero buffer size for sparse output specified");
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002085 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002086 }
2087
Peter Lieven9fd77f92017-04-21 11:11:55 +02002088 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhengee5306d2018-06-01 17:26:48 +08002089 s.copy_range = false;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002090 break;
2091 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002092 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002093 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002094 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002095 case 't':
2096 cache = optarg;
2097 break;
Max Reitz40055952014-07-22 22:58:42 +02002098 case 'T':
2099 src_cache = optarg;
2100 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002101 case 'q':
2102 quiet = true;
2103 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002104 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002105 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002106 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002107 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002108 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2109 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002110 error_report("Invalid number of coroutines. Allowed number of"
2111 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002112 goto fail_getopt;
2113 }
2114 break;
2115 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002116 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002117 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002118 case 'U':
2119 force_share = true;
2120 break;
Max Reitz3258b912017-04-26 15:46:47 +02002121 case OPTION_OBJECT: {
2122 QemuOpts *object_opts;
2123 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2124 optarg, true);
2125 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002126 goto fail_getopt;
2127 }
2128 break;
Max Reitz3258b912017-04-26 15:46:47 +02002129 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002130 case OPTION_IMAGE_OPTS:
2131 image_opts = true;
2132 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002133 case OPTION_TARGET_IMAGE_OPTS:
2134 tgt_image_opts = true;
2135 break;
bellardea2384d2004-08-01 21:59:26 +00002136 }
2137 }
ths3b46e622007-09-17 08:09:54 +00002138
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002139 if (!out_fmt && !tgt_image_opts) {
2140 out_fmt = "raw";
2141 }
2142
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002143 if (qemu_opts_foreach(&qemu_object_opts,
2144 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002145 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002146 goto fail_getopt;
2147 }
2148
Peter Lieven9fd77f92017-04-21 11:11:55 +02002149 if (!s.wr_in_order && s.compressed) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002150 error_report("Out of order write and compress are mutually exclusive");
Peter Lieven9fd77f92017-04-21 11:11:55 +02002151 goto fail_getopt;
2152 }
2153
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002154 if (tgt_image_opts && !skip_create) {
2155 error_report("--target-image-opts requires use of -n flag");
2156 goto fail_getopt;
2157 }
2158
Peter Lieven9fd77f92017-04-21 11:11:55 +02002159 s.src_num = argc - optind - 1;
2160 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2161
2162 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002163 if (out_fmt) {
2164 ret = print_block_option_help(out_filename, out_fmt);
2165 goto fail_getopt;
2166 } else {
2167 error_report("Option help requires a format be specified");
2168 goto fail_getopt;
2169 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002170 }
2171
2172 if (s.src_num < 1) {
2173 error_report("Must specify image file name");
2174 goto fail_getopt;
2175 }
2176
2177
Peter Lieven9fd77f92017-04-21 11:11:55 +02002178 /* ret is still -EINVAL until here */
2179 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2180 if (ret < 0) {
2181 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002182 goto fail_getopt;
2183 }
2184
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002185 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002186 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002187 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002188 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002189 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002190 qemu_progress_print(0, 100);
2191
Peter Lieven9fd77f92017-04-21 11:11:55 +02002192 s.src = g_new0(BlockBackend *, s.src_num);
2193 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002194
Peter Lieven9fd77f92017-04-21 11:11:55 +02002195 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2196 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002197 fmt, src_flags, src_writethrough, quiet,
2198 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002199 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002200 ret = -1;
2201 goto out;
2202 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002203 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2204 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002205 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002206 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002207 ret = -1;
2208 goto out;
2209 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002210 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002211 }
bellardea2384d2004-08-01 21:59:26 +00002212
Wenchao Xiaef806542013-12-04 17:10:57 +08002213 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002214 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002215 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2216 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2217 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002218 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002219 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002220 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002221 ret = -1;
2222 goto out;
2223 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002224
Peter Lieven9fd77f92017-04-21 11:11:55 +02002225 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2226 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002227 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002228 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002229 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002230 ret = -1;
2231 goto out;
edison51ef6722010-09-21 19:58:41 -07002232 }
2233
Max Reitz2e024cd2015-02-11 09:58:46 -05002234 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002235 /* Find driver and parse its options */
2236 drv = bdrv_find_format(out_fmt);
2237 if (!drv) {
2238 error_report("Unknown file format '%s'", out_fmt);
2239 ret = -1;
2240 goto out;
2241 }
2242
2243 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2244 if (!proto_drv) {
2245 error_report_err(local_err);
2246 ret = -1;
2247 goto out;
2248 }
2249
Max Reitz2e024cd2015-02-11 09:58:46 -05002250 if (!drv->create_opts) {
2251 error_report("Format driver '%s' does not support image creation",
2252 drv->format_name);
2253 ret = -1;
2254 goto out;
2255 }
Max Reitzf75613c2014-12-02 18:32:46 +01002256
Max Reitz2e024cd2015-02-11 09:58:46 -05002257 if (!proto_drv->create_opts) {
2258 error_report("Protocol driver '%s' does not support image creation",
2259 proto_drv->format_name);
2260 ret = -1;
2261 goto out;
2262 }
Max Reitzf75613c2014-12-02 18:32:46 +01002263
Max Reitz2e024cd2015-02-11 09:58:46 -05002264 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2265 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002266
Max Reitz2e024cd2015-02-11 09:58:46 -05002267 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002268 if (options) {
2269 qemu_opts_do_parse(opts, options, NULL, &local_err);
2270 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002271 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002272 ret = -1;
2273 goto out;
2274 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002275 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002276
Peter Lieven9fd77f92017-04-21 11:11:55 +02002277 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002278 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002279 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2280 if (ret < 0) {
2281 goto out;
2282 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002283 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002284
Kevin Wolfa18953f2010-10-14 15:46:04 +02002285 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002286 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002287 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002288 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002289 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002290 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002291
Max Reitz48758a82017-04-26 15:46:48 +02002292 if (s.src_num > 1 && out_baseimg) {
2293 error_report("Having a backing file for the target makes no sense when "
2294 "concatenating multiple input images");
2295 ret = -1;
2296 goto out;
2297 }
2298
Kevin Wolfefa84d42009-05-18 16:42:12 +02002299 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002300 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002301 bool encryption =
2302 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002303 const char *encryptfmt =
2304 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002305 const char *preallocation =
2306 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002307
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002308 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002309 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002310 ret = -1;
2311 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002312 }
2313
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002314 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002315 error_report("Compression and encryption not supported at "
2316 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002317 ret = -1;
2318 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002319 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002320
Chunyan Liu83d05212014-06-05 17:20:51 +08002321 if (preallocation
2322 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002323 {
2324 error_report("Compression and preallocation not supported at "
2325 "the same time");
2326 ret = -1;
2327 goto out;
2328 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002329 }
2330
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002331 if (!skip_create) {
2332 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002333 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002334 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002335 error_reportf_err(local_err, "%s: error while converting %s: ",
2336 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002337 goto out;
bellardea2384d2004-08-01 21:59:26 +00002338 }
2339 }
ths3b46e622007-09-17 08:09:54 +00002340
Peter Lieven9fd77f92017-04-21 11:11:55 +02002341 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002342 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002343 if (ret < 0) {
2344 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002345 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002346 }
2347
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002348 if (skip_create) {
2349 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2350 flags, writethrough, quiet, false);
2351 } else {
2352 /* TODO ultimately we should allow --target-image-opts
2353 * to be used even when -n is not given.
2354 * That has to wait for bdrv_create to be improved
2355 * to allow filenames in option syntax
2356 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01002357 s.target = img_open_new_file(out_filename, opts, out_fmt,
2358 flags, writethrough, quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002359 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002360 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002361 ret = -1;
2362 goto out;
2363 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002364 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002365
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002366 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2367 error_report("Compression not supported for this file format");
2368 ret = -1;
2369 goto out;
2370 }
2371
Eric Blake5def6b82016-06-23 16:37:19 -06002372 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lievenf2521c92013-11-27 11:07:06 +01002373 * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
2374 * as maximum. */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002375 s.buf_sectors = MIN(32768,
2376 MAX(s.buf_sectors,
2377 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2378 out_bs->bl.pdiscard_alignment >>
2379 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002380
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002381 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002382 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002383 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002384 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002385 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002386 ret = -1;
2387 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002388 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002389 error_report("output file is smaller than input file");
2390 ret = -1;
2391 goto out;
2392 }
2393 }
2394
Max Reitz351c8ef2018-05-01 18:57:49 +02002395 if (s.target_has_backing) {
2396 /* Errors are treated as "backing length unknown" (which means
2397 * s.target_backing_sectors has to be negative, which it will
2398 * be automatically). The backing file length is used only
2399 * for optimizations, so such a case is not fatal. */
2400 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2401 } else {
2402 s.target_backing_sectors = -1;
2403 }
2404
Peter Lieven24f833c2013-11-27 11:07:07 +01002405 ret = bdrv_get_info(out_bs, &bdi);
2406 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002407 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002408 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002409 goto out;
2410 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002411 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002412 s.compressed = s.compressed || bdi.needs_compressed_writes;
2413 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002414 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002415 }
2416
Peter Lieven9fd77f92017-04-21 11:11:55 +02002417 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002418out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002419 if (!ret) {
2420 qemu_progress_print(100, 0);
2421 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002422 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002423 qemu_opts_del(opts);
2424 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002425 qemu_opts_del(sn_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002426 blk_unref(s.target);
2427 if (s.src) {
2428 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2429 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002430 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002431 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002432 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002433 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002434fail_getopt:
2435 g_free(options);
2436
Peter Lieven9fd77f92017-04-21 11:11:55 +02002437 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002438}
2439
bellard57d1a2b2004-08-03 21:15:11 +00002440
bellardfaea38e2006-08-05 21:31:00 +00002441static void dump_snapshots(BlockDriverState *bs)
2442{
2443 QEMUSnapshotInfo *sn_tab, *sn;
2444 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002445
2446 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2447 if (nb_sns <= 0)
2448 return;
2449 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002450 bdrv_snapshot_dump(fprintf, stdout, NULL);
2451 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002452 for(i = 0; i < nb_sns; i++) {
2453 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002454 bdrv_snapshot_dump(fprintf, stdout, sn);
2455 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002456 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002457 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002458}
2459
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002460static void dump_json_image_info_list(ImageInfoList *list)
2461{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002462 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002463 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002464 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002465
2466 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2467 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002468 str = qobject_to_json_pretty(obj);
2469 assert(str != NULL);
2470 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002471 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002472 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002473 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002474}
2475
Benoît Canetc054b3f2012-09-05 13:09:02 +02002476static void dump_json_image_info(ImageInfo *info)
2477{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002478 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002479 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002480 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002481
2482 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2483 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002484 str = qobject_to_json_pretty(obj);
2485 assert(str != NULL);
2486 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002487 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002488 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002489 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002490}
2491
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002492static void dump_human_image_info_list(ImageInfoList *list)
2493{
2494 ImageInfoList *elem;
2495 bool delim = false;
2496
2497 for (elem = list; elem; elem = elem->next) {
2498 if (delim) {
2499 printf("\n");
2500 }
2501 delim = true;
2502
Wenchao Xia5b917042013-05-25 11:09:45 +08002503 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002504 }
2505}
2506
2507static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2508{
2509 return strcmp(a, b) == 0;
2510}
2511
2512/**
2513 * Open an image file chain and return an ImageInfoList
2514 *
2515 * @filename: topmost image filename
2516 * @fmt: topmost image format (may be NULL to autodetect)
2517 * @chain: true - enumerate entire backing file chain
2518 * false - only topmost image file
2519 *
2520 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2521 * image file. If there was an error a message will have been printed to
2522 * stderr.
2523 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002524static ImageInfoList *collect_image_info_list(bool image_opts,
2525 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002526 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002527 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002528{
2529 ImageInfoList *head = NULL;
2530 ImageInfoList **last = &head;
2531 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002532 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002533
2534 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2535
2536 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002537 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002538 BlockDriverState *bs;
2539 ImageInfo *info;
2540 ImageInfoList *elem;
2541
2542 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2543 error_report("Backing file '%s' creates an infinite loop.",
2544 filename);
2545 goto err;
2546 }
2547 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2548
Max Reitzefaa7c42016-03-16 19:54:38 +01002549 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002550 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2551 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002552 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002553 goto err;
2554 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002555 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002556
Wenchao Xia43526ec2013-06-06 12:27:58 +08002557 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002558 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002559 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002560 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002561 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002562 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002563
2564 elem = g_new0(ImageInfoList, 1);
2565 elem->value = info;
2566 *last = elem;
2567 last = &elem->next;
2568
Markus Armbruster26f54e92014-10-07 13:59:04 +02002569 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002570
2571 filename = fmt = NULL;
2572 if (chain) {
2573 if (info->has_full_backing_filename) {
2574 filename = info->full_backing_filename;
2575 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002576 error_report("Could not determine absolute backing filename,"
2577 " but backing filename '%s' present",
2578 info->backing_filename);
2579 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002580 }
2581 if (info->has_backing_filename_format) {
2582 fmt = info->backing_filename_format;
2583 }
2584 }
2585 }
2586 g_hash_table_destroy(filenames);
2587 return head;
2588
2589err:
2590 qapi_free_ImageInfoList(head);
2591 g_hash_table_destroy(filenames);
2592 return NULL;
2593}
2594
Benoît Canetc054b3f2012-09-05 13:09:02 +02002595static int img_info(int argc, char **argv)
2596{
2597 int c;
2598 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002599 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002600 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002601 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002602 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002603 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002604
bellardea2384d2004-08-01 21:59:26 +00002605 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002606 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002607 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002608 int option_index = 0;
2609 static const struct option long_options[] = {
2610 {"help", no_argument, 0, 'h'},
2611 {"format", required_argument, 0, 'f'},
2612 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002613 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002614 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002615 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002616 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002617 {0, 0, 0, 0}
2618 };
Fam Zheng335e9932017-05-03 00:35:39 +08002619 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002620 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002621 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002622 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002623 }
bellardea2384d2004-08-01 21:59:26 +00002624 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002625 case ':':
2626 missing_argument(argv[optind - 1]);
2627 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002628 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002629 unrecognized_option(argv[optind - 1]);
2630 break;
bellardea2384d2004-08-01 21:59:26 +00002631 case 'h':
2632 help();
2633 break;
2634 case 'f':
2635 fmt = optarg;
2636 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002637 case 'U':
2638 force_share = true;
2639 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002640 case OPTION_OUTPUT:
2641 output = optarg;
2642 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002643 case OPTION_BACKING_CHAIN:
2644 chain = true;
2645 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002646 case OPTION_OBJECT: {
2647 QemuOpts *opts;
2648 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2649 optarg, true);
2650 if (!opts) {
2651 return 1;
2652 }
2653 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002654 case OPTION_IMAGE_OPTS:
2655 image_opts = true;
2656 break;
bellardea2384d2004-08-01 21:59:26 +00002657 }
2658 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002659 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002660 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002661 }
bellardea2384d2004-08-01 21:59:26 +00002662 filename = argv[optind++];
2663
Benoît Canetc054b3f2012-09-05 13:09:02 +02002664 if (output && !strcmp(output, "json")) {
2665 output_format = OFORMAT_JSON;
2666 } else if (output && !strcmp(output, "human")) {
2667 output_format = OFORMAT_HUMAN;
2668 } else if (output) {
2669 error_report("--output must be used with human or json as argument.");
2670 return 1;
2671 }
2672
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002673 if (qemu_opts_foreach(&qemu_object_opts,
2674 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002675 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002676 return 1;
2677 }
2678
Fam Zheng335e9932017-05-03 00:35:39 +08002679 list = collect_image_info_list(image_opts, filename, fmt, chain,
2680 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002681 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002682 return 1;
2683 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002684
Benoît Canetc054b3f2012-09-05 13:09:02 +02002685 switch (output_format) {
2686 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002687 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002688 break;
2689 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002690 if (chain) {
2691 dump_json_image_info_list(list);
2692 } else {
2693 dump_json_image_info(list->value);
2694 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002695 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002696 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002697
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002698 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002699 return 0;
2700}
2701
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002702static void dump_map_entry(OutputFormat output_format, MapEntry *e,
2703 MapEntry *next)
2704{
2705 switch (output_format) {
2706 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002707 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002708 error_report("File contains external, encrypted or compressed clusters.");
2709 exit(1);
2710 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002711 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002712 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002713 e->start, e->length,
2714 e->has_offset ? e->offset : 0,
2715 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002716 }
2717 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2718 * Modify the flags here to allow more coalescing.
2719 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002720 if (next && (!next->data || next->zero)) {
2721 next->data = false;
2722 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002723 }
2724 break;
2725 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002726 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2727 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002728 (e->start == 0 ? "[" : ",\n"),
2729 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002730 e->zero ? "true" : "false",
2731 e->data ? "true" : "false");
2732 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002733 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002734 }
2735 putchar('}');
2736
2737 if (!next) {
2738 printf("]\n");
2739 }
2740 break;
2741 }
2742}
2743
Eric Blake5e344dd2017-10-11 22:47:02 -05002744static int get_block_status(BlockDriverState *bs, int64_t offset,
2745 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002746{
Eric Blake237d78f2017-10-11 22:47:03 -05002747 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002748 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002749 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002750 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002751 int64_t map;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002752
2753 /* As an optimization, we could cache the current range of unallocated
2754 * clusters in each file of the chain, and avoid querying the same
2755 * range repeatedly.
2756 */
2757
2758 depth = 0;
2759 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002760 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002761 if (ret < 0) {
2762 return ret;
2763 }
Eric Blake237d78f2017-10-11 22:47:03 -05002764 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002765 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2766 break;
2767 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002768 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002769 if (bs == NULL) {
2770 ret = 0;
2771 break;
2772 }
2773
2774 depth++;
2775 }
2776
John Snow28756452016-02-05 13:12:33 -05002777 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2778
2779 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002780 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002781 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002782 .data = !!(ret & BDRV_BLOCK_DATA),
2783 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002784 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002785 .has_offset = has_offset,
2786 .depth = depth,
2787 .has_filename = file && has_offset,
2788 .filename = file && has_offset ? file->filename : NULL,
2789 };
2790
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791 return 0;
2792}
2793
Fam Zheng16b0d552016-01-26 11:59:02 +08002794static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2795{
2796 if (curr->length == 0) {
2797 return false;
2798 }
2799 if (curr->zero != next->zero ||
2800 curr->data != next->data ||
2801 curr->depth != next->depth ||
2802 curr->has_filename != next->has_filename ||
2803 curr->has_offset != next->has_offset) {
2804 return false;
2805 }
2806 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2807 return false;
2808 }
2809 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2810 return false;
2811 }
2812 return true;
2813}
2814
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002815static int img_map(int argc, char **argv)
2816{
2817 int c;
2818 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002819 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002820 BlockDriverState *bs;
2821 const char *filename, *fmt, *output;
2822 int64_t length;
2823 MapEntry curr = { .length = 0 }, next;
2824 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002825 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002826 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002827
2828 fmt = NULL;
2829 output = NULL;
2830 for (;;) {
2831 int option_index = 0;
2832 static const struct option long_options[] = {
2833 {"help", no_argument, 0, 'h'},
2834 {"format", required_argument, 0, 'f'},
2835 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002836 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002837 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002838 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002839 {0, 0, 0, 0}
2840 };
Fam Zheng335e9932017-05-03 00:35:39 +08002841 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002842 long_options, &option_index);
2843 if (c == -1) {
2844 break;
2845 }
2846 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002847 case ':':
2848 missing_argument(argv[optind - 1]);
2849 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002850 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002851 unrecognized_option(argv[optind - 1]);
2852 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002853 case 'h':
2854 help();
2855 break;
2856 case 'f':
2857 fmt = optarg;
2858 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002859 case 'U':
2860 force_share = true;
2861 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002862 case OPTION_OUTPUT:
2863 output = optarg;
2864 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002865 case OPTION_OBJECT: {
2866 QemuOpts *opts;
2867 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2868 optarg, true);
2869 if (!opts) {
2870 return 1;
2871 }
2872 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002873 case OPTION_IMAGE_OPTS:
2874 image_opts = true;
2875 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002876 }
2877 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002878 if (optind != argc - 1) {
2879 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002880 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002881 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002882
2883 if (output && !strcmp(output, "json")) {
2884 output_format = OFORMAT_JSON;
2885 } else if (output && !strcmp(output, "human")) {
2886 output_format = OFORMAT_HUMAN;
2887 } else if (output) {
2888 error_report("--output must be used with human or json as argument.");
2889 return 1;
2890 }
2891
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002892 if (qemu_opts_foreach(&qemu_object_opts,
2893 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02002894 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002895 return 1;
2896 }
2897
Fam Zheng335e9932017-05-03 00:35:39 +08002898 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002899 if (!blk) {
2900 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002901 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002902 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002903
2904 if (output_format == OFORMAT_HUMAN) {
2905 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2906 }
2907
Max Reitzf1d3cd72015-02-05 13:58:18 -05002908 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002909 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002910 int64_t offset = curr.start + curr.length;
2911 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002912
2913 /* Probe up to 1 GiB at a time. */
Eric Blake5e344dd2017-10-11 22:47:02 -05002914 n = QEMU_ALIGN_DOWN(MIN(1 << 30, length - offset), BDRV_SECTOR_SIZE);
2915 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002916
2917 if (ret < 0) {
2918 error_report("Could not read file metadata: %s", strerror(-ret));
2919 goto out;
2920 }
2921
Fam Zheng16b0d552016-01-26 11:59:02 +08002922 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002923 curr.length += next.length;
2924 continue;
2925 }
2926
2927 if (curr.length > 0) {
2928 dump_map_entry(output_format, &curr, &next);
2929 }
2930 curr = next;
2931 }
2932
2933 dump_map_entry(output_format, &curr, NULL);
2934
2935out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002936 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002937 return ret < 0;
2938}
2939
aliguorif7b4a942009-01-07 17:40:15 +00002940#define SNAPSHOT_LIST 1
2941#define SNAPSHOT_CREATE 2
2942#define SNAPSHOT_APPLY 3
2943#define SNAPSHOT_DELETE 4
2944
Stuart Brady153859b2009-06-07 00:42:17 +01002945static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002946{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002947 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002948 BlockDriverState *bs;
2949 QEMUSnapshotInfo sn;
2950 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002951 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002952 int action = 0;
2953 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002954 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08002955 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002956 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002957 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00002958
Kevin Wolfce099542016-03-15 13:01:04 +01002959 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00002960 /* Parse commandline parameters */
2961 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002962 static const struct option long_options[] = {
2963 {"help", no_argument, 0, 'h'},
2964 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002965 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002966 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002967 {0, 0, 0, 0}
2968 };
Fam Zheng335e9932017-05-03 00:35:39 +08002969 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002970 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002971 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00002972 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002973 }
aliguorif7b4a942009-01-07 17:40:15 +00002974 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002975 case ':':
2976 missing_argument(argv[optind - 1]);
2977 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002978 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002979 unrecognized_option(argv[optind - 1]);
2980 break;
aliguorif7b4a942009-01-07 17:40:15 +00002981 case 'h':
2982 help();
Stuart Brady153859b2009-06-07 00:42:17 +01002983 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002984 case 'l':
2985 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002986 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002987 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002988 }
2989 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02002990 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00002991 break;
2992 case 'a':
2993 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002994 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01002995 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00002996 }
2997 action = SNAPSHOT_APPLY;
2998 snapshot_name = optarg;
2999 break;
3000 case 'c':
3001 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003002 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003003 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003004 }
3005 action = SNAPSHOT_CREATE;
3006 snapshot_name = optarg;
3007 break;
3008 case 'd':
3009 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003010 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003011 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003012 }
3013 action = SNAPSHOT_DELETE;
3014 snapshot_name = optarg;
3015 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003016 case 'q':
3017 quiet = true;
3018 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003019 case 'U':
3020 force_share = true;
3021 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003022 case OPTION_OBJECT: {
3023 QemuOpts *opts;
3024 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3025 optarg, true);
3026 if (!opts) {
3027 return 1;
3028 }
3029 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003030 case OPTION_IMAGE_OPTS:
3031 image_opts = true;
3032 break;
aliguorif7b4a942009-01-07 17:40:15 +00003033 }
3034 }
3035
Kevin Wolffc11eb22013-08-05 10:53:04 +02003036 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003037 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003038 }
aliguorif7b4a942009-01-07 17:40:15 +00003039 filename = argv[optind++];
3040
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003041 if (qemu_opts_foreach(&qemu_object_opts,
3042 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003043 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003044 return 1;
3045 }
3046
aliguorif7b4a942009-01-07 17:40:15 +00003047 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003048 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3049 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003050 if (!blk) {
3051 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003052 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003053 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003054
3055 /* Perform the requested action */
3056 switch(action) {
3057 case SNAPSHOT_LIST:
3058 dump_snapshots(bs);
3059 break;
3060
3061 case SNAPSHOT_CREATE:
3062 memset(&sn, 0, sizeof(sn));
3063 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3064
3065 qemu_gettimeofday(&tv);
3066 sn.date_sec = tv.tv_sec;
3067 sn.date_nsec = tv.tv_usec * 1000;
3068
3069 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003070 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003071 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003072 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003073 }
aliguorif7b4a942009-01-07 17:40:15 +00003074 break;
3075
3076 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003077 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003078 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003079 error_reportf_err(err, "Could not apply snapshot '%s': ",
3080 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003081 }
aliguorif7b4a942009-01-07 17:40:15 +00003082 break;
3083
3084 case SNAPSHOT_DELETE:
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003085 bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01003086 if (err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003087 error_reportf_err(err, "Could not delete snapshot '%s': ",
3088 snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003089 ret = 1;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003090 }
aliguorif7b4a942009-01-07 17:40:15 +00003091 break;
3092 }
3093
3094 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003095 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003096 if (ret) {
3097 return 1;
3098 }
Stuart Brady153859b2009-06-07 00:42:17 +01003099 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003100}
3101
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003102static int img_rebase(int argc, char **argv)
3103{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003104 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003105 uint8_t *buf_old = NULL;
3106 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003107 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003108 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003109 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3110 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003111 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003112 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003113 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003114 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003115 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003116 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003117 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003118
3119 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003120 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003121 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003122 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003123 out_baseimg = NULL;
3124 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003125 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003126 static const struct option long_options[] = {
3127 {"help", no_argument, 0, 'h'},
3128 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003129 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003130 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003131 {0, 0, 0, 0}
3132 };
Fam Zheng335e9932017-05-03 00:35:39 +08003133 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003134 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003135 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003136 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003137 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003138 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003139 case ':':
3140 missing_argument(argv[optind - 1]);
3141 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003142 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003143 unrecognized_option(argv[optind - 1]);
3144 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003145 case 'h':
3146 help();
3147 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003148 case 'f':
3149 fmt = optarg;
3150 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003151 case 'F':
3152 out_basefmt = optarg;
3153 break;
3154 case 'b':
3155 out_baseimg = optarg;
3156 break;
3157 case 'u':
3158 unsafe = 1;
3159 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003160 case 'p':
3161 progress = 1;
3162 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003163 case 't':
3164 cache = optarg;
3165 break;
Max Reitz40055952014-07-22 22:58:42 +02003166 case 'T':
3167 src_cache = optarg;
3168 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003169 case 'q':
3170 quiet = true;
3171 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003172 case OPTION_OBJECT: {
3173 QemuOpts *opts;
3174 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3175 optarg, true);
3176 if (!opts) {
3177 return 1;
3178 }
3179 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003180 case OPTION_IMAGE_OPTS:
3181 image_opts = true;
3182 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003183 case 'U':
3184 force_share = true;
3185 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003186 }
3187 }
3188
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003189 if (quiet) {
3190 progress = 0;
3191 }
3192
Fam Zhengac1307a2014-04-22 13:36:11 +08003193 if (optind != argc - 1) {
3194 error_exit("Expecting one image file name");
3195 }
3196 if (!unsafe && !out_baseimg) {
3197 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003198 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003199 filename = argv[optind++];
3200
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003201 if (qemu_opts_foreach(&qemu_object_opts,
3202 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003203 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003204 return 1;
3205 }
3206
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003207 qemu_progress_init(progress, 2.0);
3208 qemu_progress_print(0, 100);
3209
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003210 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003211 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003212 if (ret < 0) {
3213 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003214 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003215 }
3216
Kevin Wolfce099542016-03-15 13:01:04 +01003217 src_flags = 0;
3218 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003219 if (ret < 0) {
3220 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003221 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003222 }
3223
Kevin Wolfce099542016-03-15 13:01:04 +01003224 /* The source files are opened read-only, don't care about WCE */
3225 assert((src_flags & BDRV_O_RDWR) == 0);
3226 (void) src_writethrough;
3227
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003228 /*
3229 * Open the images.
3230 *
3231 * Ignore the old backing file for unsafe rebase in case we want to correct
3232 * the reference to a renamed or moved backing file.
3233 */
Fam Zheng335e9932017-05-03 00:35:39 +08003234 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3235 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003236 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003237 ret = -1;
3238 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003239 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003240 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003241
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003242 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003243 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003244 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003245 ret = -1;
3246 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003247 }
3248 }
3249
3250 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003251 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003252 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003253 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003254
Max Reitz644483d2015-02-05 13:58:17 -05003255 if (bs->backing_format[0] != '\0') {
3256 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003257 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003258 }
3259
Fam Zheng335e9932017-05-03 00:35:39 +08003260 if (force_share) {
3261 if (!options) {
3262 options = qdict_new();
3263 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003264 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003265 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003266 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003267 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003268 options, src_flags, &local_err);
3269 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003270 error_reportf_err(local_err,
3271 "Could not open old backing file '%s': ",
3272 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003273 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003274 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003275 }
Max Reitz644483d2015-02-05 13:58:17 -05003276
Alex Bligha6166732012-10-16 13:46:18 +01003277 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003278 const char *overlay_filename;
3279 char *out_real_path;
3280
Fam Zheng335e9932017-05-03 00:35:39 +08003281 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003282 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003283 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003284 }
3285 if (force_share) {
3286 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003287 }
3288
Max Reitzd16699b2018-05-09 20:20:01 +02003289 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3290 : bs->filename;
3291 out_real_path = g_malloc(PATH_MAX);
3292
3293 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3294 out_baseimg,
3295 out_real_path,
3296 PATH_MAX,
3297 &local_err);
3298 if (local_err) {
3299 error_reportf_err(local_err,
3300 "Could not resolve backing filename: ");
3301 ret = -1;
3302 g_free(out_real_path);
3303 goto out;
3304 }
3305
3306 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003307 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003308 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003309 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003310 error_reportf_err(local_err,
3311 "Could not open new backing file '%s': ",
3312 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003313 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003314 goto out;
3315 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003316 }
3317 }
3318
3319 /*
3320 * Check each unallocated cluster in the COW file. If it is unallocated,
3321 * accesses go to the backing file. We must therefore compare this cluster
3322 * in the old and new backing file, and if they differ we need to copy it
3323 * from the old backing file into the COW file.
3324 *
3325 * If qemu-img crashes during this step, no harm is done. The content of
3326 * the image is the same as the original one at any time.
3327 */
3328 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003329 int64_t size;
3330 int64_t old_backing_size;
3331 int64_t new_backing_size = 0;
3332 uint64_t offset;
3333 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003334 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003335
Max Reitzf1d3cd72015-02-05 13:58:18 -05003336 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3337 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003338
Eric Blake41536282017-10-11 22:47:15 -05003339 size = blk_getlength(blk);
3340 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003341 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003342 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003343 ret = -1;
3344 goto out;
3345 }
Eric Blake41536282017-10-11 22:47:15 -05003346 old_backing_size = blk_getlength(blk_old_backing);
3347 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003348 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003349
3350 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3351 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003352 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003353 ret = -1;
3354 goto out;
3355 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003356 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003357 new_backing_size = blk_getlength(blk_new_backing);
3358 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003359 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003360 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003361 ret = -1;
3362 goto out;
3363 }
Alex Bligha6166732012-10-16 13:46:18 +01003364 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003365
Eric Blake41536282017-10-11 22:47:15 -05003366 if (size != 0) {
3367 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003368 }
3369
Eric Blake41536282017-10-11 22:47:15 -05003370 for (offset = 0; offset < size; offset += n) {
3371 /* How many bytes can we handle with the next read? */
3372 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003373
3374 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003375 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003376 if (ret < 0) {
3377 error_report("error while reading image metadata: %s",
3378 strerror(-ret));
3379 goto out;
3380 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003381 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003382 continue;
3383 }
3384
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003385 /*
3386 * Read old and new backing file and take into consideration that
3387 * backing files may be smaller than the COW image.
3388 */
Eric Blake41536282017-10-11 22:47:15 -05003389 if (offset >= old_backing_size) {
3390 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003391 } else {
Eric Blake41536282017-10-11 22:47:15 -05003392 if (offset + n > old_backing_size) {
3393 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003394 }
3395
Eric Blake41536282017-10-11 22:47:15 -05003396 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003397 if (ret < 0) {
3398 error_report("error while reading from old backing file");
3399 goto out;
3400 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003401 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003402
Eric Blake41536282017-10-11 22:47:15 -05003403 if (offset >= new_backing_size || !blk_new_backing) {
3404 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003405 } else {
Eric Blake41536282017-10-11 22:47:15 -05003406 if (offset + n > new_backing_size) {
3407 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003408 }
3409
Eric Blake41536282017-10-11 22:47:15 -05003410 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003411 if (ret < 0) {
3412 error_report("error while reading from new backing file");
3413 goto out;
3414 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003415 }
3416
3417 /* If they differ, we need to write to the COW file */
3418 uint64_t written = 0;
3419
Eric Blake41536282017-10-11 22:47:15 -05003420 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003421 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003422
Eric Blake41536282017-10-11 22:47:15 -05003423 if (compare_buffers(buf_old + written, buf_new + written,
3424 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003425 {
Eric Blake41536282017-10-11 22:47:15 -05003426 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003427 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003428 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003429 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003430 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003431 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003432 }
3433 }
3434
3435 written += pnum;
3436 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003437 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003438 }
3439 }
3440
3441 /*
3442 * Change the backing file. All clusters that are different from the old
3443 * backing file are overwritten in the COW file now, so the visible content
3444 * doesn't change when we switch the backing file.
3445 */
Alex Bligha6166732012-10-16 13:46:18 +01003446 if (out_baseimg && *out_baseimg) {
3447 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3448 } else {
3449 ret = bdrv_change_backing_file(bs, NULL, NULL);
3450 }
3451
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003452 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003453 error_report("Could not change the backing file to '%s': No "
3454 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003455 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003456 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003457 out_baseimg, strerror(-ret));
3458 }
3459
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003460 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003461 /*
3462 * TODO At this point it is possible to check if any clusters that are
3463 * allocated in the COW file are the same in the backing file. If so, they
3464 * could be dropped from the COW file. Don't do this before switching the
3465 * backing file, in case of a crash this would lead to corruption.
3466 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003467out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003468 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003469 /* Cleanup */
3470 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003471 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003472 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003473 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003474 qemu_vfree(buf_old);
3475 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003476
Markus Armbruster26f54e92014-10-07 13:59:04 +02003477 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003478 if (ret) {
3479 return 1;
3480 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003481 return 0;
3482}
3483
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003484static int img_resize(int argc, char **argv)
3485{
Markus Armbruster6750e792015-02-12 17:43:08 +01003486 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003487 int c, ret, relative;
3488 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003489 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003490 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003491 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003492 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003493 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003494
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003495 static QemuOptsList resize_options = {
3496 .name = "resize_options",
3497 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3498 .desc = {
3499 {
3500 .name = BLOCK_OPT_SIZE,
3501 .type = QEMU_OPT_SIZE,
3502 .help = "Virtual disk size"
3503 }, {
3504 /* end of list */
3505 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003506 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003507 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003508 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003509 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003510
Kevin Wolfe80fec72011-04-29 10:58:12 +02003511 /* Remove size from argv manually so that negative numbers are not treated
3512 * as options by getopt. */
3513 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003514 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003515 return 1;
3516 }
3517
3518 size = argv[--argc];
3519
3520 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003521 fmt = NULL;
3522 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003523 static const struct option long_options[] = {
3524 {"help", no_argument, 0, 'h'},
3525 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003526 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003527 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003528 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003529 {0, 0, 0, 0}
3530 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003531 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003532 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003533 if (c == -1) {
3534 break;
3535 }
3536 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003537 case ':':
3538 missing_argument(argv[optind - 1]);
3539 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003540 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003541 unrecognized_option(argv[optind - 1]);
3542 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003543 case 'h':
3544 help();
3545 break;
3546 case 'f':
3547 fmt = optarg;
3548 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003549 case 'q':
3550 quiet = true;
3551 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003552 case OPTION_OBJECT: {
3553 QemuOpts *opts;
3554 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3555 optarg, true);
3556 if (!opts) {
3557 return 1;
3558 }
3559 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003560 case OPTION_IMAGE_OPTS:
3561 image_opts = true;
3562 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003563 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003564 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003565 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003566 if (prealloc == PREALLOC_MODE__MAX) {
3567 error_report("Invalid preallocation mode '%s'", optarg);
3568 return 1;
3569 }
3570 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003571 case OPTION_SHRINK:
3572 shrink = true;
3573 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003574 }
3575 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003576 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003577 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003578 }
3579 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003580
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003581 if (qemu_opts_foreach(&qemu_object_opts,
3582 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003583 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003584 return 1;
3585 }
3586
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003587 /* Choose grow, shrink, or absolute resize mode */
3588 switch (size[0]) {
3589 case '+':
3590 relative = 1;
3591 size++;
3592 break;
3593 case '-':
3594 relative = -1;
3595 size++;
3596 break;
3597 default:
3598 relative = 0;
3599 break;
3600 }
3601
3602 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003603 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003604 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003605 if (err) {
3606 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003607 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003608 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003609 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003610 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003611 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3612 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003613
Max Reitzefaa7c42016-03-16 19:54:38 +01003614 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003615 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3616 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003617 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003618 ret = -1;
3619 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003620 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003621
Max Reitzdc5f6902017-06-13 22:20:55 +02003622 current_size = blk_getlength(blk);
3623 if (current_size < 0) {
3624 error_report("Failed to inquire current image length: %s",
3625 strerror(-current_size));
3626 ret = -1;
3627 goto out;
3628 }
3629
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003630 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003631 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003632 } else {
3633 total_size = n;
3634 }
3635 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003636 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003637 ret = -1;
3638 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003639 }
3640
Max Reitzdc5f6902017-06-13 22:20:55 +02003641 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3642 error_report("Preallocation can only be used for growing images");
3643 ret = -1;
3644 goto out;
3645 }
3646
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003647 if (total_size < current_size && !shrink) {
3648 warn_report("Shrinking an image will delete all data beyond the "
3649 "shrunken image's end. Before performing such an "
3650 "operation, make sure there is no important data there.");
3651
3652 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3653 error_report(
3654 "Use the --shrink option to perform a shrink operation.");
3655 ret = -1;
3656 goto out;
3657 } else {
3658 warn_report("Using the --shrink option will suppress this message. "
3659 "Note that future versions of qemu-img may refuse to "
3660 "shrink images without this option.");
3661 }
3662 }
3663
Max Reitzdc5f6902017-06-13 22:20:55 +02003664 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003665 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003666 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003667 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003668 }
Max Reitz5279b302018-04-21 18:39:57 +02003669
3670 new_size = blk_getlength(blk);
3671 if (new_size < 0) {
3672 error_report("Failed to verify truncated image length: %s",
3673 strerror(-new_size));
3674 ret = -1;
3675 goto out;
3676 }
3677
3678 /* Some block drivers implement a truncation method, but only so
3679 * the user can cause qemu to refresh the image's size from disk.
3680 * The idea is that the user resizes the image outside of qemu and
3681 * then invokes block_resize to inform qemu about it.
3682 * (This includes iscsi and file-posix for device files.)
3683 * Of course, that is not the behavior someone invoking
3684 * qemu-img resize would find useful, so we catch that behavior
3685 * here and tell the user. */
3686 if (new_size != total_size && new_size == current_size) {
3687 error_report("Image was not resized; resizing may not be supported "
3688 "for this image");
3689 ret = -1;
3690 goto out;
3691 }
3692
3693 if (new_size != total_size) {
3694 warn_report("Image should have been resized to %" PRIi64
3695 " bytes, but was resized to %" PRIi64 " bytes",
3696 total_size, new_size);
3697 }
3698
3699 qprintf(quiet, "Image resized.\n");
3700
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003701out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003702 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003703 if (ret) {
3704 return 1;
3705 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003706 return 0;
3707}
3708
Max Reitz76a3a342014-10-27 11:12:51 +01003709static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003710 int64_t offset, int64_t total_work_size,
3711 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003712{
3713 qemu_progress_print(100.f * offset / total_work_size, 0);
3714}
3715
Max Reitz51641352018-05-09 23:00:20 +02003716static int print_amend_option_help(const char *format)
3717{
3718 BlockDriver *drv;
3719
3720 /* Find driver and parse its options */
3721 drv = bdrv_find_format(format);
3722 if (!drv) {
3723 error_report("Unknown file format '%s'", format);
3724 return 1;
3725 }
3726
3727 if (!drv->bdrv_amend_options) {
3728 error_report("Format driver '%s' does not support option amendment",
3729 format);
3730 return 1;
3731 }
3732
3733 /* Every driver supporting amendment must have create_opts */
3734 assert(drv->create_opts);
3735
3736 printf("Creation options for '%s':\n", format);
3737 qemu_opts_print_help(drv->create_opts);
3738 printf("\nNote that not all of these options may be amendable.\n");
3739 return 0;
3740}
3741
Max Reitz6f176b42013-09-03 10:09:50 +02003742static int img_amend(int argc, char **argv)
3743{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003744 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003745 int c, ret = 0;
3746 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003747 QemuOptsList *create_opts = NULL;
3748 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003749 const char *fmt = NULL, *filename, *cache;
3750 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003751 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003752 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003753 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003754 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003755 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003756
Max Reitzbd39e6e2014-07-22 22:58:43 +02003757 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003758 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003759 static const struct option long_options[] = {
3760 {"help", no_argument, 0, 'h'},
3761 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003762 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003763 {0, 0, 0, 0}
3764 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003765 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003766 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003767 if (c == -1) {
3768 break;
3769 }
3770
3771 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003772 case ':':
3773 missing_argument(argv[optind - 1]);
3774 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003775 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003776 unrecognized_option(argv[optind - 1]);
3777 break;
3778 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003779 help();
3780 break;
3781 case 'o':
3782 if (!is_valid_option_list(optarg)) {
3783 error_report("Invalid option list: %s", optarg);
3784 ret = -1;
3785 goto out_no_progress;
3786 }
3787 if (!options) {
3788 options = g_strdup(optarg);
3789 } else {
3790 char *old_options = options;
3791 options = g_strdup_printf("%s,%s", options, optarg);
3792 g_free(old_options);
3793 }
3794 break;
3795 case 'f':
3796 fmt = optarg;
3797 break;
3798 case 't':
3799 cache = optarg;
3800 break;
3801 case 'p':
3802 progress = true;
3803 break;
3804 case 'q':
3805 quiet = true;
3806 break;
3807 case OPTION_OBJECT:
3808 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3809 optarg, true);
3810 if (!opts) {
3811 ret = -1;
3812 goto out_no_progress;
3813 }
3814 break;
3815 case OPTION_IMAGE_OPTS:
3816 image_opts = true;
3817 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003818 }
3819 }
3820
Max Reitz6f176b42013-09-03 10:09:50 +02003821 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003822 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003823 }
3824
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003825 if (qemu_opts_foreach(&qemu_object_opts,
3826 user_creatable_add_opts_foreach,
Markus Armbruster51b9b472016-04-27 16:29:09 +02003827 NULL, NULL)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003828 ret = -1;
3829 goto out_no_progress;
3830 }
3831
Max Reitz76a3a342014-10-27 11:12:51 +01003832 if (quiet) {
3833 progress = false;
3834 }
3835 qemu_progress_init(progress, 1.0);
3836
Kevin Wolfa283cb62014-02-21 16:24:07 +01003837 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3838 if (fmt && has_help_option(options)) {
3839 /* If a format is explicitly specified (and possibly no filename is
3840 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003841 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003842 goto out;
3843 }
3844
3845 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003846 error_report("Expecting one image file name");
3847 ret = -1;
3848 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003849 }
Max Reitz6f176b42013-09-03 10:09:50 +02003850
Kevin Wolfce099542016-03-15 13:01:04 +01003851 flags = BDRV_O_RDWR;
3852 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003853 if (ret < 0) {
3854 error_report("Invalid cache option: %s", cache);
3855 goto out;
3856 }
3857
Fam Zheng335e9932017-05-03 00:35:39 +08003858 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3859 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003860 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003861 ret = -1;
3862 goto out;
3863 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003864 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003865
3866 fmt = bs->drv->format_name;
3867
Kevin Wolf626f84f2014-02-21 16:24:06 +01003868 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003869 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003870 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003871 goto out;
3872 }
3873
Max Reitz1f996682018-05-09 23:00:17 +02003874 if (!bs->drv->bdrv_amend_options) {
3875 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003876 fmt);
3877 ret = -1;
3878 goto out;
3879 }
3880
Max Reitz1f996682018-05-09 23:00:17 +02003881 /* Every driver supporting amendment must have create_opts */
3882 assert(bs->drv->create_opts);
3883
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003884 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003885 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003886 qemu_opts_do_parse(opts, options, NULL, &err);
3887 if (err) {
3888 error_report_err(err);
3889 ret = -1;
3890 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003891 }
3892
Max Reitz76a3a342014-10-27 11:12:51 +01003893 /* In case the driver does not call amend_status_cb() */
3894 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003895 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003896 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003897 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003898 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003899 goto out;
3900 }
3901
3902out:
Max Reitz76a3a342014-10-27 11:12:51 +01003903 qemu_progress_end();
3904
Max Reitze814dff2015-08-20 16:00:38 -07003905out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003906 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003907 qemu_opts_del(opts);
3908 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003909 g_free(options);
3910
Max Reitz6f176b42013-09-03 10:09:50 +02003911 if (ret) {
3912 return 1;
3913 }
3914 return 0;
3915}
3916
Kevin Wolfb6133b82014-08-05 14:17:13 +02003917typedef struct BenchData {
3918 BlockBackend *blk;
3919 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003920 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003921 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003922 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003923 int nrreq;
3924 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003925 int flush_interval;
3926 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003927 uint8_t *buf;
3928 QEMUIOVector *qiov;
3929
3930 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003931 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003932 uint64_t offset;
3933} BenchData;
3934
Kevin Wolf55d539c2016-06-03 13:59:41 +02003935static void bench_undrained_flush_cb(void *opaque, int ret)
3936{
3937 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003938 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003939 exit(EXIT_FAILURE);
3940 }
3941}
3942
Kevin Wolfb6133b82014-08-05 14:17:13 +02003943static void bench_cb(void *opaque, int ret)
3944{
3945 BenchData *b = opaque;
3946 BlockAIOCB *acb;
3947
3948 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003949 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02003950 exit(EXIT_FAILURE);
3951 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02003952
3953 if (b->in_flush) {
3954 /* Just finished a flush with drained queue: Start next requests */
3955 assert(b->in_flight == 0);
3956 b->in_flush = false;
3957 } else if (b->in_flight > 0) {
3958 int remaining = b->n - b->in_flight;
3959
Kevin Wolfb6133b82014-08-05 14:17:13 +02003960 b->n--;
3961 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003962
3963 /* Time for flush? Drain queue if requested, then flush */
3964 if (b->flush_interval && remaining % b->flush_interval == 0) {
3965 if (!b->in_flight || !b->drain_on_flush) {
3966 BlockCompletionFunc *cb;
3967
3968 if (b->drain_on_flush) {
3969 b->in_flush = true;
3970 cb = bench_cb;
3971 } else {
3972 cb = bench_undrained_flush_cb;
3973 }
3974
3975 acb = blk_aio_flush(b->blk, cb, b);
3976 if (!acb) {
3977 error_report("Failed to issue flush request");
3978 exit(EXIT_FAILURE);
3979 }
3980 }
3981 if (b->drain_on_flush) {
3982 return;
3983 }
3984 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02003985 }
3986
3987 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003988 int64_t offset = b->offset;
3989 /* blk_aio_* might look for completed I/Os and kick bench_cb
3990 * again, so make sure this operation is counted by in_flight
3991 * and b->offset is ready for the next submission.
3992 */
3993 b->in_flight++;
3994 b->offset += b->step;
3995 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003996 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003997 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003998 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01003999 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004000 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004001 if (!acb) {
4002 error_report("Failed to issue request");
4003 exit(EXIT_FAILURE);
4004 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004005 }
4006}
4007
4008static int img_bench(int argc, char **argv)
4009{
4010 int c, ret = 0;
4011 const char *fmt = NULL, *filename;
4012 bool quiet = false;
4013 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004014 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004015 int count = 75000;
4016 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004017 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004018 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004019 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004020 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004021 int flush_interval = 0;
4022 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004023 int64_t image_size;
4024 BlockBackend *blk = NULL;
4025 BenchData data = {};
4026 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004027 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004028 struct timeval t1, t2;
4029 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004030 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004031 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004032
4033 for (;;) {
4034 static const struct option long_options[] = {
4035 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004036 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004037 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004038 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004039 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004040 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004041 {0, 0, 0, 0}
4042 };
Fam Zheng335e9932017-05-03 00:35:39 +08004043 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004044 if (c == -1) {
4045 break;
4046 }
4047
4048 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004049 case ':':
4050 missing_argument(argv[optind - 1]);
4051 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004052 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004053 unrecognized_option(argv[optind - 1]);
4054 break;
4055 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004056 help();
4057 break;
4058 case 'c':
4059 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004060 unsigned long res;
4061
4062 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004063 error_report("Invalid request count specified");
4064 return 1;
4065 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004066 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004067 break;
4068 }
4069 case 'd':
4070 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004071 unsigned long res;
4072
4073 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004074 error_report("Invalid queue depth specified");
4075 return 1;
4076 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004077 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004078 break;
4079 }
4080 case 'f':
4081 fmt = optarg;
4082 break;
4083 case 'n':
4084 flags |= BDRV_O_NATIVE_AIO;
4085 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004086 case 'o':
4087 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004088 offset = cvtnum(optarg);
4089 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004090 error_report("Invalid offset specified");
4091 return 1;
4092 }
4093 break;
4094 }
4095 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004096 case 'q':
4097 quiet = true;
4098 break;
4099 case 's':
4100 {
4101 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004102
Markus Armbruster606caa02017-02-21 21:14:04 +01004103 sval = cvtnum(optarg);
4104 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004105 error_report("Invalid buffer size specified");
4106 return 1;
4107 }
4108
4109 bufsize = sval;
4110 break;
4111 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004112 case 'S':
4113 {
4114 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004115
Markus Armbruster606caa02017-02-21 21:14:04 +01004116 sval = cvtnum(optarg);
4117 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004118 error_report("Invalid step size specified");
4119 return 1;
4120 }
4121
4122 step = sval;
4123 break;
4124 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004125 case 't':
4126 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4127 if (ret < 0) {
4128 error_report("Invalid cache mode");
4129 ret = -1;
4130 goto out;
4131 }
4132 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004133 case 'w':
4134 flags |= BDRV_O_RDWR;
4135 is_write = true;
4136 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004137 case 'U':
4138 force_share = true;
4139 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004140 case OPTION_PATTERN:
4141 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004142 unsigned long res;
4143
4144 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004145 error_report("Invalid pattern byte specified");
4146 return 1;
4147 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004148 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004149 break;
4150 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004151 case OPTION_FLUSH_INTERVAL:
4152 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004153 unsigned long res;
4154
4155 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004156 error_report("Invalid flush interval specified");
4157 return 1;
4158 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004159 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004160 break;
4161 }
4162 case OPTION_NO_DRAIN:
4163 drain_on_flush = false;
4164 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004165 case OPTION_IMAGE_OPTS:
4166 image_opts = true;
4167 break;
4168 }
4169 }
4170
4171 if (optind != argc - 1) {
4172 error_exit("Expecting one image file name");
4173 }
4174 filename = argv[argc - 1];
4175
Kevin Wolf55d539c2016-06-03 13:59:41 +02004176 if (!is_write && flush_interval) {
4177 error_report("--flush-interval is only available in write tests");
4178 ret = -1;
4179 goto out;
4180 }
4181 if (flush_interval && flush_interval < depth) {
4182 error_report("Flush interval can't be smaller than depth");
4183 ret = -1;
4184 goto out;
4185 }
4186
Fam Zheng335e9932017-05-03 00:35:39 +08004187 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4188 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004189 if (!blk) {
4190 ret = -1;
4191 goto out;
4192 }
4193
4194 image_size = blk_getlength(blk);
4195 if (image_size < 0) {
4196 ret = image_size;
4197 goto out;
4198 }
4199
4200 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004201 .blk = blk,
4202 .image_size = image_size,
4203 .bufsize = bufsize,
4204 .step = step ?: bufsize,
4205 .nrreq = depth,
4206 .n = count,
4207 .offset = offset,
4208 .write = is_write,
4209 .flush_interval = flush_interval,
4210 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004211 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004212 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004213 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004214 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004215 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004216 if (flush_interval) {
4217 printf("Sending flush every %d requests\n", flush_interval);
4218 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004219
Fam Zheng79d46582018-01-16 14:08:58 +08004220 buf_size = data.nrreq * data.bufsize;
4221 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004222 memset(data.buf, pattern, data.nrreq * data.bufsize);
4223
Fam Zheng79d46582018-01-16 14:08:58 +08004224 blk_register_buf(blk, data.buf, buf_size);
4225
Kevin Wolfb6133b82014-08-05 14:17:13 +02004226 data.qiov = g_new(QEMUIOVector, data.nrreq);
4227 for (i = 0; i < data.nrreq; i++) {
4228 qemu_iovec_init(&data.qiov[i], 1);
4229 qemu_iovec_add(&data.qiov[i],
4230 data.buf + i * data.bufsize, data.bufsize);
4231 }
4232
4233 gettimeofday(&t1, NULL);
4234 bench_cb(&data, 0);
4235
4236 while (data.n > 0) {
4237 main_loop_wait(false);
4238 }
4239 gettimeofday(&t2, NULL);
4240
4241 printf("Run completed in %3.3f seconds.\n",
4242 (t2.tv_sec - t1.tv_sec)
4243 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4244
4245out:
Fam Zheng79d46582018-01-16 14:08:58 +08004246 if (data.buf) {
4247 blk_unregister_buf(blk, data.buf);
4248 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004249 qemu_vfree(data.buf);
4250 blk_unref(blk);
4251
4252 if (ret) {
4253 return 1;
4254 }
4255 return 0;
4256}
4257
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004258#define C_BS 01
4259#define C_COUNT 02
4260#define C_IF 04
4261#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004262#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004263
4264struct DdInfo {
4265 unsigned int flags;
4266 int64_t count;
4267};
4268
4269struct DdIo {
4270 int bsz; /* Block size */
4271 char *filename;
4272 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004273 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004274};
4275
4276struct DdOpts {
4277 const char *name;
4278 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4279 unsigned int flag;
4280};
4281
4282static int img_dd_bs(const char *arg,
4283 struct DdIo *in, struct DdIo *out,
4284 struct DdInfo *dd)
4285{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004286 int64_t res;
4287
Markus Armbruster606caa02017-02-21 21:14:04 +01004288 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004289
Markus Armbruster606caa02017-02-21 21:14:04 +01004290 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004291 error_report("invalid number: '%s'", arg);
4292 return 1;
4293 }
4294 in->bsz = out->bsz = res;
4295
4296 return 0;
4297}
4298
4299static int img_dd_count(const char *arg,
4300 struct DdIo *in, struct DdIo *out,
4301 struct DdInfo *dd)
4302{
Markus Armbruster606caa02017-02-21 21:14:04 +01004303 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004304
Markus Armbruster606caa02017-02-21 21:14:04 +01004305 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004306 error_report("invalid number: '%s'", arg);
4307 return 1;
4308 }
4309
4310 return 0;
4311}
4312
4313static int img_dd_if(const char *arg,
4314 struct DdIo *in, struct DdIo *out,
4315 struct DdInfo *dd)
4316{
4317 in->filename = g_strdup(arg);
4318
4319 return 0;
4320}
4321
4322static int img_dd_of(const char *arg,
4323 struct DdIo *in, struct DdIo *out,
4324 struct DdInfo *dd)
4325{
4326 out->filename = g_strdup(arg);
4327
4328 return 0;
4329}
4330
Reda Sallahif7c15532016-08-10 16:16:09 +02004331static int img_dd_skip(const char *arg,
4332 struct DdIo *in, struct DdIo *out,
4333 struct DdInfo *dd)
4334{
Markus Armbruster606caa02017-02-21 21:14:04 +01004335 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004336
Markus Armbruster606caa02017-02-21 21:14:04 +01004337 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004338 error_report("invalid number: '%s'", arg);
4339 return 1;
4340 }
4341
4342 return 0;
4343}
4344
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004345static int img_dd(int argc, char **argv)
4346{
4347 int ret = 0;
4348 char *arg = NULL;
4349 char *tmp;
4350 BlockDriver *drv = NULL, *proto_drv = NULL;
4351 BlockBackend *blk1 = NULL, *blk2 = NULL;
4352 QemuOpts *opts = NULL;
4353 QemuOptsList *create_opts = NULL;
4354 Error *local_err = NULL;
4355 bool image_opts = false;
4356 int c, i;
4357 const char *out_fmt = "raw";
4358 const char *fmt = NULL;
4359 int64_t size = 0;
4360 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004361 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004362 struct DdInfo dd = {
4363 .flags = 0,
4364 .count = 0,
4365 };
4366 struct DdIo in = {
4367 .bsz = 512, /* Block size is by default 512 bytes */
4368 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004369 .buf = NULL,
4370 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004371 };
4372 struct DdIo out = {
4373 .bsz = 512,
4374 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004375 .buf = NULL,
4376 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004377 };
4378
4379 const struct DdOpts options[] = {
4380 { "bs", img_dd_bs, C_BS },
4381 { "count", img_dd_count, C_COUNT },
4382 { "if", img_dd_if, C_IF },
4383 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004384 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004385 { NULL, NULL, 0 }
4386 };
4387 const struct option long_options[] = {
4388 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004389 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004390 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004391 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004392 { 0, 0, 0, 0 }
4393 };
4394
Fam Zheng335e9932017-05-03 00:35:39 +08004395 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004396 if (c == EOF) {
4397 break;
4398 }
4399 switch (c) {
4400 case 'O':
4401 out_fmt = optarg;
4402 break;
4403 case 'f':
4404 fmt = optarg;
4405 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004406 case ':':
4407 missing_argument(argv[optind - 1]);
4408 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004409 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004410 unrecognized_option(argv[optind - 1]);
4411 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004412 case 'h':
4413 help();
4414 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004415 case 'U':
4416 force_share = true;
4417 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004418 case OPTION_OBJECT:
4419 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004420 ret = -1;
4421 goto out;
4422 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004423 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004424 case OPTION_IMAGE_OPTS:
4425 image_opts = true;
4426 break;
4427 }
4428 }
4429
4430 for (i = optind; i < argc; i++) {
4431 int j;
4432 arg = g_strdup(argv[i]);
4433
4434 tmp = strchr(arg, '=');
4435 if (tmp == NULL) {
4436 error_report("unrecognized operand %s", arg);
4437 ret = -1;
4438 goto out;
4439 }
4440
4441 *tmp++ = '\0';
4442
4443 for (j = 0; options[j].name != NULL; j++) {
4444 if (!strcmp(arg, options[j].name)) {
4445 break;
4446 }
4447 }
4448 if (options[j].name == NULL) {
4449 error_report("unrecognized operand %s", arg);
4450 ret = -1;
4451 goto out;
4452 }
4453
4454 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4455 ret = -1;
4456 goto out;
4457 }
4458 dd.flags |= options[j].flag;
4459 g_free(arg);
4460 arg = NULL;
4461 }
4462
4463 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4464 error_report("Must specify both input and output files");
4465 ret = -1;
4466 goto out;
4467 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004468
4469 if (qemu_opts_foreach(&qemu_object_opts,
4470 user_creatable_add_opts_foreach,
4471 NULL, NULL)) {
4472 ret = -1;
4473 goto out;
4474 }
4475
Fam Zheng335e9932017-05-03 00:35:39 +08004476 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4477 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004478
4479 if (!blk1) {
4480 ret = -1;
4481 goto out;
4482 }
4483
4484 drv = bdrv_find_format(out_fmt);
4485 if (!drv) {
4486 error_report("Unknown file format");
4487 ret = -1;
4488 goto out;
4489 }
4490 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4491
4492 if (!proto_drv) {
4493 error_report_err(local_err);
4494 ret = -1;
4495 goto out;
4496 }
4497 if (!drv->create_opts) {
4498 error_report("Format driver '%s' does not support image creation",
4499 drv->format_name);
4500 ret = -1;
4501 goto out;
4502 }
4503 if (!proto_drv->create_opts) {
4504 error_report("Protocol driver '%s' does not support image creation",
4505 proto_drv->format_name);
4506 ret = -1;
4507 goto out;
4508 }
4509 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4510 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4511
4512 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4513
4514 size = blk_getlength(blk1);
4515 if (size < 0) {
4516 error_report("Failed to get size for '%s'", in.filename);
4517 ret = -1;
4518 goto out;
4519 }
4520
4521 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4522 dd.count * in.bsz < size) {
4523 size = dd.count * in.bsz;
4524 }
4525
Reda Sallahif7c15532016-08-10 16:16:09 +02004526 /* Overflow means the specified offset is beyond input image's size */
4527 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4528 size < in.bsz * in.offset)) {
4529 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4530 } else {
4531 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4532 size - in.bsz * in.offset, &error_abort);
4533 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004534
4535 ret = bdrv_create(drv, out.filename, opts, &local_err);
4536 if (ret < 0) {
4537 error_reportf_err(local_err,
4538 "%s: error while creating output image: ",
4539 out.filename);
4540 ret = -1;
4541 goto out;
4542 }
4543
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004544 /* TODO, we can't honour --image-opts for the target,
4545 * since it needs to be given in a format compatible
4546 * with the bdrv_create() call above which does not
4547 * support image-opts style.
4548 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004549 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004550 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004551
4552 if (!blk2) {
4553 ret = -1;
4554 goto out;
4555 }
4556
Reda Sallahif7c15532016-08-10 16:16:09 +02004557 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4558 size < in.offset * in.bsz)) {
4559 /* We give a warning if the skip option is bigger than the input
4560 * size and create an empty output disk image (i.e. like dd(1)).
4561 */
4562 error_report("%s: cannot skip to specified offset", in.filename);
4563 in_pos = size;
4564 } else {
4565 in_pos = in.offset * in.bsz;
4566 }
4567
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004568 in.buf = g_new(uint8_t, in.bsz);
4569
Reda Sallahif7c15532016-08-10 16:16:09 +02004570 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004571 int in_ret, out_ret;
4572
4573 if (in_pos + in.bsz > size) {
4574 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4575 } else {
4576 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4577 }
4578 if (in_ret < 0) {
4579 error_report("error while reading from input image file: %s",
4580 strerror(-in_ret));
4581 ret = -1;
4582 goto out;
4583 }
4584 in_pos += in_ret;
4585
4586 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4587
4588 if (out_ret < 0) {
4589 error_report("error while writing to output image file: %s",
4590 strerror(-out_ret));
4591 ret = -1;
4592 goto out;
4593 }
4594 out_pos += out_ret;
4595 }
4596
4597out:
4598 g_free(arg);
4599 qemu_opts_del(opts);
4600 qemu_opts_free(create_opts);
4601 blk_unref(blk1);
4602 blk_unref(blk2);
4603 g_free(in.filename);
4604 g_free(out.filename);
4605 g_free(in.buf);
4606 g_free(out.buf);
4607
4608 if (ret) {
4609 return 1;
4610 }
4611 return 0;
4612}
4613
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004614static void dump_json_block_measure_info(BlockMeasureInfo *info)
4615{
4616 QString *str;
4617 QObject *obj;
4618 Visitor *v = qobject_output_visitor_new(&obj);
4619
4620 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4621 visit_complete(v, &obj);
4622 str = qobject_to_json_pretty(obj);
4623 assert(str != NULL);
4624 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004625 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004626 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004627 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004628}
4629
4630static int img_measure(int argc, char **argv)
4631{
4632 static const struct option long_options[] = {
4633 {"help", no_argument, 0, 'h'},
4634 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4635 {"object", required_argument, 0, OPTION_OBJECT},
4636 {"output", required_argument, 0, OPTION_OUTPUT},
4637 {"size", required_argument, 0, OPTION_SIZE},
4638 {"force-share", no_argument, 0, 'U'},
4639 {0, 0, 0, 0}
4640 };
4641 OutputFormat output_format = OFORMAT_HUMAN;
4642 BlockBackend *in_blk = NULL;
4643 BlockDriver *drv;
4644 const char *filename = NULL;
4645 const char *fmt = NULL;
4646 const char *out_fmt = "raw";
4647 char *options = NULL;
4648 char *snapshot_name = NULL;
4649 bool force_share = false;
4650 QemuOpts *opts = NULL;
4651 QemuOpts *object_opts = NULL;
4652 QemuOpts *sn_opts = NULL;
4653 QemuOptsList *create_opts = NULL;
4654 bool image_opts = false;
4655 uint64_t img_size = UINT64_MAX;
4656 BlockMeasureInfo *info = NULL;
4657 Error *local_err = NULL;
4658 int ret = 1;
4659 int c;
4660
4661 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4662 long_options, NULL)) != -1) {
4663 switch (c) {
4664 case '?':
4665 case 'h':
4666 help();
4667 break;
4668 case 'f':
4669 fmt = optarg;
4670 break;
4671 case 'O':
4672 out_fmt = optarg;
4673 break;
4674 case 'o':
4675 if (!is_valid_option_list(optarg)) {
4676 error_report("Invalid option list: %s", optarg);
4677 goto out;
4678 }
4679 if (!options) {
4680 options = g_strdup(optarg);
4681 } else {
4682 char *old_options = options;
4683 options = g_strdup_printf("%s,%s", options, optarg);
4684 g_free(old_options);
4685 }
4686 break;
4687 case 'l':
4688 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4689 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4690 optarg, false);
4691 if (!sn_opts) {
4692 error_report("Failed in parsing snapshot param '%s'",
4693 optarg);
4694 goto out;
4695 }
4696 } else {
4697 snapshot_name = optarg;
4698 }
4699 break;
4700 case 'U':
4701 force_share = true;
4702 break;
4703 case OPTION_OBJECT:
4704 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4705 optarg, true);
4706 if (!object_opts) {
4707 goto out;
4708 }
4709 break;
4710 case OPTION_IMAGE_OPTS:
4711 image_opts = true;
4712 break;
4713 case OPTION_OUTPUT:
4714 if (!strcmp(optarg, "json")) {
4715 output_format = OFORMAT_JSON;
4716 } else if (!strcmp(optarg, "human")) {
4717 output_format = OFORMAT_HUMAN;
4718 } else {
4719 error_report("--output must be used with human or json "
4720 "as argument.");
4721 goto out;
4722 }
4723 break;
4724 case OPTION_SIZE:
4725 {
4726 int64_t sval;
4727
4728 sval = cvtnum(optarg);
4729 if (sval < 0) {
4730 if (sval == -ERANGE) {
4731 error_report("Image size must be less than 8 EiB!");
4732 } else {
4733 error_report("Invalid image size specified! You may use "
4734 "k, M, G, T, P or E suffixes for ");
4735 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4736 "petabytes and exabytes.");
4737 }
4738 goto out;
4739 }
4740 img_size = (uint64_t)sval;
4741 }
4742 break;
4743 }
4744 }
4745
4746 if (qemu_opts_foreach(&qemu_object_opts,
4747 user_creatable_add_opts_foreach,
4748 NULL, NULL)) {
4749 goto out;
4750 }
4751
4752 if (argc - optind > 1) {
4753 error_report("At most one filename argument is allowed.");
4754 goto out;
4755 } else if (argc - optind == 1) {
4756 filename = argv[optind];
4757 }
4758
4759 if (!filename &&
4760 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4761 error_report("--object, --image-opts, -f, and -l "
4762 "require a filename argument.");
4763 goto out;
4764 }
4765 if (filename && img_size != UINT64_MAX) {
4766 error_report("--size N cannot be used together with a filename.");
4767 goto out;
4768 }
4769 if (!filename && img_size == UINT64_MAX) {
4770 error_report("Either --size N or one filename must be specified.");
4771 goto out;
4772 }
4773
4774 if (filename) {
4775 in_blk = img_open(image_opts, filename, fmt, 0,
4776 false, false, force_share);
4777 if (!in_blk) {
4778 goto out;
4779 }
4780
4781 if (sn_opts) {
4782 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4783 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4784 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4785 &local_err);
4786 } else if (snapshot_name != NULL) {
4787 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4788 snapshot_name, &local_err);
4789 }
4790 if (local_err) {
4791 error_reportf_err(local_err, "Failed to load snapshot: ");
4792 goto out;
4793 }
4794 }
4795
4796 drv = bdrv_find_format(out_fmt);
4797 if (!drv) {
4798 error_report("Unknown file format '%s'", out_fmt);
4799 goto out;
4800 }
4801 if (!drv->create_opts) {
4802 error_report("Format driver '%s' does not support image creation",
4803 drv->format_name);
4804 goto out;
4805 }
4806
4807 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4808 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4809 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4810 if (options) {
4811 qemu_opts_do_parse(opts, options, NULL, &local_err);
4812 if (local_err) {
4813 error_report_err(local_err);
4814 error_report("Invalid options for file format '%s'", out_fmt);
4815 goto out;
4816 }
4817 }
4818 if (img_size != UINT64_MAX) {
4819 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4820 }
4821
4822 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4823 if (local_err) {
4824 error_report_err(local_err);
4825 goto out;
4826 }
4827
4828 if (output_format == OFORMAT_HUMAN) {
4829 printf("required size: %" PRIu64 "\n", info->required);
4830 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4831 } else {
4832 dump_json_block_measure_info(info);
4833 }
4834
4835 ret = 0;
4836
4837out:
4838 qapi_free_BlockMeasureInfo(info);
4839 qemu_opts_del(object_opts);
4840 qemu_opts_del(opts);
4841 qemu_opts_del(sn_opts);
4842 qemu_opts_free(create_opts);
4843 g_free(options);
4844 blk_unref(in_blk);
4845 return ret;
4846}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004847
Anthony Liguoric227f092009-10-01 16:12:16 -05004848static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004849#define DEF(option, callback, arg_string) \
4850 { option, callback },
4851#include "qemu-img-cmds.h"
4852#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004853 { NULL, NULL, },
4854};
4855
bellardea2384d2004-08-01 21:59:26 +00004856int main(int argc, char **argv)
4857{
Anthony Liguoric227f092009-10-01 16:12:16 -05004858 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004859 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004860 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004861 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004862 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004863 static const struct option long_options[] = {
4864 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004865 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004866 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004867 {0, 0, 0, 0}
4868 };
bellardea2384d2004-08-01 21:59:26 +00004869
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004870#ifdef CONFIG_POSIX
4871 signal(SIGPIPE, SIG_IGN);
4872#endif
4873
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004874 module_call_init(MODULE_INIT_TRACE);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004875 error_set_progname(argv[0]);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004876 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004877
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004878 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004879 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004880 exit(EXIT_FAILURE);
4881 }
4882
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004883 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004884
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004885 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004886 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004887 if (argc < 2) {
4888 error_exit("Not enough arguments");
4889 }
Stuart Brady153859b2009-06-07 00:42:17 +01004890
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004891 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004892 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004893 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004894
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004895 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004896 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004897 case ':':
4898 missing_argument(argv[optind - 1]);
4899 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004900 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004901 unrecognized_option(argv[optind - 1]);
4902 return 0;
4903 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004904 help();
4905 return 0;
4906 case 'V':
4907 printf(QEMU_IMG_VERSION);
4908 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004909 case 'T':
4910 g_free(trace_file);
4911 trace_file = trace_opt_parse(optarg);
4912 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004913 }
bellardea2384d2004-08-01 21:59:26 +00004914 }
Stuart Brady153859b2009-06-07 00:42:17 +01004915
Denis V. Lunev10985132016-06-17 17:44:13 +03004916 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004917
Denis V. Lunev10985132016-06-17 17:44:13 +03004918 /* reset getopt_long scanning */
4919 argc -= optind;
4920 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004921 return 0;
4922 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004923 argv += optind;
Denis V. Lunevcfef6a42016-07-04 16:16:48 +03004924 optind = 0;
Denis V. Lunev10985132016-06-17 17:44:13 +03004925
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004926 if (!trace_init_backends()) {
4927 exit(1);
4928 }
4929 trace_init_file(trace_file);
4930 qemu_set_log(LOG_TRACE);
4931
Denis V. Lunev10985132016-06-17 17:44:13 +03004932 /* find the command */
4933 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4934 if (!strcmp(cmdname, cmd->name)) {
4935 return cmd->handler(argc, argv);
4936 }
4937 }
Jeff Cody7db16892014-04-25 17:02:32 -04004938
Stuart Brady153859b2009-06-07 00:42:17 +01004939 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004940 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004941}