blob: e6ad5978e0ce186e709365aeb512ae4383340f64 [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 Reitzf4619af2019-04-13 17:20:37 +0200270 if (filename) {
271 printf("Supported options:\n");
272 } else {
273 printf("Supported %s options:\n", fmt);
274 }
Max Reitz63898712018-10-19 18:49:25 +0200275 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800276 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200277
278 if (!filename) {
279 printf("\n"
280 "The protocol level may support further options.\n"
281 "Specify the target filename to include those options.\n");
282 }
283
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100284 return 0;
285}
286
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000287
Max Reitzefaa7c42016-03-16 19:54:38 +0100288static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100289 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800290 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000291{
292 QDict *options;
293 Error *local_err = NULL;
294 BlockBackend *blk;
295 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800296 if (force_share) {
297 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200298 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800299 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200300 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800301 return NULL;
302 }
Max Reitz4615f872018-05-02 22:20:50 +0200303 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800304 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100305 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000306 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100307 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000308 return NULL;
309 }
Kevin Wolfce099542016-03-15 13:01:04 +0100310 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000311
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000312 return blk;
313}
314
Max Reitzefaa7c42016-03-16 19:54:38 +0100315static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100316 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000317 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800318 bool writethrough, bool quiet,
319 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000320{
321 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200322 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100323
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100324 if (!options) {
325 options = qdict_new();
326 }
bellard75c23802004-08-27 21:28:58 +0000327 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500328 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000329 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100330
Fam Zheng335e9932017-05-03 00:35:39 +0800331 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500332 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800333 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100334 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500335 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100336 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000337 return NULL;
bellard75c23802004-08-27 21:28:58 +0000338 }
Kevin Wolfce099542016-03-15 13:01:04 +0100339 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100340
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200341 return blk;
bellard75c23802004-08-27 21:28:58 +0000342}
343
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000344
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100345static int img_add_key_secrets(void *opaque,
346 const char *name, const char *value,
347 Error **errp)
348{
349 QDict *options = opaque;
350
351 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600352 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100353 }
354
355 return 0;
356}
357
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100358
Max Reitzefaa7c42016-03-16 19:54:38 +0100359static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000360 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100361 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800362 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000363{
364 BlockBackend *blk;
365 if (image_opts) {
366 QemuOpts *opts;
367 if (fmt) {
368 error_report("--image-opts and --format are mutually exclusive");
369 return NULL;
370 }
371 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
372 filename, true);
373 if (!opts) {
374 return NULL;
375 }
Fam Zheng335e9932017-05-03 00:35:39 +0800376 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
377 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000378 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100379 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800380 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000381 }
382 return blk;
383}
384
385
Chunyan Liu83d05212014-06-05 17:20:51 +0800386static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100387 const char *base_filename,
388 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200389{
Markus Armbruster6750e792015-02-12 17:43:08 +0100390 Error *err = NULL;
391
Kevin Wolfefa84d42009-05-18 16:42:12 +0200392 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100393 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100394 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100395 error_report("Backing file not supported for file format '%s'",
396 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100397 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900398 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200399 }
400 }
401 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100402 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100403 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100404 error_report("Backing file format not supported for file "
405 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100406 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900407 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200408 }
409 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900410 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200411}
412
Markus Armbruster606caa02017-02-21 21:14:04 +0100413static int64_t cvtnum(const char *s)
414{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100415 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100416 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100417
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100418 err = qemu_strtosz(s, NULL, &value);
419 if (err < 0) {
420 return err;
421 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100422 if (value > INT64_MAX) {
423 return -ERANGE;
424 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100425 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100426}
427
bellardea2384d2004-08-01 21:59:26 +0000428static int img_create(int argc, char **argv)
429{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200430 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100431 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000432 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000433 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000434 const char *filename;
435 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200436 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200437 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100438 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400439 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000440
bellardea2384d2004-08-01 21:59:26 +0000441 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000442 static const struct option long_options[] = {
443 {"help", no_argument, 0, 'h'},
444 {"object", required_argument, 0, OPTION_OBJECT},
445 {0, 0, 0, 0}
446 };
John Snow6e6e55f2017-07-17 20:34:22 -0400447 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000448 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100449 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000450 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100451 }
bellardea2384d2004-08-01 21:59:26 +0000452 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800453 case ':':
454 missing_argument(argv[optind - 1]);
455 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100456 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800457 unrecognized_option(argv[optind - 1]);
458 break;
bellardea2384d2004-08-01 21:59:26 +0000459 case 'h':
460 help();
461 break;
aliguori9230eaf2009-03-28 17:55:19 +0000462 case 'F':
463 base_fmt = optarg;
464 break;
bellardea2384d2004-08-01 21:59:26 +0000465 case 'b':
466 base_filename = optarg;
467 break;
468 case 'f':
469 fmt = optarg;
470 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200471 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100472 if (!is_valid_option_list(optarg)) {
473 error_report("Invalid option list: %s", optarg);
474 goto fail;
475 }
476 if (!options) {
477 options = g_strdup(optarg);
478 } else {
479 char *old_options = options;
480 options = g_strdup_printf("%s,%s", options, optarg);
481 g_free(old_options);
482 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200483 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100484 case 'q':
485 quiet = true;
486 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400487 case 'u':
488 flags |= BDRV_O_NO_BACKING;
489 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000490 case OPTION_OBJECT: {
491 QemuOpts *opts;
492 opts = qemu_opts_parse_noisily(&qemu_object_opts,
493 optarg, true);
494 if (!opts) {
495 goto fail;
496 }
497 } break;
bellardea2384d2004-08-01 21:59:26 +0000498 }
499 }
aliguori9230eaf2009-03-28 17:55:19 +0000500
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900501 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100502 filename = (optind < argc) ? argv[optind] : NULL;
503 if (options && has_help_option(options)) {
504 g_free(options);
505 return print_block_option_help(filename, fmt);
506 }
507
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100508 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800509 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100510 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100511 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900512
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000513 if (qemu_opts_foreach(&qemu_object_opts,
514 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000515 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000516 goto fail;
517 }
518
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100519 /* Get image size, if specified */
520 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100521 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100522
523 sval = cvtnum(argv[optind++]);
524 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800525 if (sval == -ERANGE) {
526 error_report("Image size must be less than 8 EiB!");
527 } else {
528 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200529 "G, T, P or E suffixes for ");
530 error_report("kilobytes, megabytes, gigabytes, terabytes, "
531 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800532 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100533 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100534 }
535 img_size = (uint64_t)sval;
536 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200537 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800538 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200539 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100540
Luiz Capitulino9b375252012-11-30 10:52:05 -0200541 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400542 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100543 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100544 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100545 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900546 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200547
Kevin Wolf77386bf2014-02-21 16:24:04 +0100548 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000549 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100550
551fail:
552 g_free(options);
553 return 1;
bellardea2384d2004-08-01 21:59:26 +0000554}
555
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100556static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500557{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500558 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500559 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100560 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600561
562 visit_type_ImageCheck(v, NULL, &check, &error_abort);
563 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500564 str = qobject_to_json_pretty(obj);
565 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100566 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200567 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600568 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200569 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500570}
571
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100572static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500573{
574 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100575 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500576 } else {
577 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100578 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
579 "Data may be corrupted, or further writes to the image "
580 "may corrupt it.\n",
581 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500582 }
583
584 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100585 qprintf(quiet,
586 "\n%" PRId64 " leaked clusters were found on the image.\n"
587 "This means waste of disk space, but no harm to data.\n",
588 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500589 }
590
591 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100592 qprintf(quiet,
593 "\n%" PRId64
594 " internal errors have occurred during the check.\n",
595 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500596 }
597 }
598
599 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100600 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
601 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
602 check->allocated_clusters, check->total_clusters,
603 check->allocated_clusters * 100.0 / check->total_clusters,
604 check->fragmented_clusters * 100.0 / check->allocated_clusters,
605 check->compressed_clusters * 100.0 /
606 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500607 }
608
609 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100610 qprintf(quiet,
611 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500612 }
613}
614
615static int collect_image_check(BlockDriverState *bs,
616 ImageCheck *check,
617 const char *filename,
618 const char *fmt,
619 int fix)
620{
621 int ret;
622 BdrvCheckResult result;
623
624 ret = bdrv_check(bs, &result, fix);
625 if (ret < 0) {
626 return ret;
627 }
628
629 check->filename = g_strdup(filename);
630 check->format = g_strdup(bdrv_get_format_name(bs));
631 check->check_errors = result.check_errors;
632 check->corruptions = result.corruptions;
633 check->has_corruptions = result.corruptions != 0;
634 check->leaks = result.leaks;
635 check->has_leaks = result.leaks != 0;
636 check->corruptions_fixed = result.corruptions_fixed;
637 check->has_corruptions_fixed = result.corruptions != 0;
638 check->leaks_fixed = result.leaks_fixed;
639 check->has_leaks_fixed = result.leaks != 0;
640 check->image_end_offset = result.image_end_offset;
641 check->has_image_end_offset = result.image_end_offset != 0;
642 check->total_clusters = result.bfi.total_clusters;
643 check->has_total_clusters = result.bfi.total_clusters != 0;
644 check->allocated_clusters = result.bfi.allocated_clusters;
645 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
646 check->fragmented_clusters = result.bfi.fragmented_clusters;
647 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100648 check->compressed_clusters = result.bfi.compressed_clusters;
649 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500650
651 return 0;
652}
653
Kevin Wolfe076f332010-06-29 11:43:13 +0200654/*
655 * Checks an image for consistency. Exit codes:
656 *
Max Reitzd6635c42014-06-02 22:15:21 +0200657 * 0 - Check completed, image is good
658 * 1 - Check not completed because of internal errors
659 * 2 - Check completed, image is corrupted
660 * 3 - Check completed, image has leaked clusters, but is good otherwise
661 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200662 */
aliguori15859692009-04-21 23:11:53 +0000663static int img_check(int argc, char **argv)
664{
665 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500666 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200667 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200668 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000669 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200670 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100671 int flags = BDRV_O_CHECK;
672 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200673 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100674 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000675 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800676 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000677
678 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200680 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100681
aliguori15859692009-04-21 23:11:53 +0000682 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 int option_index = 0;
684 static const struct option long_options[] = {
685 {"help", no_argument, 0, 'h'},
686 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530687 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500688 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000689 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000690 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800691 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500692 {0, 0, 0, 0}
693 };
Fam Zheng335e9932017-05-03 00:35:39 +0800694 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500695 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100696 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000697 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100698 }
aliguori15859692009-04-21 23:11:53 +0000699 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800700 case ':':
701 missing_argument(argv[optind - 1]);
702 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100703 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800704 unrecognized_option(argv[optind - 1]);
705 break;
aliguori15859692009-04-21 23:11:53 +0000706 case 'h':
707 help();
708 break;
709 case 'f':
710 fmt = optarg;
711 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200712 case 'r':
713 flags |= BDRV_O_RDWR;
714
715 if (!strcmp(optarg, "leaks")) {
716 fix = BDRV_FIX_LEAKS;
717 } else if (!strcmp(optarg, "all")) {
718 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
719 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800720 error_exit("Unknown option value for -r "
721 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200722 }
723 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500724 case OPTION_OUTPUT:
725 output = optarg;
726 break;
Max Reitz40055952014-07-22 22:58:42 +0200727 case 'T':
728 cache = optarg;
729 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100730 case 'q':
731 quiet = true;
732 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800733 case 'U':
734 force_share = true;
735 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000736 case OPTION_OBJECT: {
737 QemuOpts *opts;
738 opts = qemu_opts_parse_noisily(&qemu_object_opts,
739 optarg, true);
740 if (!opts) {
741 return 1;
742 }
743 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000744 case OPTION_IMAGE_OPTS:
745 image_opts = true;
746 break;
aliguori15859692009-04-21 23:11:53 +0000747 }
748 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200749 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800750 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100751 }
aliguori15859692009-04-21 23:11:53 +0000752 filename = argv[optind++];
753
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500754 if (output && !strcmp(output, "json")) {
755 output_format = OFORMAT_JSON;
756 } else if (output && !strcmp(output, "human")) {
757 output_format = OFORMAT_HUMAN;
758 } else if (output) {
759 error_report("--output must be used with human or json as argument.");
760 return 1;
761 }
762
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000763 if (qemu_opts_foreach(&qemu_object_opts,
764 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000765 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000766 return 1;
767 }
768
Kevin Wolfce099542016-03-15 13:01:04 +0100769 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200770 if (ret < 0) {
771 error_report("Invalid source cache option: %s", cache);
772 return 1;
773 }
774
Fam Zheng335e9932017-05-03 00:35:39 +0800775 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
776 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200777 if (!blk) {
778 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900779 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200780 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500781
782 check = g_new0(ImageCheck, 1);
783 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200784
785 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200786 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200787 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500788 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200789 }
790
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500791 if (check->corruptions_fixed || check->leaks_fixed) {
792 int corruptions_fixed, leaks_fixed;
793
794 leaks_fixed = check->leaks_fixed;
795 corruptions_fixed = check->corruptions_fixed;
796
797 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100798 qprintf(quiet,
799 "The following inconsistencies were found and repaired:\n\n"
800 " %" PRId64 " leaked clusters\n"
801 " %" PRId64 " corruptions\n\n"
802 "Double checking the fixed image now...\n",
803 check->leaks_fixed,
804 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500805 }
806
807 ret = collect_image_check(bs, check, filename, fmt, 0);
808
809 check->leaks_fixed = leaks_fixed;
810 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200811 }
812
Max Reitz832390a2014-10-23 15:29:12 +0200813 if (!ret) {
814 switch (output_format) {
815 case OFORMAT_HUMAN:
816 dump_human_image_check(check, quiet);
817 break;
818 case OFORMAT_JSON:
819 dump_json_image_check(check, quiet);
820 break;
821 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500822 }
823
824 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200825 if (ret) {
826 error_report("Check failed: %s", strerror(-ret));
827 } else {
828 error_report("Check failed");
829 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500830 ret = 1;
831 goto fail;
832 }
833
834 if (check->corruptions) {
835 ret = 2;
836 } else if (check->leaks) {
837 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200838 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500839 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000840 }
841
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500842fail:
843 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200844 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500845 return ret;
aliguori15859692009-04-21 23:11:53 +0000846}
847
Max Reitzd4a32382014-10-24 15:57:37 +0200848typedef struct CommonBlockJobCBInfo {
849 BlockDriverState *bs;
850 Error **errp;
851} CommonBlockJobCBInfo;
852
853static void common_block_job_cb(void *opaque, int ret)
854{
855 CommonBlockJobCBInfo *cbi = opaque;
856
857 if (ret < 0) {
858 error_setg_errno(cbi->errp, -ret, "Block job failed");
859 }
Max Reitzd4a32382014-10-24 15:57:37 +0200860}
861
862static void run_block_job(BlockJob *job, Error **errp)
863{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200864 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800865 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200866
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200867 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200868 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200869 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200870 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200871 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200872 if (job->job.progress_total) {
873 progress = (float)job->job.progress_current /
874 job->job.progress_total * 100.f;
875 }
876 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200877 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200878
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200879 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200880 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800881 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200882 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800883 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200884 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200885 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200886
sochin.jiang4172a002017-06-15 14:47:33 +0800887 /* publish completion progress only when success */
888 if (!ret) {
889 qemu_progress_print(100.f, 0);
890 }
Max Reitzd4a32382014-10-24 15:57:37 +0200891}
892
bellardea2384d2004-08-01 21:59:26 +0000893static int img_commit(int argc, char **argv)
894{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400895 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200896 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200897 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200898 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100899 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200900 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100901 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200902 Error *local_err = NULL;
903 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000904 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200905 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000906
907 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400908 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200909 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000910 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000911 static const struct option long_options[] = {
912 {"help", no_argument, 0, 'h'},
913 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000914 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000915 {0, 0, 0, 0}
916 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800917 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000918 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100919 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000920 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100921 }
bellardea2384d2004-08-01 21:59:26 +0000922 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800923 case ':':
924 missing_argument(argv[optind - 1]);
925 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100926 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800927 unrecognized_option(argv[optind - 1]);
928 break;
bellardea2384d2004-08-01 21:59:26 +0000929 case 'h':
930 help();
931 break;
932 case 'f':
933 fmt = optarg;
934 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400935 case 't':
936 cache = optarg;
937 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200938 case 'b':
939 base = optarg;
940 /* -b implies -d */
941 drop = true;
942 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200943 case 'd':
944 drop = true;
945 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200946 case 'p':
947 progress = true;
948 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100949 case 'q':
950 quiet = true;
951 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000952 case OPTION_OBJECT: {
953 QemuOpts *opts;
954 opts = qemu_opts_parse_noisily(&qemu_object_opts,
955 optarg, true);
956 if (!opts) {
957 return 1;
958 }
959 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000960 case OPTION_IMAGE_OPTS:
961 image_opts = true;
962 break;
bellardea2384d2004-08-01 21:59:26 +0000963 }
964 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200965
966 /* Progress is not shown in Quiet mode */
967 if (quiet) {
968 progress = false;
969 }
970
Kevin Wolffc11eb22013-08-05 10:53:04 +0200971 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800972 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100973 }
bellardea2384d2004-08-01 21:59:26 +0000974 filename = argv[optind++];
975
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000976 if (qemu_opts_foreach(&qemu_object_opts,
977 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +0000978 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000979 return 1;
980 }
981
Max Reitz9a86fe42014-10-24 15:57:38 +0200982 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100983 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400984 if (ret < 0) {
985 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100986 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400987 }
988
Fam Zheng335e9932017-05-03 00:35:39 +0800989 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
990 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200991 if (!blk) {
992 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900993 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200994 bs = blk_bs(blk);
995
Max Reitz687fa1d2014-10-24 15:57:39 +0200996 qemu_progress_init(progress, 1.f);
997 qemu_progress_print(0.f, 100);
998
Max Reitz1b22bff2014-10-24 15:57:40 +0200999 if (base) {
1000 base_bs = bdrv_find_backing_image(bs, base);
1001 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001002 error_setg(&local_err,
1003 "Did not find '%s' in the backing chain of '%s'",
1004 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001005 goto done;
1006 }
1007 } else {
1008 /* This is different from QMP, which by default uses the deepest file in
1009 * the backing chain (i.e., the very base); however, the traditional
1010 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001011 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001012 if (!base_bs) {
1013 error_setg(&local_err, "Image does not have a backing file");
1014 goto done;
1015 }
bellardea2384d2004-08-01 21:59:26 +00001016 }
1017
Max Reitzd4a32382014-10-24 15:57:37 +02001018 cbi = (CommonBlockJobCBInfo){
1019 .errp = &local_err,
1020 .bs = bs,
1021 };
1022
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001023 aio_context = bdrv_get_aio_context(bs);
1024 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001025 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001026 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001027 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001028 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001029 if (local_err) {
1030 goto done;
1031 }
1032
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001033 /* When the block job completes, the BlockBackend reference will point to
1034 * the old backing file. In order to avoid that the top image is already
1035 * deleted, so we can still empty it afterwards, increment the reference
1036 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001037 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001038 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001039 }
1040
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001041 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001042 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001043 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001044 if (local_err) {
1045 goto unref_backing;
1046 }
1047
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001048 if (!drop && bs->drv->bdrv_make_empty) {
1049 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001050 if (ret) {
1051 error_setg_errno(&local_err, -ret, "Could not empty %s",
1052 filename);
1053 goto unref_backing;
1054 }
1055 }
1056
1057unref_backing:
1058 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001059 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001060 }
Max Reitzd4a32382014-10-24 15:57:37 +02001061
1062done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001063 qemu_progress_end();
1064
Markus Armbruster26f54e92014-10-07 13:59:04 +02001065 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001066
1067 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001068 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001069 return 1;
1070 }
Max Reitzd4a32382014-10-24 15:57:37 +02001071
1072 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001073 return 0;
1074}
1075
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001076/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001077 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1078 * of the first sector boundary within buf where the sector contains a
1079 * non-zero byte. This function is robust to a buffer that is not
1080 * sector-aligned.
1081 */
1082static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1083{
1084 int64_t i;
1085 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1086
1087 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1088 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1089 return i;
1090 }
1091 }
1092 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1093 return i;
1094 }
1095 return -1;
1096}
1097
1098/*
thsf58c7b32008-06-05 21:53:49 +00001099 * Returns true iff the first sector pointed to by 'buf' contains at least
1100 * a non-NUL byte.
1101 *
1102 * 'pnum' is set to the number of sectors (including and immediately following
1103 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001104 * The function will try to align the end offset to alignment boundaries so
1105 * that the request will at least end aligned and consequtive requests will
1106 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001107 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001108static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1109 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001110{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001111 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001112 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001113
1114 if (n <= 0) {
1115 *pnum = 0;
1116 return 0;
1117 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001118 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001119 for(i = 1; i < n; i++) {
1120 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001121 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001122 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001123 }
bellardea2384d2004-08-01 21:59:26 +00001124 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001125
1126 tail = (sector_num + i) & (alignment - 1);
1127 if (tail) {
1128 if (is_zero && i <= tail) {
1129 /* treat unallocated areas which only consist
1130 * of a small tail as allocated. */
1131 is_zero = false;
1132 }
1133 if (!is_zero) {
1134 /* align up end offset of allocated areas. */
1135 i += alignment - tail;
1136 i = MIN(i, n);
1137 } else {
1138 /* align down end offset of zero areas. */
1139 i -= tail;
1140 }
1141 }
bellardea2384d2004-08-01 21:59:26 +00001142 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001143 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001144}
1145
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001146/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001147 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1148 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1149 * breaking up write requests for only small sparse areas.
1150 */
1151static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001152 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001153{
1154 int ret;
1155 int num_checked, num_used;
1156
1157 if (n < min) {
1158 min = n;
1159 }
1160
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001161 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001162 if (!ret) {
1163 return ret;
1164 }
1165
1166 num_used = *pnum;
1167 buf += BDRV_SECTOR_SIZE * *pnum;
1168 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001169 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001170 num_checked = num_used;
1171
1172 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001173 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001174
1175 buf += BDRV_SECTOR_SIZE * *pnum;
1176 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001177 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001178 num_checked += *pnum;
1179 if (ret) {
1180 num_used = num_checked;
1181 } else if (*pnum >= min) {
1182 break;
1183 }
1184 }
1185
1186 *pnum = num_used;
1187 return 1;
1188}
1189
1190/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001191 * Compares two buffers sector by sector. Returns 0 if the first
1192 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001193 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001194 * pnum is set to the sector-aligned size of the buffer prefix that
1195 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001196 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001197static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1198 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001199{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001200 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001201 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001202
Eric Blakedc61cd32017-10-11 22:47:14 -05001203 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001204
Eric Blakedc61cd32017-10-11 22:47:14 -05001205 res = !!memcmp(buf1, buf2, i);
1206 while (i < bytes) {
1207 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001208
Eric Blakedc61cd32017-10-11 22:47:14 -05001209 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001210 break;
1211 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001212 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001213 }
1214
1215 *pnum = i;
1216 return res;
1217}
1218
Kevin Wolf80ee15a2009-09-15 12:30:43 +02001219#define IO_BUF_SIZE (2 * 1024 * 1024)
bellardea2384d2004-08-01 21:59:26 +00001220
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001221/*
1222 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1223 *
Eric Blake0608e402017-10-11 22:47:12 -05001224 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1225 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1226 * failure), and 4 on error (the exit status for read errors), after emitting
1227 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001228 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001229 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001230 * @param offset: Starting offset to check
1231 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001232 * @param filename: Name of disk file we are checking (logging purpose)
1233 * @param buffer: Allocated buffer for storing read data
1234 * @param quiet: Flag for quiet mode
1235 */
Eric Blakec41508e2017-10-11 22:47:13 -05001236static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1237 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001238 uint8_t *buffer, bool quiet)
1239{
Eric Blakedebb38a2017-10-11 22:47:11 -05001240 int ret = 0;
1241 int64_t idx;
1242
Eric Blakec41508e2017-10-11 22:47:13 -05001243 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001244 if (ret < 0) {
1245 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001246 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001247 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001248 }
Eric Blakec41508e2017-10-11 22:47:13 -05001249 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001250 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001251 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001252 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001253 return 1;
1254 }
1255
1256 return 0;
1257}
1258
1259/*
1260 * Compares two images. Exit codes:
1261 *
1262 * 0 - Images are identical
1263 * 1 - Images differ
1264 * >1 - Error occurred
1265 */
1266static int img_compare(int argc, char **argv)
1267{
Max Reitz40055952014-07-22 22:58:42 +02001268 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001269 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001270 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001271 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001273 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001274 int allocated1, allocated2;
1275 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1276 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001277 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001278 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001279 int64_t total_size;
1280 int64_t offset = 0;
1281 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001282 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001283 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001284 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001285 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001286
Max Reitz40055952014-07-22 22:58:42 +02001287 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001289 static const struct option long_options[] = {
1290 {"help", no_argument, 0, 'h'},
1291 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001292 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001293 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001294 {0, 0, 0, 0}
1295 };
Fam Zheng335e9932017-05-03 00:35:39 +08001296 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001297 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001298 if (c == -1) {
1299 break;
1300 }
1301 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001302 case ':':
1303 missing_argument(argv[optind - 1]);
1304 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001305 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001306 unrecognized_option(argv[optind - 1]);
1307 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001308 case 'h':
1309 help();
1310 break;
1311 case 'f':
1312 fmt1 = optarg;
1313 break;
1314 case 'F':
1315 fmt2 = optarg;
1316 break;
Max Reitz40055952014-07-22 22:58:42 +02001317 case 'T':
1318 cache = optarg;
1319 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001320 case 'p':
1321 progress = true;
1322 break;
1323 case 'q':
1324 quiet = true;
1325 break;
1326 case 's':
1327 strict = true;
1328 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001329 case 'U':
1330 force_share = true;
1331 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001332 case OPTION_OBJECT: {
1333 QemuOpts *opts;
1334 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1335 optarg, true);
1336 if (!opts) {
1337 ret = 2;
1338 goto out4;
1339 }
1340 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001341 case OPTION_IMAGE_OPTS:
1342 image_opts = true;
1343 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001344 }
1345 }
1346
1347 /* Progress is not shown in Quiet mode */
1348 if (quiet) {
1349 progress = false;
1350 }
1351
1352
Kevin Wolffc11eb22013-08-05 10:53:04 +02001353 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001354 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001355 }
1356 filename1 = argv[optind++];
1357 filename2 = argv[optind++];
1358
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001359 if (qemu_opts_foreach(&qemu_object_opts,
1360 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00001361 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001362 ret = 2;
1363 goto out4;
1364 }
1365
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001366 /* Initialize before goto out */
1367 qemu_progress_init(progress, 2.0);
1368
Kevin Wolfce099542016-03-15 13:01:04 +01001369 flags = 0;
1370 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001371 if (ret < 0) {
1372 error_report("Invalid source cache option: %s", cache);
1373 ret = 2;
1374 goto out3;
1375 }
1376
Fam Zheng335e9932017-05-03 00:35:39 +08001377 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1378 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001379 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001380 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001381 goto out3;
1382 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001383
Fam Zheng335e9932017-05-03 00:35:39 +08001384 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1385 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001386 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001387 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001388 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001389 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001390 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001391 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392
Max Reitzf1d3cd72015-02-05 13:58:18 -05001393 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1394 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001395 total_size1 = blk_getlength(blk1);
1396 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001397 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001398 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001399 ret = 4;
1400 goto out;
1401 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001402 total_size2 = blk_getlength(blk2);
1403 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001404 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001405 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001406 ret = 4;
1407 goto out;
1408 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001409 total_size = MIN(total_size1, total_size2);
1410 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001411
1412 qemu_progress_print(0, 100);
1413
Eric Blake033d9fc2017-10-11 22:47:16 -05001414 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415 ret = 1;
1416 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1417 goto out;
1418 }
1419
Eric Blake033d9fc2017-10-11 22:47:16 -05001420 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001421 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001422
Eric Blake033d9fc2017-10-11 22:47:16 -05001423 status1 = bdrv_block_status_above(bs1, NULL, offset,
1424 total_size1 - offset, &pnum1, NULL,
1425 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001426 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001427 ret = 3;
1428 error_report("Sector allocation test failed for %s", filename1);
1429 goto out;
1430 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001431 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001432
Eric Blake033d9fc2017-10-11 22:47:16 -05001433 status2 = bdrv_block_status_above(bs2, NULL, offset,
1434 total_size2 - offset, &pnum2, NULL,
1435 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001436 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001437 ret = 3;
1438 error_report("Sector allocation test failed for %s", filename2);
1439 goto out;
1440 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001441 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001442
1443 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001444 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001445
Fam Zheng25ad8e62016-01-13 16:37:41 +08001446 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001447 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001448 ret = 1;
1449 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001450 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001451 goto out;
1452 }
1453 }
1454 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001455 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001456 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001457 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001458 int64_t pnum;
1459
Eric Blake033d9fc2017-10-11 22:47:16 -05001460 chunk = MIN(chunk, IO_BUF_SIZE);
1461 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001462 if (ret < 0) {
1463 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001464 " of %s: %s",
1465 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001466 ret = 4;
1467 goto out;
1468 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001469 ret = blk_pread(blk2, offset, buf2, chunk);
1470 if (ret < 0) {
1471 error_report("Error while reading offset %" PRId64
1472 " of %s: %s",
1473 offset, filename2, strerror(-ret));
1474 ret = 4;
1475 goto out;
1476 }
1477 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1478 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001480 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001481 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001482 goto out;
1483 }
1484 }
1485 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001486 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001488 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001489 filename1, buf1, quiet);
1490 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001491 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001492 filename2, buf1, quiet);
1493 }
1494 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001495 goto out;
1496 }
1497 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001498 offset += chunk;
1499 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500 }
1501
Eric Blake033d9fc2017-10-11 22:47:16 -05001502 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001503 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 const char *filename_over;
1505
1506 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001507 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001508 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 filename_over = filename1;
1510 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001511 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 filename_over = filename2;
1513 }
1514
Eric Blake033d9fc2017-10-11 22:47:16 -05001515 while (offset < progress_base) {
1516 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1517 progress_base - offset, &chunk,
1518 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 if (ret < 0) {
1520 ret = 3;
1521 error_report("Sector allocation test failed for %s",
1522 filename_over);
1523 goto out;
1524
1525 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001526 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001527 chunk = MIN(chunk, IO_BUF_SIZE);
1528 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001529 filename_over, buf1, quiet);
1530 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001531 goto out;
1532 }
1533 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001534 offset += chunk;
1535 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001536 }
1537 }
1538
1539 qprintf(quiet, "Images are identical.\n");
1540 ret = 0;
1541
1542out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001543 qemu_vfree(buf1);
1544 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001545 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001547 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001548out3:
1549 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001550out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 return ret;
1552}
1553
Kevin Wolf690c7302015-03-19 13:33:32 +01001554enum ImgConvertBlockStatus {
1555 BLK_DATA,
1556 BLK_ZERO,
1557 BLK_BACKING_FILE,
1558};
1559
Peter Lieven2d9187b2017-02-28 13:40:07 +01001560#define MAX_COROUTINES 16
1561
Kevin Wolf690c7302015-03-19 13:33:32 +01001562typedef struct ImgConvertState {
1563 BlockBackend **src;
1564 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001565 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001566 int64_t total_sectors;
1567 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001568 int64_t allocated_done;
1569 int64_t sector_num;
1570 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001571 enum ImgConvertBlockStatus status;
1572 int64_t sector_next_status;
1573 BlockBackend *target;
1574 bool has_zero_init;
1575 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001576 bool unallocated_blocks_are_zero;
Kevin Wolf690c7302015-03-19 13:33:32 +01001577 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001578 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001579 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001580 bool copy_range;
Kevin Wolf690c7302015-03-19 13:33:32 +01001581 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001582 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001583 size_t cluster_sectors;
1584 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001585 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001586 int running_coroutines;
1587 Coroutine *co[MAX_COROUTINES];
1588 int64_t wait_sector_num[MAX_COROUTINES];
1589 CoMutex lock;
1590 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001591} ImgConvertState;
1592
Peter Lieven2d9187b2017-02-28 13:40:07 +01001593static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1594 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001595{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001596 *src_cur = 0;
1597 *src_cur_offset = 0;
1598 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1599 *src_cur_offset += s->src_sectors[*src_cur];
1600 (*src_cur)++;
1601 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001602 }
1603}
1604
1605static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1606{
Eric Blake31826642017-10-11 22:47:08 -05001607 int64_t src_cur_offset;
1608 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001609 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001610
Peter Lieven2d9187b2017-02-28 13:40:07 +01001611 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001612
1613 assert(s->total_sectors > sector_num);
1614 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1615
Max Reitz351c8ef2018-05-01 18:57:49 +02001616 if (s->target_backing_sectors >= 0) {
1617 if (sector_num >= s->target_backing_sectors) {
1618 post_backing_zero = s->unallocated_blocks_are_zero;
1619 } else if (sector_num + n > s->target_backing_sectors) {
1620 /* Split requests around target_backing_sectors (because
1621 * starting from there, zeros are handled differently) */
1622 n = s->target_backing_sectors - sector_num;
1623 }
1624 }
1625
Kevin Wolf690c7302015-03-19 13:33:32 +01001626 if (s->sector_next_status <= sector_num) {
Eric Blake31826642017-10-11 22:47:08 -05001627 int64_t count = n * BDRV_SECTOR_SIZE;
1628
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001629 if (s->target_has_backing) {
Eric Blake237d78f2017-10-11 22:47:03 -05001630
1631 ret = bdrv_block_status(blk_bs(s->src[src_cur]),
1632 (sector_num - src_cur_offset) *
1633 BDRV_SECTOR_SIZE,
1634 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001635 } else {
Eric Blake31826642017-10-11 22:47:08 -05001636 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1637 (sector_num - src_cur_offset) *
1638 BDRV_SECTOR_SIZE,
1639 count, &count, NULL, NULL);
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001640 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001641 if (ret < 0) {
Eric Blake2058c2a2019-03-23 16:26:38 -05001642 error_report("error while reading block status of sector %" PRId64
1643 ": %s", sector_num, strerror(-ret));
Kevin Wolf690c7302015-03-19 13:33:32 +01001644 return ret;
1645 }
Eric Blake31826642017-10-11 22:47:08 -05001646 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001647
1648 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001649 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001650 } else if (ret & BDRV_BLOCK_DATA) {
1651 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001652 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001653 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001654 }
1655
1656 s->sector_next_status = sector_num + n;
1657 }
1658
1659 n = MIN(n, s->sector_next_status - sector_num);
1660 if (s->status == BLK_DATA) {
1661 n = MIN(n, s->buf_sectors);
1662 }
1663
1664 /* We need to write complete clusters for compressed images, so if an
1665 * unallocated area is shorter than that, we must consider the whole
1666 * cluster allocated. */
1667 if (s->compressed) {
1668 if (n < s->cluster_sectors) {
1669 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1670 s->status = BLK_DATA;
1671 } else {
1672 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1673 }
1674 }
1675
1676 return n;
1677}
1678
Peter Lieven2d9187b2017-02-28 13:40:07 +01001679static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1680 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001681{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001682 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001683
Kevin Wolf690c7302015-03-19 13:33:32 +01001684 assert(nb_sectors <= s->buf_sectors);
1685 while (nb_sectors > 0) {
1686 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001687 int src_cur;
1688 int64_t bs_sectors, src_cur_offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001689
1690 /* In the case of compression with multiple source files, we can get a
1691 * nb_sectors that spreads into the next part. So we must be able to
1692 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001693 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1694 blk = s->src[src_cur];
1695 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001696
Peter Lieven2d9187b2017-02-28 13:40:07 +01001697 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001698
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001699 ret = blk_co_pread(
Peter Lieven2d9187b2017-02-28 13:40:07 +01001700 blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001701 n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001702 if (ret < 0) {
1703 return ret;
1704 }
1705
1706 sector_num += n;
1707 nb_sectors -= n;
1708 buf += n * BDRV_SECTOR_SIZE;
1709 }
1710
1711 return 0;
1712}
1713
Peter Lieven2d9187b2017-02-28 13:40:07 +01001714
1715static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1716 int nb_sectors, uint8_t *buf,
1717 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001718{
1719 int ret;
1720
1721 while (nb_sectors > 0) {
1722 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001723 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1724
Peter Lieven2d9187b2017-02-28 13:40:07 +01001725 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001726 case BLK_BACKING_FILE:
1727 /* If we have a backing file, leave clusters unallocated that are
1728 * unallocated in the source image, so that the backing file is
1729 * visible at the respective offset. */
1730 assert(s->target_has_backing);
1731 break;
1732
1733 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001734 /* If we're told to keep the target fully allocated (-S 0) or there
1735 * is real non-zero data, we must write it. Otherwise we can treat
1736 * it as zero sectors.
1737 * Compressed clusters need to be written as a whole, so in that
1738 * case we can only save the write if the buffer is completely
1739 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001740 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001741 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001742 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1743 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001744 (s->compressed &&
1745 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001746 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001747 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1748 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 if (ret < 0) {
1750 return ret;
1751 }
1752 break;
1753 }
1754 /* fall-through */
1755
1756 case BLK_ZERO:
1757 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001758 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001759 break;
1760 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001761 ret = blk_co_pwrite_zeroes(s->target,
1762 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001763 n << BDRV_SECTOR_BITS,
1764 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001765 if (ret < 0) {
1766 return ret;
1767 }
1768 break;
1769 }
1770
1771 sector_num += n;
1772 nb_sectors -= n;
1773 buf += n * BDRV_SECTOR_SIZE;
1774 }
1775
1776 return 0;
1777}
1778
Fam Zhengee5306d2018-06-01 17:26:48 +08001779static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1780 int nb_sectors)
1781{
1782 int n, ret;
1783
1784 while (nb_sectors > 0) {
1785 BlockBackend *blk;
1786 int src_cur;
1787 int64_t bs_sectors, src_cur_offset;
1788 int64_t offset;
1789
1790 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1791 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1792 blk = s->src[src_cur];
1793 bs_sectors = s->src_sectors[src_cur];
1794
1795 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1796
1797 ret = blk_co_copy_range(blk, offset, s->target,
1798 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001799 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001800 if (ret < 0) {
1801 return ret;
1802 }
1803
1804 sector_num += n;
1805 nb_sectors -= n;
1806 }
1807 return 0;
1808}
1809
Peter Lieven2d9187b2017-02-28 13:40:07 +01001810static void coroutine_fn convert_co_do_copy(void *opaque)
1811{
1812 ImgConvertState *s = opaque;
1813 uint8_t *buf = NULL;
1814 int ret, i;
1815 int index = -1;
1816
1817 for (i = 0; i < s->num_coroutines; i++) {
1818 if (s->co[i] == qemu_coroutine_self()) {
1819 index = i;
1820 break;
1821 }
1822 }
1823 assert(index >= 0);
1824
1825 s->running_coroutines++;
1826 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1827
1828 while (1) {
1829 int n;
1830 int64_t sector_num;
1831 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001832 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001833
1834 qemu_co_mutex_lock(&s->lock);
1835 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1836 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001837 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001838 }
1839 n = convert_iteration_sectors(s, s->sector_num);
1840 if (n < 0) {
1841 qemu_co_mutex_unlock(&s->lock);
1842 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001843 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001844 }
1845 /* save current sector and allocation status to local variables */
1846 sector_num = s->sector_num;
1847 status = s->status;
1848 if (!s->min_sparse && s->status == BLK_ZERO) {
1849 n = MIN(n, s->buf_sectors);
1850 }
1851 /* increment global sector counter so that other coroutines can
1852 * already continue reading beyond this request */
1853 s->sector_num += n;
1854 qemu_co_mutex_unlock(&s->lock);
1855
1856 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1857 s->allocated_done += n;
1858 qemu_progress_print(100.0 * s->allocated_done /
1859 s->allocated_sectors, 0);
1860 }
1861
Fam Zhengee5306d2018-06-01 17:26:48 +08001862retry:
1863 copy_range = s->copy_range && s->status == BLK_DATA;
1864 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001865 ret = convert_co_read(s, sector_num, n, buf);
1866 if (ret < 0) {
1867 error_report("error while reading sector %" PRId64
1868 ": %s", sector_num, strerror(-ret));
1869 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001870 }
1871 } else if (!s->min_sparse && status == BLK_ZERO) {
1872 status = BLK_DATA;
1873 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1874 }
1875
1876 if (s->wr_in_order) {
1877 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001878 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001879 s->wait_sector_num[index] = sector_num;
1880 qemu_coroutine_yield();
1881 }
1882 s->wait_sector_num[index] = -1;
1883 }
1884
Anton Nefedovb91127e2017-04-26 11:33:15 +03001885 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001886 if (copy_range) {
1887 ret = convert_co_copy_range(s, sector_num, n);
1888 if (ret) {
1889 s->copy_range = false;
1890 goto retry;
1891 }
1892 } else {
1893 ret = convert_co_write(s, sector_num, n, buf, status);
1894 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001895 if (ret < 0) {
1896 error_report("error while writing sector %" PRId64
1897 ": %s", sector_num, strerror(-ret));
1898 s->ret = ret;
1899 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001900 }
1901
1902 if (s->wr_in_order) {
1903 /* reenter the coroutine that might have waited
1904 * for this write to complete */
1905 s->wr_offs = sector_num + n;
1906 for (i = 0; i < s->num_coroutines; i++) {
1907 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1908 /*
1909 * A -> B -> A cannot occur because A has
1910 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1911 * B will never enter A during this time window.
1912 */
1913 qemu_coroutine_enter(s->co[i]);
1914 break;
1915 }
1916 }
1917 }
1918 }
1919
Peter Lieven2d9187b2017-02-28 13:40:07 +01001920 qemu_vfree(buf);
1921 s->co[index] = NULL;
1922 s->running_coroutines--;
1923 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1924 /* the convert job finished successfully */
1925 s->ret = 0;
1926 }
1927}
1928
Kevin Wolf690c7302015-03-19 13:33:32 +01001929static int convert_do_copy(ImgConvertState *s)
1930{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001931 int ret, i, n;
1932 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001933
1934 /* Check whether we have zero initialisation or can get it efficiently */
1935 s->has_zero_init = s->min_sparse && !s->target_has_backing
1936 ? bdrv_has_zero_init(blk_bs(s->target))
1937 : false;
1938
1939 if (!s->has_zero_init && !s->target_has_backing &&
1940 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1941 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001942 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001943 if (ret == 0) {
1944 s->has_zero_init = true;
1945 }
1946 }
1947
1948 /* Allocate buffer for copied data. For compressed images, only one cluster
1949 * can be copied at a time. */
1950 if (s->compressed) {
1951 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
1952 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01001953 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01001954 }
1955 s->buf_sectors = s->cluster_sectors;
1956 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001957
Kevin Wolf690c7302015-03-19 13:33:32 +01001958 while (sector_num < s->total_sectors) {
1959 n = convert_iteration_sectors(s, sector_num);
1960 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001961 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01001962 }
Max Reitzaad15de2016-03-24 23:33:57 +01001963 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
1964 {
Kevin Wolf690c7302015-03-19 13:33:32 +01001965 s->allocated_sectors += n;
1966 }
1967 sector_num += n;
1968 }
1969
1970 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01001971 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001972 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01001973
Peter Lieven2d9187b2017-02-28 13:40:07 +01001974 qemu_co_mutex_init(&s->lock);
1975 for (i = 0; i < s->num_coroutines; i++) {
1976 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
1977 s->wait_sector_num[i] = -1;
1978 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01001979 }
1980
Anton Nefedovb91127e2017-04-26 11:33:15 +03001981 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001982 main_loop_wait(false);
1983 }
1984
1985 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001986 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03001987 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001988 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001989 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001990 }
1991 }
1992
Peter Lieven2d9187b2017-02-28 13:40:07 +01001993 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001994}
1995
Peter Lieven6360ab22018-07-13 09:15:39 +02001996#define MAX_BUF_SECTORS 32768
1997
bellardea2384d2004-08-01 21:59:26 +00001998static int img_convert(int argc, char **argv)
1999{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002000 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002001 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002002 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2003 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002004 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002005 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002006 BlockDriverState *out_bs;
2007 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002008 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002009 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002010 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002011 Error *local_err = NULL;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002012 bool writethrough, src_writethrough, quiet = false, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002013 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002014 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002015 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002016 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002017
Peter Lieven9fd77f92017-04-21 11:11:55 +02002018 ImgConvertState s = (ImgConvertState) {
2019 /* Need at least 4k of zeros for sparse detection */
2020 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002021 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002022 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2023 .wr_in_order = true,
2024 .num_coroutines = 8,
2025 };
2026
bellardea2384d2004-08-01 21:59:26 +00002027 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002028 static const struct option long_options[] = {
2029 {"help", no_argument, 0, 'h'},
2030 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002031 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002032 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002033 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002034 {0, 0, 0, 0}
2035 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002036 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002037 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002038 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002039 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002040 }
bellardea2384d2004-08-01 21:59:26 +00002041 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002042 case ':':
2043 missing_argument(argv[optind - 1]);
2044 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002045 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002046 unrecognized_option(argv[optind - 1]);
2047 break;
bellardea2384d2004-08-01 21:59:26 +00002048 case 'h':
2049 help();
2050 break;
2051 case 'f':
2052 fmt = optarg;
2053 break;
2054 case 'O':
2055 out_fmt = optarg;
2056 break;
thsf58c7b32008-06-05 21:53:49 +00002057 case 'B':
2058 out_baseimg = optarg;
2059 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002060 case 'C':
2061 s.copy_range = true;
2062 break;
bellardea2384d2004-08-01 21:59:26 +00002063 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002064 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002065 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002066 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002067 if (!is_valid_option_list(optarg)) {
2068 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002069 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002070 }
2071 if (!options) {
2072 options = g_strdup(optarg);
2073 } else {
2074 char *old_options = options;
2075 options = g_strdup_printf("%s,%s", options, optarg);
2076 g_free(old_options);
2077 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002078 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002079 case 'l':
2080 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002081 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2082 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002083 if (!sn_opts) {
2084 error_report("Failed in parsing snapshot param '%s'",
2085 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002086 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002087 }
2088 } else {
2089 snapshot_name = optarg;
2090 }
2091 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002092 case 'S':
2093 {
2094 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002095
2096 sval = cvtnum(optarg);
Peter Lieven6360ab22018-07-13 09:15:39 +02002097 if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
2098 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2099 error_report("Invalid buffer size for sparse output specified. "
2100 "Valid sizes are multiples of %llu up to %llu. Select "
2101 "0 to disable sparse detection (fully allocates output).",
2102 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002103 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002104 }
2105
Peter Lieven9fd77f92017-04-21 11:11:55 +02002106 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002107 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002108 break;
2109 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002110 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002111 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002112 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002113 case 't':
2114 cache = optarg;
2115 break;
Max Reitz40055952014-07-22 22:58:42 +02002116 case 'T':
2117 src_cache = optarg;
2118 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002119 case 'q':
2120 quiet = true;
2121 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002122 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002123 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002124 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002125 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002126 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2127 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 error_report("Invalid number of coroutines. Allowed number of"
2129 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002130 goto fail_getopt;
2131 }
2132 break;
2133 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002134 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002135 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002136 case 'U':
2137 force_share = true;
2138 break;
Max Reitz3258b912017-04-26 15:46:47 +02002139 case OPTION_OBJECT: {
2140 QemuOpts *object_opts;
2141 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2142 optarg, true);
2143 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002144 goto fail_getopt;
2145 }
2146 break;
Max Reitz3258b912017-04-26 15:46:47 +02002147 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002148 case OPTION_IMAGE_OPTS:
2149 image_opts = true;
2150 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002151 case OPTION_TARGET_IMAGE_OPTS:
2152 tgt_image_opts = true;
2153 break;
bellardea2384d2004-08-01 21:59:26 +00002154 }
2155 }
ths3b46e622007-09-17 08:09:54 +00002156
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002157 if (!out_fmt && !tgt_image_opts) {
2158 out_fmt = "raw";
2159 }
2160
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002161 if (qemu_opts_foreach(&qemu_object_opts,
2162 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002163 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002164 goto fail_getopt;
2165 }
2166
Fam Zhenge11ce122018-07-27 11:34:01 +08002167 if (s.compressed && s.copy_range) {
2168 error_report("Cannot enable copy offloading when -c is used");
2169 goto fail_getopt;
2170 }
2171
2172 if (explict_min_sparse && s.copy_range) {
2173 error_report("Cannot enable copy offloading when -S is used");
2174 goto fail_getopt;
2175 }
2176
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002177 if (tgt_image_opts && !skip_create) {
2178 error_report("--target-image-opts requires use of -n flag");
2179 goto fail_getopt;
2180 }
2181
Peter Lieven9fd77f92017-04-21 11:11:55 +02002182 s.src_num = argc - optind - 1;
2183 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2184
2185 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002186 if (out_fmt) {
2187 ret = print_block_option_help(out_filename, out_fmt);
2188 goto fail_getopt;
2189 } else {
2190 error_report("Option help requires a format be specified");
2191 goto fail_getopt;
2192 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002193 }
2194
2195 if (s.src_num < 1) {
2196 error_report("Must specify image file name");
2197 goto fail_getopt;
2198 }
2199
2200
Peter Lieven9fd77f92017-04-21 11:11:55 +02002201 /* ret is still -EINVAL until here */
2202 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2203 if (ret < 0) {
2204 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002205 goto fail_getopt;
2206 }
2207
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002208 /* Initialize before goto out */
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002209 if (quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002210 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002211 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002212 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002213 qemu_progress_print(0, 100);
2214
Peter Lieven9fd77f92017-04-21 11:11:55 +02002215 s.src = g_new0(BlockBackend *, s.src_num);
2216 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002217
Peter Lieven9fd77f92017-04-21 11:11:55 +02002218 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2219 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Fam Zheng335e9932017-05-03 00:35:39 +08002220 fmt, src_flags, src_writethrough, quiet,
2221 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002222 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002223 ret = -1;
2224 goto out;
2225 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2227 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002228 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002229 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002230 ret = -1;
2231 goto out;
2232 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002233 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002234 }
bellardea2384d2004-08-01 21:59:26 +00002235
Wenchao Xiaef806542013-12-04 17:10:57 +08002236 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002237 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002238 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2239 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2240 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002241 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002242 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002243 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002244 ret = -1;
2245 goto out;
2246 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002247
Peter Lieven9fd77f92017-04-21 11:11:55 +02002248 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2249 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002250 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002251 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002252 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002253 ret = -1;
2254 goto out;
edison51ef6722010-09-21 19:58:41 -07002255 }
2256
Max Reitz2e024cd2015-02-11 09:58:46 -05002257 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002258 /* Find driver and parse its options */
2259 drv = bdrv_find_format(out_fmt);
2260 if (!drv) {
2261 error_report("Unknown file format '%s'", out_fmt);
2262 ret = -1;
2263 goto out;
2264 }
2265
2266 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2267 if (!proto_drv) {
2268 error_report_err(local_err);
2269 ret = -1;
2270 goto out;
2271 }
2272
Max Reitz2e024cd2015-02-11 09:58:46 -05002273 if (!drv->create_opts) {
2274 error_report("Format driver '%s' does not support image creation",
2275 drv->format_name);
2276 ret = -1;
2277 goto out;
2278 }
Max Reitzf75613c2014-12-02 18:32:46 +01002279
Max Reitz2e024cd2015-02-11 09:58:46 -05002280 if (!proto_drv->create_opts) {
2281 error_report("Protocol driver '%s' does not support image creation",
2282 proto_drv->format_name);
2283 ret = -1;
2284 goto out;
2285 }
Max Reitzf75613c2014-12-02 18:32:46 +01002286
Max Reitz2e024cd2015-02-11 09:58:46 -05002287 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2288 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002289
Max Reitz2e024cd2015-02-11 09:58:46 -05002290 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002291 if (options) {
2292 qemu_opts_do_parse(opts, options, NULL, &local_err);
2293 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002294 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002295 ret = -1;
2296 goto out;
2297 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002298 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002299
Peter Lieven9fd77f92017-04-21 11:11:55 +02002300 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002301 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002302 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2303 if (ret < 0) {
2304 goto out;
2305 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002306 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002307
Kevin Wolfa18953f2010-10-14 15:46:04 +02002308 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002309 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002310 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002311 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002312 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002313 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002314
Max Reitz48758a82017-04-26 15:46:48 +02002315 if (s.src_num > 1 && out_baseimg) {
2316 error_report("Having a backing file for the target makes no sense when "
2317 "concatenating multiple input images");
2318 ret = -1;
2319 goto out;
2320 }
2321
Kevin Wolfefa84d42009-05-18 16:42:12 +02002322 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002323 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002324 bool encryption =
2325 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002326 const char *encryptfmt =
2327 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002328 const char *preallocation =
2329 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002330
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002331 if (drv && !drv->bdrv_co_pwritev_compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002332 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002333 ret = -1;
2334 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002335 }
2336
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002337 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002338 error_report("Compression and encryption not supported at "
2339 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002340 ret = -1;
2341 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002342 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002343
Chunyan Liu83d05212014-06-05 17:20:51 +08002344 if (preallocation
2345 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002346 {
2347 error_report("Compression and preallocation not supported at "
2348 "the same time");
2349 ret = -1;
2350 goto out;
2351 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002352 }
2353
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002354 /*
2355 * The later open call will need any decryption secrets, and
2356 * bdrv_create() will purge "opts", so extract them now before
2357 * they are lost.
2358 */
2359 if (!skip_create) {
2360 open_opts = qdict_new();
2361 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2362 }
2363
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002364 if (!skip_create) {
2365 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002366 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002367 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002368 error_reportf_err(local_err, "%s: error while converting %s: ",
2369 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002370 goto out;
bellardea2384d2004-08-01 21:59:26 +00002371 }
2372 }
ths3b46e622007-09-17 08:09:54 +00002373
Peter Lieven9fd77f92017-04-21 11:11:55 +02002374 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002375 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002376 if (ret < 0) {
2377 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002378 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002379 }
2380
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002381 if (skip_create) {
2382 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
2383 flags, writethrough, quiet, false);
2384 } else {
2385 /* TODO ultimately we should allow --target-image-opts
2386 * to be used even when -n is not given.
2387 * That has to wait for bdrv_create to be improved
2388 * to allow filenames in option syntax
2389 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002390 s.target = img_open_file(out_filename, open_opts, out_fmt,
2391 flags, writethrough, quiet, false);
2392 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002393 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002394 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002395 ret = -1;
2396 goto out;
2397 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002398 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002399
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002400 if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
2401 error_report("Compression not supported for this file format");
2402 ret = -1;
2403 goto out;
2404 }
2405
Eric Blake5def6b82016-06-23 16:37:19 -06002406 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002407 * or discard_alignment of the out_bs is greater. Limit to
2408 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2409 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002410 MAX(s.buf_sectors,
2411 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2412 out_bs->bl.pdiscard_alignment >>
2413 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002414
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002415 /* try to align the write requests to the destination to avoid unnecessary
2416 * RMW cycles. */
2417 s.alignment = MAX(pow2floor(s.min_sparse),
2418 DIV_ROUND_UP(out_bs->bl.request_alignment,
2419 BDRV_SECTOR_SIZE));
2420 assert(is_power_of_2(s.alignment));
2421
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002422 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002423 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002424 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002425 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002426 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002427 ret = -1;
2428 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002429 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002430 error_report("output file is smaller than input file");
2431 ret = -1;
2432 goto out;
2433 }
2434 }
2435
Max Reitz351c8ef2018-05-01 18:57:49 +02002436 if (s.target_has_backing) {
2437 /* Errors are treated as "backing length unknown" (which means
2438 * s.target_backing_sectors has to be negative, which it will
2439 * be automatically). The backing file length is used only
2440 * for optimizations, so such a case is not fatal. */
2441 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2442 } else {
2443 s.target_backing_sectors = -1;
2444 }
2445
Peter Lieven24f833c2013-11-27 11:07:07 +01002446 ret = bdrv_get_info(out_bs, &bdi);
2447 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002448 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002449 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002450 goto out;
2451 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002452 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002453 s.compressed = s.compressed || bdi.needs_compressed_writes;
2454 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002455 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002456 }
2457
Peter Lieven9fd77f92017-04-21 11:11:55 +02002458 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002459out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002460 if (!ret) {
2461 qemu_progress_print(100, 0);
2462 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002463 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002464 qemu_opts_del(opts);
2465 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002466 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002467 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002468 blk_unref(s.target);
2469 if (s.src) {
2470 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2471 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002472 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002473 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002474 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002475 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002476fail_getopt:
2477 g_free(options);
2478
Peter Lieven9fd77f92017-04-21 11:11:55 +02002479 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002480}
2481
bellard57d1a2b2004-08-03 21:15:11 +00002482
bellardfaea38e2006-08-05 21:31:00 +00002483static void dump_snapshots(BlockDriverState *bs)
2484{
2485 QEMUSnapshotInfo *sn_tab, *sn;
2486 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002487
2488 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2489 if (nb_sns <= 0)
2490 return;
2491 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002492 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002493 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002494 for(i = 0; i < nb_sns; i++) {
2495 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002496 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002497 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002498 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002499 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002500}
2501
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002502static void dump_json_image_info_list(ImageInfoList *list)
2503{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002504 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002505 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002506 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002507
2508 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2509 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002510 str = qobject_to_json_pretty(obj);
2511 assert(str != NULL);
2512 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002513 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002514 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002515 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002516}
2517
Benoît Canetc054b3f2012-09-05 13:09:02 +02002518static void dump_json_image_info(ImageInfo *info)
2519{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002520 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002521 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002522 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002523
2524 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2525 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002526 str = qobject_to_json_pretty(obj);
2527 assert(str != NULL);
2528 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002529 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002530 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002531 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002532}
2533
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002534static void dump_human_image_info_list(ImageInfoList *list)
2535{
2536 ImageInfoList *elem;
2537 bool delim = false;
2538
2539 for (elem = list; elem; elem = elem->next) {
2540 if (delim) {
2541 printf("\n");
2542 }
2543 delim = true;
2544
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002545 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002546 }
2547}
2548
2549static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2550{
2551 return strcmp(a, b) == 0;
2552}
2553
2554/**
2555 * Open an image file chain and return an ImageInfoList
2556 *
2557 * @filename: topmost image filename
2558 * @fmt: topmost image format (may be NULL to autodetect)
2559 * @chain: true - enumerate entire backing file chain
2560 * false - only topmost image file
2561 *
2562 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2563 * image file. If there was an error a message will have been printed to
2564 * stderr.
2565 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002566static ImageInfoList *collect_image_info_list(bool image_opts,
2567 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002568 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002569 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002570{
2571 ImageInfoList *head = NULL;
2572 ImageInfoList **last = &head;
2573 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002574 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002575
2576 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2577
2578 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002579 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002580 BlockDriverState *bs;
2581 ImageInfo *info;
2582 ImageInfoList *elem;
2583
2584 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2585 error_report("Backing file '%s' creates an infinite loop.",
2586 filename);
2587 goto err;
2588 }
2589 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2590
Max Reitzefaa7c42016-03-16 19:54:38 +01002591 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002592 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2593 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002594 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002595 goto err;
2596 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002597 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002598
Wenchao Xia43526ec2013-06-06 12:27:58 +08002599 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002600 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002601 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002602 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002603 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002604 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002605
2606 elem = g_new0(ImageInfoList, 1);
2607 elem->value = info;
2608 *last = elem;
2609 last = &elem->next;
2610
Markus Armbruster26f54e92014-10-07 13:59:04 +02002611 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002612
2613 filename = fmt = NULL;
2614 if (chain) {
2615 if (info->has_full_backing_filename) {
2616 filename = info->full_backing_filename;
2617 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002618 error_report("Could not determine absolute backing filename,"
2619 " but backing filename '%s' present",
2620 info->backing_filename);
2621 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002622 }
2623 if (info->has_backing_filename_format) {
2624 fmt = info->backing_filename_format;
2625 }
2626 }
2627 }
2628 g_hash_table_destroy(filenames);
2629 return head;
2630
2631err:
2632 qapi_free_ImageInfoList(head);
2633 g_hash_table_destroy(filenames);
2634 return NULL;
2635}
2636
Benoît Canetc054b3f2012-09-05 13:09:02 +02002637static int img_info(int argc, char **argv)
2638{
2639 int c;
2640 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002641 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002642 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002643 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002644 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002645 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002646
bellardea2384d2004-08-01 21:59:26 +00002647 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002648 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002649 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002650 int option_index = 0;
2651 static const struct option long_options[] = {
2652 {"help", no_argument, 0, 'h'},
2653 {"format", required_argument, 0, 'f'},
2654 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002655 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002656 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002657 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002658 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002659 {0, 0, 0, 0}
2660 };
Fam Zheng335e9932017-05-03 00:35:39 +08002661 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002662 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002663 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002664 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002665 }
bellardea2384d2004-08-01 21:59:26 +00002666 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002667 case ':':
2668 missing_argument(argv[optind - 1]);
2669 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002670 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002671 unrecognized_option(argv[optind - 1]);
2672 break;
bellardea2384d2004-08-01 21:59:26 +00002673 case 'h':
2674 help();
2675 break;
2676 case 'f':
2677 fmt = optarg;
2678 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002679 case 'U':
2680 force_share = true;
2681 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002682 case OPTION_OUTPUT:
2683 output = optarg;
2684 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002685 case OPTION_BACKING_CHAIN:
2686 chain = true;
2687 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002688 case OPTION_OBJECT: {
2689 QemuOpts *opts;
2690 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2691 optarg, true);
2692 if (!opts) {
2693 return 1;
2694 }
2695 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002696 case OPTION_IMAGE_OPTS:
2697 image_opts = true;
2698 break;
bellardea2384d2004-08-01 21:59:26 +00002699 }
2700 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002701 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002702 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002703 }
bellardea2384d2004-08-01 21:59:26 +00002704 filename = argv[optind++];
2705
Benoît Canetc054b3f2012-09-05 13:09:02 +02002706 if (output && !strcmp(output, "json")) {
2707 output_format = OFORMAT_JSON;
2708 } else if (output && !strcmp(output, "human")) {
2709 output_format = OFORMAT_HUMAN;
2710 } else if (output) {
2711 error_report("--output must be used with human or json as argument.");
2712 return 1;
2713 }
2714
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002715 if (qemu_opts_foreach(&qemu_object_opts,
2716 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002717 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002718 return 1;
2719 }
2720
Fam Zheng335e9932017-05-03 00:35:39 +08002721 list = collect_image_info_list(image_opts, filename, fmt, chain,
2722 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002723 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002724 return 1;
2725 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002726
Benoît Canetc054b3f2012-09-05 13:09:02 +02002727 switch (output_format) {
2728 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002729 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002730 break;
2731 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002732 if (chain) {
2733 dump_json_image_info_list(list);
2734 } else {
2735 dump_json_image_info(list->value);
2736 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002737 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002738 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002739
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002740 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002741 return 0;
2742}
2743
Eric Blake30065d12019-03-26 13:40:43 -05002744static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2745 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002746{
2747 switch (output_format) {
2748 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002749 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002750 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002751 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002752 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002753 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002754 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002755 e->start, e->length,
2756 e->has_offset ? e->offset : 0,
2757 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002758 }
2759 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2760 * Modify the flags here to allow more coalescing.
2761 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002762 if (next && (!next->data || next->zero)) {
2763 next->data = false;
2764 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002765 }
2766 break;
2767 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002768 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2769 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002770 (e->start == 0 ? "[" : ",\n"),
2771 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002772 e->zero ? "true" : "false",
2773 e->data ? "true" : "false");
2774 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002775 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002776 }
2777 putchar('}');
2778
2779 if (!next) {
2780 printf("]\n");
2781 }
2782 break;
2783 }
Eric Blake30065d12019-03-26 13:40:43 -05002784 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002785}
2786
Eric Blake5e344dd2017-10-11 22:47:02 -05002787static int get_block_status(BlockDriverState *bs, int64_t offset,
2788 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002789{
Eric Blake237d78f2017-10-11 22:47:03 -05002790 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002791 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002792 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002793 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002794 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002795 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002796
2797 /* As an optimization, we could cache the current range of unallocated
2798 * clusters in each file of the chain, and avoid querying the same
2799 * range repeatedly.
2800 */
2801
2802 depth = 0;
2803 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002804 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002805 if (ret < 0) {
2806 return ret;
2807 }
Eric Blake237d78f2017-10-11 22:47:03 -05002808 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002809 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2810 break;
2811 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002812 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002813 if (bs == NULL) {
2814 ret = 0;
2815 break;
2816 }
2817
2818 depth++;
2819 }
2820
John Snow28756452016-02-05 13:12:33 -05002821 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2822
Max Reitzf30c66b2019-02-01 20:29:05 +01002823 if (file && has_offset) {
2824 bdrv_refresh_filename(file);
2825 filename = file->filename;
2826 }
2827
John Snow28756452016-02-05 13:12:33 -05002828 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002829 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002830 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002831 .data = !!(ret & BDRV_BLOCK_DATA),
2832 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002833 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002834 .has_offset = has_offset,
2835 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002836 .has_filename = filename,
2837 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002838 };
2839
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002840 return 0;
2841}
2842
Fam Zheng16b0d552016-01-26 11:59:02 +08002843static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2844{
2845 if (curr->length == 0) {
2846 return false;
2847 }
2848 if (curr->zero != next->zero ||
2849 curr->data != next->data ||
2850 curr->depth != next->depth ||
2851 curr->has_filename != next->has_filename ||
2852 curr->has_offset != next->has_offset) {
2853 return false;
2854 }
2855 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2856 return false;
2857 }
2858 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2859 return false;
2860 }
2861 return true;
2862}
2863
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002864static int img_map(int argc, char **argv)
2865{
2866 int c;
2867 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002868 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002869 BlockDriverState *bs;
2870 const char *filename, *fmt, *output;
2871 int64_t length;
2872 MapEntry curr = { .length = 0 }, next;
2873 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002874 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002875 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002876
2877 fmt = NULL;
2878 output = NULL;
2879 for (;;) {
2880 int option_index = 0;
2881 static const struct option long_options[] = {
2882 {"help", no_argument, 0, 'h'},
2883 {"format", required_argument, 0, 'f'},
2884 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002885 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002886 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002887 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002888 {0, 0, 0, 0}
2889 };
Fam Zheng335e9932017-05-03 00:35:39 +08002890 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002891 long_options, &option_index);
2892 if (c == -1) {
2893 break;
2894 }
2895 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002896 case ':':
2897 missing_argument(argv[optind - 1]);
2898 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002899 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002900 unrecognized_option(argv[optind - 1]);
2901 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002902 case 'h':
2903 help();
2904 break;
2905 case 'f':
2906 fmt = optarg;
2907 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002908 case 'U':
2909 force_share = true;
2910 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002911 case OPTION_OUTPUT:
2912 output = optarg;
2913 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002914 case OPTION_OBJECT: {
2915 QemuOpts *opts;
2916 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2917 optarg, true);
2918 if (!opts) {
2919 return 1;
2920 }
2921 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002922 case OPTION_IMAGE_OPTS:
2923 image_opts = true;
2924 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002925 }
2926 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002927 if (optind != argc - 1) {
2928 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002929 }
Fam Zhengac1307a2014-04-22 13:36:11 +08002930 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002931
2932 if (output && !strcmp(output, "json")) {
2933 output_format = OFORMAT_JSON;
2934 } else if (output && !strcmp(output, "human")) {
2935 output_format = OFORMAT_HUMAN;
2936 } else if (output) {
2937 error_report("--output must be used with human or json as argument.");
2938 return 1;
2939 }
2940
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002941 if (qemu_opts_foreach(&qemu_object_opts,
2942 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00002943 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002944 return 1;
2945 }
2946
Fam Zheng335e9932017-05-03 00:35:39 +08002947 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002948 if (!blk) {
2949 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002950 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002951 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002952
2953 if (output_format == OFORMAT_HUMAN) {
2954 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
2955 }
2956
Max Reitzf1d3cd72015-02-05 13:58:18 -05002957 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002958 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002959 int64_t offset = curr.start + curr.length;
2960 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002961
2962 /* Probe up to 1 GiB at a time. */
Eric Blakee0b371e2018-06-11 16:39:26 -05002963 n = MIN(1 << 30, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05002964 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002965
2966 if (ret < 0) {
2967 error_report("Could not read file metadata: %s", strerror(-ret));
2968 goto out;
2969 }
2970
Fam Zheng16b0d552016-01-26 11:59:02 +08002971 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002972 curr.length += next.length;
2973 continue;
2974 }
2975
2976 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05002977 ret = dump_map_entry(output_format, &curr, &next);
2978 if (ret < 0) {
2979 goto out;
2980 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002981 }
2982 curr = next;
2983 }
2984
Eric Blake30065d12019-03-26 13:40:43 -05002985 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002986
2987out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02002988 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002989 return ret < 0;
2990}
2991
aliguorif7b4a942009-01-07 17:40:15 +00002992#define SNAPSHOT_LIST 1
2993#define SNAPSHOT_CREATE 2
2994#define SNAPSHOT_APPLY 3
2995#define SNAPSHOT_DELETE 4
2996
Stuart Brady153859b2009-06-07 00:42:17 +01002997static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00002998{
Markus Armbruster26f54e92014-10-07 13:59:04 +02002999 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003000 BlockDriverState *bs;
3001 QEMUSnapshotInfo sn;
3002 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003003 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003004 int action = 0;
3005 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003006 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003007 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003008 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003009 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003010
Kevin Wolfce099542016-03-15 13:01:04 +01003011 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003012 /* Parse commandline parameters */
3013 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003014 static const struct option long_options[] = {
3015 {"help", no_argument, 0, 'h'},
3016 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003017 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003018 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003019 {0, 0, 0, 0}
3020 };
Fam Zheng335e9932017-05-03 00:35:39 +08003021 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003022 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003023 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003024 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003025 }
aliguorif7b4a942009-01-07 17:40:15 +00003026 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003027 case ':':
3028 missing_argument(argv[optind - 1]);
3029 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003030 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003031 unrecognized_option(argv[optind - 1]);
3032 break;
aliguorif7b4a942009-01-07 17:40:15 +00003033 case 'h':
3034 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003035 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003036 case 'l':
3037 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003038 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003039 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003040 }
3041 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003042 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003043 break;
3044 case 'a':
3045 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003046 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003047 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003048 }
3049 action = SNAPSHOT_APPLY;
3050 snapshot_name = optarg;
3051 break;
3052 case 'c':
3053 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003054 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003055 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003056 }
3057 action = SNAPSHOT_CREATE;
3058 snapshot_name = optarg;
3059 break;
3060 case 'd':
3061 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003062 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003063 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003064 }
3065 action = SNAPSHOT_DELETE;
3066 snapshot_name = optarg;
3067 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003068 case 'q':
3069 quiet = true;
3070 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003071 case 'U':
3072 force_share = true;
3073 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003074 case OPTION_OBJECT: {
3075 QemuOpts *opts;
3076 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3077 optarg, true);
3078 if (!opts) {
3079 return 1;
3080 }
3081 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003082 case OPTION_IMAGE_OPTS:
3083 image_opts = true;
3084 break;
aliguorif7b4a942009-01-07 17:40:15 +00003085 }
3086 }
3087
Kevin Wolffc11eb22013-08-05 10:53:04 +02003088 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003089 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003090 }
aliguorif7b4a942009-01-07 17:40:15 +00003091 filename = argv[optind++];
3092
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003093 if (qemu_opts_foreach(&qemu_object_opts,
3094 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003095 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003096 return 1;
3097 }
3098
aliguorif7b4a942009-01-07 17:40:15 +00003099 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003100 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3101 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003102 if (!blk) {
3103 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003104 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003105 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003106
3107 /* Perform the requested action */
3108 switch(action) {
3109 case SNAPSHOT_LIST:
3110 dump_snapshots(bs);
3111 break;
3112
3113 case SNAPSHOT_CREATE:
3114 memset(&sn, 0, sizeof(sn));
3115 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3116
3117 qemu_gettimeofday(&tv);
3118 sn.date_sec = tv.tv_sec;
3119 sn.date_nsec = tv.tv_usec * 1000;
3120
3121 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003122 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003123 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003124 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003125 }
aliguorif7b4a942009-01-07 17:40:15 +00003126 break;
3127
3128 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003129 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003130 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003131 error_reportf_err(err, "Could not apply snapshot '%s': ",
3132 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003133 }
aliguorif7b4a942009-01-07 17:40:15 +00003134 break;
3135
3136 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003137 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3138 if (ret < 0) {
3139 error_report("Could not delete snapshot '%s': snapshot not "
3140 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003141 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003142 } else {
3143 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3144 if (ret < 0) {
3145 error_reportf_err(err, "Could not delete snapshot '%s': ",
3146 snapshot_name);
3147 ret = 1;
3148 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003149 }
aliguorif7b4a942009-01-07 17:40:15 +00003150 break;
3151 }
3152
3153 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003154 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003155 if (ret) {
3156 return 1;
3157 }
Stuart Brady153859b2009-06-07 00:42:17 +01003158 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003159}
3160
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003161static int img_rebase(int argc, char **argv)
3162{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003163 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003164 uint8_t *buf_old = NULL;
3165 uint8_t *buf_new = NULL;
Max Reitzf1d3cd72015-02-05 13:58:18 -05003166 BlockDriverState *bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003167 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003168 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3169 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003170 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003171 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003172 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003173 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003174 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003175 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003176 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003177
3178 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003179 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003180 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003181 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003182 out_baseimg = NULL;
3183 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003184 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003185 static const struct option long_options[] = {
3186 {"help", no_argument, 0, 'h'},
3187 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003188 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003189 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003190 {0, 0, 0, 0}
3191 };
Fam Zheng335e9932017-05-03 00:35:39 +08003192 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003193 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003194 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003195 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003196 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003197 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003198 case ':':
3199 missing_argument(argv[optind - 1]);
3200 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003201 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003202 unrecognized_option(argv[optind - 1]);
3203 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003204 case 'h':
3205 help();
3206 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003207 case 'f':
3208 fmt = optarg;
3209 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003210 case 'F':
3211 out_basefmt = optarg;
3212 break;
3213 case 'b':
3214 out_baseimg = optarg;
3215 break;
3216 case 'u':
3217 unsafe = 1;
3218 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003219 case 'p':
3220 progress = 1;
3221 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003222 case 't':
3223 cache = optarg;
3224 break;
Max Reitz40055952014-07-22 22:58:42 +02003225 case 'T':
3226 src_cache = optarg;
3227 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003228 case 'q':
3229 quiet = true;
3230 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003231 case OPTION_OBJECT: {
3232 QemuOpts *opts;
3233 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3234 optarg, true);
3235 if (!opts) {
3236 return 1;
3237 }
3238 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003239 case OPTION_IMAGE_OPTS:
3240 image_opts = true;
3241 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003242 case 'U':
3243 force_share = true;
3244 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003245 }
3246 }
3247
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003248 if (quiet) {
3249 progress = 0;
3250 }
3251
Fam Zhengac1307a2014-04-22 13:36:11 +08003252 if (optind != argc - 1) {
3253 error_exit("Expecting one image file name");
3254 }
3255 if (!unsafe && !out_baseimg) {
3256 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003257 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003258 filename = argv[optind++];
3259
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003260 if (qemu_opts_foreach(&qemu_object_opts,
3261 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003262 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003263 return 1;
3264 }
3265
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003266 qemu_progress_init(progress, 2.0);
3267 qemu_progress_print(0, 100);
3268
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003269 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003270 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003271 if (ret < 0) {
3272 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003273 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003274 }
3275
Kevin Wolfce099542016-03-15 13:01:04 +01003276 src_flags = 0;
3277 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003278 if (ret < 0) {
3279 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003280 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003281 }
3282
Kevin Wolfce099542016-03-15 13:01:04 +01003283 /* The source files are opened read-only, don't care about WCE */
3284 assert((src_flags & BDRV_O_RDWR) == 0);
3285 (void) src_writethrough;
3286
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003287 /*
3288 * Open the images.
3289 *
3290 * Ignore the old backing file for unsafe rebase in case we want to correct
3291 * the reference to a renamed or moved backing file.
3292 */
Fam Zheng335e9932017-05-03 00:35:39 +08003293 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3294 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003295 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003296 ret = -1;
3297 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003298 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003299 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003300
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003301 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003302 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003303 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003304 ret = -1;
3305 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003306 }
3307 }
3308
3309 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003310 if (!unsafe) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003311 char backing_name[PATH_MAX];
Max Reitz644483d2015-02-05 13:58:17 -05003312 QDict *options = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003313
Max Reitz644483d2015-02-05 13:58:17 -05003314 if (bs->backing_format[0] != '\0') {
3315 options = qdict_new();
Eric Blake46f5ac22017-04-27 16:58:17 -05003316 qdict_put_str(options, "driver", bs->backing_format);
Max Reitz644483d2015-02-05 13:58:17 -05003317 }
3318
Fam Zheng335e9932017-05-03 00:35:39 +08003319 if (force_share) {
3320 if (!options) {
3321 options = qdict_new();
3322 }
Eric Blake579cf1d2017-05-15 14:54:39 -05003323 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +08003324 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003325 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
Max Reitzefaa7c42016-03-16 19:54:38 +01003326 blk_old_backing = blk_new_open(backing_name, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003327 options, src_flags, &local_err);
3328 if (!blk_old_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003329 error_reportf_err(local_err,
3330 "Could not open old backing file '%s': ",
3331 backing_name);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003332 ret = -1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003333 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003334 }
Max Reitz644483d2015-02-05 13:58:17 -05003335
Alex Bligha6166732012-10-16 13:46:18 +01003336 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003337 const char *overlay_filename;
3338 char *out_real_path;
3339
Fam Zheng335e9932017-05-03 00:35:39 +08003340 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003341 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003342 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003343 }
3344 if (force_share) {
3345 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003346 }
3347
Max Reitzf30c66b2019-02-01 20:29:05 +01003348 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003349 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3350 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003351 out_real_path =
3352 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3353 out_baseimg,
3354 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003355 if (local_err) {
3356 error_reportf_err(local_err,
3357 "Could not resolve backing filename: ");
3358 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003359 goto out;
3360 }
3361
3362 blk_new_backing = blk_new_open(out_real_path, NULL,
Max Reitz644483d2015-02-05 13:58:17 -05003363 options, src_flags, &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003364 g_free(out_real_path);
Max Reitz644483d2015-02-05 13:58:17 -05003365 if (!blk_new_backing) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01003366 error_reportf_err(local_err,
3367 "Could not open new backing file '%s': ",
3368 out_baseimg);
Xu Tiane84a0dd2016-10-09 17:17:27 +08003369 ret = -1;
Alex Bligha6166732012-10-16 13:46:18 +01003370 goto out;
3371 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003372 }
3373 }
3374
3375 /*
3376 * Check each unallocated cluster in the COW file. If it is unallocated,
3377 * accesses go to the backing file. We must therefore compare this cluster
3378 * in the old and new backing file, and if they differ we need to copy it
3379 * from the old backing file into the COW file.
3380 *
3381 * If qemu-img crashes during this step, no harm is done. The content of
3382 * the image is the same as the original one at any time.
3383 */
3384 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003385 int64_t size;
3386 int64_t old_backing_size;
3387 int64_t new_backing_size = 0;
3388 uint64_t offset;
3389 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003390 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003391
Max Reitzf1d3cd72015-02-05 13:58:18 -05003392 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3393 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003394
Eric Blake41536282017-10-11 22:47:15 -05003395 size = blk_getlength(blk);
3396 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003397 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003398 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003399 ret = -1;
3400 goto out;
3401 }
Eric Blake41536282017-10-11 22:47:15 -05003402 old_backing_size = blk_getlength(blk_old_backing);
3403 if (old_backing_size < 0) {
Jeff Cody9a29e182015-01-22 08:03:30 -05003404 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003405
3406 bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
3407 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003408 backing_name, strerror(-old_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003409 ret = -1;
3410 goto out;
3411 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003412 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003413 new_backing_size = blk_getlength(blk_new_backing);
3414 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003415 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003416 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003417 ret = -1;
3418 goto out;
3419 }
Alex Bligha6166732012-10-16 13:46:18 +01003420 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003421
Eric Blake41536282017-10-11 22:47:15 -05003422 if (size != 0) {
3423 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003424 }
3425
Eric Blake41536282017-10-11 22:47:15 -05003426 for (offset = 0; offset < size; offset += n) {
3427 /* How many bytes can we handle with the next read? */
3428 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003429
3430 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003431 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003432 if (ret < 0) {
3433 error_report("error while reading image metadata: %s",
3434 strerror(-ret));
3435 goto out;
3436 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003437 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003438 continue;
3439 }
3440
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003441 /*
3442 * Read old and new backing file and take into consideration that
3443 * backing files may be smaller than the COW image.
3444 */
Eric Blake41536282017-10-11 22:47:15 -05003445 if (offset >= old_backing_size) {
3446 memset(buf_old, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003447 } else {
Eric Blake41536282017-10-11 22:47:15 -05003448 if (offset + n > old_backing_size) {
3449 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003450 }
3451
Eric Blake41536282017-10-11 22:47:15 -05003452 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003453 if (ret < 0) {
3454 error_report("error while reading from old backing file");
3455 goto out;
3456 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003457 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003458
Eric Blake41536282017-10-11 22:47:15 -05003459 if (offset >= new_backing_size || !blk_new_backing) {
3460 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003461 } else {
Eric Blake41536282017-10-11 22:47:15 -05003462 if (offset + n > new_backing_size) {
3463 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003464 }
3465
Eric Blake41536282017-10-11 22:47:15 -05003466 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003467 if (ret < 0) {
3468 error_report("error while reading from new backing file");
3469 goto out;
3470 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003471 }
3472
3473 /* If they differ, we need to write to the COW file */
3474 uint64_t written = 0;
3475
Eric Blake41536282017-10-11 22:47:15 -05003476 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003477 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478
Eric Blake41536282017-10-11 22:47:15 -05003479 if (compare_buffers(buf_old + written, buf_new + written,
3480 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003481 {
Eric Blake41536282017-10-11 22:47:15 -05003482 ret = blk_pwrite(blk, offset + written,
Eric Blakedc61cd32017-10-11 22:47:14 -05003483 buf_old + written, pnum, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003484 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003485 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003486 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003487 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003488 }
3489 }
3490
3491 written += pnum;
3492 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003493 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003494 }
3495 }
3496
3497 /*
3498 * Change the backing file. All clusters that are different from the old
3499 * backing file are overwritten in the COW file now, so the visible content
3500 * doesn't change when we switch the backing file.
3501 */
Alex Bligha6166732012-10-16 13:46:18 +01003502 if (out_baseimg && *out_baseimg) {
3503 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3504 } else {
3505 ret = bdrv_change_backing_file(bs, NULL, NULL);
3506 }
3507
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003508 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003509 error_report("Could not change the backing file to '%s': No "
3510 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003511 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003512 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003513 out_baseimg, strerror(-ret));
3514 }
3515
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003516 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003517 /*
3518 * TODO At this point it is possible to check if any clusters that are
3519 * allocated in the COW file are the same in the backing file. If so, they
3520 * could be dropped from the COW file. Don't do this before switching the
3521 * backing file, in case of a crash this would lead to corruption.
3522 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003523out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003524 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003525 /* Cleanup */
3526 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003527 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003528 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003529 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003530 qemu_vfree(buf_old);
3531 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532
Markus Armbruster26f54e92014-10-07 13:59:04 +02003533 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003534 if (ret) {
3535 return 1;
3536 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003537 return 0;
3538}
3539
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003540static int img_resize(int argc, char **argv)
3541{
Markus Armbruster6750e792015-02-12 17:43:08 +01003542 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003543 int c, ret, relative;
3544 const char *filename, *fmt, *size;
Max Reitz5279b302018-04-21 18:39:57 +02003545 int64_t n, total_size, current_size, new_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003546 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003547 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003548 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003549 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003550
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003551 static QemuOptsList resize_options = {
3552 .name = "resize_options",
3553 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3554 .desc = {
3555 {
3556 .name = BLOCK_OPT_SIZE,
3557 .type = QEMU_OPT_SIZE,
3558 .help = "Virtual disk size"
3559 }, {
3560 /* end of list */
3561 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003562 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003563 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003564 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003565 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003566
Kevin Wolfe80fec72011-04-29 10:58:12 +02003567 /* Remove size from argv manually so that negative numbers are not treated
3568 * as options by getopt. */
3569 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003570 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003571 return 1;
3572 }
3573
3574 size = argv[--argc];
3575
3576 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003577 fmt = NULL;
3578 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003579 static const struct option long_options[] = {
3580 {"help", no_argument, 0, 'h'},
3581 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003582 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003583 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003584 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003585 {0, 0, 0, 0}
3586 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003587 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003588 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003589 if (c == -1) {
3590 break;
3591 }
3592 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003593 case ':':
3594 missing_argument(argv[optind - 1]);
3595 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003596 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003597 unrecognized_option(argv[optind - 1]);
3598 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003599 case 'h':
3600 help();
3601 break;
3602 case 'f':
3603 fmt = optarg;
3604 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003605 case 'q':
3606 quiet = true;
3607 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003608 case OPTION_OBJECT: {
3609 QemuOpts *opts;
3610 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3611 optarg, true);
3612 if (!opts) {
3613 return 1;
3614 }
3615 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003616 case OPTION_IMAGE_OPTS:
3617 image_opts = true;
3618 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003619 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003620 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003621 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003622 if (prealloc == PREALLOC_MODE__MAX) {
3623 error_report("Invalid preallocation mode '%s'", optarg);
3624 return 1;
3625 }
3626 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003627 case OPTION_SHRINK:
3628 shrink = true;
3629 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003630 }
3631 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003632 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003633 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003634 }
3635 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003636
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003637 if (qemu_opts_foreach(&qemu_object_opts,
3638 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003639 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003640 return 1;
3641 }
3642
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003643 /* Choose grow, shrink, or absolute resize mode */
3644 switch (size[0]) {
3645 case '+':
3646 relative = 1;
3647 size++;
3648 break;
3649 case '-':
3650 relative = -1;
3651 size++;
3652 break;
3653 default:
3654 relative = 0;
3655 break;
3656 }
3657
3658 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003659 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003660 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003661 if (err) {
3662 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003663 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003664 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003665 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003666 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003667 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3668 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003669
Max Reitzefaa7c42016-03-16 19:54:38 +01003670 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003671 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3672 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003673 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003674 ret = -1;
3675 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003676 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003677
Max Reitzdc5f6902017-06-13 22:20:55 +02003678 current_size = blk_getlength(blk);
3679 if (current_size < 0) {
3680 error_report("Failed to inquire current image length: %s",
3681 strerror(-current_size));
3682 ret = -1;
3683 goto out;
3684 }
3685
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003686 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003687 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003688 } else {
3689 total_size = n;
3690 }
3691 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003692 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003693 ret = -1;
3694 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003695 }
3696
Max Reitzdc5f6902017-06-13 22:20:55 +02003697 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3698 error_report("Preallocation can only be used for growing images");
3699 ret = -1;
3700 goto out;
3701 }
3702
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003703 if (total_size < current_size && !shrink) {
3704 warn_report("Shrinking an image will delete all data beyond the "
3705 "shrunken image's end. Before performing such an "
3706 "operation, make sure there is no important data there.");
3707
3708 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3709 error_report(
3710 "Use the --shrink option to perform a shrink operation.");
3711 ret = -1;
3712 goto out;
3713 } else {
3714 warn_report("Using the --shrink option will suppress this message. "
3715 "Note that future versions of qemu-img may refuse to "
3716 "shrink images without this option.");
3717 }
3718 }
3719
Max Reitzdc5f6902017-06-13 22:20:55 +02003720 ret = blk_truncate(blk, total_size, prealloc, &err);
Max Reitz5279b302018-04-21 18:39:57 +02003721 if (ret < 0) {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003722 error_report_err(err);
Max Reitz5279b302018-04-21 18:39:57 +02003723 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003724 }
Max Reitz5279b302018-04-21 18:39:57 +02003725
3726 new_size = blk_getlength(blk);
3727 if (new_size < 0) {
3728 error_report("Failed to verify truncated image length: %s",
3729 strerror(-new_size));
3730 ret = -1;
3731 goto out;
3732 }
3733
3734 /* Some block drivers implement a truncation method, but only so
3735 * the user can cause qemu to refresh the image's size from disk.
3736 * The idea is that the user resizes the image outside of qemu and
3737 * then invokes block_resize to inform qemu about it.
3738 * (This includes iscsi and file-posix for device files.)
3739 * Of course, that is not the behavior someone invoking
3740 * qemu-img resize would find useful, so we catch that behavior
3741 * here and tell the user. */
3742 if (new_size != total_size && new_size == current_size) {
3743 error_report("Image was not resized; resizing may not be supported "
3744 "for this image");
3745 ret = -1;
3746 goto out;
3747 }
3748
3749 if (new_size != total_size) {
3750 warn_report("Image should have been resized to %" PRIi64
3751 " bytes, but was resized to %" PRIi64 " bytes",
3752 total_size, new_size);
3753 }
3754
3755 qprintf(quiet, "Image resized.\n");
3756
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003757out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003758 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003759 if (ret) {
3760 return 1;
3761 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003762 return 0;
3763}
3764
Max Reitz76a3a342014-10-27 11:12:51 +01003765static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003766 int64_t offset, int64_t total_work_size,
3767 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003768{
3769 qemu_progress_print(100.f * offset / total_work_size, 0);
3770}
3771
Max Reitz51641352018-05-09 23:00:20 +02003772static int print_amend_option_help(const char *format)
3773{
3774 BlockDriver *drv;
3775
3776 /* Find driver and parse its options */
3777 drv = bdrv_find_format(format);
3778 if (!drv) {
3779 error_report("Unknown file format '%s'", format);
3780 return 1;
3781 }
3782
3783 if (!drv->bdrv_amend_options) {
3784 error_report("Format driver '%s' does not support option amendment",
3785 format);
3786 return 1;
3787 }
3788
3789 /* Every driver supporting amendment must have create_opts */
3790 assert(drv->create_opts);
3791
3792 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003793 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003794 printf("\nNote that not all of these options may be amendable.\n");
3795 return 0;
3796}
3797
Max Reitz6f176b42013-09-03 10:09:50 +02003798static int img_amend(int argc, char **argv)
3799{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003800 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003801 int c, ret = 0;
3802 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003803 QemuOptsList *create_opts = NULL;
3804 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003805 const char *fmt = NULL, *filename, *cache;
3806 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003807 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003808 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003809 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003810 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003811 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003812
Max Reitzbd39e6e2014-07-22 22:58:43 +02003813 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003814 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003815 static const struct option long_options[] = {
3816 {"help", no_argument, 0, 'h'},
3817 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003818 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003819 {0, 0, 0, 0}
3820 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003821 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003822 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003823 if (c == -1) {
3824 break;
3825 }
3826
3827 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003828 case ':':
3829 missing_argument(argv[optind - 1]);
3830 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003831 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003832 unrecognized_option(argv[optind - 1]);
3833 break;
3834 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003835 help();
3836 break;
3837 case 'o':
3838 if (!is_valid_option_list(optarg)) {
3839 error_report("Invalid option list: %s", optarg);
3840 ret = -1;
3841 goto out_no_progress;
3842 }
3843 if (!options) {
3844 options = g_strdup(optarg);
3845 } else {
3846 char *old_options = options;
3847 options = g_strdup_printf("%s,%s", options, optarg);
3848 g_free(old_options);
3849 }
3850 break;
3851 case 'f':
3852 fmt = optarg;
3853 break;
3854 case 't':
3855 cache = optarg;
3856 break;
3857 case 'p':
3858 progress = true;
3859 break;
3860 case 'q':
3861 quiet = true;
3862 break;
3863 case OPTION_OBJECT:
3864 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3865 optarg, true);
3866 if (!opts) {
3867 ret = -1;
3868 goto out_no_progress;
3869 }
3870 break;
3871 case OPTION_IMAGE_OPTS:
3872 image_opts = true;
3873 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003874 }
3875 }
3876
Max Reitz6f176b42013-09-03 10:09:50 +02003877 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003878 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003879 }
3880
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003881 if (qemu_opts_foreach(&qemu_object_opts,
3882 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00003883 NULL, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003884 ret = -1;
3885 goto out_no_progress;
3886 }
3887
Max Reitz76a3a342014-10-27 11:12:51 +01003888 if (quiet) {
3889 progress = false;
3890 }
3891 qemu_progress_init(progress, 1.0);
3892
Kevin Wolfa283cb62014-02-21 16:24:07 +01003893 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
3894 if (fmt && has_help_option(options)) {
3895 /* If a format is explicitly specified (and possibly no filename is
3896 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003897 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01003898 goto out;
3899 }
3900
3901 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01003902 error_report("Expecting one image file name");
3903 ret = -1;
3904 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01003905 }
Max Reitz6f176b42013-09-03 10:09:50 +02003906
Kevin Wolfce099542016-03-15 13:01:04 +01003907 flags = BDRV_O_RDWR;
3908 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02003909 if (ret < 0) {
3910 error_report("Invalid cache option: %s", cache);
3911 goto out;
3912 }
3913
Fam Zheng335e9932017-05-03 00:35:39 +08003914 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3915 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003916 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02003917 ret = -1;
3918 goto out;
3919 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003920 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02003921
3922 fmt = bs->drv->format_name;
3923
Kevin Wolf626f84f2014-02-21 16:24:06 +01003924 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01003925 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02003926 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02003927 goto out;
3928 }
3929
Max Reitz1f996682018-05-09 23:00:17 +02003930 if (!bs->drv->bdrv_amend_options) {
3931 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01003932 fmt);
3933 ret = -1;
3934 goto out;
3935 }
3936
Max Reitz1f996682018-05-09 23:00:17 +02003937 /* Every driver supporting amendment must have create_opts */
3938 assert(bs->drv->create_opts);
3939
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003940 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08003941 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01003942 qemu_opts_do_parse(opts, options, NULL, &err);
3943 if (err) {
3944 error_report_err(err);
3945 ret = -1;
3946 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02003947 }
3948
Max Reitz76a3a342014-10-27 11:12:51 +01003949 /* In case the driver does not call amend_status_cb() */
3950 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02003951 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01003952 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02003953 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02003954 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02003955 goto out;
3956 }
3957
3958out:
Max Reitz76a3a342014-10-27 11:12:51 +01003959 qemu_progress_end();
3960
Max Reitze814dff2015-08-20 16:00:38 -07003961out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003962 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08003963 qemu_opts_del(opts);
3964 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01003965 g_free(options);
3966
Max Reitz6f176b42013-09-03 10:09:50 +02003967 if (ret) {
3968 return 1;
3969 }
3970 return 0;
3971}
3972
Kevin Wolfb6133b82014-08-05 14:17:13 +02003973typedef struct BenchData {
3974 BlockBackend *blk;
3975 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02003976 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003977 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02003978 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003979 int nrreq;
3980 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003981 int flush_interval;
3982 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003983 uint8_t *buf;
3984 QEMUIOVector *qiov;
3985
3986 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02003987 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02003988 uint64_t offset;
3989} BenchData;
3990
Kevin Wolf55d539c2016-06-03 13:59:41 +02003991static void bench_undrained_flush_cb(void *opaque, int ret)
3992{
3993 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02003994 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02003995 exit(EXIT_FAILURE);
3996 }
3997}
3998
Kevin Wolfb6133b82014-08-05 14:17:13 +02003999static void bench_cb(void *opaque, int ret)
4000{
4001 BenchData *b = opaque;
4002 BlockAIOCB *acb;
4003
4004 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004005 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004006 exit(EXIT_FAILURE);
4007 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004008
4009 if (b->in_flush) {
4010 /* Just finished a flush with drained queue: Start next requests */
4011 assert(b->in_flight == 0);
4012 b->in_flush = false;
4013 } else if (b->in_flight > 0) {
4014 int remaining = b->n - b->in_flight;
4015
Kevin Wolfb6133b82014-08-05 14:17:13 +02004016 b->n--;
4017 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004018
4019 /* Time for flush? Drain queue if requested, then flush */
4020 if (b->flush_interval && remaining % b->flush_interval == 0) {
4021 if (!b->in_flight || !b->drain_on_flush) {
4022 BlockCompletionFunc *cb;
4023
4024 if (b->drain_on_flush) {
4025 b->in_flush = true;
4026 cb = bench_cb;
4027 } else {
4028 cb = bench_undrained_flush_cb;
4029 }
4030
4031 acb = blk_aio_flush(b->blk, cb, b);
4032 if (!acb) {
4033 error_report("Failed to issue flush request");
4034 exit(EXIT_FAILURE);
4035 }
4036 }
4037 if (b->drain_on_flush) {
4038 return;
4039 }
4040 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004041 }
4042
4043 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004044 int64_t offset = b->offset;
4045 /* blk_aio_* might look for completed I/Os and kick bench_cb
4046 * again, so make sure this operation is counted by in_flight
4047 * and b->offset is ready for the next submission.
4048 */
4049 b->in_flight++;
4050 b->offset += b->step;
4051 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004052 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004053 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004054 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004055 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004056 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004057 if (!acb) {
4058 error_report("Failed to issue request");
4059 exit(EXIT_FAILURE);
4060 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004061 }
4062}
4063
4064static int img_bench(int argc, char **argv)
4065{
4066 int c, ret = 0;
4067 const char *fmt = NULL, *filename;
4068 bool quiet = false;
4069 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004070 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004071 int count = 75000;
4072 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004073 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004074 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004075 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004076 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004077 int flush_interval = 0;
4078 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004079 int64_t image_size;
4080 BlockBackend *blk = NULL;
4081 BenchData data = {};
4082 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004083 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004084 struct timeval t1, t2;
4085 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004086 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004087 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004088
4089 for (;;) {
4090 static const struct option long_options[] = {
4091 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004092 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004093 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004094 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004095 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004096 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004097 {0, 0, 0, 0}
4098 };
Fam Zheng335e9932017-05-03 00:35:39 +08004099 c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004100 if (c == -1) {
4101 break;
4102 }
4103
4104 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004105 case ':':
4106 missing_argument(argv[optind - 1]);
4107 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004108 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004109 unrecognized_option(argv[optind - 1]);
4110 break;
4111 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004112 help();
4113 break;
4114 case 'c':
4115 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004116 unsigned long res;
4117
4118 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004119 error_report("Invalid request count specified");
4120 return 1;
4121 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004122 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004123 break;
4124 }
4125 case 'd':
4126 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004127 unsigned long res;
4128
4129 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004130 error_report("Invalid queue depth specified");
4131 return 1;
4132 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004133 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004134 break;
4135 }
4136 case 'f':
4137 fmt = optarg;
4138 break;
4139 case 'n':
4140 flags |= BDRV_O_NATIVE_AIO;
4141 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004142 case 'o':
4143 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004144 offset = cvtnum(optarg);
4145 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004146 error_report("Invalid offset specified");
4147 return 1;
4148 }
4149 break;
4150 }
4151 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152 case 'q':
4153 quiet = true;
4154 break;
4155 case 's':
4156 {
4157 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004158
Markus Armbruster606caa02017-02-21 21:14:04 +01004159 sval = cvtnum(optarg);
4160 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004161 error_report("Invalid buffer size specified");
4162 return 1;
4163 }
4164
4165 bufsize = sval;
4166 break;
4167 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004168 case 'S':
4169 {
4170 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004171
Markus Armbruster606caa02017-02-21 21:14:04 +01004172 sval = cvtnum(optarg);
4173 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004174 error_report("Invalid step size specified");
4175 return 1;
4176 }
4177
4178 step = sval;
4179 break;
4180 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004181 case 't':
4182 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4183 if (ret < 0) {
4184 error_report("Invalid cache mode");
4185 ret = -1;
4186 goto out;
4187 }
4188 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004189 case 'w':
4190 flags |= BDRV_O_RDWR;
4191 is_write = true;
4192 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004193 case 'U':
4194 force_share = true;
4195 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004196 case OPTION_PATTERN:
4197 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004198 unsigned long res;
4199
4200 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004201 error_report("Invalid pattern byte specified");
4202 return 1;
4203 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004204 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004205 break;
4206 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004207 case OPTION_FLUSH_INTERVAL:
4208 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004209 unsigned long res;
4210
4211 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004212 error_report("Invalid flush interval specified");
4213 return 1;
4214 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004215 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004216 break;
4217 }
4218 case OPTION_NO_DRAIN:
4219 drain_on_flush = false;
4220 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004221 case OPTION_IMAGE_OPTS:
4222 image_opts = true;
4223 break;
4224 }
4225 }
4226
4227 if (optind != argc - 1) {
4228 error_exit("Expecting one image file name");
4229 }
4230 filename = argv[argc - 1];
4231
Kevin Wolf55d539c2016-06-03 13:59:41 +02004232 if (!is_write && flush_interval) {
4233 error_report("--flush-interval is only available in write tests");
4234 ret = -1;
4235 goto out;
4236 }
4237 if (flush_interval && flush_interval < depth) {
4238 error_report("Flush interval can't be smaller than depth");
4239 ret = -1;
4240 goto out;
4241 }
4242
Fam Zheng335e9932017-05-03 00:35:39 +08004243 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4244 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004245 if (!blk) {
4246 ret = -1;
4247 goto out;
4248 }
4249
4250 image_size = blk_getlength(blk);
4251 if (image_size < 0) {
4252 ret = image_size;
4253 goto out;
4254 }
4255
4256 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004257 .blk = blk,
4258 .image_size = image_size,
4259 .bufsize = bufsize,
4260 .step = step ?: bufsize,
4261 .nrreq = depth,
4262 .n = count,
4263 .offset = offset,
4264 .write = is_write,
4265 .flush_interval = flush_interval,
4266 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004267 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004268 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004269 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004270 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004271 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004272 if (flush_interval) {
4273 printf("Sending flush every %d requests\n", flush_interval);
4274 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004275
Fam Zheng79d46582018-01-16 14:08:58 +08004276 buf_size = data.nrreq * data.bufsize;
4277 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004278 memset(data.buf, pattern, data.nrreq * data.bufsize);
4279
Fam Zheng79d46582018-01-16 14:08:58 +08004280 blk_register_buf(blk, data.buf, buf_size);
4281
Kevin Wolfb6133b82014-08-05 14:17:13 +02004282 data.qiov = g_new(QEMUIOVector, data.nrreq);
4283 for (i = 0; i < data.nrreq; i++) {
4284 qemu_iovec_init(&data.qiov[i], 1);
4285 qemu_iovec_add(&data.qiov[i],
4286 data.buf + i * data.bufsize, data.bufsize);
4287 }
4288
4289 gettimeofday(&t1, NULL);
4290 bench_cb(&data, 0);
4291
4292 while (data.n > 0) {
4293 main_loop_wait(false);
4294 }
4295 gettimeofday(&t2, NULL);
4296
4297 printf("Run completed in %3.3f seconds.\n",
4298 (t2.tv_sec - t1.tv_sec)
4299 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4300
4301out:
Fam Zheng79d46582018-01-16 14:08:58 +08004302 if (data.buf) {
4303 blk_unregister_buf(blk, data.buf);
4304 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004305 qemu_vfree(data.buf);
4306 blk_unref(blk);
4307
4308 if (ret) {
4309 return 1;
4310 }
4311 return 0;
4312}
4313
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004314#define C_BS 01
4315#define C_COUNT 02
4316#define C_IF 04
4317#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004318#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004319
4320struct DdInfo {
4321 unsigned int flags;
4322 int64_t count;
4323};
4324
4325struct DdIo {
4326 int bsz; /* Block size */
4327 char *filename;
4328 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004329 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004330};
4331
4332struct DdOpts {
4333 const char *name;
4334 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4335 unsigned int flag;
4336};
4337
4338static int img_dd_bs(const char *arg,
4339 struct DdIo *in, struct DdIo *out,
4340 struct DdInfo *dd)
4341{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004342 int64_t res;
4343
Markus Armbruster606caa02017-02-21 21:14:04 +01004344 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004345
Markus Armbruster606caa02017-02-21 21:14:04 +01004346 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004347 error_report("invalid number: '%s'", arg);
4348 return 1;
4349 }
4350 in->bsz = out->bsz = res;
4351
4352 return 0;
4353}
4354
4355static int img_dd_count(const char *arg,
4356 struct DdIo *in, struct DdIo *out,
4357 struct DdInfo *dd)
4358{
Markus Armbruster606caa02017-02-21 21:14:04 +01004359 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004360
Markus Armbruster606caa02017-02-21 21:14:04 +01004361 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004362 error_report("invalid number: '%s'", arg);
4363 return 1;
4364 }
4365
4366 return 0;
4367}
4368
4369static int img_dd_if(const char *arg,
4370 struct DdIo *in, struct DdIo *out,
4371 struct DdInfo *dd)
4372{
4373 in->filename = g_strdup(arg);
4374
4375 return 0;
4376}
4377
4378static int img_dd_of(const char *arg,
4379 struct DdIo *in, struct DdIo *out,
4380 struct DdInfo *dd)
4381{
4382 out->filename = g_strdup(arg);
4383
4384 return 0;
4385}
4386
Reda Sallahif7c15532016-08-10 16:16:09 +02004387static int img_dd_skip(const char *arg,
4388 struct DdIo *in, struct DdIo *out,
4389 struct DdInfo *dd)
4390{
Markus Armbruster606caa02017-02-21 21:14:04 +01004391 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004392
Markus Armbruster606caa02017-02-21 21:14:04 +01004393 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004394 error_report("invalid number: '%s'", arg);
4395 return 1;
4396 }
4397
4398 return 0;
4399}
4400
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004401static int img_dd(int argc, char **argv)
4402{
4403 int ret = 0;
4404 char *arg = NULL;
4405 char *tmp;
4406 BlockDriver *drv = NULL, *proto_drv = NULL;
4407 BlockBackend *blk1 = NULL, *blk2 = NULL;
4408 QemuOpts *opts = NULL;
4409 QemuOptsList *create_opts = NULL;
4410 Error *local_err = NULL;
4411 bool image_opts = false;
4412 int c, i;
4413 const char *out_fmt = "raw";
4414 const char *fmt = NULL;
4415 int64_t size = 0;
4416 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004417 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004418 struct DdInfo dd = {
4419 .flags = 0,
4420 .count = 0,
4421 };
4422 struct DdIo in = {
4423 .bsz = 512, /* Block size is by default 512 bytes */
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 struct DdIo out = {
4429 .bsz = 512,
4430 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004431 .buf = NULL,
4432 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004433 };
4434
4435 const struct DdOpts options[] = {
4436 { "bs", img_dd_bs, C_BS },
4437 { "count", img_dd_count, C_COUNT },
4438 { "if", img_dd_if, C_IF },
4439 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004440 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004441 { NULL, NULL, 0 }
4442 };
4443 const struct option long_options[] = {
4444 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004445 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004446 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004447 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004448 { 0, 0, 0, 0 }
4449 };
4450
Fam Zheng335e9932017-05-03 00:35:39 +08004451 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004452 if (c == EOF) {
4453 break;
4454 }
4455 switch (c) {
4456 case 'O':
4457 out_fmt = optarg;
4458 break;
4459 case 'f':
4460 fmt = optarg;
4461 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004462 case ':':
4463 missing_argument(argv[optind - 1]);
4464 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004465 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004466 unrecognized_option(argv[optind - 1]);
4467 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004468 case 'h':
4469 help();
4470 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004471 case 'U':
4472 force_share = true;
4473 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004474 case OPTION_OBJECT:
4475 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004476 ret = -1;
4477 goto out;
4478 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004479 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004480 case OPTION_IMAGE_OPTS:
4481 image_opts = true;
4482 break;
4483 }
4484 }
4485
4486 for (i = optind; i < argc; i++) {
4487 int j;
4488 arg = g_strdup(argv[i]);
4489
4490 tmp = strchr(arg, '=');
4491 if (tmp == NULL) {
4492 error_report("unrecognized operand %s", arg);
4493 ret = -1;
4494 goto out;
4495 }
4496
4497 *tmp++ = '\0';
4498
4499 for (j = 0; options[j].name != NULL; j++) {
4500 if (!strcmp(arg, options[j].name)) {
4501 break;
4502 }
4503 }
4504 if (options[j].name == NULL) {
4505 error_report("unrecognized operand %s", arg);
4506 ret = -1;
4507 goto out;
4508 }
4509
4510 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4511 ret = -1;
4512 goto out;
4513 }
4514 dd.flags |= options[j].flag;
4515 g_free(arg);
4516 arg = NULL;
4517 }
4518
4519 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4520 error_report("Must specify both input and output files");
4521 ret = -1;
4522 goto out;
4523 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004524
4525 if (qemu_opts_foreach(&qemu_object_opts,
4526 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004527 NULL, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004528 ret = -1;
4529 goto out;
4530 }
4531
Fam Zheng335e9932017-05-03 00:35:39 +08004532 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4533 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004534
4535 if (!blk1) {
4536 ret = -1;
4537 goto out;
4538 }
4539
4540 drv = bdrv_find_format(out_fmt);
4541 if (!drv) {
4542 error_report("Unknown file format");
4543 ret = -1;
4544 goto out;
4545 }
4546 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4547
4548 if (!proto_drv) {
4549 error_report_err(local_err);
4550 ret = -1;
4551 goto out;
4552 }
4553 if (!drv->create_opts) {
4554 error_report("Format driver '%s' does not support image creation",
4555 drv->format_name);
4556 ret = -1;
4557 goto out;
4558 }
4559 if (!proto_drv->create_opts) {
4560 error_report("Protocol driver '%s' does not support image creation",
4561 proto_drv->format_name);
4562 ret = -1;
4563 goto out;
4564 }
4565 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4566 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4567
4568 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4569
4570 size = blk_getlength(blk1);
4571 if (size < 0) {
4572 error_report("Failed to get size for '%s'", in.filename);
4573 ret = -1;
4574 goto out;
4575 }
4576
4577 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4578 dd.count * in.bsz < size) {
4579 size = dd.count * in.bsz;
4580 }
4581
Reda Sallahif7c15532016-08-10 16:16:09 +02004582 /* Overflow means the specified offset is beyond input image's size */
4583 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4584 size < in.bsz * in.offset)) {
4585 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4586 } else {
4587 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4588 size - in.bsz * in.offset, &error_abort);
4589 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004590
4591 ret = bdrv_create(drv, out.filename, opts, &local_err);
4592 if (ret < 0) {
4593 error_reportf_err(local_err,
4594 "%s: error while creating output image: ",
4595 out.filename);
4596 ret = -1;
4597 goto out;
4598 }
4599
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004600 /* TODO, we can't honour --image-opts for the target,
4601 * since it needs to be given in a format compatible
4602 * with the bdrv_create() call above which does not
4603 * support image-opts style.
4604 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004605 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004606 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004607
4608 if (!blk2) {
4609 ret = -1;
4610 goto out;
4611 }
4612
Reda Sallahif7c15532016-08-10 16:16:09 +02004613 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4614 size < in.offset * in.bsz)) {
4615 /* We give a warning if the skip option is bigger than the input
4616 * size and create an empty output disk image (i.e. like dd(1)).
4617 */
4618 error_report("%s: cannot skip to specified offset", in.filename);
4619 in_pos = size;
4620 } else {
4621 in_pos = in.offset * in.bsz;
4622 }
4623
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004624 in.buf = g_new(uint8_t, in.bsz);
4625
Reda Sallahif7c15532016-08-10 16:16:09 +02004626 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004627 int in_ret, out_ret;
4628
4629 if (in_pos + in.bsz > size) {
4630 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4631 } else {
4632 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4633 }
4634 if (in_ret < 0) {
4635 error_report("error while reading from input image file: %s",
4636 strerror(-in_ret));
4637 ret = -1;
4638 goto out;
4639 }
4640 in_pos += in_ret;
4641
4642 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4643
4644 if (out_ret < 0) {
4645 error_report("error while writing to output image file: %s",
4646 strerror(-out_ret));
4647 ret = -1;
4648 goto out;
4649 }
4650 out_pos += out_ret;
4651 }
4652
4653out:
4654 g_free(arg);
4655 qemu_opts_del(opts);
4656 qemu_opts_free(create_opts);
4657 blk_unref(blk1);
4658 blk_unref(blk2);
4659 g_free(in.filename);
4660 g_free(out.filename);
4661 g_free(in.buf);
4662 g_free(out.buf);
4663
4664 if (ret) {
4665 return 1;
4666 }
4667 return 0;
4668}
4669
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004670static void dump_json_block_measure_info(BlockMeasureInfo *info)
4671{
4672 QString *str;
4673 QObject *obj;
4674 Visitor *v = qobject_output_visitor_new(&obj);
4675
4676 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4677 visit_complete(v, &obj);
4678 str = qobject_to_json_pretty(obj);
4679 assert(str != NULL);
4680 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004681 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004682 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004683 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004684}
4685
4686static int img_measure(int argc, char **argv)
4687{
4688 static const struct option long_options[] = {
4689 {"help", no_argument, 0, 'h'},
4690 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4691 {"object", required_argument, 0, OPTION_OBJECT},
4692 {"output", required_argument, 0, OPTION_OUTPUT},
4693 {"size", required_argument, 0, OPTION_SIZE},
4694 {"force-share", no_argument, 0, 'U'},
4695 {0, 0, 0, 0}
4696 };
4697 OutputFormat output_format = OFORMAT_HUMAN;
4698 BlockBackend *in_blk = NULL;
4699 BlockDriver *drv;
4700 const char *filename = NULL;
4701 const char *fmt = NULL;
4702 const char *out_fmt = "raw";
4703 char *options = NULL;
4704 char *snapshot_name = NULL;
4705 bool force_share = false;
4706 QemuOpts *opts = NULL;
4707 QemuOpts *object_opts = NULL;
4708 QemuOpts *sn_opts = NULL;
4709 QemuOptsList *create_opts = NULL;
4710 bool image_opts = false;
4711 uint64_t img_size = UINT64_MAX;
4712 BlockMeasureInfo *info = NULL;
4713 Error *local_err = NULL;
4714 int ret = 1;
4715 int c;
4716
4717 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4718 long_options, NULL)) != -1) {
4719 switch (c) {
4720 case '?':
4721 case 'h':
4722 help();
4723 break;
4724 case 'f':
4725 fmt = optarg;
4726 break;
4727 case 'O':
4728 out_fmt = optarg;
4729 break;
4730 case 'o':
4731 if (!is_valid_option_list(optarg)) {
4732 error_report("Invalid option list: %s", optarg);
4733 goto out;
4734 }
4735 if (!options) {
4736 options = g_strdup(optarg);
4737 } else {
4738 char *old_options = options;
4739 options = g_strdup_printf("%s,%s", options, optarg);
4740 g_free(old_options);
4741 }
4742 break;
4743 case 'l':
4744 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4745 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4746 optarg, false);
4747 if (!sn_opts) {
4748 error_report("Failed in parsing snapshot param '%s'",
4749 optarg);
4750 goto out;
4751 }
4752 } else {
4753 snapshot_name = optarg;
4754 }
4755 break;
4756 case 'U':
4757 force_share = true;
4758 break;
4759 case OPTION_OBJECT:
4760 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4761 optarg, true);
4762 if (!object_opts) {
4763 goto out;
4764 }
4765 break;
4766 case OPTION_IMAGE_OPTS:
4767 image_opts = true;
4768 break;
4769 case OPTION_OUTPUT:
4770 if (!strcmp(optarg, "json")) {
4771 output_format = OFORMAT_JSON;
4772 } else if (!strcmp(optarg, "human")) {
4773 output_format = OFORMAT_HUMAN;
4774 } else {
4775 error_report("--output must be used with human or json "
4776 "as argument.");
4777 goto out;
4778 }
4779 break;
4780 case OPTION_SIZE:
4781 {
4782 int64_t sval;
4783
4784 sval = cvtnum(optarg);
4785 if (sval < 0) {
4786 if (sval == -ERANGE) {
4787 error_report("Image size must be less than 8 EiB!");
4788 } else {
4789 error_report("Invalid image size specified! You may use "
4790 "k, M, G, T, P or E suffixes for ");
4791 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4792 "petabytes and exabytes.");
4793 }
4794 goto out;
4795 }
4796 img_size = (uint64_t)sval;
4797 }
4798 break;
4799 }
4800 }
4801
4802 if (qemu_opts_foreach(&qemu_object_opts,
4803 user_creatable_add_opts_foreach,
Daniel P. Berrangé334c43e2019-02-19 11:46:09 +00004804 NULL, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004805 goto out;
4806 }
4807
4808 if (argc - optind > 1) {
4809 error_report("At most one filename argument is allowed.");
4810 goto out;
4811 } else if (argc - optind == 1) {
4812 filename = argv[optind];
4813 }
4814
4815 if (!filename &&
4816 (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
4817 error_report("--object, --image-opts, -f, and -l "
4818 "require a filename argument.");
4819 goto out;
4820 }
4821 if (filename && img_size != UINT64_MAX) {
4822 error_report("--size N cannot be used together with a filename.");
4823 goto out;
4824 }
4825 if (!filename && img_size == UINT64_MAX) {
4826 error_report("Either --size N or one filename must be specified.");
4827 goto out;
4828 }
4829
4830 if (filename) {
4831 in_blk = img_open(image_opts, filename, fmt, 0,
4832 false, false, force_share);
4833 if (!in_blk) {
4834 goto out;
4835 }
4836
4837 if (sn_opts) {
4838 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4839 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4840 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4841 &local_err);
4842 } else if (snapshot_name != NULL) {
4843 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4844 snapshot_name, &local_err);
4845 }
4846 if (local_err) {
4847 error_reportf_err(local_err, "Failed to load snapshot: ");
4848 goto out;
4849 }
4850 }
4851
4852 drv = bdrv_find_format(out_fmt);
4853 if (!drv) {
4854 error_report("Unknown file format '%s'", out_fmt);
4855 goto out;
4856 }
4857 if (!drv->create_opts) {
4858 error_report("Format driver '%s' does not support image creation",
4859 drv->format_name);
4860 goto out;
4861 }
4862
4863 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4864 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4865 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4866 if (options) {
4867 qemu_opts_do_parse(opts, options, NULL, &local_err);
4868 if (local_err) {
4869 error_report_err(local_err);
4870 error_report("Invalid options for file format '%s'", out_fmt);
4871 goto out;
4872 }
4873 }
4874 if (img_size != UINT64_MAX) {
4875 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4876 }
4877
4878 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4879 if (local_err) {
4880 error_report_err(local_err);
4881 goto out;
4882 }
4883
4884 if (output_format == OFORMAT_HUMAN) {
4885 printf("required size: %" PRIu64 "\n", info->required);
4886 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
4887 } else {
4888 dump_json_block_measure_info(info);
4889 }
4890
4891 ret = 0;
4892
4893out:
4894 qapi_free_BlockMeasureInfo(info);
4895 qemu_opts_del(object_opts);
4896 qemu_opts_del(opts);
4897 qemu_opts_del(sn_opts);
4898 qemu_opts_free(create_opts);
4899 g_free(options);
4900 blk_unref(in_blk);
4901 return ret;
4902}
Kevin Wolfb6133b82014-08-05 14:17:13 +02004903
Anthony Liguoric227f092009-10-01 16:12:16 -05004904static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01004905#define DEF(option, callback, arg_string) \
4906 { option, callback },
4907#include "qemu-img-cmds.h"
4908#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01004909 { NULL, NULL, },
4910};
4911
bellardea2384d2004-08-01 21:59:26 +00004912int main(int argc, char **argv)
4913{
Anthony Liguoric227f092009-10-01 16:12:16 -05004914 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01004915 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004916 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004917 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04004918 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04004919 static const struct option long_options[] = {
4920 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03004921 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004922 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04004923 {0, 0, 0, 0}
4924 };
bellardea2384d2004-08-01 21:59:26 +00004925
MORITA Kazutaka526eda12013-07-23 17:30:11 +09004926#ifdef CONFIG_POSIX
4927 signal(SIGPIPE, SIG_IGN);
4928#endif
4929
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01004930 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01004931 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08004932 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01004933
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004934 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01004935 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03004936 exit(EXIT_FAILURE);
4937 }
4938
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03004939 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01004940
Daniel P. Berrange064097d2016-02-10 18:41:01 +00004941 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00004942 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08004943 if (argc < 2) {
4944 error_exit("Not enough arguments");
4945 }
Stuart Brady153859b2009-06-07 00:42:17 +01004946
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004947 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004948 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004949 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004950
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004951 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03004952 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004953 case ':':
4954 missing_argument(argv[optind - 1]);
4955 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08004956 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004957 unrecognized_option(argv[optind - 1]);
4958 return 0;
4959 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03004960 help();
4961 return 0;
4962 case 'V':
4963 printf(QEMU_IMG_VERSION);
4964 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004965 case 'T':
4966 g_free(trace_file);
4967 trace_file = trace_opt_parse(optarg);
4968 break;
Stuart Brady153859b2009-06-07 00:42:17 +01004969 }
bellardea2384d2004-08-01 21:59:26 +00004970 }
Stuart Brady153859b2009-06-07 00:42:17 +01004971
Denis V. Lunev10985132016-06-17 17:44:13 +03004972 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04004973
Denis V. Lunev10985132016-06-17 17:44:13 +03004974 /* reset getopt_long scanning */
4975 argc -= optind;
4976 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04004977 return 0;
4978 }
Denis V. Lunev10985132016-06-17 17:44:13 +03004979 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00004980 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03004981
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03004982 if (!trace_init_backends()) {
4983 exit(1);
4984 }
4985 trace_init_file(trace_file);
4986 qemu_set_log(LOG_TRACE);
4987
Denis V. Lunev10985132016-06-17 17:44:13 +03004988 /* find the command */
4989 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
4990 if (!strcmp(cmdname, cmd->name)) {
4991 return cmd->handler(argc, argv);
4992 }
4993 }
Jeff Cody7db16892014-04-25 17:02:32 -04004994
Stuart Brady153859b2009-06-07 00:42:17 +01004995 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08004996 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00004997}