blob: 4bc40df6d24af275eab8feaf05a6c9b13b2e8553 [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
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010031#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010032#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010033#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010034#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010035#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020036#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000037#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010038#include "qemu/option.h"
39#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030040#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020041#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020042#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020043#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000044#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020045#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010046#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020047#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080048#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010049#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030050#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000051
Thomas Huth7e563bf2018-02-15 12:06:47 +010052#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020053 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040054
Anthony Liguoric227f092009-10-01 16:12:16 -050055typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010056 const char *name;
57 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050058} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010059
Federico Simoncelli8599ea42013-01-28 06:59:47 -050060enum {
61 OPTION_OUTPUT = 256,
62 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000063 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000064 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020065 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020066 OPTION_FLUSH_INTERVAL = 261,
67 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010068 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010069 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020070 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030071 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020072 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000073 OPTION_TARGET_IS_ZERO = 268,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050074};
75
76typedef enum OutputFormat {
77 OFORMAT_JSON,
78 OFORMAT_HUMAN,
79} OutputFormat;
80
Kevin Wolfe6996142016-03-15 13:03:11 +010081/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040082#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000083
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010084static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000085{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010086 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000087}
88
Fam Zhengac1307a2014-04-22 13:36:11 +080089static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
90{
91 va_list ap;
92
Fam Zhengac1307a2014-04-22 13:36:11 +080093 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +020094 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +080095 va_end(ap);
96
Markus Armbrustere9e1d922019-04-17 21:06:27 +020097 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +080098 exit(EXIT_FAILURE);
99}
100
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800101static void QEMU_NORETURN missing_argument(const char *option)
102{
103 error_exit("missing argument for option '%s'", option);
104}
105
106static void QEMU_NORETURN unrecognized_option(const char *option)
107{
108 error_exit("unrecognized option '%s'", option);
109}
110
blueswir1d2c639d2009-01-24 18:19:25 +0000111/* Please keep in synch with qemu-img.texi */
Fam Zhengac1307a2014-04-22 13:36:11 +0800112static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000113{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100114 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400115 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300116 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300117 "QEMU disk image utility\n"
118 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300119 " '-h', '--help' display this help and exit\n"
120 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300121 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
122 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300123 "\n"
malc3f020d72010-02-08 12:04:56 +0300124 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100125#define DEF(option, callback, arg_string) \
126 " " arg_string "\n"
127#include "qemu-img-cmds.h"
128#undef DEF
malc3f020d72010-02-08 12:04:56 +0300129 "\n"
130 "Command parameters:\n"
131 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000132 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
133 " manual page for a description of the object properties. The most common\n"
134 " object type is a 'secret', which is used to supply passwords and/or\n"
135 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300136 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400137 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800138 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
139 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100140 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
141 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300142 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200143 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
144 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
145 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300146 " 'output_filename' is the destination disk image filename\n"
147 " 'output_fmt' is the destination format\n"
148 " 'options' is a comma separated list of format specific options in a\n"
149 " name=value format. Use -o ? for an overview of the options supported by the\n"
150 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800151 " 'snapshot_param' is param used for internal snapshot, format\n"
152 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
153 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300154 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400155 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
156 " new backing file match exactly. The image doesn't need a working\n"
157 " backing file before rebasing in this case (useful for renaming the\n"
158 " backing file). For image creation, allow creating without attempting\n"
159 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300160 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200161 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100162 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200163 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
164 " contain only zeros for qemu-img to create a sparse image during\n"
165 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
166 " unallocated or zero sectors, and the destination image will always be\n"
167 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200168 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100169 " '-n' skips the target volume creation (useful if the volume is created\n"
170 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300171 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200172 "Parameters to check subcommand:\n"
173 " '-r' tries to repair any inconsistencies that are found during the check.\n"
174 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
175 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200176 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200177 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100178 "Parameters to convert subcommand:\n"
179 " '-m' specifies how many coroutines work in parallel during the convert\n"
180 " process (defaults to 8)\n"
181 " '-W' allow to write to the target out of order rather than sequential\n"
182 "\n"
malc3f020d72010-02-08 12:04:56 +0300183 "Parameters to snapshot subcommand:\n"
184 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
185 " '-a' applies a snapshot (revert disk to saved state)\n"
186 " '-c' creates a snapshot\n"
187 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100188 " '-l' lists all snapshots in the given image\n"
189 "\n"
190 "Parameters to compare subcommand:\n"
191 " '-f' first image format\n"
192 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200193 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
194 "\n"
195 "Parameters to dd subcommand:\n"
196 " 'bs=BYTES' read and write up to BYTES bytes at a time "
197 "(default: 512)\n"
198 " 'count=N' copy only N input blocks\n"
199 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200200 " 'of=FILE' write to FILE\n"
201 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100202
203 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300204 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500205 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800206 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000207}
208
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000209static QemuOptsList qemu_object_opts = {
210 .name = "object",
211 .implied_opt_name = "qom-type",
212 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
213 .desc = {
214 { }
215 },
216};
217
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200218static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
219{
220 if (user_creatable_print_help(type, opts)) {
221 exit(0);
222 }
223 return true;
224}
225
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000226static QemuOptsList qemu_source_opts = {
227 .name = "source",
228 .implied_opt_name = "file",
229 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
230 .desc = {
231 { }
232 },
233};
234
Stefan Weil7c30f652013-06-16 17:01:05 +0200235static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100236{
237 int ret = 0;
238 if (!quiet) {
239 va_list args;
240 va_start(args, fmt);
241 ret = vprintf(fmt, args);
242 va_end(args);
243 }
244 return ret;
245}
246
bellardea2384d2004-08-01 21:59:26 +0000247
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100248static int print_block_option_help(const char *filename, const char *fmt)
249{
250 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800251 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500252 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100253
254 /* Find driver and parse its options */
255 drv = bdrv_find_format(fmt);
256 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100257 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100258 return 1;
259 }
260
Max Reitzd402b6a2018-05-09 23:00:21 +0200261 if (!drv->create_opts) {
262 error_report("Format driver '%s' does not support image creation", fmt);
263 return 1;
264 }
265
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800266 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100267 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500268 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100269 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100270 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800271 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100272 return 1;
273 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200274 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100275 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200276 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100277 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200278 return 1;
279 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800280 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100281 }
282
Max Reitzf4619af2019-04-13 17:20:37 +0200283 if (filename) {
284 printf("Supported options:\n");
285 } else {
286 printf("Supported %s options:\n", fmt);
287 }
Max Reitz63898712018-10-19 18:49:25 +0200288 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800289 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200290
291 if (!filename) {
292 printf("\n"
293 "The protocol level may support further options.\n"
294 "Specify the target filename to include those options.\n");
295 }
296
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100297 return 0;
298}
299
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000300
Max Reitzefaa7c42016-03-16 19:54:38 +0100301static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100302 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800303 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000304{
305 QDict *options;
306 Error *local_err = NULL;
307 BlockBackend *blk;
308 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800309 if (force_share) {
310 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200311 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800312 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200313 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800314 return NULL;
315 }
Max Reitz4615f872018-05-02 22:20:50 +0200316 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800317 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100318 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000319 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100320 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000321 return NULL;
322 }
Kevin Wolfce099542016-03-15 13:01:04 +0100323 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000324
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000325 return blk;
326}
327
Max Reitzefaa7c42016-03-16 19:54:38 +0100328static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100329 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000330 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800331 bool writethrough, bool quiet,
332 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000333{
334 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200335 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100336
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100337 if (!options) {
338 options = qdict_new();
339 }
bellard75c23802004-08-27 21:28:58 +0000340 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500341 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000342 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100343
Fam Zheng335e9932017-05-03 00:35:39 +0800344 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500345 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800346 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100347 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500348 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100349 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000350 return NULL;
bellard75c23802004-08-27 21:28:58 +0000351 }
Kevin Wolfce099542016-03-15 13:01:04 +0100352 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100353
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200354 return blk;
bellard75c23802004-08-27 21:28:58 +0000355}
356
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000357
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100358static int img_add_key_secrets(void *opaque,
359 const char *name, const char *value,
360 Error **errp)
361{
362 QDict *options = opaque;
363
364 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600365 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100366 }
367
368 return 0;
369}
370
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100371
Max Reitzefaa7c42016-03-16 19:54:38 +0100372static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000373 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100374 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800375 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000376{
377 BlockBackend *blk;
378 if (image_opts) {
379 QemuOpts *opts;
380 if (fmt) {
381 error_report("--image-opts and --format are mutually exclusive");
382 return NULL;
383 }
384 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
385 filename, true);
386 if (!opts) {
387 return NULL;
388 }
Fam Zheng335e9932017-05-03 00:35:39 +0800389 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
390 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000391 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100392 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800393 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000394 }
395 return blk;
396}
397
398
Chunyan Liu83d05212014-06-05 17:20:51 +0800399static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100400 const char *base_filename,
401 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200402{
Markus Armbruster6750e792015-02-12 17:43:08 +0100403 Error *err = NULL;
404
Kevin Wolfefa84d42009-05-18 16:42:12 +0200405 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100406 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100407 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100408 error_report("Backing file not supported for file format '%s'",
409 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100410 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900411 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200412 }
413 }
414 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100415 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100416 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100417 error_report("Backing file format not supported for file "
418 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100419 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900420 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200421 }
422 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900423 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200424}
425
Markus Armbruster606caa02017-02-21 21:14:04 +0100426static int64_t cvtnum(const char *s)
427{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100428 int err;
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100429 uint64_t value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100430
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100431 err = qemu_strtosz(s, NULL, &value);
432 if (err < 0) {
433 return err;
434 }
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100435 if (value > INT64_MAX) {
436 return -ERANGE;
437 }
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100438 return value;
Markus Armbruster606caa02017-02-21 21:14:04 +0100439}
440
bellardea2384d2004-08-01 21:59:26 +0000441static int img_create(int argc, char **argv)
442{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200443 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100444 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000445 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000446 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000447 const char *filename;
448 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200449 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200450 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100451 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400452 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000453
bellardea2384d2004-08-01 21:59:26 +0000454 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000455 static const struct option long_options[] = {
456 {"help", no_argument, 0, 'h'},
457 {"object", required_argument, 0, OPTION_OBJECT},
458 {0, 0, 0, 0}
459 };
John Snow6e6e55f2017-07-17 20:34:22 -0400460 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000461 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100462 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000463 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100464 }
bellardea2384d2004-08-01 21:59:26 +0000465 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800466 case ':':
467 missing_argument(argv[optind - 1]);
468 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100469 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800470 unrecognized_option(argv[optind - 1]);
471 break;
bellardea2384d2004-08-01 21:59:26 +0000472 case 'h':
473 help();
474 break;
aliguori9230eaf2009-03-28 17:55:19 +0000475 case 'F':
476 base_fmt = optarg;
477 break;
bellardea2384d2004-08-01 21:59:26 +0000478 case 'b':
479 base_filename = optarg;
480 break;
481 case 'f':
482 fmt = optarg;
483 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200484 case 'o':
Kevin Wolf77386bf2014-02-21 16:24:04 +0100485 if (!is_valid_option_list(optarg)) {
486 error_report("Invalid option list: %s", optarg);
487 goto fail;
488 }
489 if (!options) {
490 options = g_strdup(optarg);
491 } else {
492 char *old_options = options;
493 options = g_strdup_printf("%s,%s", options, optarg);
494 g_free(old_options);
495 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200496 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100497 case 'q':
498 quiet = true;
499 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400500 case 'u':
501 flags |= BDRV_O_NO_BACKING;
502 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000503 case OPTION_OBJECT: {
504 QemuOpts *opts;
505 opts = qemu_opts_parse_noisily(&qemu_object_opts,
506 optarg, true);
507 if (!opts) {
508 goto fail;
509 }
510 } break;
bellardea2384d2004-08-01 21:59:26 +0000511 }
512 }
aliguori9230eaf2009-03-28 17:55:19 +0000513
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900514 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100515 filename = (optind < argc) ? argv[optind] : NULL;
516 if (options && has_help_option(options)) {
517 g_free(options);
518 return print_block_option_help(filename, fmt);
519 }
520
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100521 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800522 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100523 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100524 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900525
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000526 if (qemu_opts_foreach(&qemu_object_opts,
527 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200528 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000529 goto fail;
530 }
531
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100532 /* Get image size, if specified */
533 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100534 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100535
536 sval = cvtnum(argv[optind++]);
537 if (sval < 0) {
liguang79443392012-12-17 09:49:23 +0800538 if (sval == -ERANGE) {
539 error_report("Image size must be less than 8 EiB!");
540 } else {
541 error_report("Invalid image size specified! You may use k, M, "
Kevin Wolf5e009842013-06-05 14:19:27 +0200542 "G, T, P or E suffixes for ");
543 error_report("kilobytes, megabytes, gigabytes, terabytes, "
544 "petabytes and exabytes.");
liguang79443392012-12-17 09:49:23 +0800545 }
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100547 }
548 img_size = (uint64_t)sval;
549 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200550 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800551 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200552 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100553
Luiz Capitulino9b375252012-11-30 10:52:05 -0200554 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400555 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100556 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100557 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100558 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900559 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200560
Kevin Wolf77386bf2014-02-21 16:24:04 +0100561 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000562 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100563
564fail:
565 g_free(options);
566 return 1;
bellardea2384d2004-08-01 21:59:26 +0000567}
568
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100569static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500570{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500571 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500572 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100573 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600574
575 visit_type_ImageCheck(v, NULL, &check, &error_abort);
576 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500577 str = qobject_to_json_pretty(obj);
578 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100579 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200580 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600581 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200582 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500583}
584
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100585static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500586{
587 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100588 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500589 } else {
590 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100591 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
592 "Data may be corrupted, or further writes to the image "
593 "may corrupt it.\n",
594 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500595 }
596
597 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100598 qprintf(quiet,
599 "\n%" PRId64 " leaked clusters were found on the image.\n"
600 "This means waste of disk space, but no harm to data.\n",
601 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500602 }
603
604 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100605 qprintf(quiet,
606 "\n%" PRId64
607 " internal errors have occurred during the check.\n",
608 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500609 }
610 }
611
612 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100613 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
614 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
615 check->allocated_clusters, check->total_clusters,
616 check->allocated_clusters * 100.0 / check->total_clusters,
617 check->fragmented_clusters * 100.0 / check->allocated_clusters,
618 check->compressed_clusters * 100.0 /
619 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 }
621
622 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100623 qprintf(quiet,
624 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500625 }
626}
627
628static int collect_image_check(BlockDriverState *bs,
629 ImageCheck *check,
630 const char *filename,
631 const char *fmt,
632 int fix)
633{
634 int ret;
635 BdrvCheckResult result;
636
637 ret = bdrv_check(bs, &result, fix);
638 if (ret < 0) {
639 return ret;
640 }
641
642 check->filename = g_strdup(filename);
643 check->format = g_strdup(bdrv_get_format_name(bs));
644 check->check_errors = result.check_errors;
645 check->corruptions = result.corruptions;
646 check->has_corruptions = result.corruptions != 0;
647 check->leaks = result.leaks;
648 check->has_leaks = result.leaks != 0;
649 check->corruptions_fixed = result.corruptions_fixed;
650 check->has_corruptions_fixed = result.corruptions != 0;
651 check->leaks_fixed = result.leaks_fixed;
652 check->has_leaks_fixed = result.leaks != 0;
653 check->image_end_offset = result.image_end_offset;
654 check->has_image_end_offset = result.image_end_offset != 0;
655 check->total_clusters = result.bfi.total_clusters;
656 check->has_total_clusters = result.bfi.total_clusters != 0;
657 check->allocated_clusters = result.bfi.allocated_clusters;
658 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
659 check->fragmented_clusters = result.bfi.fragmented_clusters;
660 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100661 check->compressed_clusters = result.bfi.compressed_clusters;
662 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500663
664 return 0;
665}
666
Kevin Wolfe076f332010-06-29 11:43:13 +0200667/*
668 * Checks an image for consistency. Exit codes:
669 *
Max Reitzd6635c42014-06-02 22:15:21 +0200670 * 0 - Check completed, image is good
671 * 1 - Check not completed because of internal errors
672 * 2 - Check completed, image is corrupted
673 * 3 - Check completed, image has leaked clusters, but is good otherwise
674 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200675 */
aliguori15859692009-04-21 23:11:53 +0000676static int img_check(int argc, char **argv)
677{
678 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200680 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200681 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000682 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200683 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100684 int flags = BDRV_O_CHECK;
685 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200686 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100687 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000688 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800689 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000690
691 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500692 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200693 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100694
aliguori15859692009-04-21 23:11:53 +0000695 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 int option_index = 0;
697 static const struct option long_options[] = {
698 {"help", no_argument, 0, 'h'},
699 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530700 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500701 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000702 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000703 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800704 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500705 {0, 0, 0, 0}
706 };
Fam Zheng335e9932017-05-03 00:35:39 +0800707 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500708 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100709 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000710 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100711 }
aliguori15859692009-04-21 23:11:53 +0000712 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800713 case ':':
714 missing_argument(argv[optind - 1]);
715 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100716 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800717 unrecognized_option(argv[optind - 1]);
718 break;
aliguori15859692009-04-21 23:11:53 +0000719 case 'h':
720 help();
721 break;
722 case 'f':
723 fmt = optarg;
724 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200725 case 'r':
726 flags |= BDRV_O_RDWR;
727
728 if (!strcmp(optarg, "leaks")) {
729 fix = BDRV_FIX_LEAKS;
730 } else if (!strcmp(optarg, "all")) {
731 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
732 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800733 error_exit("Unknown option value for -r "
734 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200735 }
736 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500737 case OPTION_OUTPUT:
738 output = optarg;
739 break;
Max Reitz40055952014-07-22 22:58:42 +0200740 case 'T':
741 cache = optarg;
742 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100743 case 'q':
744 quiet = true;
745 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800746 case 'U':
747 force_share = true;
748 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000749 case OPTION_OBJECT: {
750 QemuOpts *opts;
751 opts = qemu_opts_parse_noisily(&qemu_object_opts,
752 optarg, true);
753 if (!opts) {
754 return 1;
755 }
756 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000757 case OPTION_IMAGE_OPTS:
758 image_opts = true;
759 break;
aliguori15859692009-04-21 23:11:53 +0000760 }
761 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200762 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800763 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100764 }
aliguori15859692009-04-21 23:11:53 +0000765 filename = argv[optind++];
766
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500767 if (output && !strcmp(output, "json")) {
768 output_format = OFORMAT_JSON;
769 } else if (output && !strcmp(output, "human")) {
770 output_format = OFORMAT_HUMAN;
771 } else if (output) {
772 error_report("--output must be used with human or json as argument.");
773 return 1;
774 }
775
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000776 if (qemu_opts_foreach(&qemu_object_opts,
777 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200778 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000779 return 1;
780 }
781
Kevin Wolfce099542016-03-15 13:01:04 +0100782 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200783 if (ret < 0) {
784 error_report("Invalid source cache option: %s", cache);
785 return 1;
786 }
787
Fam Zheng335e9932017-05-03 00:35:39 +0800788 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
789 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200790 if (!blk) {
791 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900792 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200793 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500794
795 check = g_new0(ImageCheck, 1);
796 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200797
798 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200799 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200800 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500801 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200802 }
803
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500804 if (check->corruptions_fixed || check->leaks_fixed) {
805 int corruptions_fixed, leaks_fixed;
806
807 leaks_fixed = check->leaks_fixed;
808 corruptions_fixed = check->corruptions_fixed;
809
810 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100811 qprintf(quiet,
812 "The following inconsistencies were found and repaired:\n\n"
813 " %" PRId64 " leaked clusters\n"
814 " %" PRId64 " corruptions\n\n"
815 "Double checking the fixed image now...\n",
816 check->leaks_fixed,
817 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500818 }
819
820 ret = collect_image_check(bs, check, filename, fmt, 0);
821
822 check->leaks_fixed = leaks_fixed;
823 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200824 }
825
Max Reitz832390a2014-10-23 15:29:12 +0200826 if (!ret) {
827 switch (output_format) {
828 case OFORMAT_HUMAN:
829 dump_human_image_check(check, quiet);
830 break;
831 case OFORMAT_JSON:
832 dump_json_image_check(check, quiet);
833 break;
834 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500835 }
836
837 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200838 if (ret) {
839 error_report("Check failed: %s", strerror(-ret));
840 } else {
841 error_report("Check failed");
842 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500843 ret = 1;
844 goto fail;
845 }
846
847 if (check->corruptions) {
848 ret = 2;
849 } else if (check->leaks) {
850 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200851 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500852 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000853 }
854
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500855fail:
856 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200857 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500858 return ret;
aliguori15859692009-04-21 23:11:53 +0000859}
860
Max Reitzd4a32382014-10-24 15:57:37 +0200861typedef struct CommonBlockJobCBInfo {
862 BlockDriverState *bs;
863 Error **errp;
864} CommonBlockJobCBInfo;
865
866static void common_block_job_cb(void *opaque, int ret)
867{
868 CommonBlockJobCBInfo *cbi = opaque;
869
870 if (ret < 0) {
871 error_setg_errno(cbi->errp, -ret, "Block job failed");
872 }
Max Reitzd4a32382014-10-24 15:57:37 +0200873}
874
875static void run_block_job(BlockJob *job, Error **errp)
876{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200877 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800878 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200879
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200880 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200881 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200882 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200883 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200884 aio_poll(aio_context, true);
Kevin Wolf30a5c882018-05-04 12:17:20 +0200885 if (job->job.progress_total) {
886 progress = (float)job->job.progress_current /
887 job->job.progress_total * 100.f;
888 }
889 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200890 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200891
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200892 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200893 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800894 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200895 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800896 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200897 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200898 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200899
sochin.jiang4172a002017-06-15 14:47:33 +0800900 /* publish completion progress only when success */
901 if (!ret) {
902 qemu_progress_print(100.f, 0);
903 }
Max Reitzd4a32382014-10-24 15:57:37 +0200904}
905
bellardea2384d2004-08-01 21:59:26 +0000906static int img_commit(int argc, char **argv)
907{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400908 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200909 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200910 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200911 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100912 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200913 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100914 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200915 Error *local_err = NULL;
916 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000917 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200918 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000919
920 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400921 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200922 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000923 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000924 static const struct option long_options[] = {
925 {"help", no_argument, 0, 'h'},
926 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000927 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000928 {0, 0, 0, 0}
929 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800930 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000931 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100932 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000933 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100934 }
bellardea2384d2004-08-01 21:59:26 +0000935 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800936 case ':':
937 missing_argument(argv[optind - 1]);
938 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100939 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800940 unrecognized_option(argv[optind - 1]);
941 break;
bellardea2384d2004-08-01 21:59:26 +0000942 case 'h':
943 help();
944 break;
945 case 'f':
946 fmt = optarg;
947 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400948 case 't':
949 cache = optarg;
950 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200951 case 'b':
952 base = optarg;
953 /* -b implies -d */
954 drop = true;
955 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200956 case 'd':
957 drop = true;
958 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200959 case 'p':
960 progress = true;
961 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100962 case 'q':
963 quiet = true;
964 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000965 case OPTION_OBJECT: {
966 QemuOpts *opts;
967 opts = qemu_opts_parse_noisily(&qemu_object_opts,
968 optarg, true);
969 if (!opts) {
970 return 1;
971 }
972 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000973 case OPTION_IMAGE_OPTS:
974 image_opts = true;
975 break;
bellardea2384d2004-08-01 21:59:26 +0000976 }
977 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200978
979 /* Progress is not shown in Quiet mode */
980 if (quiet) {
981 progress = false;
982 }
983
Kevin Wolffc11eb22013-08-05 10:53:04 +0200984 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800985 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100986 }
bellardea2384d2004-08-01 21:59:26 +0000987 filename = argv[optind++];
988
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000989 if (qemu_opts_foreach(&qemu_object_opts,
990 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200991 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000992 return 1;
993 }
994
Max Reitz9a86fe42014-10-24 15:57:38 +0200995 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100996 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400997 if (ret < 0) {
998 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +0100999 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001000 }
1001
Fam Zheng335e9932017-05-03 00:35:39 +08001002 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1003 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001004 if (!blk) {
1005 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001006 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001007 bs = blk_bs(blk);
1008
Max Reitz687fa1d2014-10-24 15:57:39 +02001009 qemu_progress_init(progress, 1.f);
1010 qemu_progress_print(0.f, 100);
1011
Max Reitz1b22bff2014-10-24 15:57:40 +02001012 if (base) {
1013 base_bs = bdrv_find_backing_image(bs, base);
1014 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001015 error_setg(&local_err,
1016 "Did not find '%s' in the backing chain of '%s'",
1017 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001018 goto done;
1019 }
1020 } else {
1021 /* This is different from QMP, which by default uses the deepest file in
1022 * the backing chain (i.e., the very base); however, the traditional
1023 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001024 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001025 if (!base_bs) {
1026 error_setg(&local_err, "Image does not have a backing file");
1027 goto done;
1028 }
bellardea2384d2004-08-01 21:59:26 +00001029 }
1030
Max Reitzd4a32382014-10-24 15:57:37 +02001031 cbi = (CommonBlockJobCBInfo){
1032 .errp = &local_err,
1033 .bs = bs,
1034 };
1035
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001036 aio_context = bdrv_get_aio_context(bs);
1037 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001038 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001039 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001040 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001041 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001042 if (local_err) {
1043 goto done;
1044 }
1045
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001046 /* When the block job completes, the BlockBackend reference will point to
1047 * the old backing file. In order to avoid that the top image is already
1048 * deleted, so we can still empty it afterwards, increment the reference
1049 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001050 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001051 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001052 }
1053
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001054 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001055 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001056 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001057 if (local_err) {
1058 goto unref_backing;
1059 }
1060
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001061 if (!drop && bs->drv->bdrv_make_empty) {
1062 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001063 if (ret) {
1064 error_setg_errno(&local_err, -ret, "Could not empty %s",
1065 filename);
1066 goto unref_backing;
1067 }
1068 }
1069
1070unref_backing:
1071 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001072 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001073 }
Max Reitzd4a32382014-10-24 15:57:37 +02001074
1075done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001076 qemu_progress_end();
1077
Markus Armbruster26f54e92014-10-07 13:59:04 +02001078 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001079
1080 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001081 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001082 return 1;
1083 }
Max Reitzd4a32382014-10-24 15:57:37 +02001084
1085 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001086 return 0;
1087}
1088
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001089/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001090 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1091 * of the first sector boundary within buf where the sector contains a
1092 * non-zero byte. This function is robust to a buffer that is not
1093 * sector-aligned.
1094 */
1095static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1096{
1097 int64_t i;
1098 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1099
1100 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1101 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1102 return i;
1103 }
1104 }
1105 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1106 return i;
1107 }
1108 return -1;
1109}
1110
1111/*
thsf58c7b32008-06-05 21:53:49 +00001112 * Returns true iff the first sector pointed to by 'buf' contains at least
1113 * a non-NUL byte.
1114 *
1115 * 'pnum' is set to the number of sectors (including and immediately following
1116 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001117 * The function will try to align the end offset to alignment boundaries so
1118 * that the request will at least end aligned and consequtive requests will
1119 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001120 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001121static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1122 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001123{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001124 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001125 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001126
1127 if (n <= 0) {
1128 *pnum = 0;
1129 return 0;
1130 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001131 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001132 for(i = 1; i < n; i++) {
1133 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001134 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001135 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001136 }
bellardea2384d2004-08-01 21:59:26 +00001137 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001138
1139 tail = (sector_num + i) & (alignment - 1);
1140 if (tail) {
1141 if (is_zero && i <= tail) {
1142 /* treat unallocated areas which only consist
1143 * of a small tail as allocated. */
1144 is_zero = false;
1145 }
1146 if (!is_zero) {
1147 /* align up end offset of allocated areas. */
1148 i += alignment - tail;
1149 i = MIN(i, n);
1150 } else {
1151 /* align down end offset of zero areas. */
1152 i -= tail;
1153 }
1154 }
bellardea2384d2004-08-01 21:59:26 +00001155 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001156 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001157}
1158
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001159/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001160 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1161 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1162 * breaking up write requests for only small sparse areas.
1163 */
1164static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001165 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001166{
1167 int ret;
1168 int num_checked, num_used;
1169
1170 if (n < min) {
1171 min = n;
1172 }
1173
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001174 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001175 if (!ret) {
1176 return ret;
1177 }
1178
1179 num_used = *pnum;
1180 buf += BDRV_SECTOR_SIZE * *pnum;
1181 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001182 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001183 num_checked = num_used;
1184
1185 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001186 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001187
1188 buf += BDRV_SECTOR_SIZE * *pnum;
1189 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001190 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001191 num_checked += *pnum;
1192 if (ret) {
1193 num_used = num_checked;
1194 } else if (*pnum >= min) {
1195 break;
1196 }
1197 }
1198
1199 *pnum = num_used;
1200 return 1;
1201}
1202
1203/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001204 * Compares two buffers sector by sector. Returns 0 if the first
1205 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001206 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001207 * pnum is set to the sector-aligned size of the buffer prefix that
1208 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001209 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001210static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1211 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001212{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001213 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001214 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001215
Eric Blakedc61cd32017-10-11 22:47:14 -05001216 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001217
Eric Blakedc61cd32017-10-11 22:47:14 -05001218 res = !!memcmp(buf1, buf2, i);
1219 while (i < bytes) {
1220 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001221
Eric Blakedc61cd32017-10-11 22:47:14 -05001222 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001223 break;
1224 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001225 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001226 }
1227
1228 *pnum = i;
1229 return res;
1230}
1231
Stefano Garzarella97ede572019-05-08 12:43:24 +02001232#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001233
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001234/*
1235 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1236 *
Eric Blake0608e402017-10-11 22:47:12 -05001237 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1238 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1239 * failure), and 4 on error (the exit status for read errors), after emitting
1240 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001241 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001242 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001243 * @param offset: Starting offset to check
1244 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001245 * @param filename: Name of disk file we are checking (logging purpose)
1246 * @param buffer: Allocated buffer for storing read data
1247 * @param quiet: Flag for quiet mode
1248 */
Eric Blakec41508e2017-10-11 22:47:13 -05001249static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1250 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001251 uint8_t *buffer, bool quiet)
1252{
Eric Blakedebb38a2017-10-11 22:47:11 -05001253 int ret = 0;
1254 int64_t idx;
1255
Eric Blakec41508e2017-10-11 22:47:13 -05001256 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001257 if (ret < 0) {
1258 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001259 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001260 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001261 }
Eric Blakec41508e2017-10-11 22:47:13 -05001262 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001263 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001264 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001265 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001266 return 1;
1267 }
1268
1269 return 0;
1270}
1271
1272/*
1273 * Compares two images. Exit codes:
1274 *
1275 * 0 - Images are identical
1276 * 1 - Images differ
1277 * >1 - Error occurred
1278 */
1279static int img_compare(int argc, char **argv)
1280{
Max Reitz40055952014-07-22 22:58:42 +02001281 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001282 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001283 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001284 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001285 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001286 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 int allocated1, allocated2;
1288 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1289 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001290 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001291 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001292 int64_t total_size;
1293 int64_t offset = 0;
1294 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001295 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001296 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001297 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001298 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001299
Max Reitz40055952014-07-22 22:58:42 +02001300 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001301 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001302 static const struct option long_options[] = {
1303 {"help", no_argument, 0, 'h'},
1304 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001305 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001306 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001307 {0, 0, 0, 0}
1308 };
Fam Zheng335e9932017-05-03 00:35:39 +08001309 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001310 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 if (c == -1) {
1312 break;
1313 }
1314 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001315 case ':':
1316 missing_argument(argv[optind - 1]);
1317 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001319 unrecognized_option(argv[optind - 1]);
1320 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001321 case 'h':
1322 help();
1323 break;
1324 case 'f':
1325 fmt1 = optarg;
1326 break;
1327 case 'F':
1328 fmt2 = optarg;
1329 break;
Max Reitz40055952014-07-22 22:58:42 +02001330 case 'T':
1331 cache = optarg;
1332 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 case 'p':
1334 progress = true;
1335 break;
1336 case 'q':
1337 quiet = true;
1338 break;
1339 case 's':
1340 strict = true;
1341 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001342 case 'U':
1343 force_share = true;
1344 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001345 case OPTION_OBJECT: {
1346 QemuOpts *opts;
1347 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1348 optarg, true);
1349 if (!opts) {
1350 ret = 2;
1351 goto out4;
1352 }
1353 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001354 case OPTION_IMAGE_OPTS:
1355 image_opts = true;
1356 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001357 }
1358 }
1359
1360 /* Progress is not shown in Quiet mode */
1361 if (quiet) {
1362 progress = false;
1363 }
1364
1365
Kevin Wolffc11eb22013-08-05 10:53:04 +02001366 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001367 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001368 }
1369 filename1 = argv[optind++];
1370 filename2 = argv[optind++];
1371
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001372 if (qemu_opts_foreach(&qemu_object_opts,
1373 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001374 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001375 ret = 2;
1376 goto out4;
1377 }
1378
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001379 /* Initialize before goto out */
1380 qemu_progress_init(progress, 2.0);
1381
Kevin Wolfce099542016-03-15 13:01:04 +01001382 flags = 0;
1383 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001384 if (ret < 0) {
1385 error_report("Invalid source cache option: %s", cache);
1386 ret = 2;
1387 goto out3;
1388 }
1389
Fam Zheng335e9932017-05-03 00:35:39 +08001390 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1391 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001392 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001394 goto out3;
1395 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001396
Fam Zheng335e9932017-05-03 00:35:39 +08001397 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1398 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001399 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001400 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001401 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001402 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001403 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001404 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001405
Max Reitzf1d3cd72015-02-05 13:58:18 -05001406 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1407 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001408 total_size1 = blk_getlength(blk1);
1409 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001410 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001411 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001412 ret = 4;
1413 goto out;
1414 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001415 total_size2 = blk_getlength(blk2);
1416 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001417 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001418 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001419 ret = 4;
1420 goto out;
1421 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001422 total_size = MIN(total_size1, total_size2);
1423 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001424
1425 qemu_progress_print(0, 100);
1426
Eric Blake033d9fc2017-10-11 22:47:16 -05001427 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001428 ret = 1;
1429 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1430 goto out;
1431 }
1432
Eric Blake033d9fc2017-10-11 22:47:16 -05001433 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001434 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001435
Eric Blake033d9fc2017-10-11 22:47:16 -05001436 status1 = bdrv_block_status_above(bs1, NULL, offset,
1437 total_size1 - offset, &pnum1, NULL,
1438 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001439 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001440 ret = 3;
1441 error_report("Sector allocation test failed for %s", filename1);
1442 goto out;
1443 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001444 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001445
Eric Blake033d9fc2017-10-11 22:47:16 -05001446 status2 = bdrv_block_status_above(bs2, NULL, offset,
1447 total_size2 - offset, &pnum2, NULL,
1448 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001449 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001450 ret = 3;
1451 error_report("Sector allocation test failed for %s", filename2);
1452 goto out;
1453 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001454 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001455
1456 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001457 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001458
Fam Zheng25ad8e62016-01-13 16:37:41 +08001459 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001460 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001461 ret = 1;
1462 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001463 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001464 goto out;
1465 }
1466 }
1467 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001468 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001469 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001471 int64_t pnum;
1472
Eric Blake033d9fc2017-10-11 22:47:16 -05001473 chunk = MIN(chunk, IO_BUF_SIZE);
1474 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001475 if (ret < 0) {
1476 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001477 " of %s: %s",
1478 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479 ret = 4;
1480 goto out;
1481 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001482 ret = blk_pread(blk2, offset, buf2, chunk);
1483 if (ret < 0) {
1484 error_report("Error while reading offset %" PRId64
1485 " of %s: %s",
1486 offset, filename2, strerror(-ret));
1487 ret = 4;
1488 goto out;
1489 }
1490 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1491 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001492 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001493 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001494 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001495 goto out;
1496 }
1497 }
1498 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001501 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 filename1, buf1, quiet);
1503 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 filename2, buf1, quiet);
1506 }
1507 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001508 goto out;
1509 }
1510 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001511 offset += chunk;
1512 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001513 }
1514
Eric Blake033d9fc2017-10-11 22:47:16 -05001515 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001516 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001517 const char *filename_over;
1518
1519 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001520 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001521 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 filename_over = filename1;
1523 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001524 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525 filename_over = filename2;
1526 }
1527
Eric Blake033d9fc2017-10-11 22:47:16 -05001528 while (offset < progress_base) {
1529 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1530 progress_base - offset, &chunk,
1531 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 if (ret < 0) {
1533 ret = 3;
1534 error_report("Sector allocation test failed for %s",
1535 filename_over);
1536 goto out;
1537
1538 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001539 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001540 chunk = MIN(chunk, IO_BUF_SIZE);
1541 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001542 filename_over, buf1, quiet);
1543 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 goto out;
1545 }
1546 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001547 offset += chunk;
1548 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549 }
1550 }
1551
1552 qprintf(quiet, "Images are identical.\n");
1553 ret = 0;
1554
1555out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001556 qemu_vfree(buf1);
1557 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001558 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001559out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001560 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001561out3:
1562 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001563out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001564 return ret;
1565}
1566
Kevin Wolf690c7302015-03-19 13:33:32 +01001567enum ImgConvertBlockStatus {
1568 BLK_DATA,
1569 BLK_ZERO,
1570 BLK_BACKING_FILE,
1571};
1572
Peter Lieven2d9187b2017-02-28 13:40:07 +01001573#define MAX_COROUTINES 16
1574
Kevin Wolf690c7302015-03-19 13:33:32 +01001575typedef struct ImgConvertState {
1576 BlockBackend **src;
1577 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001578 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001579 int64_t total_sectors;
1580 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001581 int64_t allocated_done;
1582 int64_t sector_num;
1583 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001584 enum ImgConvertBlockStatus status;
1585 int64_t sector_next_status;
1586 BlockBackend *target;
1587 bool has_zero_init;
1588 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001589 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001590 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001591 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001592 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001593 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001594 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001595 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001596 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001597 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001598 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001599 size_t cluster_sectors;
1600 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001601 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001602 int running_coroutines;
1603 Coroutine *co[MAX_COROUTINES];
1604 int64_t wait_sector_num[MAX_COROUTINES];
1605 CoMutex lock;
1606 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001607} ImgConvertState;
1608
Peter Lieven2d9187b2017-02-28 13:40:07 +01001609static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1610 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001611{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001612 *src_cur = 0;
1613 *src_cur_offset = 0;
1614 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1615 *src_cur_offset += s->src_sectors[*src_cur];
1616 (*src_cur)++;
1617 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001618 }
1619}
1620
1621static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1622{
Eric Blake31826642017-10-11 22:47:08 -05001623 int64_t src_cur_offset;
1624 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001625 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001626
Peter Lieven2d9187b2017-02-28 13:40:07 +01001627 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001628
1629 assert(s->total_sectors > sector_num);
1630 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1631
Max Reitz351c8ef2018-05-01 18:57:49 +02001632 if (s->target_backing_sectors >= 0) {
1633 if (sector_num >= s->target_backing_sectors) {
1634 post_backing_zero = s->unallocated_blocks_are_zero;
1635 } else if (sector_num + n > s->target_backing_sectors) {
1636 /* Split requests around target_backing_sectors (because
1637 * starting from there, zeros are handled differently) */
1638 n = s->target_backing_sectors - sector_num;
1639 }
1640 }
1641
Kevin Wolf690c7302015-03-19 13:33:32 +01001642 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001643 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1644 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001645
Max Reitz8eaac022019-05-07 22:35:03 +02001646 do {
1647 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001648
Max Reitz8eaac022019-05-07 22:35:03 +02001649 if (s->target_has_backing) {
1650 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1651 count, &count, NULL, NULL);
1652 } else {
1653 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1654 offset, count, &count, NULL,
1655 NULL);
1656 }
1657
1658 if (ret < 0) {
1659 if (s->salvage) {
1660 if (n == 1) {
1661 if (!s->quiet) {
1662 warn_report("error while reading block status at "
1663 "offset %" PRIu64 ": %s", offset,
1664 strerror(-ret));
1665 }
1666 /* Just try to read the data, then */
1667 ret = BDRV_BLOCK_DATA;
1668 count = BDRV_SECTOR_SIZE;
1669 } else {
1670 /* Retry on a shorter range */
1671 n = DIV_ROUND_UP(n, 4);
1672 }
1673 } else {
1674 error_report("error while reading block status at offset "
1675 "%" PRIu64 ": %s", offset, strerror(-ret));
1676 return ret;
1677 }
1678 }
1679 } while (ret < 0);
1680
Eric Blake31826642017-10-11 22:47:08 -05001681 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001682
1683 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001684 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 } else if (ret & BDRV_BLOCK_DATA) {
1686 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001687 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001688 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001689 }
1690
1691 s->sector_next_status = sector_num + n;
1692 }
1693
1694 n = MIN(n, s->sector_next_status - sector_num);
1695 if (s->status == BLK_DATA) {
1696 n = MIN(n, s->buf_sectors);
1697 }
1698
1699 /* We need to write complete clusters for compressed images, so if an
1700 * unallocated area is shorter than that, we must consider the whole
1701 * cluster allocated. */
1702 if (s->compressed) {
1703 if (n < s->cluster_sectors) {
1704 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1705 s->status = BLK_DATA;
1706 } else {
1707 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1708 }
1709 }
1710
1711 return n;
1712}
1713
Peter Lieven2d9187b2017-02-28 13:40:07 +01001714static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1715 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001716{
Max Reitz8eaac022019-05-07 22:35:03 +02001717 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001718 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001719
Kevin Wolf690c7302015-03-19 13:33:32 +01001720 assert(nb_sectors <= s->buf_sectors);
1721 while (nb_sectors > 0) {
1722 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001723 int src_cur;
1724 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001725 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001726
1727 /* In the case of compression with multiple source files, we can get a
1728 * nb_sectors that spreads into the next part. So we must be able to
1729 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001730 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1731 blk = s->src[src_cur];
1732 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001733
Max Reitz8eaac022019-05-07 22:35:03 +02001734 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001735
Max Reitz8eaac022019-05-07 22:35:03 +02001736 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1737 if (single_read_until > offset) {
1738 n = 1;
1739 }
1740
1741 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001742 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001743 if (s->salvage) {
1744 if (n > 1) {
1745 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1746 continue;
1747 } else {
1748 if (!s->quiet) {
1749 warn_report("error while reading offset %" PRIu64
1750 ": %s", offset, strerror(-ret));
1751 }
1752 memset(buf, 0, BDRV_SECTOR_SIZE);
1753 }
1754 } else {
1755 return ret;
1756 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001757 }
1758
1759 sector_num += n;
1760 nb_sectors -= n;
1761 buf += n * BDRV_SECTOR_SIZE;
1762 }
1763
1764 return 0;
1765}
1766
Peter Lieven2d9187b2017-02-28 13:40:07 +01001767
1768static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1769 int nb_sectors, uint8_t *buf,
1770 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001771{
1772 int ret;
1773
1774 while (nb_sectors > 0) {
1775 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001776 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1777
Peter Lieven2d9187b2017-02-28 13:40:07 +01001778 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001779 case BLK_BACKING_FILE:
1780 /* If we have a backing file, leave clusters unallocated that are
1781 * unallocated in the source image, so that the backing file is
1782 * visible at the respective offset. */
1783 assert(s->target_has_backing);
1784 break;
1785
1786 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001787 /* If we're told to keep the target fully allocated (-S 0) or there
1788 * is real non-zero data, we must write it. Otherwise we can treat
1789 * it as zero sectors.
1790 * Compressed clusters need to be written as a whole, so in that
1791 * case we can only save the write if the buffer is completely
1792 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001793 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001794 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001795 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1796 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001797 (s->compressed &&
1798 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001799 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001800 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1801 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001802 if (ret < 0) {
1803 return ret;
1804 }
1805 break;
1806 }
1807 /* fall-through */
1808
1809 case BLK_ZERO:
1810 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001811 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001812 break;
1813 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001814 ret = blk_co_pwrite_zeroes(s->target,
1815 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001816 n << BDRV_SECTOR_BITS,
1817 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001818 if (ret < 0) {
1819 return ret;
1820 }
1821 break;
1822 }
1823
1824 sector_num += n;
1825 nb_sectors -= n;
1826 buf += n * BDRV_SECTOR_SIZE;
1827 }
1828
1829 return 0;
1830}
1831
Fam Zhengee5306d2018-06-01 17:26:48 +08001832static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1833 int nb_sectors)
1834{
1835 int n, ret;
1836
1837 while (nb_sectors > 0) {
1838 BlockBackend *blk;
1839 int src_cur;
1840 int64_t bs_sectors, src_cur_offset;
1841 int64_t offset;
1842
1843 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1844 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1845 blk = s->src[src_cur];
1846 bs_sectors = s->src_sectors[src_cur];
1847
1848 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1849
1850 ret = blk_co_copy_range(blk, offset, s->target,
1851 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001852 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001853 if (ret < 0) {
1854 return ret;
1855 }
1856
1857 sector_num += n;
1858 nb_sectors -= n;
1859 }
1860 return 0;
1861}
1862
Peter Lieven2d9187b2017-02-28 13:40:07 +01001863static void coroutine_fn convert_co_do_copy(void *opaque)
1864{
1865 ImgConvertState *s = opaque;
1866 uint8_t *buf = NULL;
1867 int ret, i;
1868 int index = -1;
1869
1870 for (i = 0; i < s->num_coroutines; i++) {
1871 if (s->co[i] == qemu_coroutine_self()) {
1872 index = i;
1873 break;
1874 }
1875 }
1876 assert(index >= 0);
1877
1878 s->running_coroutines++;
1879 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1880
1881 while (1) {
1882 int n;
1883 int64_t sector_num;
1884 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001885 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001886
1887 qemu_co_mutex_lock(&s->lock);
1888 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1889 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001890 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001891 }
1892 n = convert_iteration_sectors(s, s->sector_num);
1893 if (n < 0) {
1894 qemu_co_mutex_unlock(&s->lock);
1895 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001896 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001897 }
1898 /* save current sector and allocation status to local variables */
1899 sector_num = s->sector_num;
1900 status = s->status;
1901 if (!s->min_sparse && s->status == BLK_ZERO) {
1902 n = MIN(n, s->buf_sectors);
1903 }
1904 /* increment global sector counter so that other coroutines can
1905 * already continue reading beyond this request */
1906 s->sector_num += n;
1907 qemu_co_mutex_unlock(&s->lock);
1908
1909 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1910 s->allocated_done += n;
1911 qemu_progress_print(100.0 * s->allocated_done /
1912 s->allocated_sectors, 0);
1913 }
1914
Fam Zhengee5306d2018-06-01 17:26:48 +08001915retry:
1916 copy_range = s->copy_range && s->status == BLK_DATA;
1917 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001918 ret = convert_co_read(s, sector_num, n, buf);
1919 if (ret < 0) {
1920 error_report("error while reading sector %" PRId64
1921 ": %s", sector_num, strerror(-ret));
1922 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001923 }
1924 } else if (!s->min_sparse && status == BLK_ZERO) {
1925 status = BLK_DATA;
1926 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1927 }
1928
1929 if (s->wr_in_order) {
1930 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001931 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001932 s->wait_sector_num[index] = sector_num;
1933 qemu_coroutine_yield();
1934 }
1935 s->wait_sector_num[index] = -1;
1936 }
1937
Anton Nefedovb91127e2017-04-26 11:33:15 +03001938 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001939 if (copy_range) {
1940 ret = convert_co_copy_range(s, sector_num, n);
1941 if (ret) {
1942 s->copy_range = false;
1943 goto retry;
1944 }
1945 } else {
1946 ret = convert_co_write(s, sector_num, n, buf, status);
1947 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001948 if (ret < 0) {
1949 error_report("error while writing sector %" PRId64
1950 ": %s", sector_num, strerror(-ret));
1951 s->ret = ret;
1952 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001953 }
1954
1955 if (s->wr_in_order) {
1956 /* reenter the coroutine that might have waited
1957 * for this write to complete */
1958 s->wr_offs = sector_num + n;
1959 for (i = 0; i < s->num_coroutines; i++) {
1960 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1961 /*
1962 * A -> B -> A cannot occur because A has
1963 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1964 * B will never enter A during this time window.
1965 */
1966 qemu_coroutine_enter(s->co[i]);
1967 break;
1968 }
1969 }
1970 }
1971 }
1972
Peter Lieven2d9187b2017-02-28 13:40:07 +01001973 qemu_vfree(buf);
1974 s->co[index] = NULL;
1975 s->running_coroutines--;
1976 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1977 /* the convert job finished successfully */
1978 s->ret = 0;
1979 }
1980}
1981
Kevin Wolf690c7302015-03-19 13:33:32 +01001982static int convert_do_copy(ImgConvertState *s)
1983{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001984 int ret, i, n;
1985 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001986
1987 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00001988 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
1989 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02001990 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02001991 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001992
1993 if (!s->has_zero_init && !s->target_has_backing &&
1994 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1995 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001996 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001997 if (ret == 0) {
1998 s->has_zero_init = true;
1999 }
2000 }
2001
2002 /* Allocate buffer for copied data. For compressed images, only one cluster
2003 * can be copied at a time. */
2004 if (s->compressed) {
2005 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2006 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002007 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002008 }
2009 s->buf_sectors = s->cluster_sectors;
2010 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002011
Kevin Wolf690c7302015-03-19 13:33:32 +01002012 while (sector_num < s->total_sectors) {
2013 n = convert_iteration_sectors(s, sector_num);
2014 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002015 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002016 }
Max Reitzaad15de2016-03-24 23:33:57 +01002017 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2018 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002019 s->allocated_sectors += n;
2020 }
2021 sector_num += n;
2022 }
2023
2024 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002025 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002026 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002027
Peter Lieven2d9187b2017-02-28 13:40:07 +01002028 qemu_co_mutex_init(&s->lock);
2029 for (i = 0; i < s->num_coroutines; i++) {
2030 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2031 s->wait_sector_num[i] = -1;
2032 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002033 }
2034
Anton Nefedovb91127e2017-04-26 11:33:15 +03002035 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002036 main_loop_wait(false);
2037 }
2038
2039 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002040 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002041 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002042 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002043 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002044 }
2045 }
2046
Peter Lieven2d9187b2017-02-28 13:40:07 +01002047 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002048}
2049
Peter Lieven6360ab22018-07-13 09:15:39 +02002050#define MAX_BUF_SECTORS 32768
2051
bellardea2384d2004-08-01 21:59:26 +00002052static int img_convert(int argc, char **argv)
2053{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002054 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002055 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002056 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2057 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002058 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002059 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002060 BlockDriverState *out_bs;
2061 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002062 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002063 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002064 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002065 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002066 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002067 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002068 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002069 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002070 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002071
Peter Lieven9fd77f92017-04-21 11:11:55 +02002072 ImgConvertState s = (ImgConvertState) {
2073 /* Need at least 4k of zeros for sparse detection */
2074 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002075 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002076 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2077 .wr_in_order = true,
2078 .num_coroutines = 8,
2079 };
2080
bellardea2384d2004-08-01 21:59:26 +00002081 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002082 static const struct option long_options[] = {
2083 {"help", no_argument, 0, 'h'},
2084 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002085 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002086 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002087 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002088 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002089 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002090 {0, 0, 0, 0}
2091 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002092 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002093 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002094 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002095 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002096 }
bellardea2384d2004-08-01 21:59:26 +00002097 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002098 case ':':
2099 missing_argument(argv[optind - 1]);
2100 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002101 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002102 unrecognized_option(argv[optind - 1]);
2103 break;
bellardea2384d2004-08-01 21:59:26 +00002104 case 'h':
2105 help();
2106 break;
2107 case 'f':
2108 fmt = optarg;
2109 break;
2110 case 'O':
2111 out_fmt = optarg;
2112 break;
thsf58c7b32008-06-05 21:53:49 +00002113 case 'B':
2114 out_baseimg = optarg;
2115 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002116 case 'C':
2117 s.copy_range = true;
2118 break;
bellardea2384d2004-08-01 21:59:26 +00002119 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002120 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002121 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002122 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002123 if (!is_valid_option_list(optarg)) {
2124 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002125 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002126 }
2127 if (!options) {
2128 options = g_strdup(optarg);
2129 } else {
2130 char *old_options = options;
2131 options = g_strdup_printf("%s,%s", options, optarg);
2132 g_free(old_options);
2133 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002134 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002135 case 'l':
2136 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002137 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2138 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002139 if (!sn_opts) {
2140 error_report("Failed in parsing snapshot param '%s'",
2141 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002142 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002143 }
2144 } else {
2145 snapshot_name = optarg;
2146 }
2147 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002148 case 'S':
2149 {
2150 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002151
2152 sval = cvtnum(optarg);
Nir Soffer1bbbf322019-08-27 21:59:12 +03002153 if (sval < 0 || !QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002154 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2155 error_report("Invalid buffer size for sparse output specified. "
2156 "Valid sizes are multiples of %llu up to %llu. Select "
2157 "0 to disable sparse detection (fully allocates output).",
2158 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002159 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002160 }
2161
Peter Lieven9fd77f92017-04-21 11:11:55 +02002162 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002163 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002164 break;
2165 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002166 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002167 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002168 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002169 case 't':
2170 cache = optarg;
2171 break;
Max Reitz40055952014-07-22 22:58:42 +02002172 case 'T':
2173 src_cache = optarg;
2174 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002175 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002176 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002177 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002178 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002179 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002180 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002181 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002182 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2183 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002184 error_report("Invalid number of coroutines. Allowed number of"
2185 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002186 goto fail_getopt;
2187 }
2188 break;
2189 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002190 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002191 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002192 case 'U':
2193 force_share = true;
2194 break;
Max Reitz3258b912017-04-26 15:46:47 +02002195 case OPTION_OBJECT: {
2196 QemuOpts *object_opts;
2197 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2198 optarg, true);
2199 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002200 goto fail_getopt;
2201 }
2202 break;
Max Reitz3258b912017-04-26 15:46:47 +02002203 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002204 case OPTION_IMAGE_OPTS:
2205 image_opts = true;
2206 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002207 case OPTION_SALVAGE:
2208 s.salvage = true;
2209 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002210 case OPTION_TARGET_IMAGE_OPTS:
2211 tgt_image_opts = true;
2212 break;
David Edmondson168468f2020-02-05 11:02:48 +00002213 case OPTION_TARGET_IS_ZERO:
2214 /*
2215 * The user asserting that the target is blank has the
2216 * same effect as the target driver supporting zero
2217 * initialisation.
2218 */
2219 s.has_zero_init = true;
2220 break;
bellardea2384d2004-08-01 21:59:26 +00002221 }
2222 }
ths3b46e622007-09-17 08:09:54 +00002223
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002224 if (!out_fmt && !tgt_image_opts) {
2225 out_fmt = "raw";
2226 }
2227
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002228 if (qemu_opts_foreach(&qemu_object_opts,
2229 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002230 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002231 goto fail_getopt;
2232 }
2233
Fam Zhenge11ce122018-07-27 11:34:01 +08002234 if (s.compressed && s.copy_range) {
2235 error_report("Cannot enable copy offloading when -c is used");
2236 goto fail_getopt;
2237 }
2238
2239 if (explict_min_sparse && s.copy_range) {
2240 error_report("Cannot enable copy offloading when -S is used");
2241 goto fail_getopt;
2242 }
2243
Max Reitz8eaac022019-05-07 22:35:03 +02002244 if (s.copy_range && s.salvage) {
2245 error_report("Cannot use copy offloading in salvaging mode");
2246 goto fail_getopt;
2247 }
2248
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002249 if (tgt_image_opts && !skip_create) {
2250 error_report("--target-image-opts requires use of -n flag");
2251 goto fail_getopt;
2252 }
2253
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002254 if (skip_create && options) {
2255 warn_report("-o has no effect when skipping image creation");
2256 warn_report("This will become an error in future QEMU versions.");
2257 }
2258
David Edmondson168468f2020-02-05 11:02:48 +00002259 if (s.has_zero_init && !skip_create) {
2260 error_report("--target-is-zero requires use of -n flag");
2261 goto fail_getopt;
2262 }
2263
Peter Lieven9fd77f92017-04-21 11:11:55 +02002264 s.src_num = argc - optind - 1;
2265 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2266
2267 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002268 if (out_fmt) {
2269 ret = print_block_option_help(out_filename, out_fmt);
2270 goto fail_getopt;
2271 } else {
2272 error_report("Option help requires a format be specified");
2273 goto fail_getopt;
2274 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002275 }
2276
2277 if (s.src_num < 1) {
2278 error_report("Must specify image file name");
2279 goto fail_getopt;
2280 }
2281
2282
Peter Lieven9fd77f92017-04-21 11:11:55 +02002283 /* ret is still -EINVAL until here */
2284 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2285 if (ret < 0) {
2286 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002287 goto fail_getopt;
2288 }
2289
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002290 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002291 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002292 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002293 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002294 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002295 qemu_progress_print(0, 100);
2296
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 s.src = g_new0(BlockBackend *, s.src_num);
2298 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002299
Peter Lieven9fd77f92017-04-21 11:11:55 +02002300 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2301 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002302 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002303 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002304 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002305 ret = -1;
2306 goto out;
2307 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002308 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2309 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002310 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002311 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002312 ret = -1;
2313 goto out;
2314 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002315 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002316 }
bellardea2384d2004-08-01 21:59:26 +00002317
Wenchao Xiaef806542013-12-04 17:10:57 +08002318 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002319 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002320 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2321 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2322 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002323 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002325 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002326 ret = -1;
2327 goto out;
2328 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002329
Peter Lieven9fd77f92017-04-21 11:11:55 +02002330 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2331 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002332 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002333 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002334 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002335 ret = -1;
2336 goto out;
edison51ef6722010-09-21 19:58:41 -07002337 }
2338
Max Reitz2e024cd2015-02-11 09:58:46 -05002339 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002340 /* Find driver and parse its options */
2341 drv = bdrv_find_format(out_fmt);
2342 if (!drv) {
2343 error_report("Unknown file format '%s'", out_fmt);
2344 ret = -1;
2345 goto out;
2346 }
2347
2348 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2349 if (!proto_drv) {
2350 error_report_err(local_err);
2351 ret = -1;
2352 goto out;
2353 }
2354
Max Reitz2e024cd2015-02-11 09:58:46 -05002355 if (!drv->create_opts) {
2356 error_report("Format driver '%s' does not support image creation",
2357 drv->format_name);
2358 ret = -1;
2359 goto out;
2360 }
Max Reitzf75613c2014-12-02 18:32:46 +01002361
Max Reitz2e024cd2015-02-11 09:58:46 -05002362 if (!proto_drv->create_opts) {
2363 error_report("Protocol driver '%s' does not support image creation",
2364 proto_drv->format_name);
2365 ret = -1;
2366 goto out;
2367 }
Max Reitzf75613c2014-12-02 18:32:46 +01002368
Max Reitz2e024cd2015-02-11 09:58:46 -05002369 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2370 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002371
Max Reitz2e024cd2015-02-11 09:58:46 -05002372 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002373 if (options) {
2374 qemu_opts_do_parse(opts, options, NULL, &local_err);
2375 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002376 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002377 ret = -1;
2378 goto out;
2379 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002380 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002381
Peter Lieven9fd77f92017-04-21 11:11:55 +02002382 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002383 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002384 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2385 if (ret < 0) {
2386 goto out;
2387 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002388 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002389
Kevin Wolfa18953f2010-10-14 15:46:04 +02002390 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002391 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002392 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002393 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002394 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002395 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002396
David Edmondson168468f2020-02-05 11:02:48 +00002397 if (s.has_zero_init && s.target_has_backing) {
2398 error_report("Cannot use --target-is-zero when the destination "
2399 "image has a backing file");
2400 goto out;
2401 }
2402
Max Reitz48758a82017-04-26 15:46:48 +02002403 if (s.src_num > 1 && out_baseimg) {
2404 error_report("Having a backing file for the target makes no sense when "
2405 "concatenating multiple input images");
2406 ret = -1;
2407 goto out;
2408 }
2409
Kevin Wolfefa84d42009-05-18 16:42:12 +02002410 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002411 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002412 bool encryption =
2413 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002414 const char *encryptfmt =
2415 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002416 const char *preallocation =
2417 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002418
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002419 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002420 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002421 ret = -1;
2422 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002423 }
2424
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002425 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002426 error_report("Compression and encryption not supported at "
2427 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002428 ret = -1;
2429 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002430 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002431
Chunyan Liu83d05212014-06-05 17:20:51 +08002432 if (preallocation
2433 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002434 {
2435 error_report("Compression and preallocation not supported at "
2436 "the same time");
2437 ret = -1;
2438 goto out;
2439 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002440 }
2441
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002442 /*
2443 * The later open call will need any decryption secrets, and
2444 * bdrv_create() will purge "opts", so extract them now before
2445 * they are lost.
2446 */
2447 if (!skip_create) {
2448 open_opts = qdict_new();
2449 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2450 }
2451
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002452 if (!skip_create) {
2453 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002454 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002455 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002456 error_reportf_err(local_err, "%s: error while converting %s: ",
2457 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002458 goto out;
bellardea2384d2004-08-01 21:59:26 +00002459 }
2460 }
ths3b46e622007-09-17 08:09:54 +00002461
Max Reitz4d7c4872019-07-24 19:12:29 +02002462 s.target_is_new = !skip_create;
2463
Peter Lieven9fd77f92017-04-21 11:11:55 +02002464 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002465 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002466 if (ret < 0) {
2467 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002468 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002469 }
2470
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002471 if (skip_create) {
2472 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002473 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002474 } else {
2475 /* TODO ultimately we should allow --target-image-opts
2476 * to be used even when -n is not given.
2477 * That has to wait for bdrv_create to be improved
2478 * to allow filenames in option syntax
2479 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002480 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002481 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002482 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002483 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002484 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002485 ret = -1;
2486 goto out;
2487 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002488 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002489
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002490 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002491 error_report("Compression not supported for this file format");
2492 ret = -1;
2493 goto out;
2494 }
2495
Eric Blake5def6b82016-06-23 16:37:19 -06002496 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002497 * or discard_alignment of the out_bs is greater. Limit to
2498 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2499 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002500 MAX(s.buf_sectors,
2501 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2502 out_bs->bl.pdiscard_alignment >>
2503 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002504
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002505 /* try to align the write requests to the destination to avoid unnecessary
2506 * RMW cycles. */
2507 s.alignment = MAX(pow2floor(s.min_sparse),
2508 DIV_ROUND_UP(out_bs->bl.request_alignment,
2509 BDRV_SECTOR_SIZE));
2510 assert(is_power_of_2(s.alignment));
2511
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002512 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002513 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002514 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002515 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002516 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002517 ret = -1;
2518 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002519 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002520 error_report("output file is smaller than input file");
2521 ret = -1;
2522 goto out;
2523 }
2524 }
2525
Max Reitzc69291e2020-01-21 16:59:14 +01002526 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002527 /* Errors are treated as "backing length unknown" (which means
2528 * s.target_backing_sectors has to be negative, which it will
2529 * be automatically). The backing file length is used only
2530 * for optimizations, so such a case is not fatal. */
2531 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2532 } else {
2533 s.target_backing_sectors = -1;
2534 }
2535
Peter Lieven24f833c2013-11-27 11:07:07 +01002536 ret = bdrv_get_info(out_bs, &bdi);
2537 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002538 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002539 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002540 goto out;
2541 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002542 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002543 s.compressed = s.compressed || bdi.needs_compressed_writes;
2544 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002545 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002546 }
2547
Peter Lieven9fd77f92017-04-21 11:11:55 +02002548 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002549out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002550 if (!ret) {
2551 qemu_progress_print(100, 0);
2552 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002553 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002554 qemu_opts_del(opts);
2555 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002556 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002557 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002558 blk_unref(s.target);
2559 if (s.src) {
2560 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2561 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002562 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002563 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002564 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002565 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002566fail_getopt:
2567 g_free(options);
2568
Peter Lieven9fd77f92017-04-21 11:11:55 +02002569 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002570}
2571
bellard57d1a2b2004-08-03 21:15:11 +00002572
bellardfaea38e2006-08-05 21:31:00 +00002573static void dump_snapshots(BlockDriverState *bs)
2574{
2575 QEMUSnapshotInfo *sn_tab, *sn;
2576 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002577
2578 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2579 if (nb_sns <= 0)
2580 return;
2581 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002582 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002583 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002584 for(i = 0; i < nb_sns; i++) {
2585 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002586 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002587 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002588 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002589 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002590}
2591
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002592static void dump_json_image_info_list(ImageInfoList *list)
2593{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002594 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002595 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002596 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002597
2598 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2599 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002600 str = qobject_to_json_pretty(obj);
2601 assert(str != NULL);
2602 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002603 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002604 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002605 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002606}
2607
Benoît Canetc054b3f2012-09-05 13:09:02 +02002608static void dump_json_image_info(ImageInfo *info)
2609{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002610 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002611 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002612 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002613
2614 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2615 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002616 str = qobject_to_json_pretty(obj);
2617 assert(str != NULL);
2618 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002619 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002620 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002621 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002622}
2623
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002624static void dump_human_image_info_list(ImageInfoList *list)
2625{
2626 ImageInfoList *elem;
2627 bool delim = false;
2628
2629 for (elem = list; elem; elem = elem->next) {
2630 if (delim) {
2631 printf("\n");
2632 }
2633 delim = true;
2634
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002635 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002636 }
2637}
2638
2639static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2640{
2641 return strcmp(a, b) == 0;
2642}
2643
2644/**
2645 * Open an image file chain and return an ImageInfoList
2646 *
2647 * @filename: topmost image filename
2648 * @fmt: topmost image format (may be NULL to autodetect)
2649 * @chain: true - enumerate entire backing file chain
2650 * false - only topmost image file
2651 *
2652 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2653 * image file. If there was an error a message will have been printed to
2654 * stderr.
2655 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002656static ImageInfoList *collect_image_info_list(bool image_opts,
2657 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002658 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002659 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002660{
2661 ImageInfoList *head = NULL;
2662 ImageInfoList **last = &head;
2663 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002664 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002665
2666 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2667
2668 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002669 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002670 BlockDriverState *bs;
2671 ImageInfo *info;
2672 ImageInfoList *elem;
2673
2674 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2675 error_report("Backing file '%s' creates an infinite loop.",
2676 filename);
2677 goto err;
2678 }
2679 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2680
Max Reitzefaa7c42016-03-16 19:54:38 +01002681 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002682 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2683 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002684 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002685 goto err;
2686 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002687 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002688
Wenchao Xia43526ec2013-06-06 12:27:58 +08002689 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002690 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002691 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002692 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002693 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002694 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002695
2696 elem = g_new0(ImageInfoList, 1);
2697 elem->value = info;
2698 *last = elem;
2699 last = &elem->next;
2700
Markus Armbruster26f54e92014-10-07 13:59:04 +02002701 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002702
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002703 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002704 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002705 image_opts = false;
2706
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002707 if (chain) {
2708 if (info->has_full_backing_filename) {
2709 filename = info->full_backing_filename;
2710 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002711 error_report("Could not determine absolute backing filename,"
2712 " but backing filename '%s' present",
2713 info->backing_filename);
2714 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002715 }
2716 if (info->has_backing_filename_format) {
2717 fmt = info->backing_filename_format;
2718 }
2719 }
2720 }
2721 g_hash_table_destroy(filenames);
2722 return head;
2723
2724err:
2725 qapi_free_ImageInfoList(head);
2726 g_hash_table_destroy(filenames);
2727 return NULL;
2728}
2729
Benoît Canetc054b3f2012-09-05 13:09:02 +02002730static int img_info(int argc, char **argv)
2731{
2732 int c;
2733 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002734 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002735 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002736 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002737 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002738 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002739
bellardea2384d2004-08-01 21:59:26 +00002740 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002741 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002742 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002743 int option_index = 0;
2744 static const struct option long_options[] = {
2745 {"help", no_argument, 0, 'h'},
2746 {"format", required_argument, 0, 'f'},
2747 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002748 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002749 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002750 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002751 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002752 {0, 0, 0, 0}
2753 };
Fam Zheng335e9932017-05-03 00:35:39 +08002754 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002755 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002756 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002757 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002758 }
bellardea2384d2004-08-01 21:59:26 +00002759 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002760 case ':':
2761 missing_argument(argv[optind - 1]);
2762 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002763 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002764 unrecognized_option(argv[optind - 1]);
2765 break;
bellardea2384d2004-08-01 21:59:26 +00002766 case 'h':
2767 help();
2768 break;
2769 case 'f':
2770 fmt = optarg;
2771 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002772 case 'U':
2773 force_share = true;
2774 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002775 case OPTION_OUTPUT:
2776 output = optarg;
2777 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002778 case OPTION_BACKING_CHAIN:
2779 chain = true;
2780 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002781 case OPTION_OBJECT: {
2782 QemuOpts *opts;
2783 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2784 optarg, true);
2785 if (!opts) {
2786 return 1;
2787 }
2788 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002789 case OPTION_IMAGE_OPTS:
2790 image_opts = true;
2791 break;
bellardea2384d2004-08-01 21:59:26 +00002792 }
2793 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002794 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002795 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002796 }
bellardea2384d2004-08-01 21:59:26 +00002797 filename = argv[optind++];
2798
Benoît Canetc054b3f2012-09-05 13:09:02 +02002799 if (output && !strcmp(output, "json")) {
2800 output_format = OFORMAT_JSON;
2801 } else if (output && !strcmp(output, "human")) {
2802 output_format = OFORMAT_HUMAN;
2803 } else if (output) {
2804 error_report("--output must be used with human or json as argument.");
2805 return 1;
2806 }
2807
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002808 if (qemu_opts_foreach(&qemu_object_opts,
2809 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002810 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002811 return 1;
2812 }
2813
Fam Zheng335e9932017-05-03 00:35:39 +08002814 list = collect_image_info_list(image_opts, filename, fmt, chain,
2815 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002816 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002817 return 1;
2818 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002819
Benoît Canetc054b3f2012-09-05 13:09:02 +02002820 switch (output_format) {
2821 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002822 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002823 break;
2824 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002825 if (chain) {
2826 dump_json_image_info_list(list);
2827 } else {
2828 dump_json_image_info(list->value);
2829 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002830 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002831 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002832
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002833 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002834 return 0;
2835}
2836
Eric Blake30065d12019-03-26 13:40:43 -05002837static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2838 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002839{
2840 switch (output_format) {
2841 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002842 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002843 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002844 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002845 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002846 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002847 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002848 e->start, e->length,
2849 e->has_offset ? e->offset : 0,
2850 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002851 }
2852 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2853 * Modify the flags here to allow more coalescing.
2854 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002855 if (next && (!next->data || next->zero)) {
2856 next->data = false;
2857 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002858 }
2859 break;
2860 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002861 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2862 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002863 (e->start == 0 ? "[" : ",\n"),
2864 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002865 e->zero ? "true" : "false",
2866 e->data ? "true" : "false");
2867 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002868 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002869 }
2870 putchar('}');
2871
2872 if (!next) {
2873 printf("]\n");
2874 }
2875 break;
2876 }
Eric Blake30065d12019-03-26 13:40:43 -05002877 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002878}
2879
Eric Blake5e344dd2017-10-11 22:47:02 -05002880static int get_block_status(BlockDriverState *bs, int64_t offset,
2881 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002882{
Eric Blake237d78f2017-10-11 22:47:03 -05002883 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002884 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002885 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002886 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002887 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002888 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002889
2890 /* As an optimization, we could cache the current range of unallocated
2891 * clusters in each file of the chain, and avoid querying the same
2892 * range repeatedly.
2893 */
2894
2895 depth = 0;
2896 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002897 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002898 if (ret < 0) {
2899 return ret;
2900 }
Eric Blake237d78f2017-10-11 22:47:03 -05002901 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002902 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2903 break;
2904 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002905 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002906 if (bs == NULL) {
2907 ret = 0;
2908 break;
2909 }
2910
2911 depth++;
2912 }
2913
John Snow28756452016-02-05 13:12:33 -05002914 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2915
Max Reitzf30c66b2019-02-01 20:29:05 +01002916 if (file && has_offset) {
2917 bdrv_refresh_filename(file);
2918 filename = file->filename;
2919 }
2920
John Snow28756452016-02-05 13:12:33 -05002921 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002922 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002923 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002924 .data = !!(ret & BDRV_BLOCK_DATA),
2925 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002926 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002927 .has_offset = has_offset,
2928 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002929 .has_filename = filename,
2930 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002931 };
2932
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002933 return 0;
2934}
2935
Fam Zheng16b0d552016-01-26 11:59:02 +08002936static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2937{
2938 if (curr->length == 0) {
2939 return false;
2940 }
2941 if (curr->zero != next->zero ||
2942 curr->data != next->data ||
2943 curr->depth != next->depth ||
2944 curr->has_filename != next->has_filename ||
2945 curr->has_offset != next->has_offset) {
2946 return false;
2947 }
2948 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2949 return false;
2950 }
2951 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2952 return false;
2953 }
2954 return true;
2955}
2956
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002957static int img_map(int argc, char **argv)
2958{
2959 int c;
2960 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002961 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002962 BlockDriverState *bs;
2963 const char *filename, *fmt, *output;
2964 int64_t length;
2965 MapEntry curr = { .length = 0 }, next;
2966 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002967 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002968 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002969
2970 fmt = NULL;
2971 output = NULL;
2972 for (;;) {
2973 int option_index = 0;
2974 static const struct option long_options[] = {
2975 {"help", no_argument, 0, 'h'},
2976 {"format", required_argument, 0, 'f'},
2977 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002978 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002979 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002980 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002981 {0, 0, 0, 0}
2982 };
Fam Zheng335e9932017-05-03 00:35:39 +08002983 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002984 long_options, &option_index);
2985 if (c == -1) {
2986 break;
2987 }
2988 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002989 case ':':
2990 missing_argument(argv[optind - 1]);
2991 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002992 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002993 unrecognized_option(argv[optind - 1]);
2994 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002995 case 'h':
2996 help();
2997 break;
2998 case 'f':
2999 fmt = optarg;
3000 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003001 case 'U':
3002 force_share = true;
3003 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003004 case OPTION_OUTPUT:
3005 output = optarg;
3006 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003007 case OPTION_OBJECT: {
3008 QemuOpts *opts;
3009 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3010 optarg, true);
3011 if (!opts) {
3012 return 1;
3013 }
3014 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003015 case OPTION_IMAGE_OPTS:
3016 image_opts = true;
3017 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003018 }
3019 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003020 if (optind != argc - 1) {
3021 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003022 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003023 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003024
3025 if (output && !strcmp(output, "json")) {
3026 output_format = OFORMAT_JSON;
3027 } else if (output && !strcmp(output, "human")) {
3028 output_format = OFORMAT_HUMAN;
3029 } else if (output) {
3030 error_report("--output must be used with human or json as argument.");
3031 return 1;
3032 }
3033
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003034 if (qemu_opts_foreach(&qemu_object_opts,
3035 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003036 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003037 return 1;
3038 }
3039
Fam Zheng335e9932017-05-03 00:35:39 +08003040 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003041 if (!blk) {
3042 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003043 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003044 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045
3046 if (output_format == OFORMAT_HUMAN) {
3047 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3048 }
3049
Max Reitzf1d3cd72015-02-05 13:58:18 -05003050 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003052 int64_t offset = curr.start + curr.length;
3053 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003054
3055 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003056 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003057 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003058
3059 if (ret < 0) {
3060 error_report("Could not read file metadata: %s", strerror(-ret));
3061 goto out;
3062 }
3063
Fam Zheng16b0d552016-01-26 11:59:02 +08003064 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003065 curr.length += next.length;
3066 continue;
3067 }
3068
3069 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003070 ret = dump_map_entry(output_format, &curr, &next);
3071 if (ret < 0) {
3072 goto out;
3073 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003074 }
3075 curr = next;
3076 }
3077
Eric Blake30065d12019-03-26 13:40:43 -05003078 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003079
3080out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003081 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003082 return ret < 0;
3083}
3084
aliguorif7b4a942009-01-07 17:40:15 +00003085#define SNAPSHOT_LIST 1
3086#define SNAPSHOT_CREATE 2
3087#define SNAPSHOT_APPLY 3
3088#define SNAPSHOT_DELETE 4
3089
Stuart Brady153859b2009-06-07 00:42:17 +01003090static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003091{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003092 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003093 BlockDriverState *bs;
3094 QEMUSnapshotInfo sn;
3095 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003096 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003097 int action = 0;
3098 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003099 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003100 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003101 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003102 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003103
Kevin Wolfce099542016-03-15 13:01:04 +01003104 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003105 /* Parse commandline parameters */
3106 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003107 static const struct option long_options[] = {
3108 {"help", no_argument, 0, 'h'},
3109 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003110 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003111 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003112 {0, 0, 0, 0}
3113 };
Fam Zheng335e9932017-05-03 00:35:39 +08003114 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003115 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003116 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003117 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003118 }
aliguorif7b4a942009-01-07 17:40:15 +00003119 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003120 case ':':
3121 missing_argument(argv[optind - 1]);
3122 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003123 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003124 unrecognized_option(argv[optind - 1]);
3125 break;
aliguorif7b4a942009-01-07 17:40:15 +00003126 case 'h':
3127 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003128 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003129 case 'l':
3130 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003131 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003132 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003133 }
3134 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003135 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003136 break;
3137 case 'a':
3138 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003139 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003140 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003141 }
3142 action = SNAPSHOT_APPLY;
3143 snapshot_name = optarg;
3144 break;
3145 case 'c':
3146 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003147 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003148 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003149 }
3150 action = SNAPSHOT_CREATE;
3151 snapshot_name = optarg;
3152 break;
3153 case 'd':
3154 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003155 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003156 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003157 }
3158 action = SNAPSHOT_DELETE;
3159 snapshot_name = optarg;
3160 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003161 case 'q':
3162 quiet = true;
3163 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003164 case 'U':
3165 force_share = true;
3166 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003167 case OPTION_OBJECT: {
3168 QemuOpts *opts;
3169 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3170 optarg, true);
3171 if (!opts) {
3172 return 1;
3173 }
3174 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003175 case OPTION_IMAGE_OPTS:
3176 image_opts = true;
3177 break;
aliguorif7b4a942009-01-07 17:40:15 +00003178 }
3179 }
3180
Kevin Wolffc11eb22013-08-05 10:53:04 +02003181 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003182 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003183 }
aliguorif7b4a942009-01-07 17:40:15 +00003184 filename = argv[optind++];
3185
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003186 if (qemu_opts_foreach(&qemu_object_opts,
3187 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003188 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003189 return 1;
3190 }
3191
aliguorif7b4a942009-01-07 17:40:15 +00003192 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003193 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3194 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003195 if (!blk) {
3196 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003197 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003198 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003199
3200 /* Perform the requested action */
3201 switch(action) {
3202 case SNAPSHOT_LIST:
3203 dump_snapshots(bs);
3204 break;
3205
3206 case SNAPSHOT_CREATE:
3207 memset(&sn, 0, sizeof(sn));
3208 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3209
3210 qemu_gettimeofday(&tv);
3211 sn.date_sec = tv.tv_sec;
3212 sn.date_nsec = tv.tv_usec * 1000;
3213
3214 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003215 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003216 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003217 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003218 }
aliguorif7b4a942009-01-07 17:40:15 +00003219 break;
3220
3221 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003222 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003223 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003224 error_reportf_err(err, "Could not apply snapshot '%s': ",
3225 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003226 }
aliguorif7b4a942009-01-07 17:40:15 +00003227 break;
3228
3229 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003230 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3231 if (ret < 0) {
3232 error_report("Could not delete snapshot '%s': snapshot not "
3233 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003234 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003235 } else {
3236 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3237 if (ret < 0) {
3238 error_reportf_err(err, "Could not delete snapshot '%s': ",
3239 snapshot_name);
3240 ret = 1;
3241 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003242 }
aliguorif7b4a942009-01-07 17:40:15 +00003243 break;
3244 }
3245
3246 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003247 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003248 if (ret) {
3249 return 1;
3250 }
Stuart Brady153859b2009-06-07 00:42:17 +01003251 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003252}
3253
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003254static int img_rebase(int argc, char **argv)
3255{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003256 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003257 uint8_t *buf_old = NULL;
3258 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003259 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003260 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003261 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3262 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003263 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003264 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003265 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003266 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003267 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003268 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003269 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003270
3271 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003272 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003273 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003274 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003275 out_baseimg = NULL;
3276 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003277 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003278 static const struct option long_options[] = {
3279 {"help", no_argument, 0, 'h'},
3280 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003281 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003282 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003283 {0, 0, 0, 0}
3284 };
Fam Zheng335e9932017-05-03 00:35:39 +08003285 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003286 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003287 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003288 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003289 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003290 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003291 case ':':
3292 missing_argument(argv[optind - 1]);
3293 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003294 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003295 unrecognized_option(argv[optind - 1]);
3296 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003297 case 'h':
3298 help();
3299 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003300 case 'f':
3301 fmt = optarg;
3302 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003303 case 'F':
3304 out_basefmt = optarg;
3305 break;
3306 case 'b':
3307 out_baseimg = optarg;
3308 break;
3309 case 'u':
3310 unsafe = 1;
3311 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003312 case 'p':
3313 progress = 1;
3314 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003315 case 't':
3316 cache = optarg;
3317 break;
Max Reitz40055952014-07-22 22:58:42 +02003318 case 'T':
3319 src_cache = optarg;
3320 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003321 case 'q':
3322 quiet = true;
3323 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003324 case OPTION_OBJECT: {
3325 QemuOpts *opts;
3326 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3327 optarg, true);
3328 if (!opts) {
3329 return 1;
3330 }
3331 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003332 case OPTION_IMAGE_OPTS:
3333 image_opts = true;
3334 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003335 case 'U':
3336 force_share = true;
3337 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003338 }
3339 }
3340
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003341 if (quiet) {
3342 progress = 0;
3343 }
3344
Fam Zhengac1307a2014-04-22 13:36:11 +08003345 if (optind != argc - 1) {
3346 error_exit("Expecting one image file name");
3347 }
3348 if (!unsafe && !out_baseimg) {
3349 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003350 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003351 filename = argv[optind++];
3352
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003353 if (qemu_opts_foreach(&qemu_object_opts,
3354 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003355 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003356 return 1;
3357 }
3358
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003359 qemu_progress_init(progress, 2.0);
3360 qemu_progress_print(0, 100);
3361
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003362 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003363 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003364 if (ret < 0) {
3365 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003366 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003367 }
3368
Kevin Wolfce099542016-03-15 13:01:04 +01003369 src_flags = 0;
3370 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003371 if (ret < 0) {
3372 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003373 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003374 }
3375
Kevin Wolfce099542016-03-15 13:01:04 +01003376 /* The source files are opened read-only, don't care about WCE */
3377 assert((src_flags & BDRV_O_RDWR) == 0);
3378 (void) src_writethrough;
3379
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003380 /*
3381 * Open the images.
3382 *
3383 * Ignore the old backing file for unsafe rebase in case we want to correct
3384 * the reference to a renamed or moved backing file.
3385 */
Fam Zheng335e9932017-05-03 00:35:39 +08003386 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3387 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003388 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003389 ret = -1;
3390 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003391 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003392 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003393
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003394 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003395 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003396 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003397 ret = -1;
3398 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003399 }
3400 }
3401
3402 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003403 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003404 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003405 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003406
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003407 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003408 blk_old_backing = blk_new(qemu_get_aio_context(),
3409 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003410 BLK_PERM_ALL);
3411 ret = blk_insert_bs(blk_old_backing, base_bs,
3412 &local_err);
3413 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003414 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003415 "Could not reuse old backing file '%s': ",
3416 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003417 goto out;
3418 }
3419 } else {
3420 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003421 }
Max Reitz644483d2015-02-05 13:58:17 -05003422
Alex Bligha6166732012-10-16 13:46:18 +01003423 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003424 const char *overlay_filename;
3425 char *out_real_path;
3426
Fam Zheng335e9932017-05-03 00:35:39 +08003427 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003428 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003429 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003430 }
3431 if (force_share) {
3432 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003433 }
3434
Max Reitzf30c66b2019-02-01 20:29:05 +01003435 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003436 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3437 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003438 out_real_path =
3439 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3440 out_baseimg,
3441 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003442 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003443 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003444 error_reportf_err(local_err,
3445 "Could not resolve backing filename: ");
3446 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003447 goto out;
3448 }
3449
Sam Eiderman863cc782019-05-23 19:33:36 +03003450 /*
3451 * Find out whether we rebase an image on top of a previous image
3452 * in its chain.
3453 */
3454 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003455 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003456 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003457 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003458
Kevin Wolfd861ab32019-04-25 14:25:10 +02003459 blk_new_backing = blk_new(qemu_get_aio_context(),
3460 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003461 BLK_PERM_ALL);
3462 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3463 &local_err);
3464 if (ret < 0) {
3465 error_reportf_err(local_err,
3466 "Could not reuse backing file '%s': ",
3467 out_baseimg);
3468 goto out;
3469 }
3470 } else {
3471 blk_new_backing = blk_new_open(out_real_path, NULL,
3472 options, src_flags, &local_err);
3473 g_free(out_real_path);
3474 if (!blk_new_backing) {
3475 error_reportf_err(local_err,
3476 "Could not open new backing file '%s': ",
3477 out_baseimg);
3478 ret = -1;
3479 goto out;
3480 }
Alex Bligha6166732012-10-16 13:46:18 +01003481 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003482 }
3483 }
3484
3485 /*
3486 * Check each unallocated cluster in the COW file. If it is unallocated,
3487 * accesses go to the backing file. We must therefore compare this cluster
3488 * in the old and new backing file, and if they differ we need to copy it
3489 * from the old backing file into the COW file.
3490 *
3491 * If qemu-img crashes during this step, no harm is done. The content of
3492 * the image is the same as the original one at any time.
3493 */
3494 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003495 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003496 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003497 int64_t new_backing_size = 0;
3498 uint64_t offset;
3499 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003500 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003501
Max Reitzf1d3cd72015-02-05 13:58:18 -05003502 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3503 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003504
Eric Blake41536282017-10-11 22:47:15 -05003505 size = blk_getlength(blk);
3506 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003507 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003508 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003509 ret = -1;
3510 goto out;
3511 }
Max Reitz35ddd932019-05-09 19:52:35 +02003512 if (blk_old_backing) {
3513 old_backing_size = blk_getlength(blk_old_backing);
3514 if (old_backing_size < 0) {
3515 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003516
Max Reitz35ddd932019-05-09 19:52:35 +02003517 bdrv_get_backing_filename(bs, backing_name,
3518 sizeof(backing_name));
3519 error_report("Could not get size of '%s': %s",
3520 backing_name, strerror(-old_backing_size));
3521 ret = -1;
3522 goto out;
3523 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003524 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003525 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003526 new_backing_size = blk_getlength(blk_new_backing);
3527 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003528 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003529 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003530 ret = -1;
3531 goto out;
3532 }
Alex Bligha6166732012-10-16 13:46:18 +01003533 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003534
Eric Blake41536282017-10-11 22:47:15 -05003535 if (size != 0) {
3536 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003537 }
3538
Eric Blake41536282017-10-11 22:47:15 -05003539 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003540 bool buf_old_is_zero = false;
3541
Eric Blake41536282017-10-11 22:47:15 -05003542 /* How many bytes can we handle with the next read? */
3543 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003544
3545 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003546 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003547 if (ret < 0) {
3548 error_report("error while reading image metadata: %s",
3549 strerror(-ret));
3550 goto out;
3551 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003552 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003553 continue;
3554 }
3555
Sam Eiderman863cc782019-05-23 19:33:36 +03003556 if (prefix_chain_bs) {
3557 /*
3558 * If cluster wasn't changed since prefix_chain, we don't need
3559 * to take action
3560 */
3561 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003562 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003563 if (ret < 0) {
3564 error_report("error while reading image metadata: %s",
3565 strerror(-ret));
3566 goto out;
3567 }
3568 if (!ret) {
3569 continue;
3570 }
3571 }
3572
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003573 /*
3574 * Read old and new backing file and take into consideration that
3575 * backing files may be smaller than the COW image.
3576 */
Eric Blake41536282017-10-11 22:47:15 -05003577 if (offset >= old_backing_size) {
3578 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003579 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003580 } else {
Eric Blake41536282017-10-11 22:47:15 -05003581 if (offset + n > old_backing_size) {
3582 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003583 }
3584
Eric Blake41536282017-10-11 22:47:15 -05003585 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003586 if (ret < 0) {
3587 error_report("error while reading from old backing file");
3588 goto out;
3589 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003590 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003591
Eric Blake41536282017-10-11 22:47:15 -05003592 if (offset >= new_backing_size || !blk_new_backing) {
3593 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003594 } else {
Eric Blake41536282017-10-11 22:47:15 -05003595 if (offset + n > new_backing_size) {
3596 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003597 }
3598
Eric Blake41536282017-10-11 22:47:15 -05003599 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003600 if (ret < 0) {
3601 error_report("error while reading from new backing file");
3602 goto out;
3603 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003604 }
3605
3606 /* If they differ, we need to write to the COW file */
3607 uint64_t written = 0;
3608
Eric Blake41536282017-10-11 22:47:15 -05003609 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003610 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003611
Eric Blake41536282017-10-11 22:47:15 -05003612 if (compare_buffers(buf_old + written, buf_new + written,
3613 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003614 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003615 if (buf_old_is_zero) {
3616 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3617 } else {
3618 ret = blk_pwrite(blk, offset + written,
3619 buf_old + written, pnum, 0);
3620 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003621 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003622 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003623 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003624 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003625 }
3626 }
3627
3628 written += pnum;
3629 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003630 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003631 }
3632 }
3633
3634 /*
3635 * Change the backing file. All clusters that are different from the old
3636 * backing file are overwritten in the COW file now, so the visible content
3637 * doesn't change when we switch the backing file.
3638 */
Alex Bligha6166732012-10-16 13:46:18 +01003639 if (out_baseimg && *out_baseimg) {
3640 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3641 } else {
3642 ret = bdrv_change_backing_file(bs, NULL, NULL);
3643 }
3644
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003645 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003646 error_report("Could not change the backing file to '%s': No "
3647 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003648 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003649 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003650 out_baseimg, strerror(-ret));
3651 }
3652
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003653 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003654 /*
3655 * TODO At this point it is possible to check if any clusters that are
3656 * allocated in the COW file are the same in the backing file. If so, they
3657 * could be dropped from the COW file. Don't do this before switching the
3658 * backing file, in case of a crash this would lead to corruption.
3659 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003660out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003661 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003662 /* Cleanup */
3663 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003664 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003665 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003666 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003667 qemu_vfree(buf_old);
3668 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003669
Markus Armbruster26f54e92014-10-07 13:59:04 +02003670 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003671 if (ret) {
3672 return 1;
3673 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003674 return 0;
3675}
3676
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003677static int img_resize(int argc, char **argv)
3678{
Markus Armbruster6750e792015-02-12 17:43:08 +01003679 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003680 int c, ret, relative;
3681 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003682 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003683 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003684 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003685 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003686 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003687
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003688 static QemuOptsList resize_options = {
3689 .name = "resize_options",
3690 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3691 .desc = {
3692 {
3693 .name = BLOCK_OPT_SIZE,
3694 .type = QEMU_OPT_SIZE,
3695 .help = "Virtual disk size"
3696 }, {
3697 /* end of list */
3698 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003699 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003700 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003701 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003702 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003703
Kevin Wolfe80fec72011-04-29 10:58:12 +02003704 /* Remove size from argv manually so that negative numbers are not treated
3705 * as options by getopt. */
3706 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003707 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003708 return 1;
3709 }
3710
3711 size = argv[--argc];
3712
3713 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003714 fmt = NULL;
3715 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003716 static const struct option long_options[] = {
3717 {"help", no_argument, 0, 'h'},
3718 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003719 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003720 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003721 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003722 {0, 0, 0, 0}
3723 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003724 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003725 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003726 if (c == -1) {
3727 break;
3728 }
3729 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003730 case ':':
3731 missing_argument(argv[optind - 1]);
3732 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003733 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003734 unrecognized_option(argv[optind - 1]);
3735 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003736 case 'h':
3737 help();
3738 break;
3739 case 'f':
3740 fmt = optarg;
3741 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003742 case 'q':
3743 quiet = true;
3744 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003745 case OPTION_OBJECT: {
3746 QemuOpts *opts;
3747 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3748 optarg, true);
3749 if (!opts) {
3750 return 1;
3751 }
3752 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003753 case OPTION_IMAGE_OPTS:
3754 image_opts = true;
3755 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003756 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003757 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003758 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003759 if (prealloc == PREALLOC_MODE__MAX) {
3760 error_report("Invalid preallocation mode '%s'", optarg);
3761 return 1;
3762 }
3763 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003764 case OPTION_SHRINK:
3765 shrink = true;
3766 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003767 }
3768 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003769 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003770 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003771 }
3772 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003773
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003774 if (qemu_opts_foreach(&qemu_object_opts,
3775 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003776 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003777 return 1;
3778 }
3779
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003780 /* Choose grow, shrink, or absolute resize mode */
3781 switch (size[0]) {
3782 case '+':
3783 relative = 1;
3784 size++;
3785 break;
3786 case '-':
3787 relative = -1;
3788 size++;
3789 break;
3790 default:
3791 relative = 0;
3792 break;
3793 }
3794
3795 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003796 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003797 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003798 if (err) {
3799 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003800 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003801 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003802 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003803 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003804 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3805 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003806
Max Reitzefaa7c42016-03-16 19:54:38 +01003807 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003808 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3809 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003810 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003811 ret = -1;
3812 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003813 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003814
Max Reitzdc5f6902017-06-13 22:20:55 +02003815 current_size = blk_getlength(blk);
3816 if (current_size < 0) {
3817 error_report("Failed to inquire current image length: %s",
3818 strerror(-current_size));
3819 ret = -1;
3820 goto out;
3821 }
3822
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003823 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003824 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003825 } else {
3826 total_size = n;
3827 }
3828 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003829 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003830 ret = -1;
3831 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003832 }
3833
Max Reitzdc5f6902017-06-13 22:20:55 +02003834 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3835 error_report("Preallocation can only be used for growing images");
3836 ret = -1;
3837 goto out;
3838 }
3839
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003840 if (total_size < current_size && !shrink) {
3841 warn_report("Shrinking an image will delete all data beyond the "
3842 "shrunken image's end. Before performing such an "
3843 "operation, make sure there is no important data there.");
3844
3845 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3846 error_report(
3847 "Use the --shrink option to perform a shrink operation.");
3848 ret = -1;
3849 goto out;
3850 } else {
3851 warn_report("Using the --shrink option will suppress this message. "
3852 "Note that future versions of qemu-img may refuse to "
3853 "shrink images without this option.");
3854 }
3855 }
3856
Max Reitze8d04f92019-09-18 11:51:43 +02003857 /*
3858 * The user expects the image to have the desired size after
3859 * resizing, so pass @exact=true. It is of no use to report
3860 * success when the image has not actually been resized.
3861 */
3862 ret = blk_truncate(blk, total_size, true, prealloc, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02003863 if (!ret) {
3864 qprintf(quiet, "Image resized.\n");
3865 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003866 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003867 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003868out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003869 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003870 if (ret) {
3871 return 1;
3872 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003873 return 0;
3874}
3875
Max Reitz76a3a342014-10-27 11:12:51 +01003876static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003877 int64_t offset, int64_t total_work_size,
3878 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003879{
3880 qemu_progress_print(100.f * offset / total_work_size, 0);
3881}
3882
Max Reitz51641352018-05-09 23:00:20 +02003883static int print_amend_option_help(const char *format)
3884{
3885 BlockDriver *drv;
3886
3887 /* Find driver and parse its options */
3888 drv = bdrv_find_format(format);
3889 if (!drv) {
3890 error_report("Unknown file format '%s'", format);
3891 return 1;
3892 }
3893
3894 if (!drv->bdrv_amend_options) {
3895 error_report("Format driver '%s' does not support option amendment",
3896 format);
3897 return 1;
3898 }
3899
3900 /* Every driver supporting amendment must have create_opts */
3901 assert(drv->create_opts);
3902
3903 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003904 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003905 printf("\nNote that not all of these options may be amendable.\n");
3906 return 0;
3907}
3908
Max Reitz6f176b42013-09-03 10:09:50 +02003909static int img_amend(int argc, char **argv)
3910{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003911 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003912 int c, ret = 0;
3913 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003914 QemuOptsList *create_opts = NULL;
3915 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003916 const char *fmt = NULL, *filename, *cache;
3917 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003918 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003919 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003920 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003921 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003922 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003923
Max Reitzbd39e6e2014-07-22 22:58:43 +02003924 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003925 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003926 static const struct option long_options[] = {
3927 {"help", no_argument, 0, 'h'},
3928 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003929 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003930 {0, 0, 0, 0}
3931 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003932 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003933 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003934 if (c == -1) {
3935 break;
3936 }
3937
3938 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003939 case ':':
3940 missing_argument(argv[optind - 1]);
3941 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003942 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003943 unrecognized_option(argv[optind - 1]);
3944 break;
3945 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003946 help();
3947 break;
3948 case 'o':
3949 if (!is_valid_option_list(optarg)) {
3950 error_report("Invalid option list: %s", optarg);
3951 ret = -1;
3952 goto out_no_progress;
3953 }
3954 if (!options) {
3955 options = g_strdup(optarg);
3956 } else {
3957 char *old_options = options;
3958 options = g_strdup_printf("%s,%s", options, optarg);
3959 g_free(old_options);
3960 }
3961 break;
3962 case 'f':
3963 fmt = optarg;
3964 break;
3965 case 't':
3966 cache = optarg;
3967 break;
3968 case 'p':
3969 progress = true;
3970 break;
3971 case 'q':
3972 quiet = true;
3973 break;
3974 case OPTION_OBJECT:
3975 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3976 optarg, true);
3977 if (!opts) {
3978 ret = -1;
3979 goto out_no_progress;
3980 }
3981 break;
3982 case OPTION_IMAGE_OPTS:
3983 image_opts = true;
3984 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003985 }
3986 }
3987
Max Reitz6f176b42013-09-03 10:09:50 +02003988 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003989 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003990 }
3991
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003992 if (qemu_opts_foreach(&qemu_object_opts,
3993 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003994 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003995 ret = -1;
3996 goto out_no_progress;
3997 }
3998
Max Reitz76a3a342014-10-27 11:12:51 +01003999 if (quiet) {
4000 progress = false;
4001 }
4002 qemu_progress_init(progress, 1.0);
4003
Kevin Wolfa283cb62014-02-21 16:24:07 +01004004 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4005 if (fmt && has_help_option(options)) {
4006 /* If a format is explicitly specified (and possibly no filename is
4007 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004008 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004009 goto out;
4010 }
4011
4012 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004013 error_report("Expecting one image file name");
4014 ret = -1;
4015 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004016 }
Max Reitz6f176b42013-09-03 10:09:50 +02004017
Kevin Wolfce099542016-03-15 13:01:04 +01004018 flags = BDRV_O_RDWR;
4019 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004020 if (ret < 0) {
4021 error_report("Invalid cache option: %s", cache);
4022 goto out;
4023 }
4024
Fam Zheng335e9932017-05-03 00:35:39 +08004025 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4026 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004027 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004028 ret = -1;
4029 goto out;
4030 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004031 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004032
4033 fmt = bs->drv->format_name;
4034
Kevin Wolf626f84f2014-02-21 16:24:06 +01004035 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004036 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004037 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004038 goto out;
4039 }
4040
Max Reitz1f996682018-05-09 23:00:17 +02004041 if (!bs->drv->bdrv_amend_options) {
4042 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004043 fmt);
4044 ret = -1;
4045 goto out;
4046 }
4047
Max Reitz1f996682018-05-09 23:00:17 +02004048 /* Every driver supporting amendment must have create_opts */
4049 assert(bs->drv->create_opts);
4050
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004051 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004052 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004053 qemu_opts_do_parse(opts, options, NULL, &err);
4054 if (err) {
4055 error_report_err(err);
4056 ret = -1;
4057 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004058 }
4059
Max Reitz76a3a342014-10-27 11:12:51 +01004060 /* In case the driver does not call amend_status_cb() */
4061 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004062 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004063 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004064 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004065 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004066 goto out;
4067 }
4068
4069out:
Max Reitz76a3a342014-10-27 11:12:51 +01004070 qemu_progress_end();
4071
Max Reitze814dff2015-08-20 16:00:38 -07004072out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004073 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004074 qemu_opts_del(opts);
4075 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004076 g_free(options);
4077
Max Reitz6f176b42013-09-03 10:09:50 +02004078 if (ret) {
4079 return 1;
4080 }
4081 return 0;
4082}
4083
Kevin Wolfb6133b82014-08-05 14:17:13 +02004084typedef struct BenchData {
4085 BlockBackend *blk;
4086 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004087 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004088 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004089 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004090 int nrreq;
4091 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004092 int flush_interval;
4093 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004094 uint8_t *buf;
4095 QEMUIOVector *qiov;
4096
4097 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004098 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004099 uint64_t offset;
4100} BenchData;
4101
Kevin Wolf55d539c2016-06-03 13:59:41 +02004102static void bench_undrained_flush_cb(void *opaque, int ret)
4103{
4104 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004105 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004106 exit(EXIT_FAILURE);
4107 }
4108}
4109
Kevin Wolfb6133b82014-08-05 14:17:13 +02004110static void bench_cb(void *opaque, int ret)
4111{
4112 BenchData *b = opaque;
4113 BlockAIOCB *acb;
4114
4115 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004116 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004117 exit(EXIT_FAILURE);
4118 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004119
4120 if (b->in_flush) {
4121 /* Just finished a flush with drained queue: Start next requests */
4122 assert(b->in_flight == 0);
4123 b->in_flush = false;
4124 } else if (b->in_flight > 0) {
4125 int remaining = b->n - b->in_flight;
4126
Kevin Wolfb6133b82014-08-05 14:17:13 +02004127 b->n--;
4128 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004129
4130 /* Time for flush? Drain queue if requested, then flush */
4131 if (b->flush_interval && remaining % b->flush_interval == 0) {
4132 if (!b->in_flight || !b->drain_on_flush) {
4133 BlockCompletionFunc *cb;
4134
4135 if (b->drain_on_flush) {
4136 b->in_flush = true;
4137 cb = bench_cb;
4138 } else {
4139 cb = bench_undrained_flush_cb;
4140 }
4141
4142 acb = blk_aio_flush(b->blk, cb, b);
4143 if (!acb) {
4144 error_report("Failed to issue flush request");
4145 exit(EXIT_FAILURE);
4146 }
4147 }
4148 if (b->drain_on_flush) {
4149 return;
4150 }
4151 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004152 }
4153
4154 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004155 int64_t offset = b->offset;
4156 /* blk_aio_* might look for completed I/Os and kick bench_cb
4157 * again, so make sure this operation is counted by in_flight
4158 * and b->offset is ready for the next submission.
4159 */
4160 b->in_flight++;
4161 b->offset += b->step;
4162 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004163 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004164 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004165 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004166 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004167 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004168 if (!acb) {
4169 error_report("Failed to issue request");
4170 exit(EXIT_FAILURE);
4171 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004172 }
4173}
4174
4175static int img_bench(int argc, char **argv)
4176{
4177 int c, ret = 0;
4178 const char *fmt = NULL, *filename;
4179 bool quiet = false;
4180 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004181 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004182 int count = 75000;
4183 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004184 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004185 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004186 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004187 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004188 int flush_interval = 0;
4189 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004190 int64_t image_size;
4191 BlockBackend *blk = NULL;
4192 BenchData data = {};
4193 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004194 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004195 struct timeval t1, t2;
4196 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004197 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004198 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004199
4200 for (;;) {
4201 static const struct option long_options[] = {
4202 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004203 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004204 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004205 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004206 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004207 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004208 {0, 0, 0, 0}
4209 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004210 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4211 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004212 if (c == -1) {
4213 break;
4214 }
4215
4216 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004217 case ':':
4218 missing_argument(argv[optind - 1]);
4219 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004220 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004221 unrecognized_option(argv[optind - 1]);
4222 break;
4223 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004224 help();
4225 break;
4226 case 'c':
4227 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004228 unsigned long res;
4229
4230 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004231 error_report("Invalid request count specified");
4232 return 1;
4233 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004234 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004235 break;
4236 }
4237 case 'd':
4238 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004239 unsigned long res;
4240
4241 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004242 error_report("Invalid queue depth specified");
4243 return 1;
4244 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004245 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004246 break;
4247 }
4248 case 'f':
4249 fmt = optarg;
4250 break;
4251 case 'n':
4252 flags |= BDRV_O_NATIVE_AIO;
4253 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004254 case 'i':
4255 ret = bdrv_parse_aio(optarg, &flags);
4256 if (ret < 0) {
4257 error_report("Invalid aio option: %s", optarg);
4258 ret = -1;
4259 goto out;
4260 }
4261 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004262 case 'o':
4263 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004264 offset = cvtnum(optarg);
4265 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004266 error_report("Invalid offset specified");
4267 return 1;
4268 }
4269 break;
4270 }
4271 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004272 case 'q':
4273 quiet = true;
4274 break;
4275 case 's':
4276 {
4277 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004278
Markus Armbruster606caa02017-02-21 21:14:04 +01004279 sval = cvtnum(optarg);
4280 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004281 error_report("Invalid buffer size specified");
4282 return 1;
4283 }
4284
4285 bufsize = sval;
4286 break;
4287 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004288 case 'S':
4289 {
4290 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004291
Markus Armbruster606caa02017-02-21 21:14:04 +01004292 sval = cvtnum(optarg);
4293 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004294 error_report("Invalid step size specified");
4295 return 1;
4296 }
4297
4298 step = sval;
4299 break;
4300 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004301 case 't':
4302 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4303 if (ret < 0) {
4304 error_report("Invalid cache mode");
4305 ret = -1;
4306 goto out;
4307 }
4308 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004309 case 'w':
4310 flags |= BDRV_O_RDWR;
4311 is_write = true;
4312 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004313 case 'U':
4314 force_share = true;
4315 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004316 case OPTION_PATTERN:
4317 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004318 unsigned long res;
4319
4320 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004321 error_report("Invalid pattern byte specified");
4322 return 1;
4323 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004324 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004325 break;
4326 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004327 case OPTION_FLUSH_INTERVAL:
4328 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004329 unsigned long res;
4330
4331 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004332 error_report("Invalid flush interval specified");
4333 return 1;
4334 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004335 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004336 break;
4337 }
4338 case OPTION_NO_DRAIN:
4339 drain_on_flush = false;
4340 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004341 case OPTION_IMAGE_OPTS:
4342 image_opts = true;
4343 break;
4344 }
4345 }
4346
4347 if (optind != argc - 1) {
4348 error_exit("Expecting one image file name");
4349 }
4350 filename = argv[argc - 1];
4351
Kevin Wolf55d539c2016-06-03 13:59:41 +02004352 if (!is_write && flush_interval) {
4353 error_report("--flush-interval is only available in write tests");
4354 ret = -1;
4355 goto out;
4356 }
4357 if (flush_interval && flush_interval < depth) {
4358 error_report("Flush interval can't be smaller than depth");
4359 ret = -1;
4360 goto out;
4361 }
4362
Fam Zheng335e9932017-05-03 00:35:39 +08004363 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4364 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004365 if (!blk) {
4366 ret = -1;
4367 goto out;
4368 }
4369
4370 image_size = blk_getlength(blk);
4371 if (image_size < 0) {
4372 ret = image_size;
4373 goto out;
4374 }
4375
4376 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004377 .blk = blk,
4378 .image_size = image_size,
4379 .bufsize = bufsize,
4380 .step = step ?: bufsize,
4381 .nrreq = depth,
4382 .n = count,
4383 .offset = offset,
4384 .write = is_write,
4385 .flush_interval = flush_interval,
4386 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004387 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004388 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004389 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004390 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004391 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004392 if (flush_interval) {
4393 printf("Sending flush every %d requests\n", flush_interval);
4394 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004395
Fam Zheng79d46582018-01-16 14:08:58 +08004396 buf_size = data.nrreq * data.bufsize;
4397 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004398 memset(data.buf, pattern, data.nrreq * data.bufsize);
4399
Fam Zheng79d46582018-01-16 14:08:58 +08004400 blk_register_buf(blk, data.buf, buf_size);
4401
Kevin Wolfb6133b82014-08-05 14:17:13 +02004402 data.qiov = g_new(QEMUIOVector, data.nrreq);
4403 for (i = 0; i < data.nrreq; i++) {
4404 qemu_iovec_init(&data.qiov[i], 1);
4405 qemu_iovec_add(&data.qiov[i],
4406 data.buf + i * data.bufsize, data.bufsize);
4407 }
4408
4409 gettimeofday(&t1, NULL);
4410 bench_cb(&data, 0);
4411
4412 while (data.n > 0) {
4413 main_loop_wait(false);
4414 }
4415 gettimeofday(&t2, NULL);
4416
4417 printf("Run completed in %3.3f seconds.\n",
4418 (t2.tv_sec - t1.tv_sec)
4419 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4420
4421out:
Fam Zheng79d46582018-01-16 14:08:58 +08004422 if (data.buf) {
4423 blk_unregister_buf(blk, data.buf);
4424 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004425 qemu_vfree(data.buf);
4426 blk_unref(blk);
4427
4428 if (ret) {
4429 return 1;
4430 }
4431 return 0;
4432}
4433
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004434#define C_BS 01
4435#define C_COUNT 02
4436#define C_IF 04
4437#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004438#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004439
4440struct DdInfo {
4441 unsigned int flags;
4442 int64_t count;
4443};
4444
4445struct DdIo {
4446 int bsz; /* Block size */
4447 char *filename;
4448 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004449 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004450};
4451
4452struct DdOpts {
4453 const char *name;
4454 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4455 unsigned int flag;
4456};
4457
4458static int img_dd_bs(const char *arg,
4459 struct DdIo *in, struct DdIo *out,
4460 struct DdInfo *dd)
4461{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004462 int64_t res;
4463
Markus Armbruster606caa02017-02-21 21:14:04 +01004464 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004465
Markus Armbruster606caa02017-02-21 21:14:04 +01004466 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004467 error_report("invalid number: '%s'", arg);
4468 return 1;
4469 }
4470 in->bsz = out->bsz = res;
4471
4472 return 0;
4473}
4474
4475static int img_dd_count(const char *arg,
4476 struct DdIo *in, struct DdIo *out,
4477 struct DdInfo *dd)
4478{
Markus Armbruster606caa02017-02-21 21:14:04 +01004479 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004480
Markus Armbruster606caa02017-02-21 21:14:04 +01004481 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004482 error_report("invalid number: '%s'", arg);
4483 return 1;
4484 }
4485
4486 return 0;
4487}
4488
4489static int img_dd_if(const char *arg,
4490 struct DdIo *in, struct DdIo *out,
4491 struct DdInfo *dd)
4492{
4493 in->filename = g_strdup(arg);
4494
4495 return 0;
4496}
4497
4498static int img_dd_of(const char *arg,
4499 struct DdIo *in, struct DdIo *out,
4500 struct DdInfo *dd)
4501{
4502 out->filename = g_strdup(arg);
4503
4504 return 0;
4505}
4506
Reda Sallahif7c15532016-08-10 16:16:09 +02004507static int img_dd_skip(const char *arg,
4508 struct DdIo *in, struct DdIo *out,
4509 struct DdInfo *dd)
4510{
Markus Armbruster606caa02017-02-21 21:14:04 +01004511 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004512
Markus Armbruster606caa02017-02-21 21:14:04 +01004513 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004514 error_report("invalid number: '%s'", arg);
4515 return 1;
4516 }
4517
4518 return 0;
4519}
4520
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004521static int img_dd(int argc, char **argv)
4522{
4523 int ret = 0;
4524 char *arg = NULL;
4525 char *tmp;
4526 BlockDriver *drv = NULL, *proto_drv = NULL;
4527 BlockBackend *blk1 = NULL, *blk2 = NULL;
4528 QemuOpts *opts = NULL;
4529 QemuOptsList *create_opts = NULL;
4530 Error *local_err = NULL;
4531 bool image_opts = false;
4532 int c, i;
4533 const char *out_fmt = "raw";
4534 const char *fmt = NULL;
4535 int64_t size = 0;
4536 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004537 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004538 struct DdInfo dd = {
4539 .flags = 0,
4540 .count = 0,
4541 };
4542 struct DdIo in = {
4543 .bsz = 512, /* Block size is by default 512 bytes */
4544 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004545 .buf = NULL,
4546 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004547 };
4548 struct DdIo out = {
4549 .bsz = 512,
4550 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004551 .buf = NULL,
4552 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004553 };
4554
4555 const struct DdOpts options[] = {
4556 { "bs", img_dd_bs, C_BS },
4557 { "count", img_dd_count, C_COUNT },
4558 { "if", img_dd_if, C_IF },
4559 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004560 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004561 { NULL, NULL, 0 }
4562 };
4563 const struct option long_options[] = {
4564 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004565 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004566 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004567 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004568 { 0, 0, 0, 0 }
4569 };
4570
Fam Zheng335e9932017-05-03 00:35:39 +08004571 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004572 if (c == EOF) {
4573 break;
4574 }
4575 switch (c) {
4576 case 'O':
4577 out_fmt = optarg;
4578 break;
4579 case 'f':
4580 fmt = optarg;
4581 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004582 case ':':
4583 missing_argument(argv[optind - 1]);
4584 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004585 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004586 unrecognized_option(argv[optind - 1]);
4587 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004588 case 'h':
4589 help();
4590 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004591 case 'U':
4592 force_share = true;
4593 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004594 case OPTION_OBJECT:
4595 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004596 ret = -1;
4597 goto out;
4598 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004599 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004600 case OPTION_IMAGE_OPTS:
4601 image_opts = true;
4602 break;
4603 }
4604 }
4605
4606 for (i = optind; i < argc; i++) {
4607 int j;
4608 arg = g_strdup(argv[i]);
4609
4610 tmp = strchr(arg, '=');
4611 if (tmp == NULL) {
4612 error_report("unrecognized operand %s", arg);
4613 ret = -1;
4614 goto out;
4615 }
4616
4617 *tmp++ = '\0';
4618
4619 for (j = 0; options[j].name != NULL; j++) {
4620 if (!strcmp(arg, options[j].name)) {
4621 break;
4622 }
4623 }
4624 if (options[j].name == NULL) {
4625 error_report("unrecognized operand %s", arg);
4626 ret = -1;
4627 goto out;
4628 }
4629
4630 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4631 ret = -1;
4632 goto out;
4633 }
4634 dd.flags |= options[j].flag;
4635 g_free(arg);
4636 arg = NULL;
4637 }
4638
4639 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4640 error_report("Must specify both input and output files");
4641 ret = -1;
4642 goto out;
4643 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004644
4645 if (qemu_opts_foreach(&qemu_object_opts,
4646 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004647 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004648 ret = -1;
4649 goto out;
4650 }
4651
Fam Zheng335e9932017-05-03 00:35:39 +08004652 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4653 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004654
4655 if (!blk1) {
4656 ret = -1;
4657 goto out;
4658 }
4659
4660 drv = bdrv_find_format(out_fmt);
4661 if (!drv) {
4662 error_report("Unknown file format");
4663 ret = -1;
4664 goto out;
4665 }
4666 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4667
4668 if (!proto_drv) {
4669 error_report_err(local_err);
4670 ret = -1;
4671 goto out;
4672 }
4673 if (!drv->create_opts) {
4674 error_report("Format driver '%s' does not support image creation",
4675 drv->format_name);
4676 ret = -1;
4677 goto out;
4678 }
4679 if (!proto_drv->create_opts) {
4680 error_report("Protocol driver '%s' does not support image creation",
4681 proto_drv->format_name);
4682 ret = -1;
4683 goto out;
4684 }
4685 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4686 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4687
4688 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4689
4690 size = blk_getlength(blk1);
4691 if (size < 0) {
4692 error_report("Failed to get size for '%s'", in.filename);
4693 ret = -1;
4694 goto out;
4695 }
4696
4697 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4698 dd.count * in.bsz < size) {
4699 size = dd.count * in.bsz;
4700 }
4701
Reda Sallahif7c15532016-08-10 16:16:09 +02004702 /* Overflow means the specified offset is beyond input image's size */
4703 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4704 size < in.bsz * in.offset)) {
4705 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4706 } else {
4707 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4708 size - in.bsz * in.offset, &error_abort);
4709 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004710
4711 ret = bdrv_create(drv, out.filename, opts, &local_err);
4712 if (ret < 0) {
4713 error_reportf_err(local_err,
4714 "%s: error while creating output image: ",
4715 out.filename);
4716 ret = -1;
4717 goto out;
4718 }
4719
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004720 /* TODO, we can't honour --image-opts for the target,
4721 * since it needs to be given in a format compatible
4722 * with the bdrv_create() call above which does not
4723 * support image-opts style.
4724 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004725 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004726 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004727
4728 if (!blk2) {
4729 ret = -1;
4730 goto out;
4731 }
4732
Reda Sallahif7c15532016-08-10 16:16:09 +02004733 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4734 size < in.offset * in.bsz)) {
4735 /* We give a warning if the skip option is bigger than the input
4736 * size and create an empty output disk image (i.e. like dd(1)).
4737 */
4738 error_report("%s: cannot skip to specified offset", in.filename);
4739 in_pos = size;
4740 } else {
4741 in_pos = in.offset * in.bsz;
4742 }
4743
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004744 in.buf = g_new(uint8_t, in.bsz);
4745
Reda Sallahif7c15532016-08-10 16:16:09 +02004746 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004747 int in_ret, out_ret;
4748
4749 if (in_pos + in.bsz > size) {
4750 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4751 } else {
4752 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4753 }
4754 if (in_ret < 0) {
4755 error_report("error while reading from input image file: %s",
4756 strerror(-in_ret));
4757 ret = -1;
4758 goto out;
4759 }
4760 in_pos += in_ret;
4761
4762 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4763
4764 if (out_ret < 0) {
4765 error_report("error while writing to output image file: %s",
4766 strerror(-out_ret));
4767 ret = -1;
4768 goto out;
4769 }
4770 out_pos += out_ret;
4771 }
4772
4773out:
4774 g_free(arg);
4775 qemu_opts_del(opts);
4776 qemu_opts_free(create_opts);
4777 blk_unref(blk1);
4778 blk_unref(blk2);
4779 g_free(in.filename);
4780 g_free(out.filename);
4781 g_free(in.buf);
4782 g_free(out.buf);
4783
4784 if (ret) {
4785 return 1;
4786 }
4787 return 0;
4788}
4789
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004790static void dump_json_block_measure_info(BlockMeasureInfo *info)
4791{
4792 QString *str;
4793 QObject *obj;
4794 Visitor *v = qobject_output_visitor_new(&obj);
4795
4796 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4797 visit_complete(v, &obj);
4798 str = qobject_to_json_pretty(obj);
4799 assert(str != NULL);
4800 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004801 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004802 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004803 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004804}
4805
4806static int img_measure(int argc, char **argv)
4807{
4808 static const struct option long_options[] = {
4809 {"help", no_argument, 0, 'h'},
4810 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4811 {"object", required_argument, 0, OPTION_OBJECT},
4812 {"output", required_argument, 0, OPTION_OUTPUT},
4813 {"size", required_argument, 0, OPTION_SIZE},
4814 {"force-share", no_argument, 0, 'U'},
4815 {0, 0, 0, 0}
4816 };
4817 OutputFormat output_format = OFORMAT_HUMAN;
4818 BlockBackend *in_blk = NULL;
4819 BlockDriver *drv;
4820 const char *filename = NULL;
4821 const char *fmt = NULL;
4822 const char *out_fmt = "raw";
4823 char *options = NULL;
4824 char *snapshot_name = NULL;
4825 bool force_share = false;
4826 QemuOpts *opts = NULL;
4827 QemuOpts *object_opts = NULL;
4828 QemuOpts *sn_opts = NULL;
4829 QemuOptsList *create_opts = NULL;
4830 bool image_opts = false;
4831 uint64_t img_size = UINT64_MAX;
4832 BlockMeasureInfo *info = NULL;
4833 Error *local_err = NULL;
4834 int ret = 1;
4835 int c;
4836
4837 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4838 long_options, NULL)) != -1) {
4839 switch (c) {
4840 case '?':
4841 case 'h':
4842 help();
4843 break;
4844 case 'f':
4845 fmt = optarg;
4846 break;
4847 case 'O':
4848 out_fmt = optarg;
4849 break;
4850 case 'o':
4851 if (!is_valid_option_list(optarg)) {
4852 error_report("Invalid option list: %s", optarg);
4853 goto out;
4854 }
4855 if (!options) {
4856 options = g_strdup(optarg);
4857 } else {
4858 char *old_options = options;
4859 options = g_strdup_printf("%s,%s", options, optarg);
4860 g_free(old_options);
4861 }
4862 break;
4863 case 'l':
4864 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4865 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4866 optarg, false);
4867 if (!sn_opts) {
4868 error_report("Failed in parsing snapshot param '%s'",
4869 optarg);
4870 goto out;
4871 }
4872 } else {
4873 snapshot_name = optarg;
4874 }
4875 break;
4876 case 'U':
4877 force_share = true;
4878 break;
4879 case OPTION_OBJECT:
4880 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4881 optarg, true);
4882 if (!object_opts) {
4883 goto out;
4884 }
4885 break;
4886 case OPTION_IMAGE_OPTS:
4887 image_opts = true;
4888 break;
4889 case OPTION_OUTPUT:
4890 if (!strcmp(optarg, "json")) {
4891 output_format = OFORMAT_JSON;
4892 } else if (!strcmp(optarg, "human")) {
4893 output_format = OFORMAT_HUMAN;
4894 } else {
4895 error_report("--output must be used with human or json "
4896 "as argument.");
4897 goto out;
4898 }
4899 break;
4900 case OPTION_SIZE:
4901 {
4902 int64_t sval;
4903
4904 sval = cvtnum(optarg);
4905 if (sval < 0) {
4906 if (sval == -ERANGE) {
4907 error_report("Image size must be less than 8 EiB!");
4908 } else {
4909 error_report("Invalid image size specified! You may use "
4910 "k, M, G, T, P or E suffixes for ");
4911 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4912 "petabytes and exabytes.");
4913 }
4914 goto out;
4915 }
4916 img_size = (uint64_t)sval;
4917 }
4918 break;
4919 }
4920 }
4921
4922 if (qemu_opts_foreach(&qemu_object_opts,
4923 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004924 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004925 goto out;
4926 }
4927
4928 if (argc - optind > 1) {
4929 error_report("At most one filename argument is allowed.");
4930 goto out;
4931 } else if (argc - optind == 1) {
4932 filename = argv[optind];
4933 }
4934
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00004935 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
4936 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004937 goto out;
4938 }
4939 if (filename && img_size != UINT64_MAX) {
4940 error_report("--size N cannot be used together with a filename.");
4941 goto out;
4942 }
4943 if (!filename && img_size == UINT64_MAX) {
4944 error_report("Either --size N or one filename must be specified.");
4945 goto out;
4946 }
4947
4948 if (filename) {
4949 in_blk = img_open(image_opts, filename, fmt, 0,
4950 false, false, force_share);
4951 if (!in_blk) {
4952 goto out;
4953 }
4954
4955 if (sn_opts) {
4956 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4957 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4958 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4959 &local_err);
4960 } else if (snapshot_name != NULL) {
4961 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4962 snapshot_name, &local_err);
4963 }
4964 if (local_err) {
4965 error_reportf_err(local_err, "Failed to load snapshot: ");
4966 goto out;
4967 }
4968 }
4969
4970 drv = bdrv_find_format(out_fmt);
4971 if (!drv) {
4972 error_report("Unknown file format '%s'", out_fmt);
4973 goto out;
4974 }
4975 if (!drv->create_opts) {
4976 error_report("Format driver '%s' does not support image creation",
4977 drv->format_name);
4978 goto out;
4979 }
4980
4981 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4982 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4983 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4984 if (options) {
4985 qemu_opts_do_parse(opts, options, NULL, &local_err);
4986 if (local_err) {
4987 error_report_err(local_err);
4988 error_report("Invalid options for file format '%s'", out_fmt);
4989 goto out;
4990 }
4991 }
4992 if (img_size != UINT64_MAX) {
4993 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4994 }
4995
4996 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4997 if (local_err) {
4998 error_report_err(local_err);
4999 goto out;
5000 }
5001
5002 if (output_format == OFORMAT_HUMAN) {
5003 printf("required size: %" PRIu64 "\n", info->required);
5004 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5005 } else {
5006 dump_json_block_measure_info(info);
5007 }
5008
5009 ret = 0;
5010
5011out:
5012 qapi_free_BlockMeasureInfo(info);
5013 qemu_opts_del(object_opts);
5014 qemu_opts_del(opts);
5015 qemu_opts_del(sn_opts);
5016 qemu_opts_free(create_opts);
5017 g_free(options);
5018 blk_unref(in_blk);
5019 return ret;
5020}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005021
Anthony Liguoric227f092009-10-01 16:12:16 -05005022static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005023#define DEF(option, callback, arg_string) \
5024 { option, callback },
5025#include "qemu-img-cmds.h"
5026#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005027 { NULL, NULL, },
5028};
5029
bellardea2384d2004-08-01 21:59:26 +00005030int main(int argc, char **argv)
5031{
Anthony Liguoric227f092009-10-01 16:12:16 -05005032 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005033 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005034 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005035 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005036 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005037 static const struct option long_options[] = {
5038 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005039 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005040 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005041 {0, 0, 0, 0}
5042 };
bellardea2384d2004-08-01 21:59:26 +00005043
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005044#ifdef CONFIG_POSIX
5045 signal(SIGPIPE, SIG_IGN);
5046#endif
5047
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005048 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005049 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005050 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005051
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005052 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005053 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005054 exit(EXIT_FAILURE);
5055 }
5056
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005057 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005058
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005059 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005060 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005061 if (argc < 2) {
5062 error_exit("Not enough arguments");
5063 }
Stuart Brady153859b2009-06-07 00:42:17 +01005064
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005065 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005066 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005067 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005068
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005069 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005070 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005071 case ':':
5072 missing_argument(argv[optind - 1]);
5073 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005074 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005075 unrecognized_option(argv[optind - 1]);
5076 return 0;
5077 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005078 help();
5079 return 0;
5080 case 'V':
5081 printf(QEMU_IMG_VERSION);
5082 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005083 case 'T':
5084 g_free(trace_file);
5085 trace_file = trace_opt_parse(optarg);
5086 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005087 }
bellardea2384d2004-08-01 21:59:26 +00005088 }
Stuart Brady153859b2009-06-07 00:42:17 +01005089
Denis V. Lunev10985132016-06-17 17:44:13 +03005090 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005091
Denis V. Lunev10985132016-06-17 17:44:13 +03005092 /* reset getopt_long scanning */
5093 argc -= optind;
5094 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005095 return 0;
5096 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005097 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005098 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005099
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005100 if (!trace_init_backends()) {
5101 exit(1);
5102 }
5103 trace_init_file(trace_file);
5104 qemu_set_log(LOG_TRACE);
5105
Denis V. Lunev10985132016-06-17 17:44:13 +03005106 /* find the command */
5107 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5108 if (!strcmp(cmdname, cmd->name)) {
5109 return cmd->handler(argc, argv);
5110 }
5111 }
Jeff Cody7db16892014-04-25 17:02:32 -04005112
Stuart Brady153859b2009-06-07 00:42:17 +01005113 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005114 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005115}