blob: c376e91ca0a5768fed414a0d6a80dd99d778bd7a [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
Fam Zhengac1307a2014-04-22 13:36:11 +080088 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020089 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080090 va_end(ap);
91
Markus Armbrustere9e1d922019-04-17 21:06:27 +020092 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080093 exit(EXIT_FAILURE);
94}
95
Stefan Hajnoczic9192972017-03-17 18:45:41 +080096static void QEMU_NORETURN missing_argument(const char *option)
97{
98 error_exit("missing argument for option '%s'", option);
99}
100
101static void QEMU_NORETURN unrecognized_option(const char *option)
102{
103 error_exit("unrecognized option '%s'", option);
104}
105
blueswir1d2c639d2009-01-24 18:19:25 +0000106/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800107static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000108{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100109 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400110 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300111 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300112 "QEMU disk image utility\n"
113 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300114 " '-h', '--help' display this help and exit\n"
115 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300116 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
117 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300118 "\n"
malc3f020d72010-02-08 12:04:56 +0300119 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100120#define DEF(option, callback, arg_string) \
121 " " arg_string "\n"
122#include "qemu-img-cmds.h"
123#undef DEF
malc3f020d72010-02-08 12:04:56 +0300124 "\n"
125 "Command parameters:\n"
126 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000127 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
128 " manual page for a description of the object properties. The most common\n"
129 " object type is a 'secret', which is used to supply passwords and/or\n"
130 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300131 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400132 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800133 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
134 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100135 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
136 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300137 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200138 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
139 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
140 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300141 " 'output_filename' is the destination disk image filename\n"
142 " 'output_fmt' is the destination format\n"
143 " 'options' is a comma separated list of format specific options in a\n"
144 " name=value format. Use -o ? for an overview of the options supported by the\n"
145 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800146 " 'snapshot_param' is param used for internal snapshot, format\n"
147 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
148 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300149 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400150 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
151 " new backing file match exactly. The image doesn't need a working\n"
152 " backing file before rebasing in this case (useful for renaming the\n"
153 " backing file). For image creation, allow creating without attempting\n"
154 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300155 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200156 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100157 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200158 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
159 " contain only zeros for qemu-img to create a sparse image during\n"
160 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
161 " unallocated or zero sectors, and the destination image will always be\n"
162 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200163 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100164 " '-n' skips the target volume creation (useful if the volume is created\n"
165 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300166 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200167 "Parameters to check subcommand:\n"
168 " '-r' tries to repair any inconsistencies that are found during the check.\n"
169 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
170 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200171 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200172 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100173 "Parameters to convert subcommand:\n"
174 " '-m' specifies how many coroutines work in parallel during the convert\n"
175 " process (defaults to 8)\n"
176 " '-W' allow to write to the target out of order rather than sequential\n"
177 "\n"
malc3f020d72010-02-08 12:04:56 +0300178 "Parameters to snapshot subcommand:\n"
179 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
180 " '-a' applies a snapshot (revert disk to saved state)\n"
181 " '-c' creates a snapshot\n"
182 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100183 " '-l' lists all snapshots in the given image\n"
184 "\n"
185 "Parameters to compare subcommand:\n"
186 " '-f' first image format\n"
187 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200188 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
189 "\n"
190 "Parameters to dd subcommand:\n"
191 " 'bs=BYTES' read and write up to BYTES bytes at a time "
192 "(default: 512)\n"
193 " 'count=N' copy only N input blocks\n"
194 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200195 " 'of=FILE' write to FILE\n"
196 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100197
198 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300199 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500200 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800201 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000202}
203
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000204static QemuOptsList qemu_object_opts = {
205 .name = "object",
206 .implied_opt_name = "qom-type",
207 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
208 .desc = {
209 { }
210 },
211};
212
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000213static QemuOptsList qemu_source_opts = {
214 .name = "source",
215 .implied_opt_name = "file",
216 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
217 .desc = {
218 { }
219 },
220};
221
Stefan Weil7c30f652013-06-16 17:01:05 +0200222static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100223{
224 int ret = 0;
225 if (!quiet) {
226 va_list args;
227 va_start(args, fmt);
228 ret = vprintf(fmt, args);
229 va_end(args);
230 }
231 return ret;
232}
233
bellardea2384d2004-08-01 21:59:26 +0000234
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100235static int print_block_option_help(const char *filename, const char *fmt)
236{
237 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800238 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500239 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100240
241 /* Find driver and parse its options */
242 drv = bdrv_find_format(fmt);
243 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100244 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100245 return 1;
246 }
247
Max Reitzd402b6a2018-05-09 23:00:21 +0200248 if (!drv->create_opts) {
249 error_report("Format driver '%s' does not support image creation", fmt);
250 return 1;
251 }
252
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800253 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100254 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500255 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100256 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100257 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800258 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100259 return 1;
260 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200261 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100262 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200263 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100264 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200265 return 1;
266 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800267 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100268 }
269
Max Reitz7f3fb002018-05-09 23:00:19 +0200270 printf("Supported options:\n");
Max Reitz63898712018-10-19 18:49:25 +0200271 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800272 qemu_opts_free(create_opts);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100273 return 0;
274}
275
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000276
Max Reitzefaa7c42016-03-16 19:54:38 +0100277static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100278 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800279 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000280{
281 QDict *options;
282 Error *local_err = NULL;
283 BlockBackend *blk;
284 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800285 if (force_share) {
286 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200287 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800288 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200289 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800290 return NULL;
291 }
Max Reitz4615f872018-05-02 22:20:50 +0200292 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800293 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100294 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000295 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100296 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000297 return NULL;
298 }
Kevin Wolfce099542016-03-15 13:01:04 +0100299 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000300
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000301 return blk;
302}
303
Max Reitzefaa7c42016-03-16 19:54:38 +0100304static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100305 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000306 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800307 bool writethrough, bool quiet,
308 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000309{
310 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200311 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100312
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100313 if (!options) {
314 options = qdict_new();
315 }
bellard75c23802004-08-27 21:28:58 +0000316 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500317 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000318 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100319
Fam Zheng335e9932017-05-03 00:35:39 +0800320 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500321 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800322 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100323 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500324 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100325 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000326 return NULL;
bellard75c23802004-08-27 21:28:58 +0000327 }
Kevin Wolfce099542016-03-15 13:01:04 +0100328 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100329
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200330 return blk;
bellard75c23802004-08-27 21:28:58 +0000331}
332
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000333
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100334static int img_add_key_secrets(void *opaque,
335 const char *name, const char *value,
336 Error **errp)
337{
338 QDict *options = opaque;
339
340 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600341 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100342 }
343
344 return 0;
345}
346
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100347
Max Reitzefaa7c42016-03-16 19:54:38 +0100348static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000349 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100350 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800351 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000352{
353 BlockBackend *blk;
354 if (image_opts) {
355 QemuOpts *opts;
356 if (fmt) {
357 error_report("--image-opts and --format are mutually exclusive");
358 return NULL;
359 }
360 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
361 filename, true);
362 if (!opts) {
363 return NULL;
364 }
Fam Zheng335e9932017-05-03 00:35:39 +0800365 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
366 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000367 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100368 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800369 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000370 }
371 return blk;
372}
373
374
Chunyan Liu83d05212014-06-05 17:20:51 +0800375static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100376 const char *base_filename,
377 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200378{
Markus Armbruster6750e792015-02-12 17:43:08 +0100379 Error *err = NULL;
380
Kevin Wolfefa84d42009-05-18 16:42:12 +0200381 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100382 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100383 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100384 error_report("Backing file not supported for file format '%s'",
385 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100386 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900387 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200388 }
389 }
390 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100391 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100392 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100393 error_report("Backing file format not supported for file "
394 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100395 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900396 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200397 }
398 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900399 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200400}
401
Markus Armbruster606caa02017-02-21 21:14:04 +0100402static int64_t cvtnum(const char *s)
403{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100404 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100405 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100406
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100407 err = qemu_strtosz(s, NULL, &value);
408 if (err < 0) {
409 return err;
410 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100411 if (value > INT64_MAX) {
412 return -ERANGE;
413 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100414 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100415}
416
bellardea2384d2004-08-01 21:59:26 +0000417static int img_create(int argc, char **argv)
418{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200419 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100420 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000421 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000422 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000423 const char *filename;
424 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200425 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200426 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100427 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400428 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000429
bellardea2384d2004-08-01 21:59:26 +0000430 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000431 static const struct option long_options[] = {
432 {"help", no_argument, 0, 'h'},
433 {"object", required_argument, 0, OPTION_OBJECT},
434 {0, 0, 0, 0}
435 };
John Snow6e6e55f2017-07-17 20:34:22 -0400436 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000437 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100438 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000439 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100440 }
bellardea2384d2004-08-01 21:59:26 +0000441 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800442 case ':':
443 missing_argument(argv[optind - 1]);
444 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100445 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800446 unrecognized_option(argv[optind - 1]);
447 break;
bellardea2384d2004-08-01 21:59:26 +0000448 case 'h':
449 help();
450 break;
aliguori9230eaf2009-03-28 17:55:19 +0000451 case 'F':
452 base_fmt = optarg;
453 break;
bellardea2384d2004-08-01 21:59:26 +0000454 case 'b':
455 base_filename = optarg;
456 break;
457 case 'f':
458 fmt = optarg;
459 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200460 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100461 if (!is_valid_option_list(optarg)) {
462 error_report("Invalid option list: %s", optarg);
463 goto fail;
464 }
465 if (!options) {
466 options = g_strdup(optarg);
467 } else {
468 char *old_options = options;
469 options = g_strdup_printf("%s,%s", options, optarg);
470 g_free(old_options);
471 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200472 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100473 case 'q':
474 quiet = true;
475 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400476 case 'u':
477 flags |= BDRV_O_NO_BACKING;
478 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000479 case OPTION_OBJECT: {
480 QemuOpts *opts;
481 opts = qemu_opts_parse_noisily(&qemu_object_opts,
482 optarg, true);
483 if (!opts) {
484 goto fail;
485 }
486 } break;
bellardea2384d2004-08-01 21:59:26 +0000487 }
488 }
aliguori9230eaf2009-03-28 17:55:19 +0000489
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900490 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100491 filename = (optind < argc) ? argv[optind] : NULL;
492 if (options && has_help_option(options)) {
493 g_free(options);
494 return print_block_option_help(filename, fmt);
495 }
496
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100497 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800498 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100499 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100500 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900501
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000502 if (qemu_opts_foreach(&qemu_object_opts,
503 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000504 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000505 goto fail;
506 }
507
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100508 /* Get image size, if specified */
509 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100510 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100511
512 sval = cvtnum(argv[optind++]);
513 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800514 if (sval == -ERANGE) {
515 error_report("Image size must be less than 8 EiB!");
516 } else {
517 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200518 "G, T, P or E suffixes for ");
519 error_report("kilobytes, megabytes, gigabytes, terabytes, "
520 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800521 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100522 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100523 }
524 img_size = (uint64_t)sval;
525 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200526 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800527 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200528 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100529
Luiz Capitulino9b375252012-11-30 10:52:05 -0200530 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400531 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100532 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100533 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100534 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900535 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200536
Kevin Wolf77386bf2014-02-21 16:24:04 +0100537 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000538 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100539
540fail:
541 g_free(options);
542 return 1;
bellardea2384d2004-08-01 21:59:26 +0000543}
544
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100545static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500546{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500547 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500548 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100549 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600550
551 visit_type_ImageCheck(v, NULL, &check, &error_abort);
552 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500553 str = qobject_to_json_pretty(obj);
554 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100555 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200556 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600557 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200558 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559}
560
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100561static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500562{
563 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100564 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500565 } else {
566 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100567 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
568 "Data may be corrupted, or further writes to the image "
569 "may corrupt it.\n",
570 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571 }
572
573 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100574 qprintf(quiet,
575 "\n%" PRId64 " leaked clusters were found on the image.\n"
576 "This means waste of disk space, but no harm to data.\n",
577 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500578 }
579
580 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100581 qprintf(quiet,
582 "\n%" PRId64
583 " internal errors have occurred during the check.\n",
584 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500585 }
586 }
587
588 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100589 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
590 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
591 check->allocated_clusters, check->total_clusters,
592 check->allocated_clusters * 100.0 / check->total_clusters,
593 check->fragmented_clusters * 100.0 / check->allocated_clusters,
594 check->compressed_clusters * 100.0 /
595 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500596 }
597
598 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100599 qprintf(quiet,
600 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500601 }
602}
603
604static int collect_image_check(BlockDriverState *bs,
605 ImageCheck *check,
606 const char *filename,
607 const char *fmt,
608 int fix)
609{
610 int ret;
611 BdrvCheckResult result;
612
613 ret = bdrv_check(bs, &result, fix);
614 if (ret < 0) {
615 return ret;
616 }
617
618 check->filename = g_strdup(filename);
619 check->format = g_strdup(bdrv_get_format_name(bs));
620 check->check_errors = result.check_errors;
621 check->corruptions = result.corruptions;
622 check->has_corruptions = result.corruptions != 0;
623 check->leaks = result.leaks;
624 check->has_leaks = result.leaks != 0;
625 check->corruptions_fixed = result.corruptions_fixed;
626 check->has_corruptions_fixed = result.corruptions != 0;
627 check->leaks_fixed = result.leaks_fixed;
628 check->has_leaks_fixed = result.leaks != 0;
629 check->image_end_offset = result.image_end_offset;
630 check->has_image_end_offset = result.image_end_offset != 0;
631 check->total_clusters = result.bfi.total_clusters;
632 check->has_total_clusters = result.bfi.total_clusters != 0;
633 check->allocated_clusters = result.bfi.allocated_clusters;
634 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
635 check->fragmented_clusters = result.bfi.fragmented_clusters;
636 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100637 check->compressed_clusters = result.bfi.compressed_clusters;
638 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500639
640 return 0;
641}
642
Kevin Wolfe076f332010-06-29 11:43:13 +0200643/*
644 * Checks an image for consistency. Exit codes:
645 *
Max Reitzd6635c42014-06-02 22:15:21 +0200646 * 0 - Check completed, image is good
647 * 1 - Check not completed because of internal errors
648 * 2 - Check completed, image is corrupted
649 * 3 - Check completed, image has leaked clusters, but is good otherwise
650 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200651 */
aliguori15859692009-04-21 23:11:53 +0000652static int img_check(int argc, char **argv)
653{
654 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500655 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200656 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200657 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000658 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200659 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100660 int flags = BDRV_O_CHECK;
661 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200662 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100663 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000664 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800665 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000666
667 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200669 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100670
aliguori15859692009-04-21 23:11:53 +0000671 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500672 int option_index = 0;
673 static const struct option long_options[] = {
674 {"help", no_argument, 0, 'h'},
675 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530676 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500677 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000678 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000679 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800680 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500681 {0, 0, 0, 0}
682 };
Fam Zheng335e9932017-05-03 00:35:39 +0800683 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100685 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000686 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100687 }
aliguori15859692009-04-21 23:11:53 +0000688 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800689 case ':':
690 missing_argument(argv[optind - 1]);
691 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100692 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800693 unrecognized_option(argv[optind - 1]);
694 break;
aliguori15859692009-04-21 23:11:53 +0000695 case 'h':
696 help();
697 break;
698 case 'f':
699 fmt = optarg;
700 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200701 case 'r':
702 flags |= BDRV_O_RDWR;
703
704 if (!strcmp(optarg, "leaks")) {
705 fix = BDRV_FIX_LEAKS;
706 } else if (!strcmp(optarg, "all")) {
707 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
708 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800709 error_exit("Unknown option value for -r "
710 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200711 }
712 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500713 case OPTION_OUTPUT:
714 output = optarg;
715 break;
Max Reitz40055952014-07-22 22:58:42 +0200716 case 'T':
717 cache = optarg;
718 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100719 case 'q':
720 quiet = true;
721 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800722 case 'U':
723 force_share = true;
724 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000725 case OPTION_OBJECT: {
726 QemuOpts *opts;
727 opts = qemu_opts_parse_noisily(&qemu_object_opts,
728 optarg, true);
729 if (!opts) {
730 return 1;
731 }
732 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000733 case OPTION_IMAGE_OPTS:
734 image_opts = true;
735 break;
aliguori15859692009-04-21 23:11:53 +0000736 }
737 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200738 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800739 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100740 }
aliguori15859692009-04-21 23:11:53 +0000741 filename = argv[optind++];
742
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500743 if (output && !strcmp(output, "json")) {
744 output_format = OFORMAT_JSON;
745 } else if (output && !strcmp(output, "human")) {
746 output_format = OFORMAT_HUMAN;
747 } else if (output) {
748 error_report("--output must be used with human or json as argument.");
749 return 1;
750 }
751
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000752 if (qemu_opts_foreach(&qemu_object_opts,
753 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000754 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000755 return 1;
756 }
757
Kevin Wolfce099542016-03-15 13:01:04 +0100758 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200759 if (ret < 0) {
760 error_report("Invalid source cache option: %s", cache);
761 return 1;
762 }
763
Fam Zheng335e9932017-05-03 00:35:39 +0800764 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
765 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200766 if (!blk) {
767 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900768 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200769 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500770
771 check = g_new0(ImageCheck, 1);
772 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200773
774 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200775 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200776 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500777 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200778 }
779
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500780 if (check->corruptions_fixed || check->leaks_fixed) {
781 int corruptions_fixed, leaks_fixed;
782
783 leaks_fixed = check->leaks_fixed;
784 corruptions_fixed = check->corruptions_fixed;
785
786 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100787 qprintf(quiet,
788 "The following inconsistencies were found and repaired:\n\n"
789 " %" PRId64 " leaked clusters\n"
790 " %" PRId64 " corruptions\n\n"
791 "Double checking the fixed image now...\n",
792 check->leaks_fixed,
793 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500794 }
795
796 ret = collect_image_check(bs, check, filename, fmt, 0);
797
798 check->leaks_fixed = leaks_fixed;
799 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200800 }
801
Max Reitz832390a2014-10-23 15:29:12 +0200802 if (!ret) {
803 switch (output_format) {
804 case OFORMAT_HUMAN:
805 dump_human_image_check(check, quiet);
806 break;
807 case OFORMAT_JSON:
808 dump_json_image_check(check, quiet);
809 break;
810 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500811 }
812
813 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200814 if (ret) {
815 error_report("Check failed: %s", strerror(-ret));
816 } else {
817 error_report("Check failed");
818 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500819 ret = 1;
820 goto fail;
821 }
822
823 if (check->corruptions) {
824 ret = 2;
825 } else if (check->leaks) {
826 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200827 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500828 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000829 }
830
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500831fail:
832 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200833 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834 return ret;
aliguori15859692009-04-21 23:11:53 +0000835}
836
Max Reitzd4a32382014-10-24 15:57:37 +0200837typedef struct CommonBlockJobCBInfo {
838 BlockDriverState *bs;
839 Error **errp;
840} CommonBlockJobCBInfo;
841
842static void common_block_job_cb(void *opaque, int ret)
843{
844 CommonBlockJobCBInfo *cbi = opaque;
845
846 if (ret < 0) {
847 error_setg_errno(cbi->errp, -ret, "Block job failed");
848 }
Max Reitzd4a32382014-10-24 15:57:37 +0200849}
850
851static void run_block_job(BlockJob *job, Error **errp)
852{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200853 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800854 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200855
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200856 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200857 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200858 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200859 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200860 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200861 if (job->job.progress_total) {
862 progress = (float)job->job.progress_current /
863 job->job.progress_total * 100.f;
864 }
865 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200866 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200867
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200868 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200869 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800870 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200871 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800872 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200873 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200874 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200875
sochin.jiang4172a002017-06-15 14:47:33 +0800876 /* publish completion progress only when success */
877 if (!ret) {
878 qemu_progress_print(100.f, 0);
879 }
Max Reitzd4a32382014-10-24 15:57:37 +0200880}
881
bellardea2384d2004-08-01 21:59:26 +0000882static int img_commit(int argc, char **argv)
883{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400884 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200885 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200886 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200887 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100888 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200889 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100890 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200891 Error *local_err = NULL;
892 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000893 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200894 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000895
896 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400897 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200898 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000899 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000900 static const struct option long_options[] = {
901 {"help", no_argument, 0, 'h'},
902 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000903 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000904 {0, 0, 0, 0}
905 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800906 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000907 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100908 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000909 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100910 }
bellardea2384d2004-08-01 21:59:26 +0000911 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800912 case ':':
913 missing_argument(argv[optind - 1]);
914 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100915 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800916 unrecognized_option(argv[optind - 1]);
917 break;
bellardea2384d2004-08-01 21:59:26 +0000918 case 'h':
919 help();
920 break;
921 case 'f':
922 fmt = optarg;
923 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400924 case 't':
925 cache = optarg;
926 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200927 case 'b':
928 base = optarg;
929 /* -b implies -d */
930 drop = true;
931 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200932 case 'd':
933 drop = true;
934 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200935 case 'p':
936 progress = true;
937 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100938 case 'q':
939 quiet = true;
940 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000941 case OPTION_OBJECT: {
942 QemuOpts *opts;
943 opts = qemu_opts_parse_noisily(&qemu_object_opts,
944 optarg, true);
945 if (!opts) {
946 return 1;
947 }
948 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000949 case OPTION_IMAGE_OPTS:
950 image_opts = true;
951 break;
bellardea2384d2004-08-01 21:59:26 +0000952 }
953 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200954
955 /* Progress is not shown in Quiet mode */
956 if (quiet) {
957 progress = false;
958 }
959
Kevin Wolffc11eb22013-08-05 10:53:04 +0200960 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800961 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100962 }
bellardea2384d2004-08-01 21:59:26 +0000963 filename = argv[optind++];
964
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000965 if (qemu_opts_foreach(&qemu_object_opts,
966 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000967 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000968 return 1;
969 }
970
Max Reitz9a86fe42014-10-24 15:57:38 +0200971 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100972 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400973 if (ret < 0) {
974 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100975 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400976 }
977
Fam Zheng335e9932017-05-03 00:35:39 +0800978 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
979 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200980 if (!blk) {
981 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900982 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200983 bs = blk_bs(blk);
984
Max Reitz687fa1d2014-10-24 15:57:39 +0200985 qemu_progress_init(progress, 1.f);
986 qemu_progress_print(0.f, 100);
987
Max Reitz1b22bff2014-10-24 15:57:40 +0200988 if (base) {
989 base_bs = bdrv_find_backing_image(bs, base);
990 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +0100991 error_setg(&local_err,
992 "Did not find '%s' in the backing chain of '%s'",
993 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +0200994 goto done;
995 }
996 } else {
997 /* This is different from QMP, which by default uses the deepest file in
998 * the backing chain (i.e., the very base); however, the traditional
999 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001000 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001001 if (!base_bs) {
1002 error_setg(&local_err, "Image does not have a backing file");
1003 goto done;
1004 }
bellardea2384d2004-08-01 21:59:26 +00001005 }
1006
Max Reitzd4a32382014-10-24 15:57:37 +02001007 cbi = (CommonBlockJobCBInfo){
1008 .errp = &local_err,
1009 .bs = bs,
1010 };
1011
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001012 aio_context = bdrv_get_aio_context(bs);
1013 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001014 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001015 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001016 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001017 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001018 if (local_err) {
1019 goto done;
1020 }
1021
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001022 /* When the block job completes, the BlockBackend reference will point to
1023 * the old backing file. In order to avoid that the top image is already
1024 * deleted, so we can still empty it afterwards, increment the reference
1025 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001026 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001027 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001028 }
1029
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001030 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001031 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001032 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001033 if (local_err) {
1034 goto unref_backing;
1035 }
1036
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001037 if (!drop && bs->drv->bdrv_make_empty) {
1038 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001039 if (ret) {
1040 error_setg_errno(&local_err, -ret, "Could not empty %s",
1041 filename);
1042 goto unref_backing;
1043 }
1044 }
1045
1046unref_backing:
1047 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001048 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001049 }
Max Reitzd4a32382014-10-24 15:57:37 +02001050
1051done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001052 qemu_progress_end();
1053
Markus Armbruster26f54e92014-10-07 13:59:04 +02001054 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001055
1056 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001057 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001058 return 1;
1059 }
Max Reitzd4a32382014-10-24 15:57:37 +02001060
1061 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001062 return 0;
1063}
1064
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001065/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001066 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1067 * of the first sector boundary within buf where the sector contains a
1068 * non-zero byte. This function is robust to a buffer that is not
1069 * sector-aligned.
1070 */
1071static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1072{
1073 int64_t i;
1074 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1075
1076 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1077 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1078 return i;
1079 }
1080 }
1081 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1082 return i;
1083 }
1084 return -1;
1085}
1086
1087/*
thsf58c7b32008-06-05 21:53:49 +00001088 * Returns true iff the first sector pointed to by 'buf' contains at least
1089 * a non-NUL byte.
1090 *
1091 * 'pnum' is set to the number of sectors (including and immediately following
1092 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001093 * The function will try to align the end offset to alignment boundaries so
1094 * that the request will at least end aligned and consequtive requests will
1095 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001096 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001097static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1098 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001099{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001100 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001101 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001102
1103 if (n <= 0) {
1104 *pnum = 0;
1105 return 0;
1106 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001107 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001108 for(i = 1; i < n; i++) {
1109 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001110 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001111 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001112 }
bellardea2384d2004-08-01 21:59:26 +00001113 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001114
1115 tail = (sector_num + i) & (alignment - 1);
1116 if (tail) {
1117 if (is_zero && i <= tail) {
1118 /* treat unallocated areas which only consist
1119 * of a small tail as allocated. */
1120 is_zero = false;
1121 }
1122 if (!is_zero) {
1123 /* align up end offset of allocated areas. */
1124 i += alignment - tail;
1125 i = MIN(i, n);
1126 } else {
1127 /* align down end offset of zero areas. */
1128 i -= tail;
1129 }
1130 }
bellardea2384d2004-08-01 21:59:26 +00001131 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001132 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001133}
1134
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001135/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001136 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1137 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1138 * breaking up write requests for only small sparse areas.
1139 */
1140static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001141 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001142{
1143 int ret;
1144 int num_checked, num_used;
1145
1146 if (n < min) {
1147 min = n;
1148 }
1149
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001150 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001151 if (!ret) {
1152 return ret;
1153 }
1154
1155 num_used = *pnum;
1156 buf += BDRV_SECTOR_SIZE * *pnum;
1157 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001158 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001159 num_checked = num_used;
1160
1161 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001162 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001163
1164 buf += BDRV_SECTOR_SIZE * *pnum;
1165 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001166 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001167 num_checked += *pnum;
1168 if (ret) {
1169 num_used = num_checked;
1170 } else if (*pnum >= min) {
1171 break;
1172 }
1173 }
1174
1175 *pnum = num_used;
1176 return 1;
1177}
1178
1179/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001180 * Compares two buffers sector by sector. Returns 0 if the first
1181 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001182 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001183 * pnum is set to the sector-aligned size of the buffer prefix that
1184 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001185 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001186static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1187 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001188{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001189 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001190 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001191
Eric Blakedc61cd32017-10-11 22:47:14 -05001192 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001193
Eric Blakedc61cd32017-10-11 22:47:14 -05001194 res = !!memcmp(buf1, buf2, i);
1195 while (i < bytes) {
1196 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001197
Eric Blakedc61cd32017-10-11 22:47:14 -05001198 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001199 break;
1200 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001201 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001202 }
1203
1204 *pnum = i;
1205 return res;
1206}
1207
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001208#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001209
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001210/*
1211 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1212 *
Eric Blake0608e402017-10-11 22:47:12 -05001213 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1214 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1215 * failure), and 4 on error (the exit status for read errors), after emitting
1216 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001217 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001218 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001219 * @param offset: Starting offset to check
1220 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221 * @param filename: Name of disk file we are checking (logging purpose)
1222 * @param buffer: Allocated buffer for storing read data
1223 * @param quiet: Flag for quiet mode
1224 */
Eric Blakec41508e2017-10-11 22:47:13 -05001225static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1226 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001227 uint8_t *buffer, bool quiet)
1228{
Eric Blakedebb38a2017-10-11 22:47:11 -05001229 int ret = 0;
1230 int64_t idx;
1231
Eric Blakec41508e2017-10-11 22:47:13 -05001232 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001233 if (ret < 0) {
1234 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001235 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001236 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001237 }
Eric Blakec41508e2017-10-11 22:47:13 -05001238 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001239 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001240 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001241 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001242 return 1;
1243 }
1244
1245 return 0;
1246}
1247
1248/*
1249 * Compares two images. Exit codes:
1250 *
1251 * 0 - Images are identical
1252 * 1 - Images differ
1253 * >1 - Error occurred
1254 */
1255static int img_compare(int argc, char **argv)
1256{
Max Reitz40055952014-07-22 22:58:42 +02001257 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001258 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001259 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001260 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001262 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 int allocated1, allocated2;
1264 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1265 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001266 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001267 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001268 int64_t total_size;
1269 int64_t offset = 0;
1270 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001271 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001273 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001274 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001275
Max Reitz40055952014-07-22 22:58:42 +02001276 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001277 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001278 static const struct option long_options[] = {
1279 {"help", no_argument, 0, 'h'},
1280 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001281 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001282 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001283 {0, 0, 0, 0}
1284 };
Fam Zheng335e9932017-05-03 00:35:39 +08001285 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001286 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 if (c == -1) {
1288 break;
1289 }
1290 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001291 case ':':
1292 missing_argument(argv[optind - 1]);
1293 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001294 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001295 unrecognized_option(argv[optind - 1]);
1296 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001297 case 'h':
1298 help();
1299 break;
1300 case 'f':
1301 fmt1 = optarg;
1302 break;
1303 case 'F':
1304 fmt2 = optarg;
1305 break;
Max Reitz40055952014-07-22 22:58:42 +02001306 case 'T':
1307 cache = optarg;
1308 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 case 'p':
1310 progress = true;
1311 break;
1312 case 'q':
1313 quiet = true;
1314 break;
1315 case 's':
1316 strict = true;
1317 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001318 case 'U':
1319 force_share = true;
1320 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001321 case OPTION_OBJECT: {
1322 QemuOpts *opts;
1323 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1324 optarg, true);
1325 if (!opts) {
1326 ret = 2;
1327 goto out4;
1328 }
1329 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001330 case OPTION_IMAGE_OPTS:
1331 image_opts = true;
1332 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 }
1334 }
1335
1336 /* Progress is not shown in Quiet mode */
1337 if (quiet) {
1338 progress = false;
1339 }
1340
1341
Kevin Wolffc11eb22013-08-05 10:53:04 +02001342 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001343 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001344 }
1345 filename1 = argv[optind++];
1346 filename2 = argv[optind++];
1347
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001348 if (qemu_opts_foreach(&qemu_object_opts,
1349 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001350 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001351 ret = 2;
1352 goto out4;
1353 }
1354
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001355 /* Initialize before goto out */
1356 qemu_progress_init(progress, 2.0);
1357
Kevin Wolfce099542016-03-15 13:01:04 +01001358 flags = 0;
1359 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001360 if (ret < 0) {
1361 error_report("Invalid source cache option: %s", cache);
1362 ret = 2;
1363 goto out3;
1364 }
1365
Fam Zheng335e9932017-05-03 00:35:39 +08001366 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1367 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001368 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001369 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001370 goto out3;
1371 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001372
Fam Zheng335e9932017-05-03 00:35:39 +08001373 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1374 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001375 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001376 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001377 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001379 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001380 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381
Max Reitzf1d3cd72015-02-05 13:58:18 -05001382 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1383 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001384 total_size1 = blk_getlength(blk1);
1385 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001386 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001387 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001388 ret = 4;
1389 goto out;
1390 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001391 total_size2 = blk_getlength(blk2);
1392 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001393 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001394 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001395 ret = 4;
1396 goto out;
1397 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001398 total_size = MIN(total_size1, total_size2);
1399 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001400
1401 qemu_progress_print(0, 100);
1402
Eric Blake033d9fc2017-10-11 22:47:16 -05001403 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001404 ret = 1;
1405 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1406 goto out;
1407 }
1408
Eric Blake033d9fc2017-10-11 22:47:16 -05001409 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001410 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001411
Eric Blake033d9fc2017-10-11 22:47:16 -05001412 status1 = bdrv_block_status_above(bs1, NULL, offset,
1413 total_size1 - offset, &pnum1, NULL,
1414 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001415 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001416 ret = 3;
1417 error_report("Sector allocation test failed for %s", filename1);
1418 goto out;
1419 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001420 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001421
Eric Blake033d9fc2017-10-11 22:47:16 -05001422 status2 = bdrv_block_status_above(bs2, NULL, offset,
1423 total_size2 - offset, &pnum2, NULL,
1424 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001425 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001426 ret = 3;
1427 error_report("Sector allocation test failed for %s", filename2);
1428 goto out;
1429 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001430 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001431
1432 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001433 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434
Fam Zheng25ad8e62016-01-13 16:37:41 +08001435 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001436 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001437 ret = 1;
1438 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001439 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001440 goto out;
1441 }
1442 }
1443 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001444 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001445 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001446 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001447 int64_t pnum;
1448
Eric Blake033d9fc2017-10-11 22:47:16 -05001449 chunk = MIN(chunk, IO_BUF_SIZE);
1450 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451 if (ret < 0) {
1452 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001453 " of %s: %s",
1454 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001455 ret = 4;
1456 goto out;
1457 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001458 ret = blk_pread(blk2, offset, buf2, chunk);
1459 if (ret < 0) {
1460 error_report("Error while reading offset %" PRId64
1461 " of %s: %s",
1462 offset, filename2, strerror(-ret));
1463 ret = 4;
1464 goto out;
1465 }
1466 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1467 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001468 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001469 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001470 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001471 goto out;
1472 }
1473 }
1474 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001475 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001476 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001477 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 filename1, buf1, quiet);
1479 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001480 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 filename2, buf1, quiet);
1482 }
1483 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001484 goto out;
1485 }
1486 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 offset += chunk;
1488 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001489 }
1490
Eric Blake033d9fc2017-10-11 22:47:16 -05001491 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001492 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001493 const char *filename_over;
1494
1495 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001496 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001497 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001498 filename_over = filename1;
1499 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001500 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 filename_over = filename2;
1502 }
1503
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 while (offset < progress_base) {
1505 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1506 progress_base - offset, &chunk,
1507 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001508 if (ret < 0) {
1509 ret = 3;
1510 error_report("Sector allocation test failed for %s",
1511 filename_over);
1512 goto out;
1513
1514 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001515 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001516 chunk = MIN(chunk, IO_BUF_SIZE);
1517 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001518 filename_over, buf1, quiet);
1519 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001520 goto out;
1521 }
1522 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001523 offset += chunk;
1524 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525 }
1526 }
1527
1528 qprintf(quiet, "Images are identical.\n");
1529 ret = 0;
1530
1531out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 qemu_vfree(buf1);
1533 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001534 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001536 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001537out3:
1538 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001539out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540 return ret;
1541}
1542
Kevin Wolf690c7302015-03-19 13:33:32 +01001543enum ImgConvertBlockStatus {
1544 BLK_DATA,
1545 BLK_ZERO,
1546 BLK_BACKING_FILE,
1547};
1548
Peter Lieven2d9187b2017-02-28 13:40:07 +01001549#define MAX_COROUTINES 16
1550
Kevin Wolf690c7302015-03-19 13:33:32 +01001551typedef struct ImgConvertState {
1552 BlockBackend **src;
1553 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001554 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001555 int64_t total_sectors;
1556 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001557 int64_t allocated_done;
1558 int64_t sector_num;
1559 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001560 enum ImgConvertBlockStatus status;
1561 int64_t sector_next_status;
1562 BlockBackend *target;
1563 bool has_zero_init;
1564 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001565 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001566 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001567 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001569 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001570 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001571 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001572 size_t cluster_sectors;
1573 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001574 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001575 int running_coroutines;
1576 Coroutine *co[MAX_COROUTINES];
1577 int64_t wait_sector_num[MAX_COROUTINES];
1578 CoMutex lock;
1579 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001580} ImgConvertState;
1581
Peter Lieven2d9187b2017-02-28 13:40:07 +01001582static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1583 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001584{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001585 *src_cur = 0;
1586 *src_cur_offset = 0;
1587 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1588 *src_cur_offset += s->src_sectors[*src_cur];
1589 (*src_cur)++;
1590 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001591 }
1592}
1593
1594static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1595{
Eric Blake31826642017-10-11 22:47:08 -05001596 int64_t src_cur_offset;
1597 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001598 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001599
Peter Lieven2d9187b2017-02-28 13:40:07 +01001600 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001601
1602 assert(s->total_sectors > sector_num);
1603 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1604
Max Reitz351c8ef2018-05-01 18:57:49 +02001605 if (s->target_backing_sectors >= 0) {
1606 if (sector_num >= s->target_backing_sectors) {
1607 post_backing_zero = s->unallocated_blocks_are_zero;
1608 } else if (sector_num + n > s->target_backing_sectors) {
1609 /* Split requests around target_backing_sectors (because
1610 * starting from there, zeros are handled differently) */
1611 n = s->target_backing_sectors - sector_num;
1612 }
1613 }
1614
Kevin Wolf690c7302015-03-19 13:33:32 +01001615 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001616 int64_t count = n * BDRV_SECTOR_SIZE;
1617
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001618 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001619
1620 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1621 (sector_num - src_cur_offset) *
1622 BDRV_SECTOR_SIZE,
1623 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001624 } else {
Eric Blake31826642017-10-11 22:47:08 -05001625 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1626 (sector_num - src_cur_offset) *
1627 BDRV_SECTOR_SIZE,
1628 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001629 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001630 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001631 error_report("error while reading block status of sector %" PRId64
1632 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001633 return ret;
1634 }
Eric Blake31826642017-10-11 22:47:08 -05001635 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001636
1637 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001638 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001639 } else if (ret & BDRV_BLOCK_DATA) {
1640 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001641 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001642 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001643 }
1644
1645 s->sector_next_status = sector_num + n;
1646 }
1647
1648 n = MIN(n, s->sector_next_status - sector_num);
1649 if (s->status == BLK_DATA) {
1650 n = MIN(n, s->buf_sectors);
1651 }
1652
1653 /* We need to write complete clusters for compressed images, so if an
1654 * unallocated area is shorter than that, we must consider the whole
1655 * cluster allocated. */
1656 if (s->compressed) {
1657 if (n < s->cluster_sectors) {
1658 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1659 s->status = BLK_DATA;
1660 } else {
1661 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1662 }
1663 }
1664
1665 return n;
1666}
1667
Peter Lieven2d9187b2017-02-28 13:40:07 +01001668static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1669 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001670{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001671 int n, ret;
1672 QEMUIOVector qiov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673
Kevin Wolf690c7302015-03-19 13:33:32 +01001674 assert(nb_sectors <= s->buf_sectors);
1675 while (nb_sectors > 0) {
1676 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001677 int src_cur;
1678 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001679
1680 /* In the case of compression with multiple source files, we can get a
1681 * nb_sectors that spreads into the next part. So we must be able to
1682 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001683 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1684 blk = s->src[src_cur];
1685 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001686
Peter Lieven2d9187b2017-02-28 13:40:07 +01001687 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Vladimir Sementsov-Ogievskiyc075a0a2019-02-18 17:09:21 +03001688 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
Peter Lieven2d9187b2017-02-28 13:40:07 +01001689
1690 ret = blk_co_preadv(
1691 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
1692 n << BDRV_SECTOR_BITS, &qiov, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001693 if (ret < 0) {
1694 return ret;
1695 }
1696
1697 sector_num += n;
1698 nb_sectors -= n;
1699 buf += n * BDRV_SECTOR_SIZE;
1700 }
1701
1702 return 0;
1703}
1704
Peter Lieven2d9187b2017-02-28 13:40:07 +01001705
1706static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1707 int nb_sectors, uint8_t *buf,
1708 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001709{
1710 int ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001711 QEMUIOVector qiov;
Kevin Wolf690c7302015-03-19 13:33:32 +01001712
1713 while (nb_sectors > 0) {
1714 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001715 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1716
Peter Lieven2d9187b2017-02-28 13:40:07 +01001717 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001718 case BLK_BACKING_FILE:
1719 /* If we have a backing file, leave clusters unallocated that are
1720 * unallocated in the source image, so that the backing file is
1721 * visible at the respective offset. */
1722 assert(s->target_has_backing);
1723 break;
1724
1725 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001726 /* If we're told to keep the target fully allocated (-S 0) or there
1727 * is real non-zero data, we must write it. Otherwise we can treat
1728 * it as zero sectors.
1729 * Compressed clusters need to be written as a whole, so in that
1730 * case we can only save the write if the buffer is completely
1731 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001732 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001733 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001734 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1735 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001736 (s->compressed &&
1737 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001738 {
Vladimir Sementsov-Ogievskiyc075a0a2019-02-18 17:09:21 +03001739 qemu_iovec_init_buf(&qiov, buf, n << BDRV_SECTOR_BITS);
Peter Lieven2d9187b2017-02-28 13:40:07 +01001740
1741 ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
Lidong Chendb933fb2017-04-27 10:58:27 +08001742 n << BDRV_SECTOR_BITS, &qiov, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001743 if (ret < 0) {
1744 return ret;
1745 }
1746 break;
1747 }
1748 /* fall-through */
1749
1750 case BLK_ZERO:
1751 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001752 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001753 break;
1754 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001755 ret = blk_co_pwrite_zeroes(s->target,
1756 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001757 n << BDRV_SECTOR_BITS,
1758 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001759 if (ret < 0) {
1760 return ret;
1761 }
1762 break;
1763 }
1764
1765 sector_num += n;
1766 nb_sectors -= n;
1767 buf += n * BDRV_SECTOR_SIZE;
1768 }
1769
1770 return 0;
1771}
1772
Fam Zhengee5306d2018-06-01 17:26:48 +08001773static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1774 int nb_sectors)
1775{
1776 int n, ret;
1777
1778 while (nb_sectors > 0) {
1779 BlockBackend *blk;
1780 int src_cur;
1781 int64_t bs_sectors, src_cur_offset;
1782 int64_t offset;
1783
1784 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1785 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1786 blk = s->src[src_cur];
1787 bs_sectors = s->src_sectors[src_cur];
1788
1789 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1790
1791 ret = blk_co_copy_range(blk, offset, s->target,
1792 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001793 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001794 if (ret < 0) {
1795 return ret;
1796 }
1797
1798 sector_num += n;
1799 nb_sectors -= n;
1800 }
1801 return 0;
1802}
1803
Peter Lieven2d9187b2017-02-28 13:40:07 +01001804static void coroutine_fn convert_co_do_copy(void *opaque)
1805{
1806 ImgConvertState *s = opaque;
1807 uint8_t *buf = NULL;
1808 int ret, i;
1809 int index = -1;
1810
1811 for (i = 0; i < s->num_coroutines; i++) {
1812 if (s->co[i] == qemu_coroutine_self()) {
1813 index = i;
1814 break;
1815 }
1816 }
1817 assert(index >= 0);
1818
1819 s->running_coroutines++;
1820 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1821
1822 while (1) {
1823 int n;
1824 int64_t sector_num;
1825 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001826 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001827
1828 qemu_co_mutex_lock(&s->lock);
1829 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1830 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001831 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001832 }
1833 n = convert_iteration_sectors(s, s->sector_num);
1834 if (n < 0) {
1835 qemu_co_mutex_unlock(&s->lock);
1836 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001837 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001838 }
1839 /* save current sector and allocation status to local variables */
1840 sector_num = s->sector_num;
1841 status = s->status;
1842 if (!s->min_sparse && s->status == BLK_ZERO) {
1843 n = MIN(n, s->buf_sectors);
1844 }
1845 /* increment global sector counter so that other coroutines can
1846 * already continue reading beyond this request */
1847 s->sector_num += n;
1848 qemu_co_mutex_unlock(&s->lock);
1849
1850 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1851 s->allocated_done += n;
1852 qemu_progress_print(100.0 * s->allocated_done /
1853 s->allocated_sectors, 0);
1854 }
1855
Fam Zhengee5306d2018-06-01 17:26:48 +08001856retry:
1857 copy_range = s->copy_range && s->status == BLK_DATA;
1858 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001859 ret = convert_co_read(s, sector_num, n, buf);
1860 if (ret < 0) {
1861 error_report("error while reading sector %" PRId64
1862 ": %s", sector_num, strerror(-ret));
1863 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001864 }
1865 } else if (!s->min_sparse && status == BLK_ZERO) {
1866 status = BLK_DATA;
1867 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1868 }
1869
1870 if (s->wr_in_order) {
1871 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001872 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001873 s->wait_sector_num[index] = sector_num;
1874 qemu_coroutine_yield();
1875 }
1876 s->wait_sector_num[index] = -1;
1877 }
1878
Anton Nefedovb91127e2017-04-26 11:33:15 +03001879 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001880 if (copy_range) {
1881 ret = convert_co_copy_range(s, sector_num, n);
1882 if (ret) {
1883 s->copy_range = false;
1884 goto retry;
1885 }
1886 } else {
1887 ret = convert_co_write(s, sector_num, n, buf, status);
1888 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001889 if (ret < 0) {
1890 error_report("error while writing sector %" PRId64
1891 ": %s", sector_num, strerror(-ret));
1892 s->ret = ret;
1893 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001894 }
1895
1896 if (s->wr_in_order) {
1897 /* reenter the coroutine that might have waited
1898 * for this write to complete */
1899 s->wr_offs = sector_num + n;
1900 for (i = 0; i < s->num_coroutines; i++) {
1901 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1902 /*
1903 * A -> B -> A cannot occur because A has
1904 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1905 * B will never enter A during this time window.
1906 */
1907 qemu_coroutine_enter(s->co[i]);
1908 break;
1909 }
1910 }
1911 }
1912 }
1913
Peter Lieven2d9187b2017-02-28 13:40:07 +01001914 qemu_vfree(buf);
1915 s->co[index] = NULL;
1916 s->running_coroutines--;
1917 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1918 /* the convert job finished successfully */
1919 s->ret = 0;
1920 }
1921}
1922
Kevin Wolf690c7302015-03-19 13:33:32 +01001923static int convert_do_copy(ImgConvertState *s)
1924{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001925 int ret, i, n;
1926 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001927
1928 /* Check whether we have zero initialisation or can get it efficiently */
1929 s->has_zero_init = s->min_sparse && !s->target_has_backing
1930 ? bdrv_has_zero_init(blk_bs(s->target))
1931 : false;
1932
1933 if (!s->has_zero_init && !s->target_has_backing &&
1934 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1935 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001936 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001937 if (ret == 0) {
1938 s->has_zero_init = true;
1939 }
1940 }
1941
1942 /* Allocate buffer for copied data. For compressed images, only one cluster
1943 * can be copied at a time. */
1944 if (s->compressed) {
1945 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1946 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001947 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001948 }
1949 s->buf_sectors = s->cluster_sectors;
1950 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001951
Kevin Wolf690c7302015-03-19 13:33:32 +01001952 while (sector_num < s->total_sectors) {
1953 n = convert_iteration_sectors(s, sector_num);
1954 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001955 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001956 }
Max Reitzaad15de2016-03-24 23:33:57 +01001957 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1958 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001959 s->allocated_sectors += n;
1960 }
1961 sector_num += n;
1962 }
1963
1964 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001965 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001966 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001967
Peter Lieven2d9187b2017-02-28 13:40:07 +01001968 qemu_co_mutex_init(&s->lock);
1969 for (i = 0; i < s->num_coroutines; i++) {
1970 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1971 s->wait_sector_num[i] = -1;
1972 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001973 }
1974
Anton Nefedovb91127e2017-04-26 11:33:15 +03001975 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001976 main_loop_wait(false);
1977 }
1978
1979 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001980 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001981 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001982 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001984 }
1985 }
1986
Peter Lieven2d9187b2017-02-28 13:40:07 +01001987 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001988}
1989
Peter Lieven6360ab22018-07-13 09:15:39 +02001990#define MAX_BUF_SECTORS 32768
1991
bellardea2384d2004-08-01 21:59:26 +00001992static int img_convert(int argc, char **argv)
1993{
Peter Lieven9fd77f92017-04-21 11:11:55 +02001994 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001995 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02001996 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
1997 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01001998 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00001999 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002000 BlockDriverState *out_bs;
2001 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002002 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002003 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002004 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002005 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002006 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002007 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002008 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002009 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002010 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002011
Peter Lieven9fd77f92017-04-21 11:11:55 +02002012 ImgConvertState s = (ImgConvertState) {
2013 /* Need at least 4k of zeros for sparse detection */
2014 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002015 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002016 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2017 .wr_in_order = true,
2018 .num_coroutines = 8,
2019 };
2020
bellardea2384d2004-08-01 21:59:26 +00002021 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002022 static const struct option long_options[] = {
2023 {"help", no_argument, 0, 'h'},
2024 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002025 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002026 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002027 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002028 {0, 0, 0, 0}
2029 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002030 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002031 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002032 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002033 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002034 }
bellardea2384d2004-08-01 21:59:26 +00002035 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002036 case ':':
2037 missing_argument(argv[optind - 1]);
2038 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002039 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002040 unrecognized_option(argv[optind - 1]);
2041 break;
bellardea2384d2004-08-01 21:59:26 +00002042 case 'h':
2043 help();
2044 break;
2045 case 'f':
2046 fmt = optarg;
2047 break;
2048 case 'O':
2049 out_fmt = optarg;
2050 break;
thsf58c7b32008-06-05 21:53:49 +00002051 case 'B':
2052 out_baseimg = optarg;
2053 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002054 case 'C':
2055 s.copy_range = true;
2056 break;
bellardea2384d2004-08-01 21:59:26 +00002057 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002058 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002059 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002060 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002061 if (!is_valid_option_list(optarg)) {
2062 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002063 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002064 }
2065 if (!options) {
2066 options = g_strdup(optarg);
2067 } else {
2068 char *old_options = options;
2069 options = g_strdup_printf("%s,%s", options, optarg);
2070 g_free(old_options);
2071 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002072 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002073 case 'l':
2074 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002075 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2076 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002077 if (!sn_opts) {
2078 error_report("Failed in parsing snapshot param '%s'",
2079 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002080 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002081 }
2082 } else {
2083 snapshot_name = optarg;
2084 }
2085 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002086 case 'S':
2087 {
2088 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002089
2090 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002091 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2092 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2093 error_report("Invalid buffer size for sparse output specified. "
2094 "Valid sizes are multiples of %llu up to %llu. Select "
2095 "0 to disable sparse detection (fully allocates output).",
2096 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002097 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002098 }
2099
Peter Lieven9fd77f92017-04-21 11:11:55 +02002100 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002101 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002102 break;
2103 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002104 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002105 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002106 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002107 case 't':
2108 cache = optarg;
2109 break;
Max Reitz40055952014-07-22 22:58:42 +02002110 case 'T':
2111 src_cache = optarg;
2112 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002113 case 'q':
2114 quiet = true;
2115 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002116 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002117 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002118 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002119 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002120 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2121 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002122 error_report("Invalid number of coroutines. Allowed number of"
2123 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002124 goto fail_getopt;
2125 }
2126 break;
2127 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002128 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002129 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002130 case 'U':
2131 force_share = true;
2132 break;
Max Reitz3258b912017-04-26 15:46:47 +02002133 case OPTION_OBJECT: {
2134 QemuOpts *object_opts;
2135 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2136 optarg, true);
2137 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002138 goto fail_getopt;
2139 }
2140 break;
Max Reitz3258b912017-04-26 15:46:47 +02002141 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002142 case OPTION_IMAGE_OPTS:
2143 image_opts = true;
2144 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002145 case OPTION_TARGET_IMAGE_OPTS:
2146 tgt_image_opts = true;
2147 break;
bellardea2384d2004-08-01 21:59:26 +00002148 }
2149 }
ths3b46e622007-09-17 08:09:54 +00002150
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002151 if (!out_fmt && !tgt_image_opts) {
2152 out_fmt = "raw";
2153 }
2154
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002155 if (qemu_opts_foreach(&qemu_object_opts,
2156 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002157 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002158 goto fail_getopt;
2159 }
2160
Fam Zhenge11ce122018-07-27 11:34:01 +08002161 if (s.compressed && s.copy_range) {
2162 error_report("Cannot enable copy offloading when -c is used");
2163 goto fail_getopt;
2164 }
2165
2166 if (explict_min_sparse && s.copy_range) {
2167 error_report("Cannot enable copy offloading when -S is used");
2168 goto fail_getopt;
2169 }
2170
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002171 if (tgt_image_opts && !skip_create) {
2172 error_report("--target-image-opts requires use of -n flag");
2173 goto fail_getopt;
2174 }
2175
Peter Lieven9fd77f92017-04-21 11:11:55 +02002176 s.src_num = argc - optind - 1;
2177 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2178
2179 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002180 if (out_fmt) {
2181 ret = print_block_option_help(out_filename, out_fmt);
2182 goto fail_getopt;
2183 } else {
2184 error_report("Option help requires a format be specified");
2185 goto fail_getopt;
2186 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002187 }
2188
2189 if (s.src_num < 1) {
2190 error_report("Must specify image file name");
2191 goto fail_getopt;
2192 }
2193
2194
Peter Lieven9fd77f92017-04-21 11:11:55 +02002195 /* ret is still -EINVAL until here */
2196 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2197 if (ret < 0) {
2198 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002199 goto fail_getopt;
2200 }
2201
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002202 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002203 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002204 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002205 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002206 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002207 qemu_progress_print(0, 100);
2208
Peter Lieven9fd77f92017-04-21 11:11:55 +02002209 s.src = g_new0(BlockBackend *, s.src_num);
2210 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002211
Peter Lieven9fd77f92017-04-21 11:11:55 +02002212 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2213 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002214 fmt, src_flags, src_writethrough, quiet,
2215 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002217 ret = -1;
2218 goto out;
2219 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002220 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2221 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002222 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002224 ret = -1;
2225 goto out;
2226 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002228 }
bellardea2384d2004-08-01 21:59:26 +00002229
Wenchao Xiaef806542013-12-04 17:10:57 +08002230 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002231 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002232 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2233 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2234 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002235 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002236 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002237 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002238 ret = -1;
2239 goto out;
2240 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002241
Peter Lieven9fd77f92017-04-21 11:11:55 +02002242 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2243 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002244 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002245 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002246 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002247 ret = -1;
2248 goto out;
edison51ef6722010-09-21 19:58:41 -07002249 }
2250
Max Reitz2e024cd2015-02-11 09:58:46 -05002251 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002252 /* Find driver and parse its options */
2253 drv = bdrv_find_format(out_fmt);
2254 if (!drv) {
2255 error_report("Unknown file format '%s'", out_fmt);
2256 ret = -1;
2257 goto out;
2258 }
2259
2260 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2261 if (!proto_drv) {
2262 error_report_err(local_err);
2263 ret = -1;
2264 goto out;
2265 }
2266
Max Reitz2e024cd2015-02-11 09:58:46 -05002267 if (!drv->create_opts) {
2268 error_report("Format driver '%s' does not support image creation",
2269 drv->format_name);
2270 ret = -1;
2271 goto out;
2272 }
Max Reitzf75613c2014-12-02 18:32:46 +01002273
Max Reitz2e024cd2015-02-11 09:58:46 -05002274 if (!proto_drv->create_opts) {
2275 error_report("Protocol driver '%s' does not support image creation",
2276 proto_drv->format_name);
2277 ret = -1;
2278 goto out;
2279 }
Max Reitzf75613c2014-12-02 18:32:46 +01002280
Max Reitz2e024cd2015-02-11 09:58:46 -05002281 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2282 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002283
Max Reitz2e024cd2015-02-11 09:58:46 -05002284 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002285 if (options) {
2286 qemu_opts_do_parse(opts, options, NULL, &local_err);
2287 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002288 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002289 ret = -1;
2290 goto out;
2291 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002292 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002293
Peter Lieven9fd77f92017-04-21 11:11:55 +02002294 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002295 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002296 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2297 if (ret < 0) {
2298 goto out;
2299 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002300 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002301
Kevin Wolfa18953f2010-10-14 15:46:04 +02002302 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002303 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002304 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002305 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002306 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002307 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002308
Max Reitz48758a82017-04-26 15:46:48 +02002309 if (s.src_num > 1 && out_baseimg) {
2310 error_report("Having a backing file for the target makes no sense when "
2311 "concatenating multiple input images");
2312 ret = -1;
2313 goto out;
2314 }
2315
Kevin Wolfefa84d42009-05-18 16:42:12 +02002316 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002317 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002318 bool encryption =
2319 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002320 const char *encryptfmt =
2321 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002322 const char *preallocation =
2323 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002324
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002325 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002326 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002327 ret = -1;
2328 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002329 }
2330
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002331 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002332 error_report("Compression and encryption not supported at "
2333 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002334 ret = -1;
2335 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002336 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002337
Chunyan Liu83d05212014-06-05 17:20:51 +08002338 if (preallocation
2339 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002340 {
2341 error_report("Compression and preallocation not supported at "
2342 "the same time");
2343 ret = -1;
2344 goto out;
2345 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002346 }
2347
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002348 /*
2349 * The later open call will need any decryption secrets, and
2350 * bdrv_create() will purge "opts", so extract them now before
2351 * they are lost.
2352 */
2353 if (!skip_create) {
2354 open_opts = qdict_new();
2355 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2356 }
2357
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002358 if (!skip_create) {
2359 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002360 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002361 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002362 error_reportf_err(local_err, "%s: error while converting %s: ",
2363 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002364 goto out;
bellardea2384d2004-08-01 21:59:26 +00002365 }
2366 }
ths3b46e622007-09-17 08:09:54 +00002367
Peter Lieven9fd77f92017-04-21 11:11:55 +02002368 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002369 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002370 if (ret < 0) {
2371 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002372 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002373 }
2374
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002375 if (skip_create) {
2376 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2377 flags, writethrough, quiet, false);
2378 } else {
2379 /* TODO ultimately we should allow --target-image-opts
2380 * to be used even when -n is not given.
2381 * That has to wait for bdrv_create to be improved
2382 * to allow filenames in option syntax
2383 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002384 s.target = img_open_file(out_filename, open_opts, out_fmt,
2385 flags, writethrough, quiet, false);
2386 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002387 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002388 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002389 ret = -1;
2390 goto out;
2391 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002392 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002393
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002394 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2395 error_report("Compression not supported for this file format");
2396 ret = -1;
2397 goto out;
2398 }
2399
Eric Blake5def6b82016-06-23 16:37:19 -06002400 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002401 * or discard_alignment of the out_bs is greater. Limit to
2402 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2403 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002404 MAX(s.buf_sectors,
2405 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2406 out_bs->bl.pdiscard_alignment >>
2407 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002408
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002409 /* try to align the write requests to the destination to avoid unnecessary
2410 * RMW cycles. */
2411 s.alignment = MAX(pow2floor(s.min_sparse),
2412 DIV_ROUND_UP(out_bs->bl.request_alignment,
2413 BDRV_SECTOR_SIZE));
2414 assert(is_power_of_2(s.alignment));
2415
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002416 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002417 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002418 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002419 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002420 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002421 ret = -1;
2422 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002423 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002424 error_report("output file is smaller than input file");
2425 ret = -1;
2426 goto out;
2427 }
2428 }
2429
Max Reitz351c8ef2018-05-01 18:57:49 +02002430 if (s.target_has_backing) {
2431 /* Errors are treated as "backing length unknown" (which means
2432 * s.target_backing_sectors has to be negative, which it will
2433 * be automatically). The backing file length is used only
2434 * for optimizations, so such a case is not fatal. */
2435 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2436 } else {
2437 s.target_backing_sectors = -1;
2438 }
2439
Peter Lieven24f833c2013-11-27 11:07:07 +01002440 ret = bdrv_get_info(out_bs, &bdi);
2441 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002442 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002443 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002444 goto out;
2445 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002446 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002447 s.compressed = s.compressed || bdi.needs_compressed_writes;
2448 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002449 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002450 }
2451
Peter Lieven9fd77f92017-04-21 11:11:55 +02002452 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002453out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002454 if (!ret) {
2455 qemu_progress_print(100, 0);
2456 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002457 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002458 qemu_opts_del(opts);
2459 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002460 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002461 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002462 blk_unref(s.target);
2463 if (s.src) {
2464 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2465 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002466 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002467 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002468 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002469 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002470fail_getopt:
2471 g_free(options);
2472
Peter Lieven9fd77f92017-04-21 11:11:55 +02002473 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002474}
2475
bellard57d1a2b2004-08-03 21:15:11 +00002476
bellardfaea38e2006-08-05 21:31:00 +00002477static void dump_snapshots(BlockDriverState *bs)
2478{
2479 QEMUSnapshotInfo *sn_tab, *sn;
2480 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002481
2482 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2483 if (nb_sns <= 0)
2484 return;
2485 printf("Snapshot list:\n");
Wenchao Xia5b917042013-05-25 11:09:45 +08002486 bdrv_snapshot_dump(fprintf, stdout, NULL);
2487 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002488 for(i = 0; i < nb_sns; i++) {
2489 sn = &sn_tab[i];
Wenchao Xia5b917042013-05-25 11:09:45 +08002490 bdrv_snapshot_dump(fprintf, stdout, sn);
2491 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002492 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002493 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002494}
2495
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002496static void dump_json_image_info_list(ImageInfoList *list)
2497{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002498 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002499 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002500 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002501
2502 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2503 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002504 str = qobject_to_json_pretty(obj);
2505 assert(str != NULL);
2506 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002507 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002508 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002509 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002510}
2511
Benoît Canetc054b3f2012-09-05 13:09:02 +02002512static void dump_json_image_info(ImageInfo *info)
2513{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002514 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002515 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002516 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002517
2518 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2519 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002520 str = qobject_to_json_pretty(obj);
2521 assert(str != NULL);
2522 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002523 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002524 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002525 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002526}
2527
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002528static void dump_human_image_info_list(ImageInfoList *list)
2529{
2530 ImageInfoList *elem;
2531 bool delim = false;
2532
2533 for (elem = list; elem; elem = elem->next) {
2534 if (delim) {
2535 printf("\n");
2536 }
2537 delim = true;
2538
Wenchao Xia5b917042013-05-25 11:09:45 +08002539 bdrv_image_info_dump(fprintf, stdout, elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002540 }
2541}
2542
2543static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2544{
2545 return strcmp(a, b) == 0;
2546}
2547
2548/**
2549 * Open an image file chain and return an ImageInfoList
2550 *
2551 * @filename: topmost image filename
2552 * @fmt: topmost image format (may be NULL to autodetect)
2553 * @chain: true - enumerate entire backing file chain
2554 * false - only topmost image file
2555 *
2556 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2557 * image file. If there was an error a message will have been printed to
2558 * stderr.
2559 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002560static ImageInfoList *collect_image_info_list(bool image_opts,
2561 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002562 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002563 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002564{
2565 ImageInfoList *head = NULL;
2566 ImageInfoList **last = &head;
2567 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002568 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002569
2570 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2571
2572 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002573 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002574 BlockDriverState *bs;
2575 ImageInfo *info;
2576 ImageInfoList *elem;
2577
2578 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2579 error_report("Backing file '%s' creates an infinite loop.",
2580 filename);
2581 goto err;
2582 }
2583 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2584
Max Reitzefaa7c42016-03-16 19:54:38 +01002585 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002586 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2587 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002588 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002589 goto err;
2590 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002591 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002592
Wenchao Xia43526ec2013-06-06 12:27:58 +08002593 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002594 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002595 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002596 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002597 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002598 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002599
2600 elem = g_new0(ImageInfoList, 1);
2601 elem->value = info;
2602 *last = elem;
2603 last = &elem->next;
2604
Markus Armbruster26f54e92014-10-07 13:59:04 +02002605 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002606
2607 filename = fmt = NULL;
2608 if (chain) {
2609 if (info->has_full_backing_filename) {
2610 filename = info->full_backing_filename;
2611 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002612 error_report("Could not determine absolute backing filename,"
2613 " but backing filename '%s' present",
2614 info->backing_filename);
2615 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002616 }
2617 if (info->has_backing_filename_format) {
2618 fmt = info->backing_filename_format;
2619 }
2620 }
2621 }
2622 g_hash_table_destroy(filenames);
2623 return head;
2624
2625err:
2626 qapi_free_ImageInfoList(head);
2627 g_hash_table_destroy(filenames);
2628 return NULL;
2629}
2630
Benoît Canetc054b3f2012-09-05 13:09:02 +02002631static int img_info(int argc, char **argv)
2632{
2633 int c;
2634 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002635 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002636 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002637 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002638 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002639 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002640
bellardea2384d2004-08-01 21:59:26 +00002641 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002642 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002643 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002644 int option_index = 0;
2645 static const struct option long_options[] = {
2646 {"help", no_argument, 0, 'h'},
2647 {"format", required_argument, 0, 'f'},
2648 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002649 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002650 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002651 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002652 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002653 {0, 0, 0, 0}
2654 };
Fam Zheng335e9932017-05-03 00:35:39 +08002655 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002656 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002657 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002658 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002659 }
bellardea2384d2004-08-01 21:59:26 +00002660 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002661 case ':':
2662 missing_argument(argv[optind - 1]);
2663 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002664 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002665 unrecognized_option(argv[optind - 1]);
2666 break;
bellardea2384d2004-08-01 21:59:26 +00002667 case 'h':
2668 help();
2669 break;
2670 case 'f':
2671 fmt = optarg;
2672 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002673 case 'U':
2674 force_share = true;
2675 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002676 case OPTION_OUTPUT:
2677 output = optarg;
2678 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002679 case OPTION_BACKING_CHAIN:
2680 chain = true;
2681 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002682 case OPTION_OBJECT: {
2683 QemuOpts *opts;
2684 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2685 optarg, true);
2686 if (!opts) {
2687 return 1;
2688 }
2689 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002690 case OPTION_IMAGE_OPTS:
2691 image_opts = true;
2692 break;
bellardea2384d2004-08-01 21:59:26 +00002693 }
2694 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002695 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002696 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002697 }
bellardea2384d2004-08-01 21:59:26 +00002698 filename = argv[optind++];
2699
Benoît Canetc054b3f2012-09-05 13:09:02 +02002700 if (output && !strcmp(output, "json")) {
2701 output_format = OFORMAT_JSON;
2702 } else if (output && !strcmp(output, "human")) {
2703 output_format = OFORMAT_HUMAN;
2704 } else if (output) {
2705 error_report("--output must be used with human or json as argument.");
2706 return 1;
2707 }
2708
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002709 if (qemu_opts_foreach(&qemu_object_opts,
2710 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002711 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002712 return 1;
2713 }
2714
Fam Zheng335e9932017-05-03 00:35:39 +08002715 list = collect_image_info_list(image_opts, filename, fmt, chain,
2716 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002717 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002718 return 1;
2719 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002720
Benoît Canetc054b3f2012-09-05 13:09:02 +02002721 switch (output_format) {
2722 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002723 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002724 break;
2725 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002726 if (chain) {
2727 dump_json_image_info_list(list);
2728 } else {
2729 dump_json_image_info(list->value);
2730 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002731 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002732 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002733
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002734 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002735 return 0;
2736}
2737
Eric Blake30065d12019-03-26 13:40:43 -05002738static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2739 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002740{
2741 switch (output_format) {
2742 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002743 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002744 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002745 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002746 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002747 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002748 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002749 e->start, e->length,
2750 e->has_offset ? e->offset : 0,
2751 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002752 }
2753 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2754 * Modify the flags here to allow more coalescing.
2755 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002756 if (next && (!next->data || next->zero)) {
2757 next->data = false;
2758 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002759 }
2760 break;
2761 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002762 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2763 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002764 (e->start == 0 ? "[" : ",\n"),
2765 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002766 e->zero ? "true" : "false",
2767 e->data ? "true" : "false");
2768 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002769 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002770 }
2771 putchar('}');
2772
2773 if (!next) {
2774 printf("]\n");
2775 }
2776 break;
2777 }
Eric Blake30065d12019-03-26 13:40:43 -05002778 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002779}
2780
Eric Blake5e344dd2017-10-11 22:47:02 -05002781static int get_block_status(BlockDriverState *bs, int64_t offset,
2782 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002783{
Eric Blake237d78f2017-10-11 22:47:03 -05002784 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002785 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002786 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002787 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002788 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002789 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002790
2791 /* As an optimization, we could cache the current range of unallocated
2792 * clusters in each file of the chain, and avoid querying the same
2793 * range repeatedly.
2794 */
2795
2796 depth = 0;
2797 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002798 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002799 if (ret < 0) {
2800 return ret;
2801 }
Eric Blake237d78f2017-10-11 22:47:03 -05002802 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002803 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2804 break;
2805 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002806 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002807 if (bs == NULL) {
2808 ret = 0;
2809 break;
2810 }
2811
2812 depth++;
2813 }
2814
John Snow28756452016-02-05 13:12:33 -05002815 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2816
Max Reitzf30c66b2019-02-01 20:29:05 +01002817 if (file && has_offset) {
2818 bdrv_refresh_filename(file);
2819 filename = file->filename;
2820 }
2821
John Snow28756452016-02-05 13:12:33 -05002822 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002823 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002824 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002825 .data = !!(ret & BDRV_BLOCK_DATA),
2826 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002827 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002828 .has_offset = has_offset,
2829 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002830 .has_filename = filename,
2831 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002832 };
2833
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002834 return 0;
2835}
2836
Fam Zheng16b0d552016-01-26 11:59:02 +08002837static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2838{
2839 if (curr->length == 0) {
2840 return false;
2841 }
2842 if (curr->zero != next->zero ||
2843 curr->data != next->data ||
2844 curr->depth != next->depth ||
2845 curr->has_filename != next->has_filename ||
2846 curr->has_offset != next->has_offset) {
2847 return false;
2848 }
2849 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2850 return false;
2851 }
2852 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2853 return false;
2854 }
2855 return true;
2856}
2857
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858static int img_map(int argc, char **argv)
2859{
2860 int c;
2861 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002862 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002863 BlockDriverState *bs;
2864 const char *filename, *fmt, *output;
2865 int64_t length;
2866 MapEntry curr = { .length = 0 }, next;
2867 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002868 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002869 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002870
2871 fmt = NULL;
2872 output = NULL;
2873 for (;;) {
2874 int option_index = 0;
2875 static const struct option long_options[] = {
2876 {"help", no_argument, 0, 'h'},
2877 {"format", required_argument, 0, 'f'},
2878 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002879 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002880 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002881 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002882 {0, 0, 0, 0}
2883 };
Fam Zheng335e9932017-05-03 00:35:39 +08002884 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002885 long_options, &option_index);
2886 if (c == -1) {
2887 break;
2888 }
2889 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002890 case ':':
2891 missing_argument(argv[optind - 1]);
2892 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002893 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002894 unrecognized_option(argv[optind - 1]);
2895 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002896 case 'h':
2897 help();
2898 break;
2899 case 'f':
2900 fmt = optarg;
2901 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002902 case 'U':
2903 force_share = true;
2904 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002905 case OPTION_OUTPUT:
2906 output = optarg;
2907 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002908 case OPTION_OBJECT: {
2909 QemuOpts *opts;
2910 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2911 optarg, true);
2912 if (!opts) {
2913 return 1;
2914 }
2915 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002916 case OPTION_IMAGE_OPTS:
2917 image_opts = true;
2918 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002919 }
2920 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002921 if (optind != argc - 1) {
2922 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002923 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002924 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002925
2926 if (output && !strcmp(output, "json")) {
2927 output_format = OFORMAT_JSON;
2928 } else if (output && !strcmp(output, "human")) {
2929 output_format = OFORMAT_HUMAN;
2930 } else if (output) {
2931 error_report("--output must be used with human or json as argument.");
2932 return 1;
2933 }
2934
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002935 if (qemu_opts_foreach(&qemu_object_opts,
2936 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002937 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002938 return 1;
2939 }
2940
Fam Zheng335e9932017-05-03 00:35:39 +08002941 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002942 if (!blk) {
2943 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002944 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002945 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002946
2947 if (output_format == OFORMAT_HUMAN) {
2948 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2949 }
2950
Max Reitzf1d3cd72015-02-05 13:58:18 -05002951 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002952 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002953 int64_t offset = curr.start + curr.length;
2954 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002955
2956 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002957 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002958 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002959
2960 if (ret < 0) {
2961 error_report("Could not read file metadata: %s", strerror(-ret));
2962 goto out;
2963 }
2964
Fam Zheng16b0d552016-01-26 11:59:02 +08002965 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002966 curr.length += next.length;
2967 continue;
2968 }
2969
2970 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002971 ret = dump_map_entry(output_format, &curr, &next);
2972 if (ret < 0) {
2973 goto out;
2974 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002975 }
2976 curr = next;
2977 }
2978
Eric Blake30065d12019-03-26 13:40:43 -05002979 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002980
2981out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002982 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002983 return ret < 0;
2984}
2985
aliguorif7b4a942009-01-07 17:40:15 +00002986#define SNAPSHOT_LIST 1
2987#define SNAPSHOT_CREATE 2
2988#define SNAPSHOT_APPLY 3
2989#define SNAPSHOT_DELETE 4
2990
Stuart Brady153859b2009-06-07 00:42:17 +01002991static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002992{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002993 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00002994 BlockDriverState *bs;
2995 QEMUSnapshotInfo sn;
2996 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002997 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00002998 int action = 0;
2999 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003000 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003001 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003002 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003003 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003004
Kevin Wolfce099542016-03-15 13:01:04 +01003005 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003006 /* Parse commandline parameters */
3007 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003008 static const struct option long_options[] = {
3009 {"help", no_argument, 0, 'h'},
3010 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003011 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003012 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003013 {0, 0, 0, 0}
3014 };
Fam Zheng335e9932017-05-03 00:35:39 +08003015 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003016 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003017 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003018 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003019 }
aliguorif7b4a942009-01-07 17:40:15 +00003020 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003021 case ':':
3022 missing_argument(argv[optind - 1]);
3023 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003024 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003025 unrecognized_option(argv[optind - 1]);
3026 break;
aliguorif7b4a942009-01-07 17:40:15 +00003027 case 'h':
3028 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003029 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003030 case 'l':
3031 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003032 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003033 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003034 }
3035 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003036 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003037 break;
3038 case 'a':
3039 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003040 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003041 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003042 }
3043 action = SNAPSHOT_APPLY;
3044 snapshot_name = optarg;
3045 break;
3046 case 'c':
3047 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003048 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003049 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003050 }
3051 action = SNAPSHOT_CREATE;
3052 snapshot_name = optarg;
3053 break;
3054 case 'd':
3055 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003056 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003057 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003058 }
3059 action = SNAPSHOT_DELETE;
3060 snapshot_name = optarg;
3061 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003062 case 'q':
3063 quiet = true;
3064 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003065 case 'U':
3066 force_share = true;
3067 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003068 case OPTION_OBJECT: {
3069 QemuOpts *opts;
3070 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3071 optarg, true);
3072 if (!opts) {
3073 return 1;
3074 }
3075 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003076 case OPTION_IMAGE_OPTS:
3077 image_opts = true;
3078 break;
aliguorif7b4a942009-01-07 17:40:15 +00003079 }
3080 }
3081
Kevin Wolffc11eb22013-08-05 10:53:04 +02003082 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003083 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003084 }
aliguorif7b4a942009-01-07 17:40:15 +00003085 filename = argv[optind++];
3086
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003087 if (qemu_opts_foreach(&qemu_object_opts,
3088 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003089 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003090 return 1;
3091 }
3092
aliguorif7b4a942009-01-07 17:40:15 +00003093 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003094 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3095 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003096 if (!blk) {
3097 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003098 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003099 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003100
3101 /* Perform the requested action */
3102 switch(action) {
3103 case SNAPSHOT_LIST:
3104 dump_snapshots(bs);
3105 break;
3106
3107 case SNAPSHOT_CREATE:
3108 memset(&sn, 0, sizeof(sn));
3109 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3110
3111 qemu_gettimeofday(&tv);
3112 sn.date_sec = tv.tv_sec;
3113 sn.date_nsec = tv.tv_usec * 1000;
3114
3115 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003116 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003117 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003118 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003119 }
aliguorif7b4a942009-01-07 17:40:15 +00003120 break;
3121
3122 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003123 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003124 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003125 error_reportf_err(err, "Could not apply snapshot '%s': ",
3126 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003127 }
aliguorif7b4a942009-01-07 17:40:15 +00003128 break;
3129
3130 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003131 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3132 if (ret < 0) {
3133 error_report("Could not delete snapshot '%s': snapshot not "
3134 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003135 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003136 } else {
3137 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3138 if (ret < 0) {
3139 error_reportf_err(err, "Could not delete snapshot '%s': ",
3140 snapshot_name);
3141 ret = 1;
3142 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003143 }
aliguorif7b4a942009-01-07 17:40:15 +00003144 break;
3145 }
3146
3147 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003148 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003149 if (ret) {
3150 return 1;
3151 }
Stuart Brady153859b2009-06-07 00:42:17 +01003152 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003153}
3154
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003155static int img_rebase(int argc, char **argv)
3156{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003157 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003158 uint8_t *buf_old = NULL;
3159 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003160 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003161 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003162 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3163 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003164 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003165 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003166 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003167 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003168 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003169 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003170 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003171
3172 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003173 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003174 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003175 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003176 out_baseimg = NULL;
3177 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003178 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003179 static const struct option long_options[] = {
3180 {"help", no_argument, 0, 'h'},
3181 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003182 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003183 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003184 {0, 0, 0, 0}
3185 };
Fam Zheng335e9932017-05-03 00:35:39 +08003186 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003187 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003188 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003189 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003190 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003191 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003192 case ':':
3193 missing_argument(argv[optind - 1]);
3194 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003195 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003196 unrecognized_option(argv[optind - 1]);
3197 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003198 case 'h':
3199 help();
3200 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003201 case 'f':
3202 fmt = optarg;
3203 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003204 case 'F':
3205 out_basefmt = optarg;
3206 break;
3207 case 'b':
3208 out_baseimg = optarg;
3209 break;
3210 case 'u':
3211 unsafe = 1;
3212 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003213 case 'p':
3214 progress = 1;
3215 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003216 case 't':
3217 cache = optarg;
3218 break;
Max Reitz40055952014-07-22 22:58:42 +02003219 case 'T':
3220 src_cache = optarg;
3221 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003222 case 'q':
3223 quiet = true;
3224 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003225 case OPTION_OBJECT: {
3226 QemuOpts *opts;
3227 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3228 optarg, true);
3229 if (!opts) {
3230 return 1;
3231 }
3232 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003233 case OPTION_IMAGE_OPTS:
3234 image_opts = true;
3235 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003236 case 'U':
3237 force_share = true;
3238 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003239 }
3240 }
3241
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003242 if (quiet) {
3243 progress = 0;
3244 }
3245
Fam Zhengac1307a2014-04-22 13:36:11 +08003246 if (optind != argc - 1) {
3247 error_exit("Expecting one image file name");
3248 }
3249 if (!unsafe && !out_baseimg) {
3250 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003251 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003252 filename = argv[optind++];
3253
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003254 if (qemu_opts_foreach(&qemu_object_opts,
3255 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003256 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003257 return 1;
3258 }
3259
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003260 qemu_progress_init(progress, 2.0);
3261 qemu_progress_print(0, 100);
3262
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003263 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003264 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003265 if (ret < 0) {
3266 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003267 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003268 }
3269
Kevin Wolfce099542016-03-15 13:01:04 +01003270 src_flags = 0;
3271 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003272 if (ret < 0) {
3273 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003274 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003275 }
3276
Kevin Wolfce099542016-03-15 13:01:04 +01003277 /* The source files are opened read-only, don't care about WCE */
3278 assert((src_flags & BDRV_O_RDWR) == 0);
3279 (void) src_writethrough;
3280
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003281 /*
3282 * Open the images.
3283 *
3284 * Ignore the old backing file for unsafe rebase in case we want to correct
3285 * the reference to a renamed or moved backing file.
3286 */
Fam Zheng335e9932017-05-03 00:35:39 +08003287 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3288 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003289 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003290 ret = -1;
3291 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003292 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003293 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003294
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003295 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003296 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003297 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003298 ret = -1;
3299 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003300 }
3301 }
3302
3303 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003304 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003305 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003306 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003307
Max Reitz644483d2015-02-05 13:58:17 -05003308 if (bs->backing_format[0] != '\0') {
3309 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003310 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003311 }
3312
Fam Zheng335e9932017-05-03 00:35:39 +08003313 if (force_share) {
3314 if (!options) {
3315 options = qdict_new();
3316 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003317 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003318 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003319 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003320 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003321 options, src_flags, &local_err);
3322 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003323 error_reportf_err(local_err,
3324 "Could not open old backing file '%s': ",
3325 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003326 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003327 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003328 }
Max Reitz644483d2015-02-05 13:58:17 -05003329
Alex Bligha6166732012-10-16 13:46:18 +01003330 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003331 const char *overlay_filename;
3332 char *out_real_path;
3333
Fam Zheng335e9932017-05-03 00:35:39 +08003334 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003335 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003336 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003337 }
3338 if (force_share) {
3339 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003340 }
3341
Max Reitzf30c66b2019-02-01 20:29:05 +01003342 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003343 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3344 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003345 out_real_path =
3346 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3347 out_baseimg,
3348 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003349 if (local_err) {
3350 error_reportf_err(local_err,
3351 "Could not resolve backing filename: ");
3352 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003353 goto out;
3354 }
3355
3356 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003357 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003358 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003359 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003360 error_reportf_err(local_err,
3361 "Could not open new backing file '%s': ",
3362 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003363 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003364 goto out;
3365 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003366 }
3367 }
3368
3369 /*
3370 * Check each unallocated cluster in the COW file. If it is unallocated,
3371 * accesses go to the backing file. We must therefore compare this cluster
3372 * in the old and new backing file, and if they differ we need to copy it
3373 * from the old backing file into the COW file.
3374 *
3375 * If qemu-img crashes during this step, no harm is done. The content of
3376 * the image is the same as the original one at any time.
3377 */
3378 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003379 int64_t size;
3380 int64_t old_backing_size;
3381 int64_t new_backing_size = 0;
3382 uint64_t offset;
3383 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003384 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003385
Max Reitzf1d3cd72015-02-05 13:58:18 -05003386 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3387 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003388
Eric Blake41536282017-10-11 22:47:15 -05003389 size = blk_getlength(blk);
3390 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003391 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003392 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003393 ret = -1;
3394 goto out;
3395 }
Eric Blake41536282017-10-11 22:47:15 -05003396 old_backing_size = blk_getlength(blk_old_backing);
3397 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003398 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003399
3400 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3401 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003402 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003403 ret = -1;
3404 goto out;
3405 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003406 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003407 new_backing_size = blk_getlength(blk_new_backing);
3408 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003409 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003410 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003411 ret = -1;
3412 goto out;
3413 }
Alex Bligha6166732012-10-16 13:46:18 +01003414 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003415
Eric Blake41536282017-10-11 22:47:15 -05003416 if (size != 0) {
3417 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003418 }
3419
Eric Blake41536282017-10-11 22:47:15 -05003420 for (offset = 0; offset < size; offset += n) {
3421 /* How many bytes can we handle with the next read? */
3422 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003423
3424 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003425 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003426 if (ret < 0) {
3427 error_report("error while reading image metadata: %s",
3428 strerror(-ret));
3429 goto out;
3430 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003431 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003432 continue;
3433 }
3434
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003435 /*
3436 * Read old and new backing file and take into consideration that
3437 * backing files may be smaller than the COW image.
3438 */
Eric Blake41536282017-10-11 22:47:15 -05003439 if (offset >= old_backing_size) {
3440 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003441 } else {
Eric Blake41536282017-10-11 22:47:15 -05003442 if (offset + n > old_backing_size) {
3443 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003444 }
3445
Eric Blake41536282017-10-11 22:47:15 -05003446 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003447 if (ret < 0) {
3448 error_report("error while reading from old backing file");
3449 goto out;
3450 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003451 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003452
Eric Blake41536282017-10-11 22:47:15 -05003453 if (offset >= new_backing_size || !blk_new_backing) {
3454 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003455 } else {
Eric Blake41536282017-10-11 22:47:15 -05003456 if (offset + n > new_backing_size) {
3457 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003458 }
3459
Eric Blake41536282017-10-11 22:47:15 -05003460 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003461 if (ret < 0) {
3462 error_report("error while reading from new backing file");
3463 goto out;
3464 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003465 }
3466
3467 /* If they differ, we need to write to the COW file */
3468 uint64_t written = 0;
3469
Eric Blake41536282017-10-11 22:47:15 -05003470 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003471 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003472
Eric Blake41536282017-10-11 22:47:15 -05003473 if (compare_buffers(buf_old + written, buf_new + written,
3474 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003475 {
Eric Blake41536282017-10-11 22:47:15 -05003476 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003477 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003479 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003480 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003481 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003482 }
3483 }
3484
3485 written += pnum;
3486 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003487 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003488 }
3489 }
3490
3491 /*
3492 * Change the backing file. All clusters that are different from the old
3493 * backing file are overwritten in the COW file now, so the visible content
3494 * doesn't change when we switch the backing file.
3495 */
Alex Bligha6166732012-10-16 13:46:18 +01003496 if (out_baseimg && *out_baseimg) {
3497 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3498 } else {
3499 ret = bdrv_change_backing_file(bs, NULL, NULL);
3500 }
3501
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003502 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003503 error_report("Could not change the backing file to '%s': No "
3504 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003505 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003506 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003507 out_baseimg, strerror(-ret));
3508 }
3509
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003510 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003511 /*
3512 * TODO At this point it is possible to check if any clusters that are
3513 * allocated in the COW file are the same in the backing file. If so, they
3514 * could be dropped from the COW file. Don't do this before switching the
3515 * backing file, in case of a crash this would lead to corruption.
3516 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003517out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003518 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003519 /* Cleanup */
3520 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003521 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003522 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003523 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003524 qemu_vfree(buf_old);
3525 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003526
Markus Armbruster26f54e92014-10-07 13:59:04 +02003527 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003528 if (ret) {
3529 return 1;
3530 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003531 return 0;
3532}
3533
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003534static int img_resize(int argc, char **argv)
3535{
Markus Armbruster6750e792015-02-12 17:43:08 +01003536 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003537 int c, ret, relative;
3538 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003539 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003540 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003541 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003542 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003543 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003544
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003545 static QemuOptsList resize_options = {
3546 .name = "resize_options",
3547 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3548 .desc = {
3549 {
3550 .name = BLOCK_OPT_SIZE,
3551 .type = QEMU_OPT_SIZE,
3552 .help = "Virtual disk size"
3553 }, {
3554 /* end of list */
3555 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003556 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003557 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003558 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003559 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003560
Kevin Wolfe80fec72011-04-29 10:58:12 +02003561 /* Remove size from argv manually so that negative numbers are not treated
3562 * as options by getopt. */
3563 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003564 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003565 return 1;
3566 }
3567
3568 size = argv[--argc];
3569
3570 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003571 fmt = NULL;
3572 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003573 static const struct option long_options[] = {
3574 {"help", no_argument, 0, 'h'},
3575 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003576 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003577 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003578 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003579 {0, 0, 0, 0}
3580 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003581 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003582 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003583 if (c == -1) {
3584 break;
3585 }
3586 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003587 case ':':
3588 missing_argument(argv[optind - 1]);
3589 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003590 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003591 unrecognized_option(argv[optind - 1]);
3592 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003593 case 'h':
3594 help();
3595 break;
3596 case 'f':
3597 fmt = optarg;
3598 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003599 case 'q':
3600 quiet = true;
3601 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003602 case OPTION_OBJECT: {
3603 QemuOpts *opts;
3604 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3605 optarg, true);
3606 if (!opts) {
3607 return 1;
3608 }
3609 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003610 case OPTION_IMAGE_OPTS:
3611 image_opts = true;
3612 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003613 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003614 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003615 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003616 if (prealloc == PREALLOC_MODE__MAX) {
3617 error_report("Invalid preallocation mode '%s'", optarg);
3618 return 1;
3619 }
3620 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003621 case OPTION_SHRINK:
3622 shrink = true;
3623 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003624 }
3625 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003626 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003627 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003628 }
3629 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003630
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003631 if (qemu_opts_foreach(&qemu_object_opts,
3632 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003633 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003634 return 1;
3635 }
3636
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003637 /* Choose grow, shrink, or absolute resize mode */
3638 switch (size[0]) {
3639 case '+':
3640 relative = 1;
3641 size++;
3642 break;
3643 case '-':
3644 relative = -1;
3645 size++;
3646 break;
3647 default:
3648 relative = 0;
3649 break;
3650 }
3651
3652 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003653 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003654 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003655 if (err) {
3656 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003657 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003658 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003659 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003660 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003661 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3662 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003663
Max Reitzefaa7c42016-03-16 19:54:38 +01003664 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003665 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3666 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003667 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003668 ret = -1;
3669 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003670 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003671
Max Reitzdc5f6902017-06-13 22:20:55 +02003672 current_size = blk_getlength(blk);
3673 if (current_size < 0) {
3674 error_report("Failed to inquire current image length: %s",
3675 strerror(-current_size));
3676 ret = -1;
3677 goto out;
3678 }
3679
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003680 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003681 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003682 } else {
3683 total_size = n;
3684 }
3685 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003686 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003687 ret = -1;
3688 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003689 }
3690
Max Reitzdc5f6902017-06-13 22:20:55 +02003691 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3692 error_report("Preallocation can only be used for growing images");
3693 ret = -1;
3694 goto out;
3695 }
3696
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003697 if (total_size < current_size && !shrink) {
3698 warn_report("Shrinking an image will delete all data beyond the "
3699 "shrunken image's end. Before performing such an "
3700 "operation, make sure there is no important data there.");
3701
3702 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3703 error_report(
3704 "Use the --shrink option to perform a shrink operation.");
3705 ret = -1;
3706 goto out;
3707 } else {
3708 warn_report("Using the --shrink option will suppress this message. "
3709 "Note that future versions of qemu-img may refuse to "
3710 "shrink images without this option.");
3711 }
3712 }
3713
Max Reitzdc5f6902017-06-13 22:20:55 +02003714 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003715 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003716 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003717 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003718 }
Max Reitz5279b302018-04-21 18:39:57 +02003719
3720 new_size = blk_getlength(blk);
3721 if (new_size < 0) {
3722 error_report("Failed to verify truncated image length: %s",
3723 strerror(-new_size));
3724 ret = -1;
3725 goto out;
3726 }
3727
3728 /* Some block drivers implement a truncation method, but only so
3729 * the user can cause qemu to refresh the image's size from disk.
3730 * The idea is that the user resizes the image outside of qemu and
3731 * then invokes block_resize to inform qemu about it.
3732 * (This includes iscsi and file-posix for device files.)
3733 * Of course, that is not the behavior someone invoking
3734 * qemu-img resize would find useful, so we catch that behavior
3735 * here and tell the user. */
3736 if (new_size != total_size && new_size == current_size) {
3737 error_report("Image was not resized; resizing may not be supported "
3738 "for this image");
3739 ret = -1;
3740 goto out;
3741 }
3742
3743 if (new_size != total_size) {
3744 warn_report("Image should have been resized to %" PRIi64
3745 " bytes, but was resized to %" PRIi64 " bytes",
3746 total_size, new_size);
3747 }
3748
3749 qprintf(quiet, "Image resized.\n");
3750
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003751out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003752 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003753 if (ret) {
3754 return 1;
3755 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003756 return 0;
3757}
3758
Max Reitz76a3a342014-10-27 11:12:51 +01003759static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003760 int64_t offset, int64_t total_work_size,
3761 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003762{
3763 qemu_progress_print(100.f * offset / total_work_size, 0);
3764}
3765
Max Reitz51641352018-05-09 23:00:20 +02003766static int print_amend_option_help(const char *format)
3767{
3768 BlockDriver *drv;
3769
3770 /* Find driver and parse its options */
3771 drv = bdrv_find_format(format);
3772 if (!drv) {
3773 error_report("Unknown file format '%s'", format);
3774 return 1;
3775 }
3776
3777 if (!drv->bdrv_amend_options) {
3778 error_report("Format driver '%s' does not support option amendment",
3779 format);
3780 return 1;
3781 }
3782
3783 /* Every driver supporting amendment must have create_opts */
3784 assert(drv->create_opts);
3785
3786 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003787 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003788 printf("\nNote that not all of these options may be amendable.\n");
3789 return 0;
3790}
3791
Max Reitz6f176b42013-09-03 10:09:50 +02003792static int img_amend(int argc, char **argv)
3793{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003794 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003795 int c, ret = 0;
3796 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003797 QemuOptsList *create_opts = NULL;
3798 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003799 const char *fmt = NULL, *filename, *cache;
3800 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003801 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003802 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003803 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003804 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003805 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003806
Max Reitzbd39e6e2014-07-22 22:58:43 +02003807 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003808 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003809 static const struct option long_options[] = {
3810 {"help", no_argument, 0, 'h'},
3811 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003813 {0, 0, 0, 0}
3814 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003815 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003816 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003817 if (c == -1) {
3818 break;
3819 }
3820
3821 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003822 case ':':
3823 missing_argument(argv[optind - 1]);
3824 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003825 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003826 unrecognized_option(argv[optind - 1]);
3827 break;
3828 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003829 help();
3830 break;
3831 case 'o':
3832 if (!is_valid_option_list(optarg)) {
3833 error_report("Invalid option list: %s", optarg);
3834 ret = -1;
3835 goto out_no_progress;
3836 }
3837 if (!options) {
3838 options = g_strdup(optarg);
3839 } else {
3840 char *old_options = options;
3841 options = g_strdup_printf("%s,%s", options, optarg);
3842 g_free(old_options);
3843 }
3844 break;
3845 case 'f':
3846 fmt = optarg;
3847 break;
3848 case 't':
3849 cache = optarg;
3850 break;
3851 case 'p':
3852 progress = true;
3853 break;
3854 case 'q':
3855 quiet = true;
3856 break;
3857 case OPTION_OBJECT:
3858 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3859 optarg, true);
3860 if (!opts) {
3861 ret = -1;
3862 goto out_no_progress;
3863 }
3864 break;
3865 case OPTION_IMAGE_OPTS:
3866 image_opts = true;
3867 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003868 }
3869 }
3870
Max Reitz6f176b42013-09-03 10:09:50 +02003871 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003872 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003873 }
3874
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003875 if (qemu_opts_foreach(&qemu_object_opts,
3876 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003877 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003878 ret = -1;
3879 goto out_no_progress;
3880 }
3881
Max Reitz76a3a342014-10-27 11:12:51 +01003882 if (quiet) {
3883 progress = false;
3884 }
3885 qemu_progress_init(progress, 1.0);
3886
Kevin Wolfa283cb62014-02-21 16:24:07 +01003887 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3888 if (fmt && has_help_option(options)) {
3889 /* If a format is explicitly specified (and possibly no filename is
3890 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003891 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003892 goto out;
3893 }
3894
3895 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003896 error_report("Expecting one image file name");
3897 ret = -1;
3898 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003899 }
Max Reitz6f176b42013-09-03 10:09:50 +02003900
Kevin Wolfce099542016-03-15 13:01:04 +01003901 flags = BDRV_O_RDWR;
3902 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003903 if (ret < 0) {
3904 error_report("Invalid cache option: %s", cache);
3905 goto out;
3906 }
3907
Fam Zheng335e9932017-05-03 00:35:39 +08003908 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3909 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003910 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003911 ret = -1;
3912 goto out;
3913 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003914 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003915
3916 fmt = bs->drv->format_name;
3917
Kevin Wolf626f84f2014-02-21 16:24:06 +01003918 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003919 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003920 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003921 goto out;
3922 }
3923
Max Reitz1f996682018-05-09 23:00:17 +02003924 if (!bs->drv->bdrv_amend_options) {
3925 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003926 fmt);
3927 ret = -1;
3928 goto out;
3929 }
3930
Max Reitz1f996682018-05-09 23:00:17 +02003931 /* Every driver supporting amendment must have create_opts */
3932 assert(bs->drv->create_opts);
3933
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003934 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003935 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003936 qemu_opts_do_parse(opts, options, NULL, &err);
3937 if (err) {
3938 error_report_err(err);
3939 ret = -1;
3940 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003941 }
3942
Max Reitz76a3a342014-10-27 11:12:51 +01003943 /* In case the driver does not call amend_status_cb() */
3944 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003945 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003946 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003947 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003948 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003949 goto out;
3950 }
3951
3952out:
Max Reitz76a3a342014-10-27 11:12:51 +01003953 qemu_progress_end();
3954
Max Reitze814dff2015-08-20 16:00:38 -07003955out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003956 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003957 qemu_opts_del(opts);
3958 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003959 g_free(options);
3960
Max Reitz6f176b42013-09-03 10:09:50 +02003961 if (ret) {
3962 return 1;
3963 }
3964 return 0;
3965}
3966
Kevin Wolfb6133b82014-08-05 14:17:13 +02003967typedef struct BenchData {
3968 BlockBackend *blk;
3969 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003970 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003971 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003972 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003973 int nrreq;
3974 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003975 int flush_interval;
3976 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003977 uint8_t *buf;
3978 QEMUIOVector *qiov;
3979
3980 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003981 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003982 uint64_t offset;
3983} BenchData;
3984
Kevin Wolf55d539c2016-06-03 13:59:41 +02003985static void bench_undrained_flush_cb(void *opaque, int ret)
3986{
3987 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003988 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003989 exit(EXIT_FAILURE);
3990 }
3991}
3992
Kevin Wolfb6133b82014-08-05 14:17:13 +02003993static void bench_cb(void *opaque, int ret)
3994{
3995 BenchData *b = opaque;
3996 BlockAIOCB *acb;
3997
3998 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003999 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004000 exit(EXIT_FAILURE);
4001 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004002
4003 if (b->in_flush) {
4004 /* Just finished a flush with drained queue: Start next requests */
4005 assert(b->in_flight == 0);
4006 b->in_flush = false;
4007 } else if (b->in_flight > 0) {
4008 int remaining = b->n - b->in_flight;
4009
Kevin Wolfb6133b82014-08-05 14:17:13 +02004010 b->n--;
4011 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004012
4013 /* Time for flush? Drain queue if requested, then flush */
4014 if (b->flush_interval && remaining % b->flush_interval == 0) {
4015 if (!b->in_flight || !b->drain_on_flush) {
4016 BlockCompletionFunc *cb;
4017
4018 if (b->drain_on_flush) {
4019 b->in_flush = true;
4020 cb = bench_cb;
4021 } else {
4022 cb = bench_undrained_flush_cb;
4023 }
4024
4025 acb = blk_aio_flush(b->blk, cb, b);
4026 if (!acb) {
4027 error_report("Failed to issue flush request");
4028 exit(EXIT_FAILURE);
4029 }
4030 }
4031 if (b->drain_on_flush) {
4032 return;
4033 }
4034 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004035 }
4036
4037 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004038 int64_t offset = b->offset;
4039 /* blk_aio_* might look for completed I/Os and kick bench_cb
4040 * again, so make sure this operation is counted by in_flight
4041 * and b->offset is ready for the next submission.
4042 */
4043 b->in_flight++;
4044 b->offset += b->step;
4045 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004046 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004047 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004048 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004049 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004050 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004051 if (!acb) {
4052 error_report("Failed to issue request");
4053 exit(EXIT_FAILURE);
4054 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004055 }
4056}
4057
4058static int img_bench(int argc, char **argv)
4059{
4060 int c, ret = 0;
4061 const char *fmt = NULL, *filename;
4062 bool quiet = false;
4063 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004064 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004065 int count = 75000;
4066 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004067 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004068 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004069 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004070 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004071 int flush_interval = 0;
4072 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004073 int64_t image_size;
4074 BlockBackend *blk = NULL;
4075 BenchData data = {};
4076 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004077 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004078 struct timeval t1, t2;
4079 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004080 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004081 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004082
4083 for (;;) {
4084 static const struct option long_options[] = {
4085 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004086 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004087 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004088 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004089 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004090 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004091 {0, 0, 0, 0}
4092 };
Fam Zheng335e9932017-05-03 00:35:39 +08004093 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004094 if (c == -1) {
4095 break;
4096 }
4097
4098 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004099 case ':':
4100 missing_argument(argv[optind - 1]);
4101 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004102 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004103 unrecognized_option(argv[optind - 1]);
4104 break;
4105 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004106 help();
4107 break;
4108 case 'c':
4109 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004110 unsigned long res;
4111
4112 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004113 error_report("Invalid request count specified");
4114 return 1;
4115 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004116 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004117 break;
4118 }
4119 case 'd':
4120 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004121 unsigned long res;
4122
4123 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004124 error_report("Invalid queue depth specified");
4125 return 1;
4126 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004127 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004128 break;
4129 }
4130 case 'f':
4131 fmt = optarg;
4132 break;
4133 case 'n':
4134 flags |= BDRV_O_NATIVE_AIO;
4135 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004136 case 'o':
4137 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004138 offset = cvtnum(optarg);
4139 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004140 error_report("Invalid offset specified");
4141 return 1;
4142 }
4143 break;
4144 }
4145 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004146 case 'q':
4147 quiet = true;
4148 break;
4149 case 's':
4150 {
4151 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152
Markus Armbruster606caa02017-02-21 21:14:04 +01004153 sval = cvtnum(optarg);
4154 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004155 error_report("Invalid buffer size specified");
4156 return 1;
4157 }
4158
4159 bufsize = sval;
4160 break;
4161 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004162 case 'S':
4163 {
4164 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004165
Markus Armbruster606caa02017-02-21 21:14:04 +01004166 sval = cvtnum(optarg);
4167 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004168 error_report("Invalid step size specified");
4169 return 1;
4170 }
4171
4172 step = sval;
4173 break;
4174 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004175 case 't':
4176 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4177 if (ret < 0) {
4178 error_report("Invalid cache mode");
4179 ret = -1;
4180 goto out;
4181 }
4182 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004183 case 'w':
4184 flags |= BDRV_O_RDWR;
4185 is_write = true;
4186 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004187 case 'U':
4188 force_share = true;
4189 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004190 case OPTION_PATTERN:
4191 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004192 unsigned long res;
4193
4194 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004195 error_report("Invalid pattern byte specified");
4196 return 1;
4197 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004198 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004199 break;
4200 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004201 case OPTION_FLUSH_INTERVAL:
4202 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004203 unsigned long res;
4204
4205 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004206 error_report("Invalid flush interval specified");
4207 return 1;
4208 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004209 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004210 break;
4211 }
4212 case OPTION_NO_DRAIN:
4213 drain_on_flush = false;
4214 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004215 case OPTION_IMAGE_OPTS:
4216 image_opts = true;
4217 break;
4218 }
4219 }
4220
4221 if (optind != argc - 1) {
4222 error_exit("Expecting one image file name");
4223 }
4224 filename = argv[argc - 1];
4225
Kevin Wolf55d539c2016-06-03 13:59:41 +02004226 if (!is_write && flush_interval) {
4227 error_report("--flush-interval is only available in write tests");
4228 ret = -1;
4229 goto out;
4230 }
4231 if (flush_interval && flush_interval < depth) {
4232 error_report("Flush interval can't be smaller than depth");
4233 ret = -1;
4234 goto out;
4235 }
4236
Fam Zheng335e9932017-05-03 00:35:39 +08004237 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4238 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004239 if (!blk) {
4240 ret = -1;
4241 goto out;
4242 }
4243
4244 image_size = blk_getlength(blk);
4245 if (image_size < 0) {
4246 ret = image_size;
4247 goto out;
4248 }
4249
4250 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004251 .blk = blk,
4252 .image_size = image_size,
4253 .bufsize = bufsize,
4254 .step = step ?: bufsize,
4255 .nrreq = depth,
4256 .n = count,
4257 .offset = offset,
4258 .write = is_write,
4259 .flush_interval = flush_interval,
4260 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004261 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004262 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004263 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004264 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004265 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004266 if (flush_interval) {
4267 printf("Sending flush every %d requests\n", flush_interval);
4268 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004269
Fam Zheng79d46582018-01-16 14:08:58 +08004270 buf_size = data.nrreq * data.bufsize;
4271 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004272 memset(data.buf, pattern, data.nrreq * data.bufsize);
4273
Fam Zheng79d46582018-01-16 14:08:58 +08004274 blk_register_buf(blk, data.buf, buf_size);
4275
Kevin Wolfb6133b82014-08-05 14:17:13 +02004276 data.qiov = g_new(QEMUIOVector, data.nrreq);
4277 for (i = 0; i < data.nrreq; i++) {
4278 qemu_iovec_init(&data.qiov[i], 1);
4279 qemu_iovec_add(&data.qiov[i],
4280 data.buf + i * data.bufsize, data.bufsize);
4281 }
4282
4283 gettimeofday(&t1, NULL);
4284 bench_cb(&data, 0);
4285
4286 while (data.n > 0) {
4287 main_loop_wait(false);
4288 }
4289 gettimeofday(&t2, NULL);
4290
4291 printf("Run completed in %3.3f seconds.\n",
4292 (t2.tv_sec - t1.tv_sec)
4293 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4294
4295out:
Fam Zheng79d46582018-01-16 14:08:58 +08004296 if (data.buf) {
4297 blk_unregister_buf(blk, data.buf);
4298 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004299 qemu_vfree(data.buf);
4300 blk_unref(blk);
4301
4302 if (ret) {
4303 return 1;
4304 }
4305 return 0;
4306}
4307
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004308#define C_BS 01
4309#define C_COUNT 02
4310#define C_IF 04
4311#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004312#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004313
4314struct DdInfo {
4315 unsigned int flags;
4316 int64_t count;
4317};
4318
4319struct DdIo {
4320 int bsz; /* Block size */
4321 char *filename;
4322 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004323 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004324};
4325
4326struct DdOpts {
4327 const char *name;
4328 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4329 unsigned int flag;
4330};
4331
4332static int img_dd_bs(const char *arg,
4333 struct DdIo *in, struct DdIo *out,
4334 struct DdInfo *dd)
4335{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004336 int64_t res;
4337
Markus Armbruster606caa02017-02-21 21:14:04 +01004338 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004339
Markus Armbruster606caa02017-02-21 21:14:04 +01004340 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004341 error_report("invalid number: '%s'", arg);
4342 return 1;
4343 }
4344 in->bsz = out->bsz = res;
4345
4346 return 0;
4347}
4348
4349static int img_dd_count(const char *arg,
4350 struct DdIo *in, struct DdIo *out,
4351 struct DdInfo *dd)
4352{
Markus Armbruster606caa02017-02-21 21:14:04 +01004353 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004354
Markus Armbruster606caa02017-02-21 21:14:04 +01004355 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004356 error_report("invalid number: '%s'", arg);
4357 return 1;
4358 }
4359
4360 return 0;
4361}
4362
4363static int img_dd_if(const char *arg,
4364 struct DdIo *in, struct DdIo *out,
4365 struct DdInfo *dd)
4366{
4367 in->filename = g_strdup(arg);
4368
4369 return 0;
4370}
4371
4372static int img_dd_of(const char *arg,
4373 struct DdIo *in, struct DdIo *out,
4374 struct DdInfo *dd)
4375{
4376 out->filename = g_strdup(arg);
4377
4378 return 0;
4379}
4380
Reda Sallahif7c15532016-08-10 16:16:09 +02004381static int img_dd_skip(const char *arg,
4382 struct DdIo *in, struct DdIo *out,
4383 struct DdInfo *dd)
4384{
Markus Armbruster606caa02017-02-21 21:14:04 +01004385 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004386
Markus Armbruster606caa02017-02-21 21:14:04 +01004387 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004388 error_report("invalid number: '%s'", arg);
4389 return 1;
4390 }
4391
4392 return 0;
4393}
4394
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004395static int img_dd(int argc, char **argv)
4396{
4397 int ret = 0;
4398 char *arg = NULL;
4399 char *tmp;
4400 BlockDriver *drv = NULL, *proto_drv = NULL;
4401 BlockBackend *blk1 = NULL, *blk2 = NULL;
4402 QemuOpts *opts = NULL;
4403 QemuOptsList *create_opts = NULL;
4404 Error *local_err = NULL;
4405 bool image_opts = false;
4406 int c, i;
4407 const char *out_fmt = "raw";
4408 const char *fmt = NULL;
4409 int64_t size = 0;
4410 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004411 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004412 struct DdInfo dd = {
4413 .flags = 0,
4414 .count = 0,
4415 };
4416 struct DdIo in = {
4417 .bsz = 512, /* Block size is by default 512 bytes */
4418 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004419 .buf = NULL,
4420 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004421 };
4422 struct DdIo out = {
4423 .bsz = 512,
4424 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004425 .buf = NULL,
4426 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004427 };
4428
4429 const struct DdOpts options[] = {
4430 { "bs", img_dd_bs, C_BS },
4431 { "count", img_dd_count, C_COUNT },
4432 { "if", img_dd_if, C_IF },
4433 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004434 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004435 { NULL, NULL, 0 }
4436 };
4437 const struct option long_options[] = {
4438 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004439 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004440 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004441 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004442 { 0, 0, 0, 0 }
4443 };
4444
Fam Zheng335e9932017-05-03 00:35:39 +08004445 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004446 if (c == EOF) {
4447 break;
4448 }
4449 switch (c) {
4450 case 'O':
4451 out_fmt = optarg;
4452 break;
4453 case 'f':
4454 fmt = optarg;
4455 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004456 case ':':
4457 missing_argument(argv[optind - 1]);
4458 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004459 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004460 unrecognized_option(argv[optind - 1]);
4461 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004462 case 'h':
4463 help();
4464 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004465 case 'U':
4466 force_share = true;
4467 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004468 case OPTION_OBJECT:
4469 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004470 ret = -1;
4471 goto out;
4472 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004473 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004474 case OPTION_IMAGE_OPTS:
4475 image_opts = true;
4476 break;
4477 }
4478 }
4479
4480 for (i = optind; i < argc; i++) {
4481 int j;
4482 arg = g_strdup(argv[i]);
4483
4484 tmp = strchr(arg, '=');
4485 if (tmp == NULL) {
4486 error_report("unrecognized operand %s", arg);
4487 ret = -1;
4488 goto out;
4489 }
4490
4491 *tmp++ = '\0';
4492
4493 for (j = 0; options[j].name != NULL; j++) {
4494 if (!strcmp(arg, options[j].name)) {
4495 break;
4496 }
4497 }
4498 if (options[j].name == NULL) {
4499 error_report("unrecognized operand %s", arg);
4500 ret = -1;
4501 goto out;
4502 }
4503
4504 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4505 ret = -1;
4506 goto out;
4507 }
4508 dd.flags |= options[j].flag;
4509 g_free(arg);
4510 arg = NULL;
4511 }
4512
4513 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4514 error_report("Must specify both input and output files");
4515 ret = -1;
4516 goto out;
4517 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004518
4519 if (qemu_opts_foreach(&qemu_object_opts,
4520 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004521 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004522 ret = -1;
4523 goto out;
4524 }
4525
Fam Zheng335e9932017-05-03 00:35:39 +08004526 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4527 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004528
4529 if (!blk1) {
4530 ret = -1;
4531 goto out;
4532 }
4533
4534 drv = bdrv_find_format(out_fmt);
4535 if (!drv) {
4536 error_report("Unknown file format");
4537 ret = -1;
4538 goto out;
4539 }
4540 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4541
4542 if (!proto_drv) {
4543 error_report_err(local_err);
4544 ret = -1;
4545 goto out;
4546 }
4547 if (!drv->create_opts) {
4548 error_report("Format driver '%s' does not support image creation",
4549 drv->format_name);
4550 ret = -1;
4551 goto out;
4552 }
4553 if (!proto_drv->create_opts) {
4554 error_report("Protocol driver '%s' does not support image creation",
4555 proto_drv->format_name);
4556 ret = -1;
4557 goto out;
4558 }
4559 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4560 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4561
4562 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4563
4564 size = blk_getlength(blk1);
4565 if (size < 0) {
4566 error_report("Failed to get size for '%s'", in.filename);
4567 ret = -1;
4568 goto out;
4569 }
4570
4571 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4572 dd.count * in.bsz < size) {
4573 size = dd.count * in.bsz;
4574 }
4575
Reda Sallahif7c15532016-08-10 16:16:09 +02004576 /* Overflow means the specified offset is beyond input image's size */
4577 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4578 size < in.bsz * in.offset)) {
4579 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4580 } else {
4581 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4582 size - in.bsz * in.offset, &error_abort);
4583 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004584
4585 ret = bdrv_create(drv, out.filename, opts, &local_err);
4586 if (ret < 0) {
4587 error_reportf_err(local_err,
4588 "%s: error while creating output image: ",
4589 out.filename);
4590 ret = -1;
4591 goto out;
4592 }
4593
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004594 /* TODO, we can't honour --image-opts for the target,
4595 * since it needs to be given in a format compatible
4596 * with the bdrv_create() call above which does not
4597 * support image-opts style.
4598 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004599 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004600 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004601
4602 if (!blk2) {
4603 ret = -1;
4604 goto out;
4605 }
4606
Reda Sallahif7c15532016-08-10 16:16:09 +02004607 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4608 size < in.offset * in.bsz)) {
4609 /* We give a warning if the skip option is bigger than the input
4610 * size and create an empty output disk image (i.e. like dd(1)).
4611 */
4612 error_report("%s: cannot skip to specified offset", in.filename);
4613 in_pos = size;
4614 } else {
4615 in_pos = in.offset * in.bsz;
4616 }
4617
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004618 in.buf = g_new(uint8_t, in.bsz);
4619
Reda Sallahif7c15532016-08-10 16:16:09 +02004620 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004621 int in_ret, out_ret;
4622
4623 if (in_pos + in.bsz > size) {
4624 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4625 } else {
4626 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4627 }
4628 if (in_ret < 0) {
4629 error_report("error while reading from input image file: %s",
4630 strerror(-in_ret));
4631 ret = -1;
4632 goto out;
4633 }
4634 in_pos += in_ret;
4635
4636 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4637
4638 if (out_ret < 0) {
4639 error_report("error while writing to output image file: %s",
4640 strerror(-out_ret));
4641 ret = -1;
4642 goto out;
4643 }
4644 out_pos += out_ret;
4645 }
4646
4647out:
4648 g_free(arg);
4649 qemu_opts_del(opts);
4650 qemu_opts_free(create_opts);
4651 blk_unref(blk1);
4652 blk_unref(blk2);
4653 g_free(in.filename);
4654 g_free(out.filename);
4655 g_free(in.buf);
4656 g_free(out.buf);
4657
4658 if (ret) {
4659 return 1;
4660 }
4661 return 0;
4662}
4663
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004664static void dump_json_block_measure_info(BlockMeasureInfo *info)
4665{
4666 QString *str;
4667 QObject *obj;
4668 Visitor *v = qobject_output_visitor_new(&obj);
4669
4670 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4671 visit_complete(v, &obj);
4672 str = qobject_to_json_pretty(obj);
4673 assert(str != NULL);
4674 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004675 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004676 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004677 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004678}
4679
4680static int img_measure(int argc, char **argv)
4681{
4682 static const struct option long_options[] = {
4683 {"help", no_argument, 0, 'h'},
4684 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4685 {"object", required_argument, 0, OPTION_OBJECT},
4686 {"output", required_argument, 0, OPTION_OUTPUT},
4687 {"size", required_argument, 0, OPTION_SIZE},
4688 {"force-share", no_argument, 0, 'U'},
4689 {0, 0, 0, 0}
4690 };
4691 OutputFormat output_format = OFORMAT_HUMAN;
4692 BlockBackend *in_blk = NULL;
4693 BlockDriver *drv;
4694 const char *filename = NULL;
4695 const char *fmt = NULL;
4696 const char *out_fmt = "raw";
4697 char *options = NULL;
4698 char *snapshot_name = NULL;
4699 bool force_share = false;
4700 QemuOpts *opts = NULL;
4701 QemuOpts *object_opts = NULL;
4702 QemuOpts *sn_opts = NULL;
4703 QemuOptsList *create_opts = NULL;
4704 bool image_opts = false;
4705 uint64_t img_size = UINT64_MAX;
4706 BlockMeasureInfo *info = NULL;
4707 Error *local_err = NULL;
4708 int ret = 1;
4709 int c;
4710
4711 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4712 long_options, NULL)) != -1) {
4713 switch (c) {
4714 case '?':
4715 case 'h':
4716 help();
4717 break;
4718 case 'f':
4719 fmt = optarg;
4720 break;
4721 case 'O':
4722 out_fmt = optarg;
4723 break;
4724 case 'o':
4725 if (!is_valid_option_list(optarg)) {
4726 error_report("Invalid option list: %s", optarg);
4727 goto out;
4728 }
4729 if (!options) {
4730 options = g_strdup(optarg);
4731 } else {
4732 char *old_options = options;
4733 options = g_strdup_printf("%s,%s", options, optarg);
4734 g_free(old_options);
4735 }
4736 break;
4737 case 'l':
4738 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4739 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4740 optarg, false);
4741 if (!sn_opts) {
4742 error_report("Failed in parsing snapshot param '%s'",
4743 optarg);
4744 goto out;
4745 }
4746 } else {
4747 snapshot_name = optarg;
4748 }
4749 break;
4750 case 'U':
4751 force_share = true;
4752 break;
4753 case OPTION_OBJECT:
4754 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4755 optarg, true);
4756 if (!object_opts) {
4757 goto out;
4758 }
4759 break;
4760 case OPTION_IMAGE_OPTS:
4761 image_opts = true;
4762 break;
4763 case OPTION_OUTPUT:
4764 if (!strcmp(optarg, "json")) {
4765 output_format = OFORMAT_JSON;
4766 } else if (!strcmp(optarg, "human")) {
4767 output_format = OFORMAT_HUMAN;
4768 } else {
4769 error_report("--output must be used with human or json "
4770 "as argument.");
4771 goto out;
4772 }
4773 break;
4774 case OPTION_SIZE:
4775 {
4776 int64_t sval;
4777
4778 sval = cvtnum(optarg);
4779 if (sval < 0) {
4780 if (sval == -ERANGE) {
4781 error_report("Image size must be less than 8 EiB!");
4782 } else {
4783 error_report("Invalid image size specified! You may use "
4784 "k, M, G, T, P or E suffixes for ");
4785 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4786 "petabytes and exabytes.");
4787 }
4788 goto out;
4789 }
4790 img_size = (uint64_t)sval;
4791 }
4792 break;
4793 }
4794 }
4795
4796 if (qemu_opts_foreach(&qemu_object_opts,
4797 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004798 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004799 goto out;
4800 }
4801
4802 if (argc - optind > 1) {
4803 error_report("At most one filename argument is allowed.");
4804 goto out;
4805 } else if (argc - optind == 1) {
4806 filename = argv[optind];
4807 }
4808
4809 if (!filename &&
4810 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4811 error_report("--object, --image-opts, -f, and -l "
4812 "require a filename argument.");
4813 goto out;
4814 }
4815 if (filename && img_size != UINT64_MAX) {
4816 error_report("--size N cannot be used together with a filename.");
4817 goto out;
4818 }
4819 if (!filename && img_size == UINT64_MAX) {
4820 error_report("Either --size N or one filename must be specified.");
4821 goto out;
4822 }
4823
4824 if (filename) {
4825 in_blk = img_open(image_opts, filename, fmt, 0,
4826 false, false, force_share);
4827 if (!in_blk) {
4828 goto out;
4829 }
4830
4831 if (sn_opts) {
4832 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4833 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4834 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4835 &local_err);
4836 } else if (snapshot_name != NULL) {
4837 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4838 snapshot_name, &local_err);
4839 }
4840 if (local_err) {
4841 error_reportf_err(local_err, "Failed to load snapshot: ");
4842 goto out;
4843 }
4844 }
4845
4846 drv = bdrv_find_format(out_fmt);
4847 if (!drv) {
4848 error_report("Unknown file format '%s'", out_fmt);
4849 goto out;
4850 }
4851 if (!drv->create_opts) {
4852 error_report("Format driver '%s' does not support image creation",
4853 drv->format_name);
4854 goto out;
4855 }
4856
4857 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4858 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4859 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4860 if (options) {
4861 qemu_opts_do_parse(opts, options, NULL, &local_err);
4862 if (local_err) {
4863 error_report_err(local_err);
4864 error_report("Invalid options for file format '%s'", out_fmt);
4865 goto out;
4866 }
4867 }
4868 if (img_size != UINT64_MAX) {
4869 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4870 }
4871
4872 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4873 if (local_err) {
4874 error_report_err(local_err);
4875 goto out;
4876 }
4877
4878 if (output_format == OFORMAT_HUMAN) {
4879 printf("required size: %" PRIu64 "\n", info->required);
4880 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4881 } else {
4882 dump_json_block_measure_info(info);
4883 }
4884
4885 ret = 0;
4886
4887out:
4888 qapi_free_BlockMeasureInfo(info);
4889 qemu_opts_del(object_opts);
4890 qemu_opts_del(opts);
4891 qemu_opts_del(sn_opts);
4892 qemu_opts_free(create_opts);
4893 g_free(options);
4894 blk_unref(in_blk);
4895 return ret;
4896}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004897
Anthony Liguoric227f092009-10-01 16:12:16 -05004898static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004899#define DEF(option, callback, arg_string) \
4900 { option, callback },
4901#include "qemu-img-cmds.h"
4902#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004903 { NULL, NULL, },
4904};
4905
bellardea2384d2004-08-01 21:59:26 +00004906int main(int argc, char **argv)
4907{
Anthony Liguoric227f092009-10-01 16:12:16 -05004908 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004909 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004910 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004911 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004912 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004913 static const struct option long_options[] = {
4914 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004915 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004916 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004917 {0, 0, 0, 0}
4918 };
bellardea2384d2004-08-01 21:59:26 +00004919
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004920#ifdef CONFIG_POSIX
4921 signal(SIGPIPE, SIG_IGN);
4922#endif
4923
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004924 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004925 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004926 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004927
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004928 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004929 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004930 exit(EXIT_FAILURE);
4931 }
4932
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004933 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004934
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004935 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004936 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004937 if (argc < 2) {
4938 error_exit("Not enough arguments");
4939 }
Stuart Brady153859b2009-06-07 00:42:17 +01004940
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004941 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004942 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004943 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004944
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004945 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004946 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004947 case ':':
4948 missing_argument(argv[optind - 1]);
4949 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004950 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004951 unrecognized_option(argv[optind - 1]);
4952 return 0;
4953 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004954 help();
4955 return 0;
4956 case 'V':
4957 printf(QEMU_IMG_VERSION);
4958 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004959 case 'T':
4960 g_free(trace_file);
4961 trace_file = trace_opt_parse(optarg);
4962 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004963 }
bellardea2384d2004-08-01 21:59:26 +00004964 }
Stuart Brady153859b2009-06-07 00:42:17 +01004965
Denis V. Lunev10985132016-06-17 17:44:13 +03004966 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004967
Denis V. Lunev10985132016-06-17 17:44:13 +03004968 /* reset getopt_long scanning */
4969 argc -= optind;
4970 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004971 return 0;
4972 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004973 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00004974 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03004975
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004976 if (!trace_init_backends()) {
4977 exit(1);
4978 }
4979 trace_init_file(trace_file);
4980 qemu_set_log(LOG_TRACE);
4981
Denis V. Lunev10985132016-06-17 17:44:13 +03004982 /* find the command */
4983 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4984 if (!strcmp(cmdname, cmd->name)) {
4985 return cmd->handler(argc, argv);
4986 }
4987 }
Jeff Cody7db16892014-04-25 17:02:32 -04004988
Stuart Brady153859b2009-06-07 00:42:17 +01004989 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004990 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004991}