blob: afddf33f08c66b0c2ad1946655f119fa1feb7c0f [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
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800820 qapi_free_ImageCheck(check);
821 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500822 ret = collect_image_check(bs, check, filename, fmt, 0);
823
824 check->leaks_fixed = leaks_fixed;
825 check->corruptions_fixed = corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200826 }
827
Max Reitz832390a2014-10-23 15:29:12 +0200828 if (!ret) {
829 switch (output_format) {
830 case OFORMAT_HUMAN:
831 dump_human_image_check(check, quiet);
832 break;
833 case OFORMAT_JSON:
834 dump_json_image_check(check, quiet);
835 break;
836 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500837 }
838
839 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200840 if (ret) {
841 error_report("Check failed: %s", strerror(-ret));
842 } else {
843 error_report("Check failed");
844 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500845 ret = 1;
846 goto fail;
847 }
848
849 if (check->corruptions) {
850 ret = 2;
851 } else if (check->leaks) {
852 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200853 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500854 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000855 }
856
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500857fail:
858 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200859 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500860 return ret;
aliguori15859692009-04-21 23:11:53 +0000861}
862
Max Reitzd4a32382014-10-24 15:57:37 +0200863typedef struct CommonBlockJobCBInfo {
864 BlockDriverState *bs;
865 Error **errp;
866} CommonBlockJobCBInfo;
867
868static void common_block_job_cb(void *opaque, int ret)
869{
870 CommonBlockJobCBInfo *cbi = opaque;
871
872 if (ret < 0) {
873 error_setg_errno(cbi->errp, -ret, "Block job failed");
874 }
Max Reitzd4a32382014-10-24 15:57:37 +0200875}
876
877static void run_block_job(BlockJob *job, Error **errp)
878{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200879 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800880 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200881
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200882 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200883 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200884 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200885 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200886 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300887 if (job->job.progress.total) {
888 progress = (float)job->job.progress.current /
889 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200890 }
891 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200892 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200893
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200894 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200895 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800896 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200897 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800898 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200899 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200900 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200901
sochin.jiang4172a002017-06-15 14:47:33 +0800902 /* publish completion progress only when success */
903 if (!ret) {
904 qemu_progress_print(100.f, 0);
905 }
Max Reitzd4a32382014-10-24 15:57:37 +0200906}
907
bellardea2384d2004-08-01 21:59:26 +0000908static int img_commit(int argc, char **argv)
909{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400910 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200911 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200912 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200913 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100914 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200915 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100916 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200917 Error *local_err = NULL;
918 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000919 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200920 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000921
922 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400923 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200924 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000925 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000926 static const struct option long_options[] = {
927 {"help", no_argument, 0, 'h'},
928 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000929 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000930 {0, 0, 0, 0}
931 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800932 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000933 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100934 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000935 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100936 }
bellardea2384d2004-08-01 21:59:26 +0000937 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800938 case ':':
939 missing_argument(argv[optind - 1]);
940 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100941 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800942 unrecognized_option(argv[optind - 1]);
943 break;
bellardea2384d2004-08-01 21:59:26 +0000944 case 'h':
945 help();
946 break;
947 case 'f':
948 fmt = optarg;
949 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400950 case 't':
951 cache = optarg;
952 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200953 case 'b':
954 base = optarg;
955 /* -b implies -d */
956 drop = true;
957 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200958 case 'd':
959 drop = true;
960 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200961 case 'p':
962 progress = true;
963 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100964 case 'q':
965 quiet = true;
966 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000967 case OPTION_OBJECT: {
968 QemuOpts *opts;
969 opts = qemu_opts_parse_noisily(&qemu_object_opts,
970 optarg, true);
971 if (!opts) {
972 return 1;
973 }
974 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000975 case OPTION_IMAGE_OPTS:
976 image_opts = true;
977 break;
bellardea2384d2004-08-01 21:59:26 +0000978 }
979 }
Max Reitz687fa1d2014-10-24 15:57:39 +0200980
981 /* Progress is not shown in Quiet mode */
982 if (quiet) {
983 progress = false;
984 }
985
Kevin Wolffc11eb22013-08-05 10:53:04 +0200986 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800987 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100988 }
bellardea2384d2004-08-01 21:59:26 +0000989 filename = argv[optind++];
990
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000991 if (qemu_opts_foreach(&qemu_object_opts,
992 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200993 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000994 return 1;
995 }
996
Max Reitz9a86fe42014-10-24 15:57:38 +0200997 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +0100998 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400999 if (ret < 0) {
1000 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001001 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001002 }
1003
Fam Zheng335e9932017-05-03 00:35:39 +08001004 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1005 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001006 if (!blk) {
1007 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001008 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001009 bs = blk_bs(blk);
1010
Max Reitz687fa1d2014-10-24 15:57:39 +02001011 qemu_progress_init(progress, 1.f);
1012 qemu_progress_print(0.f, 100);
1013
Max Reitz1b22bff2014-10-24 15:57:40 +02001014 if (base) {
1015 base_bs = bdrv_find_backing_image(bs, base);
1016 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001017 error_setg(&local_err,
1018 "Did not find '%s' in the backing chain of '%s'",
1019 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001020 goto done;
1021 }
1022 } else {
1023 /* This is different from QMP, which by default uses the deepest file in
1024 * the backing chain (i.e., the very base); however, the traditional
1025 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001026 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001027 if (!base_bs) {
1028 error_setg(&local_err, "Image does not have a backing file");
1029 goto done;
1030 }
bellardea2384d2004-08-01 21:59:26 +00001031 }
1032
Max Reitzd4a32382014-10-24 15:57:37 +02001033 cbi = (CommonBlockJobCBInfo){
1034 .errp = &local_err,
1035 .bs = bs,
1036 };
1037
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001038 aio_context = bdrv_get_aio_context(bs);
1039 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001040 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001041 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001042 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001043 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001044 if (local_err) {
1045 goto done;
1046 }
1047
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001048 /* When the block job completes, the BlockBackend reference will point to
1049 * the old backing file. In order to avoid that the top image is already
1050 * deleted, so we can still empty it afterwards, increment the reference
1051 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001052 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001053 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001054 }
1055
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001056 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001057 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001058 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001059 if (local_err) {
1060 goto unref_backing;
1061 }
1062
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001063 if (!drop && bs->drv->bdrv_make_empty) {
1064 ret = bs->drv->bdrv_make_empty(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001065 if (ret) {
1066 error_setg_errno(&local_err, -ret, "Could not empty %s",
1067 filename);
1068 goto unref_backing;
1069 }
1070 }
1071
1072unref_backing:
1073 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001074 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001075 }
Max Reitzd4a32382014-10-24 15:57:37 +02001076
1077done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001078 qemu_progress_end();
1079
Markus Armbruster26f54e92014-10-07 13:59:04 +02001080 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001081
1082 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001083 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001084 return 1;
1085 }
Max Reitzd4a32382014-10-24 15:57:37 +02001086
1087 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001088 return 0;
1089}
1090
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001091/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001092 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1093 * of the first sector boundary within buf where the sector contains a
1094 * non-zero byte. This function is robust to a buffer that is not
1095 * sector-aligned.
1096 */
1097static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1098{
1099 int64_t i;
1100 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1101
1102 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1103 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1104 return i;
1105 }
1106 }
1107 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1108 return i;
1109 }
1110 return -1;
1111}
1112
1113/*
thsf58c7b32008-06-05 21:53:49 +00001114 * Returns true iff the first sector pointed to by 'buf' contains at least
1115 * a non-NUL byte.
1116 *
1117 * 'pnum' is set to the number of sectors (including and immediately following
1118 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001119 * The function will try to align the end offset to alignment boundaries so
1120 * that the request will at least end aligned and consequtive requests will
1121 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001122 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001123static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1124 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001125{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001126 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001127 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001128
1129 if (n <= 0) {
1130 *pnum = 0;
1131 return 0;
1132 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001133 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001134 for(i = 1; i < n; i++) {
1135 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001136 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001137 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001138 }
bellardea2384d2004-08-01 21:59:26 +00001139 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001140
1141 tail = (sector_num + i) & (alignment - 1);
1142 if (tail) {
1143 if (is_zero && i <= tail) {
1144 /* treat unallocated areas which only consist
1145 * of a small tail as allocated. */
1146 is_zero = false;
1147 }
1148 if (!is_zero) {
1149 /* align up end offset of allocated areas. */
1150 i += alignment - tail;
1151 i = MIN(i, n);
1152 } else {
1153 /* align down end offset of zero areas. */
1154 i -= tail;
1155 }
1156 }
bellardea2384d2004-08-01 21:59:26 +00001157 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001158 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001159}
1160
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001161/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001162 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1163 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1164 * breaking up write requests for only small sparse areas.
1165 */
1166static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001167 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001168{
1169 int ret;
1170 int num_checked, num_used;
1171
1172 if (n < min) {
1173 min = n;
1174 }
1175
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001176 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001177 if (!ret) {
1178 return ret;
1179 }
1180
1181 num_used = *pnum;
1182 buf += BDRV_SECTOR_SIZE * *pnum;
1183 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001184 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001185 num_checked = num_used;
1186
1187 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001188 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001189
1190 buf += BDRV_SECTOR_SIZE * *pnum;
1191 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001192 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001193 num_checked += *pnum;
1194 if (ret) {
1195 num_used = num_checked;
1196 } else if (*pnum >= min) {
1197 break;
1198 }
1199 }
1200
1201 *pnum = num_used;
1202 return 1;
1203}
1204
1205/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001206 * Compares two buffers sector by sector. Returns 0 if the first
1207 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001208 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001209 * pnum is set to the sector-aligned size of the buffer prefix that
1210 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001212static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1213 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001214{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001215 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001216 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001217
Eric Blakedc61cd32017-10-11 22:47:14 -05001218 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001219
Eric Blakedc61cd32017-10-11 22:47:14 -05001220 res = !!memcmp(buf1, buf2, i);
1221 while (i < bytes) {
1222 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001223
Eric Blakedc61cd32017-10-11 22:47:14 -05001224 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001225 break;
1226 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001227 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001228 }
1229
1230 *pnum = i;
1231 return res;
1232}
1233
Stefano Garzarella97ede572019-05-08 12:43:24 +02001234#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001235
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001236/*
1237 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1238 *
Eric Blake0608e402017-10-11 22:47:12 -05001239 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1240 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1241 * failure), and 4 on error (the exit status for read errors), after emitting
1242 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001243 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001244 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001245 * @param offset: Starting offset to check
1246 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001247 * @param filename: Name of disk file we are checking (logging purpose)
1248 * @param buffer: Allocated buffer for storing read data
1249 * @param quiet: Flag for quiet mode
1250 */
Eric Blakec41508e2017-10-11 22:47:13 -05001251static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1252 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001253 uint8_t *buffer, bool quiet)
1254{
Eric Blakedebb38a2017-10-11 22:47:11 -05001255 int ret = 0;
1256 int64_t idx;
1257
Eric Blakec41508e2017-10-11 22:47:13 -05001258 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001259 if (ret < 0) {
1260 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001261 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001262 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001263 }
Eric Blakec41508e2017-10-11 22:47:13 -05001264 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001265 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001266 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001267 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001268 return 1;
1269 }
1270
1271 return 0;
1272}
1273
1274/*
1275 * Compares two images. Exit codes:
1276 *
1277 * 0 - Images are identical
1278 * 1 - Images differ
1279 * >1 - Error occurred
1280 */
1281static int img_compare(int argc, char **argv)
1282{
Max Reitz40055952014-07-22 22:58:42 +02001283 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001284 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001285 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001286 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001287 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001288 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001289 int allocated1, allocated2;
1290 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1291 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001292 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001293 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001294 int64_t total_size;
1295 int64_t offset = 0;
1296 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001297 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001298 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001299 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001300 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001301
Max Reitz40055952014-07-22 22:58:42 +02001302 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001303 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001304 static const struct option long_options[] = {
1305 {"help", no_argument, 0, 'h'},
1306 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001307 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001308 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001309 {0, 0, 0, 0}
1310 };
Fam Zheng335e9932017-05-03 00:35:39 +08001311 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001312 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001313 if (c == -1) {
1314 break;
1315 }
1316 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001317 case ':':
1318 missing_argument(argv[optind - 1]);
1319 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001320 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001321 unrecognized_option(argv[optind - 1]);
1322 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001323 case 'h':
1324 help();
1325 break;
1326 case 'f':
1327 fmt1 = optarg;
1328 break;
1329 case 'F':
1330 fmt2 = optarg;
1331 break;
Max Reitz40055952014-07-22 22:58:42 +02001332 case 'T':
1333 cache = optarg;
1334 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 case 'p':
1336 progress = true;
1337 break;
1338 case 'q':
1339 quiet = true;
1340 break;
1341 case 's':
1342 strict = true;
1343 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001344 case 'U':
1345 force_share = true;
1346 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001347 case OPTION_OBJECT: {
1348 QemuOpts *opts;
1349 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1350 optarg, true);
1351 if (!opts) {
1352 ret = 2;
1353 goto out4;
1354 }
1355 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001356 case OPTION_IMAGE_OPTS:
1357 image_opts = true;
1358 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359 }
1360 }
1361
1362 /* Progress is not shown in Quiet mode */
1363 if (quiet) {
1364 progress = false;
1365 }
1366
1367
Kevin Wolffc11eb22013-08-05 10:53:04 +02001368 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001369 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001370 }
1371 filename1 = argv[optind++];
1372 filename2 = argv[optind++];
1373
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001374 if (qemu_opts_foreach(&qemu_object_opts,
1375 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001376 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001377 ret = 2;
1378 goto out4;
1379 }
1380
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001381 /* Initialize before goto out */
1382 qemu_progress_init(progress, 2.0);
1383
Kevin Wolfce099542016-03-15 13:01:04 +01001384 flags = 0;
1385 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001386 if (ret < 0) {
1387 error_report("Invalid source cache option: %s", cache);
1388 ret = 2;
1389 goto out3;
1390 }
1391
Fam Zheng335e9932017-05-03 00:35:39 +08001392 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1393 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001394 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001396 goto out3;
1397 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001398
Fam Zheng335e9932017-05-03 00:35:39 +08001399 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1400 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001401 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001402 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001403 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001404 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001405 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001406 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001407
Max Reitzf1d3cd72015-02-05 13:58:18 -05001408 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1409 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001410 total_size1 = blk_getlength(blk1);
1411 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001412 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001413 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001414 ret = 4;
1415 goto out;
1416 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001417 total_size2 = blk_getlength(blk2);
1418 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001419 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001420 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001421 ret = 4;
1422 goto out;
1423 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001424 total_size = MIN(total_size1, total_size2);
1425 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001426
1427 qemu_progress_print(0, 100);
1428
Eric Blake033d9fc2017-10-11 22:47:16 -05001429 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001430 ret = 1;
1431 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1432 goto out;
1433 }
1434
Eric Blake033d9fc2017-10-11 22:47:16 -05001435 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001436 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001437
Eric Blake033d9fc2017-10-11 22:47:16 -05001438 status1 = bdrv_block_status_above(bs1, NULL, offset,
1439 total_size1 - offset, &pnum1, NULL,
1440 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001441 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001442 ret = 3;
1443 error_report("Sector allocation test failed for %s", filename1);
1444 goto out;
1445 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001446 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447
Eric Blake033d9fc2017-10-11 22:47:16 -05001448 status2 = bdrv_block_status_above(bs2, NULL, offset,
1449 total_size2 - offset, &pnum2, NULL,
1450 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001451 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001452 ret = 3;
1453 error_report("Sector allocation test failed for %s", filename2);
1454 goto out;
1455 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001456 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001457
1458 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001459 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001460
Fam Zheng25ad8e62016-01-13 16:37:41 +08001461 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001462 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001463 ret = 1;
1464 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001465 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001466 goto out;
1467 }
1468 }
1469 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001470 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001471 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001472 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001473 int64_t pnum;
1474
Eric Blake033d9fc2017-10-11 22:47:16 -05001475 chunk = MIN(chunk, IO_BUF_SIZE);
1476 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477 if (ret < 0) {
1478 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001479 " of %s: %s",
1480 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481 ret = 4;
1482 goto out;
1483 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001484 ret = blk_pread(blk2, offset, buf2, chunk);
1485 if (ret < 0) {
1486 error_report("Error while reading offset %" PRId64
1487 " of %s: %s",
1488 offset, filename2, strerror(-ret));
1489 ret = 4;
1490 goto out;
1491 }
1492 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1493 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001494 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001496 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001497 goto out;
1498 }
1499 }
1500 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001501 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 filename1, buf1, quiet);
1505 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001506 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001507 filename2, buf1, quiet);
1508 }
1509 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 goto out;
1511 }
1512 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001513 offset += chunk;
1514 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001515 }
1516
Eric Blake033d9fc2017-10-11 22:47:16 -05001517 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001518 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 const char *filename_over;
1520
1521 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001522 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001523 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001524 filename_over = filename1;
1525 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001526 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001527 filename_over = filename2;
1528 }
1529
Eric Blake033d9fc2017-10-11 22:47:16 -05001530 while (offset < progress_base) {
1531 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1532 progress_base - offset, &chunk,
1533 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534 if (ret < 0) {
1535 ret = 3;
1536 error_report("Sector allocation test failed for %s",
1537 filename_over);
1538 goto out;
1539
1540 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001541 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001542 chunk = MIN(chunk, IO_BUF_SIZE);
1543 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 filename_over, buf1, quiet);
1545 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546 goto out;
1547 }
1548 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001549 offset += chunk;
1550 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 }
1552 }
1553
1554 qprintf(quiet, "Images are identical.\n");
1555 ret = 0;
1556
1557out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001558 qemu_vfree(buf1);
1559 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001560 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001561out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001562 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001563out3:
1564 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001565out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001566 return ret;
1567}
1568
Kevin Wolf690c7302015-03-19 13:33:32 +01001569enum ImgConvertBlockStatus {
1570 BLK_DATA,
1571 BLK_ZERO,
1572 BLK_BACKING_FILE,
1573};
1574
Peter Lieven2d9187b2017-02-28 13:40:07 +01001575#define MAX_COROUTINES 16
1576
Kevin Wolf690c7302015-03-19 13:33:32 +01001577typedef struct ImgConvertState {
1578 BlockBackend **src;
1579 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001580 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001581 int64_t total_sectors;
1582 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001583 int64_t allocated_done;
1584 int64_t sector_num;
1585 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001586 enum ImgConvertBlockStatus status;
1587 int64_t sector_next_status;
1588 BlockBackend *target;
1589 bool has_zero_init;
1590 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001591 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001592 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001593 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001594 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001595 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001596 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001597 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001598 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001599 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001600 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001601 size_t cluster_sectors;
1602 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001603 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001604 int running_coroutines;
1605 Coroutine *co[MAX_COROUTINES];
1606 int64_t wait_sector_num[MAX_COROUTINES];
1607 CoMutex lock;
1608 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001609} ImgConvertState;
1610
Peter Lieven2d9187b2017-02-28 13:40:07 +01001611static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1612 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001613{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001614 *src_cur = 0;
1615 *src_cur_offset = 0;
1616 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1617 *src_cur_offset += s->src_sectors[*src_cur];
1618 (*src_cur)++;
1619 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001620 }
1621}
1622
1623static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1624{
Eric Blake31826642017-10-11 22:47:08 -05001625 int64_t src_cur_offset;
1626 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001627 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001628
Peter Lieven2d9187b2017-02-28 13:40:07 +01001629 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001630
1631 assert(s->total_sectors > sector_num);
1632 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1633
Max Reitz351c8ef2018-05-01 18:57:49 +02001634 if (s->target_backing_sectors >= 0) {
1635 if (sector_num >= s->target_backing_sectors) {
1636 post_backing_zero = s->unallocated_blocks_are_zero;
1637 } else if (sector_num + n > s->target_backing_sectors) {
1638 /* Split requests around target_backing_sectors (because
1639 * starting from there, zeros are handled differently) */
1640 n = s->target_backing_sectors - sector_num;
1641 }
1642 }
1643
Kevin Wolf690c7302015-03-19 13:33:32 +01001644 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001645 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1646 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001647
Max Reitz8eaac022019-05-07 22:35:03 +02001648 do {
1649 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001650
Max Reitz8eaac022019-05-07 22:35:03 +02001651 if (s->target_has_backing) {
1652 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1653 count, &count, NULL, NULL);
1654 } else {
1655 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1656 offset, count, &count, NULL,
1657 NULL);
1658 }
1659
1660 if (ret < 0) {
1661 if (s->salvage) {
1662 if (n == 1) {
1663 if (!s->quiet) {
1664 warn_report("error while reading block status at "
1665 "offset %" PRIu64 ": %s", offset,
1666 strerror(-ret));
1667 }
1668 /* Just try to read the data, then */
1669 ret = BDRV_BLOCK_DATA;
1670 count = BDRV_SECTOR_SIZE;
1671 } else {
1672 /* Retry on a shorter range */
1673 n = DIV_ROUND_UP(n, 4);
1674 }
1675 } else {
1676 error_report("error while reading block status at offset "
1677 "%" PRIu64 ": %s", offset, strerror(-ret));
1678 return ret;
1679 }
1680 }
1681 } while (ret < 0);
1682
Eric Blake31826642017-10-11 22:47:08 -05001683 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001684
1685 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001686 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001687 } else if (ret & BDRV_BLOCK_DATA) {
1688 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001689 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001690 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001691 }
1692
1693 s->sector_next_status = sector_num + n;
1694 }
1695
1696 n = MIN(n, s->sector_next_status - sector_num);
1697 if (s->status == BLK_DATA) {
1698 n = MIN(n, s->buf_sectors);
1699 }
1700
1701 /* We need to write complete clusters for compressed images, so if an
1702 * unallocated area is shorter than that, we must consider the whole
1703 * cluster allocated. */
1704 if (s->compressed) {
1705 if (n < s->cluster_sectors) {
1706 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1707 s->status = BLK_DATA;
1708 } else {
1709 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1710 }
1711 }
1712
1713 return n;
1714}
1715
Peter Lieven2d9187b2017-02-28 13:40:07 +01001716static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1717 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001718{
Max Reitz8eaac022019-05-07 22:35:03 +02001719 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001720 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001721
Kevin Wolf690c7302015-03-19 13:33:32 +01001722 assert(nb_sectors <= s->buf_sectors);
1723 while (nb_sectors > 0) {
1724 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001725 int src_cur;
1726 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001727 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001728
1729 /* In the case of compression with multiple source files, we can get a
1730 * nb_sectors that spreads into the next part. So we must be able to
1731 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001732 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1733 blk = s->src[src_cur];
1734 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001735
Max Reitz8eaac022019-05-07 22:35:03 +02001736 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001737
Max Reitz8eaac022019-05-07 22:35:03 +02001738 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1739 if (single_read_until > offset) {
1740 n = 1;
1741 }
1742
1743 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001744 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001745 if (s->salvage) {
1746 if (n > 1) {
1747 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1748 continue;
1749 } else {
1750 if (!s->quiet) {
1751 warn_report("error while reading offset %" PRIu64
1752 ": %s", offset, strerror(-ret));
1753 }
1754 memset(buf, 0, BDRV_SECTOR_SIZE);
1755 }
1756 } else {
1757 return ret;
1758 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001759 }
1760
1761 sector_num += n;
1762 nb_sectors -= n;
1763 buf += n * BDRV_SECTOR_SIZE;
1764 }
1765
1766 return 0;
1767}
1768
Peter Lieven2d9187b2017-02-28 13:40:07 +01001769
1770static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1771 int nb_sectors, uint8_t *buf,
1772 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001773{
1774 int ret;
1775
1776 while (nb_sectors > 0) {
1777 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001778 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1779
Peter Lieven2d9187b2017-02-28 13:40:07 +01001780 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001781 case BLK_BACKING_FILE:
1782 /* If we have a backing file, leave clusters unallocated that are
1783 * unallocated in the source image, so that the backing file is
1784 * visible at the respective offset. */
1785 assert(s->target_has_backing);
1786 break;
1787
1788 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001789 /* If we're told to keep the target fully allocated (-S 0) or there
1790 * is real non-zero data, we must write it. Otherwise we can treat
1791 * it as zero sectors.
1792 * Compressed clusters need to be written as a whole, so in that
1793 * case we can only save the write if the buffer is completely
1794 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001795 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001796 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001797 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1798 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001799 (s->compressed &&
1800 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001801 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001802 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1803 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001804 if (ret < 0) {
1805 return ret;
1806 }
1807 break;
1808 }
1809 /* fall-through */
1810
1811 case BLK_ZERO:
1812 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001813 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001814 break;
1815 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001816 ret = blk_co_pwrite_zeroes(s->target,
1817 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001818 n << BDRV_SECTOR_BITS,
1819 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001820 if (ret < 0) {
1821 return ret;
1822 }
1823 break;
1824 }
1825
1826 sector_num += n;
1827 nb_sectors -= n;
1828 buf += n * BDRV_SECTOR_SIZE;
1829 }
1830
1831 return 0;
1832}
1833
Fam Zhengee5306d2018-06-01 17:26:48 +08001834static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1835 int nb_sectors)
1836{
1837 int n, ret;
1838
1839 while (nb_sectors > 0) {
1840 BlockBackend *blk;
1841 int src_cur;
1842 int64_t bs_sectors, src_cur_offset;
1843 int64_t offset;
1844
1845 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1846 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1847 blk = s->src[src_cur];
1848 bs_sectors = s->src_sectors[src_cur];
1849
1850 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1851
1852 ret = blk_co_copy_range(blk, offset, s->target,
1853 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001854 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001855 if (ret < 0) {
1856 return ret;
1857 }
1858
1859 sector_num += n;
1860 nb_sectors -= n;
1861 }
1862 return 0;
1863}
1864
Peter Lieven2d9187b2017-02-28 13:40:07 +01001865static void coroutine_fn convert_co_do_copy(void *opaque)
1866{
1867 ImgConvertState *s = opaque;
1868 uint8_t *buf = NULL;
1869 int ret, i;
1870 int index = -1;
1871
1872 for (i = 0; i < s->num_coroutines; i++) {
1873 if (s->co[i] == qemu_coroutine_self()) {
1874 index = i;
1875 break;
1876 }
1877 }
1878 assert(index >= 0);
1879
1880 s->running_coroutines++;
1881 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1882
1883 while (1) {
1884 int n;
1885 int64_t sector_num;
1886 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001887 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001888
1889 qemu_co_mutex_lock(&s->lock);
1890 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1891 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001892 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001893 }
1894 n = convert_iteration_sectors(s, s->sector_num);
1895 if (n < 0) {
1896 qemu_co_mutex_unlock(&s->lock);
1897 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001898 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001899 }
1900 /* save current sector and allocation status to local variables */
1901 sector_num = s->sector_num;
1902 status = s->status;
1903 if (!s->min_sparse && s->status == BLK_ZERO) {
1904 n = MIN(n, s->buf_sectors);
1905 }
1906 /* increment global sector counter so that other coroutines can
1907 * already continue reading beyond this request */
1908 s->sector_num += n;
1909 qemu_co_mutex_unlock(&s->lock);
1910
1911 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1912 s->allocated_done += n;
1913 qemu_progress_print(100.0 * s->allocated_done /
1914 s->allocated_sectors, 0);
1915 }
1916
Fam Zhengee5306d2018-06-01 17:26:48 +08001917retry:
1918 copy_range = s->copy_range && s->status == BLK_DATA;
1919 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001920 ret = convert_co_read(s, sector_num, n, buf);
1921 if (ret < 0) {
1922 error_report("error while reading sector %" PRId64
1923 ": %s", sector_num, strerror(-ret));
1924 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001925 }
1926 } else if (!s->min_sparse && status == BLK_ZERO) {
1927 status = BLK_DATA;
1928 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1929 }
1930
1931 if (s->wr_in_order) {
1932 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001933 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001934 s->wait_sector_num[index] = sector_num;
1935 qemu_coroutine_yield();
1936 }
1937 s->wait_sector_num[index] = -1;
1938 }
1939
Anton Nefedovb91127e2017-04-26 11:33:15 +03001940 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001941 if (copy_range) {
1942 ret = convert_co_copy_range(s, sector_num, n);
1943 if (ret) {
1944 s->copy_range = false;
1945 goto retry;
1946 }
1947 } else {
1948 ret = convert_co_write(s, sector_num, n, buf, status);
1949 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03001950 if (ret < 0) {
1951 error_report("error while writing sector %" PRId64
1952 ": %s", sector_num, strerror(-ret));
1953 s->ret = ret;
1954 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001955 }
1956
1957 if (s->wr_in_order) {
1958 /* reenter the coroutine that might have waited
1959 * for this write to complete */
1960 s->wr_offs = sector_num + n;
1961 for (i = 0; i < s->num_coroutines; i++) {
1962 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
1963 /*
1964 * A -> B -> A cannot occur because A has
1965 * s->wait_sector_num[i] == -1 during A -> B. Therefore
1966 * B will never enter A during this time window.
1967 */
1968 qemu_coroutine_enter(s->co[i]);
1969 break;
1970 }
1971 }
1972 }
1973 }
1974
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975 qemu_vfree(buf);
1976 s->co[index] = NULL;
1977 s->running_coroutines--;
1978 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
1979 /* the convert job finished successfully */
1980 s->ret = 0;
1981 }
1982}
1983
Kevin Wolf690c7302015-03-19 13:33:32 +01001984static int convert_do_copy(ImgConvertState *s)
1985{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001986 int ret, i, n;
1987 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01001988
1989 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00001990 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
1991 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02001992 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02001993 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001994
1995 if (!s->has_zero_init && !s->target_has_backing &&
1996 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
1997 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01001998 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01001999 if (ret == 0) {
2000 s->has_zero_init = true;
2001 }
2002 }
2003
2004 /* Allocate buffer for copied data. For compressed images, only one cluster
2005 * can be copied at a time. */
2006 if (s->compressed) {
2007 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2008 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002009 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002010 }
2011 s->buf_sectors = s->cluster_sectors;
2012 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002013
Kevin Wolf690c7302015-03-19 13:33:32 +01002014 while (sector_num < s->total_sectors) {
2015 n = convert_iteration_sectors(s, sector_num);
2016 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002017 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002018 }
Max Reitzaad15de2016-03-24 23:33:57 +01002019 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2020 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002021 s->allocated_sectors += n;
2022 }
2023 sector_num += n;
2024 }
2025
2026 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002027 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002028 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002029
Peter Lieven2d9187b2017-02-28 13:40:07 +01002030 qemu_co_mutex_init(&s->lock);
2031 for (i = 0; i < s->num_coroutines; i++) {
2032 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2033 s->wait_sector_num[i] = -1;
2034 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002035 }
2036
Anton Nefedovb91127e2017-04-26 11:33:15 +03002037 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002038 main_loop_wait(false);
2039 }
2040
2041 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002042 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002043 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002044 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002045 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002046 }
2047 }
2048
Peter Lieven2d9187b2017-02-28 13:40:07 +01002049 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002050}
2051
Peter Lieven6360ab22018-07-13 09:15:39 +02002052#define MAX_BUF_SECTORS 32768
2053
bellardea2384d2004-08-01 21:59:26 +00002054static int img_convert(int argc, char **argv)
2055{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002056 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002057 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002058 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2059 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002060 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002061 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002062 BlockDriverState *out_bs;
2063 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002064 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002065 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002066 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002067 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002068 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002069 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002070 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002071 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002072 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002073
Peter Lieven9fd77f92017-04-21 11:11:55 +02002074 ImgConvertState s = (ImgConvertState) {
2075 /* Need at least 4k of zeros for sparse detection */
2076 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002077 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002078 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2079 .wr_in_order = true,
2080 .num_coroutines = 8,
2081 };
2082
bellardea2384d2004-08-01 21:59:26 +00002083 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002084 static const struct option long_options[] = {
2085 {"help", no_argument, 0, 'h'},
2086 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002087 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002088 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002089 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002090 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002091 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002092 {0, 0, 0, 0}
2093 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002094 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002095 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002096 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002097 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002098 }
bellardea2384d2004-08-01 21:59:26 +00002099 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002100 case ':':
2101 missing_argument(argv[optind - 1]);
2102 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002103 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002104 unrecognized_option(argv[optind - 1]);
2105 break;
bellardea2384d2004-08-01 21:59:26 +00002106 case 'h':
2107 help();
2108 break;
2109 case 'f':
2110 fmt = optarg;
2111 break;
2112 case 'O':
2113 out_fmt = optarg;
2114 break;
thsf58c7b32008-06-05 21:53:49 +00002115 case 'B':
2116 out_baseimg = optarg;
2117 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002118 case 'C':
2119 s.copy_range = true;
2120 break;
bellardea2384d2004-08-01 21:59:26 +00002121 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002122 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002123 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002124 case 'o':
Kevin Wolf2dc83282014-02-21 16:24:05 +01002125 if (!is_valid_option_list(optarg)) {
2126 error_report("Invalid option list: %s", optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002127 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002128 }
2129 if (!options) {
2130 options = g_strdup(optarg);
2131 } else {
2132 char *old_options = options;
2133 options = g_strdup_printf("%s,%s", options, optarg);
2134 g_free(old_options);
2135 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002136 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002137 case 'l':
2138 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002139 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2140 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002141 if (!sn_opts) {
2142 error_report("Failed in parsing snapshot param '%s'",
2143 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002144 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002145 }
2146 } else {
2147 snapshot_name = optarg;
2148 }
2149 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002150 case 'S':
2151 {
2152 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002153
2154 sval = cvtnum(optarg);
Nir Soffer1bbbf322019-08-27 21:59:12 +03002155 if (sval < 0 || !QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002156 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2157 error_report("Invalid buffer size for sparse output specified. "
2158 "Valid sizes are multiples of %llu up to %llu. Select "
2159 "0 to disable sparse detection (fully allocates output).",
2160 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002161 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002162 }
2163
Peter Lieven9fd77f92017-04-21 11:11:55 +02002164 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002165 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002166 break;
2167 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002168 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002169 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002170 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002171 case 't':
2172 cache = optarg;
2173 break;
Max Reitz40055952014-07-22 22:58:42 +02002174 case 'T':
2175 src_cache = optarg;
2176 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002177 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002178 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002179 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002180 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002181 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002182 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002183 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002184 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2185 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002186 error_report("Invalid number of coroutines. Allowed number of"
2187 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002188 goto fail_getopt;
2189 }
2190 break;
2191 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002192 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002193 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002194 case 'U':
2195 force_share = true;
2196 break;
Max Reitz3258b912017-04-26 15:46:47 +02002197 case OPTION_OBJECT: {
2198 QemuOpts *object_opts;
2199 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2200 optarg, true);
2201 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002202 goto fail_getopt;
2203 }
2204 break;
Max Reitz3258b912017-04-26 15:46:47 +02002205 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002206 case OPTION_IMAGE_OPTS:
2207 image_opts = true;
2208 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002209 case OPTION_SALVAGE:
2210 s.salvage = true;
2211 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002212 case OPTION_TARGET_IMAGE_OPTS:
2213 tgt_image_opts = true;
2214 break;
David Edmondson168468f2020-02-05 11:02:48 +00002215 case OPTION_TARGET_IS_ZERO:
2216 /*
2217 * The user asserting that the target is blank has the
2218 * same effect as the target driver supporting zero
2219 * initialisation.
2220 */
2221 s.has_zero_init = true;
2222 break;
bellardea2384d2004-08-01 21:59:26 +00002223 }
2224 }
ths3b46e622007-09-17 08:09:54 +00002225
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002226 if (!out_fmt && !tgt_image_opts) {
2227 out_fmt = "raw";
2228 }
2229
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002230 if (qemu_opts_foreach(&qemu_object_opts,
2231 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002232 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002233 goto fail_getopt;
2234 }
2235
Fam Zhenge11ce122018-07-27 11:34:01 +08002236 if (s.compressed && s.copy_range) {
2237 error_report("Cannot enable copy offloading when -c is used");
2238 goto fail_getopt;
2239 }
2240
2241 if (explict_min_sparse && s.copy_range) {
2242 error_report("Cannot enable copy offloading when -S is used");
2243 goto fail_getopt;
2244 }
2245
Max Reitz8eaac022019-05-07 22:35:03 +02002246 if (s.copy_range && s.salvage) {
2247 error_report("Cannot use copy offloading in salvaging mode");
2248 goto fail_getopt;
2249 }
2250
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002251 if (tgt_image_opts && !skip_create) {
2252 error_report("--target-image-opts requires use of -n flag");
2253 goto fail_getopt;
2254 }
2255
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002256 if (skip_create && options) {
2257 warn_report("-o has no effect when skipping image creation");
2258 warn_report("This will become an error in future QEMU versions.");
2259 }
2260
David Edmondson168468f2020-02-05 11:02:48 +00002261 if (s.has_zero_init && !skip_create) {
2262 error_report("--target-is-zero requires use of -n flag");
2263 goto fail_getopt;
2264 }
2265
Peter Lieven9fd77f92017-04-21 11:11:55 +02002266 s.src_num = argc - optind - 1;
2267 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2268
2269 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002270 if (out_fmt) {
2271 ret = print_block_option_help(out_filename, out_fmt);
2272 goto fail_getopt;
2273 } else {
2274 error_report("Option help requires a format be specified");
2275 goto fail_getopt;
2276 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002277 }
2278
2279 if (s.src_num < 1) {
2280 error_report("Must specify image file name");
2281 goto fail_getopt;
2282 }
2283
2284
Peter Lieven9fd77f92017-04-21 11:11:55 +02002285 /* ret is still -EINVAL until here */
2286 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2287 if (ret < 0) {
2288 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002289 goto fail_getopt;
2290 }
2291
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002292 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002293 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002294 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002295 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002296 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002297 qemu_progress_print(0, 100);
2298
Peter Lieven9fd77f92017-04-21 11:11:55 +02002299 s.src = g_new0(BlockBackend *, s.src_num);
2300 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002301
Peter Lieven9fd77f92017-04-21 11:11:55 +02002302 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2303 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002304 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002305 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002306 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002307 ret = -1;
2308 goto out;
2309 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002310 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2311 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002312 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002313 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002314 ret = -1;
2315 goto out;
2316 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002317 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002318 }
bellardea2384d2004-08-01 21:59:26 +00002319
Wenchao Xiaef806542013-12-04 17:10:57 +08002320 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002321 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002322 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2323 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2324 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002325 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002326 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002327 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002328 ret = -1;
2329 goto out;
2330 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002331
Peter Lieven9fd77f92017-04-21 11:11:55 +02002332 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2333 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002334 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002335 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002336 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002337 ret = -1;
2338 goto out;
edison51ef6722010-09-21 19:58:41 -07002339 }
2340
Max Reitz2e024cd2015-02-11 09:58:46 -05002341 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002342 /* Find driver and parse its options */
2343 drv = bdrv_find_format(out_fmt);
2344 if (!drv) {
2345 error_report("Unknown file format '%s'", out_fmt);
2346 ret = -1;
2347 goto out;
2348 }
2349
2350 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2351 if (!proto_drv) {
2352 error_report_err(local_err);
2353 ret = -1;
2354 goto out;
2355 }
2356
Max Reitz2e024cd2015-02-11 09:58:46 -05002357 if (!drv->create_opts) {
2358 error_report("Format driver '%s' does not support image creation",
2359 drv->format_name);
2360 ret = -1;
2361 goto out;
2362 }
Max Reitzf75613c2014-12-02 18:32:46 +01002363
Max Reitz2e024cd2015-02-11 09:58:46 -05002364 if (!proto_drv->create_opts) {
2365 error_report("Protocol driver '%s' does not support image creation",
2366 proto_drv->format_name);
2367 ret = -1;
2368 goto out;
2369 }
Max Reitzf75613c2014-12-02 18:32:46 +01002370
Max Reitz2e024cd2015-02-11 09:58:46 -05002371 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2372 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002373
Max Reitz2e024cd2015-02-11 09:58:46 -05002374 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002375 if (options) {
2376 qemu_opts_do_parse(opts, options, NULL, &local_err);
2377 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002378 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002379 ret = -1;
2380 goto out;
2381 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002382 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002383
Peter Lieven9fd77f92017-04-21 11:11:55 +02002384 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002385 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002386 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2387 if (ret < 0) {
2388 goto out;
2389 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002390 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002391
Kevin Wolfa18953f2010-10-14 15:46:04 +02002392 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002393 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002394 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002395 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002396 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002397 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002398
David Edmondson168468f2020-02-05 11:02:48 +00002399 if (s.has_zero_init && s.target_has_backing) {
2400 error_report("Cannot use --target-is-zero when the destination "
2401 "image has a backing file");
2402 goto out;
2403 }
2404
Max Reitz48758a82017-04-26 15:46:48 +02002405 if (s.src_num > 1 && out_baseimg) {
2406 error_report("Having a backing file for the target makes no sense when "
2407 "concatenating multiple input images");
2408 ret = -1;
2409 goto out;
2410 }
2411
Kevin Wolfefa84d42009-05-18 16:42:12 +02002412 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002413 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002414 bool encryption =
2415 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002416 const char *encryptfmt =
2417 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002418 const char *preallocation =
2419 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002420
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002421 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002422 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002423 ret = -1;
2424 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002425 }
2426
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002427 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002428 error_report("Compression and encryption not supported at "
2429 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002430 ret = -1;
2431 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002432 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002433
Chunyan Liu83d05212014-06-05 17:20:51 +08002434 if (preallocation
2435 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002436 {
2437 error_report("Compression and preallocation not supported at "
2438 "the same time");
2439 ret = -1;
2440 goto out;
2441 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002442 }
2443
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002444 /*
2445 * The later open call will need any decryption secrets, and
2446 * bdrv_create() will purge "opts", so extract them now before
2447 * they are lost.
2448 */
2449 if (!skip_create) {
2450 open_opts = qdict_new();
2451 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2452 }
2453
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002454 if (!skip_create) {
2455 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002456 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002457 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002458 error_reportf_err(local_err, "%s: error while converting %s: ",
2459 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002460 goto out;
bellardea2384d2004-08-01 21:59:26 +00002461 }
2462 }
ths3b46e622007-09-17 08:09:54 +00002463
Max Reitz4d7c4872019-07-24 19:12:29 +02002464 s.target_is_new = !skip_create;
2465
Peter Lieven9fd77f92017-04-21 11:11:55 +02002466 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002467 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002468 if (ret < 0) {
2469 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002470 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002471 }
2472
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002473 if (skip_create) {
2474 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002475 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002476 } else {
2477 /* TODO ultimately we should allow --target-image-opts
2478 * to be used even when -n is not given.
2479 * That has to wait for bdrv_create to be improved
2480 * to allow filenames in option syntax
2481 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002482 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002483 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002484 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002485 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002486 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002487 ret = -1;
2488 goto out;
2489 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002490 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002491
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002492 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002493 error_report("Compression not supported for this file format");
2494 ret = -1;
2495 goto out;
2496 }
2497
Eric Blake5def6b82016-06-23 16:37:19 -06002498 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002499 * or discard_alignment of the out_bs is greater. Limit to
2500 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2501 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002502 MAX(s.buf_sectors,
2503 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2504 out_bs->bl.pdiscard_alignment >>
2505 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002506
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002507 /* try to align the write requests to the destination to avoid unnecessary
2508 * RMW cycles. */
2509 s.alignment = MAX(pow2floor(s.min_sparse),
2510 DIV_ROUND_UP(out_bs->bl.request_alignment,
2511 BDRV_SECTOR_SIZE));
2512 assert(is_power_of_2(s.alignment));
2513
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002514 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002515 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002516 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002517 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002518 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002519 ret = -1;
2520 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002521 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002522 error_report("output file is smaller than input file");
2523 ret = -1;
2524 goto out;
2525 }
2526 }
2527
Max Reitzc69291e2020-01-21 16:59:14 +01002528 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002529 /* Errors are treated as "backing length unknown" (which means
2530 * s.target_backing_sectors has to be negative, which it will
2531 * be automatically). The backing file length is used only
2532 * for optimizations, so such a case is not fatal. */
2533 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2534 } else {
2535 s.target_backing_sectors = -1;
2536 }
2537
Peter Lieven24f833c2013-11-27 11:07:07 +01002538 ret = bdrv_get_info(out_bs, &bdi);
2539 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002540 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002541 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002542 goto out;
2543 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002544 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002545 s.compressed = s.compressed || bdi.needs_compressed_writes;
2546 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002547 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002548 }
2549
Peter Lieven9fd77f92017-04-21 11:11:55 +02002550 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002551out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002552 if (!ret) {
2553 qemu_progress_print(100, 0);
2554 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002555 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002556 qemu_opts_del(opts);
2557 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002558 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002559 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002560 blk_unref(s.target);
2561 if (s.src) {
2562 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2563 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002564 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002565 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002566 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002567 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002568fail_getopt:
2569 g_free(options);
2570
Peter Lieven9fd77f92017-04-21 11:11:55 +02002571 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002572}
2573
bellard57d1a2b2004-08-03 21:15:11 +00002574
bellardfaea38e2006-08-05 21:31:00 +00002575static void dump_snapshots(BlockDriverState *bs)
2576{
2577 QEMUSnapshotInfo *sn_tab, *sn;
2578 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002579
2580 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2581 if (nb_sns <= 0)
2582 return;
2583 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002584 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002585 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002586 for(i = 0; i < nb_sns; i++) {
2587 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002588 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002589 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002590 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002591 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002592}
2593
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002594static void dump_json_image_info_list(ImageInfoList *list)
2595{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002596 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002597 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002598 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002599
2600 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2601 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002602 str = qobject_to_json_pretty(obj);
2603 assert(str != NULL);
2604 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002605 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002606 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002607 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002608}
2609
Benoît Canetc054b3f2012-09-05 13:09:02 +02002610static void dump_json_image_info(ImageInfo *info)
2611{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002612 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002613 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002614 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002615
2616 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2617 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002618 str = qobject_to_json_pretty(obj);
2619 assert(str != NULL);
2620 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002621 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002622 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002623 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002624}
2625
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002626static void dump_human_image_info_list(ImageInfoList *list)
2627{
2628 ImageInfoList *elem;
2629 bool delim = false;
2630
2631 for (elem = list; elem; elem = elem->next) {
2632 if (delim) {
2633 printf("\n");
2634 }
2635 delim = true;
2636
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002637 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002638 }
2639}
2640
2641static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2642{
2643 return strcmp(a, b) == 0;
2644}
2645
2646/**
2647 * Open an image file chain and return an ImageInfoList
2648 *
2649 * @filename: topmost image filename
2650 * @fmt: topmost image format (may be NULL to autodetect)
2651 * @chain: true - enumerate entire backing file chain
2652 * false - only topmost image file
2653 *
2654 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2655 * image file. If there was an error a message will have been printed to
2656 * stderr.
2657 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002658static ImageInfoList *collect_image_info_list(bool image_opts,
2659 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002660 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002661 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002662{
2663 ImageInfoList *head = NULL;
2664 ImageInfoList **last = &head;
2665 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002666 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002667
2668 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2669
2670 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002671 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002672 BlockDriverState *bs;
2673 ImageInfo *info;
2674 ImageInfoList *elem;
2675
2676 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2677 error_report("Backing file '%s' creates an infinite loop.",
2678 filename);
2679 goto err;
2680 }
2681 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2682
Max Reitzefaa7c42016-03-16 19:54:38 +01002683 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002684 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2685 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002686 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002687 goto err;
2688 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002689 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002690
Wenchao Xia43526ec2013-06-06 12:27:58 +08002691 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002692 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002693 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002694 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002695 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002696 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002697
2698 elem = g_new0(ImageInfoList, 1);
2699 elem->value = info;
2700 *last = elem;
2701 last = &elem->next;
2702
Markus Armbruster26f54e92014-10-07 13:59:04 +02002703 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002704
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002705 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002706 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002707 image_opts = false;
2708
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002709 if (chain) {
2710 if (info->has_full_backing_filename) {
2711 filename = info->full_backing_filename;
2712 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002713 error_report("Could not determine absolute backing filename,"
2714 " but backing filename '%s' present",
2715 info->backing_filename);
2716 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002717 }
2718 if (info->has_backing_filename_format) {
2719 fmt = info->backing_filename_format;
2720 }
2721 }
2722 }
2723 g_hash_table_destroy(filenames);
2724 return head;
2725
2726err:
2727 qapi_free_ImageInfoList(head);
2728 g_hash_table_destroy(filenames);
2729 return NULL;
2730}
2731
Benoît Canetc054b3f2012-09-05 13:09:02 +02002732static int img_info(int argc, char **argv)
2733{
2734 int c;
2735 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002736 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002737 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002738 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002739 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002740 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002741
bellardea2384d2004-08-01 21:59:26 +00002742 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002743 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002744 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002745 int option_index = 0;
2746 static const struct option long_options[] = {
2747 {"help", no_argument, 0, 'h'},
2748 {"format", required_argument, 0, 'f'},
2749 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002750 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002751 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002752 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002753 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002754 {0, 0, 0, 0}
2755 };
Fam Zheng335e9932017-05-03 00:35:39 +08002756 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002757 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002758 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002759 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002760 }
bellardea2384d2004-08-01 21:59:26 +00002761 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002762 case ':':
2763 missing_argument(argv[optind - 1]);
2764 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002765 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002766 unrecognized_option(argv[optind - 1]);
2767 break;
bellardea2384d2004-08-01 21:59:26 +00002768 case 'h':
2769 help();
2770 break;
2771 case 'f':
2772 fmt = optarg;
2773 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002774 case 'U':
2775 force_share = true;
2776 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002777 case OPTION_OUTPUT:
2778 output = optarg;
2779 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002780 case OPTION_BACKING_CHAIN:
2781 chain = true;
2782 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002783 case OPTION_OBJECT: {
2784 QemuOpts *opts;
2785 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2786 optarg, true);
2787 if (!opts) {
2788 return 1;
2789 }
2790 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002791 case OPTION_IMAGE_OPTS:
2792 image_opts = true;
2793 break;
bellardea2384d2004-08-01 21:59:26 +00002794 }
2795 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002796 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002797 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002798 }
bellardea2384d2004-08-01 21:59:26 +00002799 filename = argv[optind++];
2800
Benoît Canetc054b3f2012-09-05 13:09:02 +02002801 if (output && !strcmp(output, "json")) {
2802 output_format = OFORMAT_JSON;
2803 } else if (output && !strcmp(output, "human")) {
2804 output_format = OFORMAT_HUMAN;
2805 } else if (output) {
2806 error_report("--output must be used with human or json as argument.");
2807 return 1;
2808 }
2809
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002810 if (qemu_opts_foreach(&qemu_object_opts,
2811 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002812 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002813 return 1;
2814 }
2815
Fam Zheng335e9932017-05-03 00:35:39 +08002816 list = collect_image_info_list(image_opts, filename, fmt, chain,
2817 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002818 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002819 return 1;
2820 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002821
Benoît Canetc054b3f2012-09-05 13:09:02 +02002822 switch (output_format) {
2823 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002824 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002825 break;
2826 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002827 if (chain) {
2828 dump_json_image_info_list(list);
2829 } else {
2830 dump_json_image_info(list->value);
2831 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002832 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002833 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002834
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002835 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002836 return 0;
2837}
2838
Eric Blake30065d12019-03-26 13:40:43 -05002839static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2840 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002841{
2842 switch (output_format) {
2843 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002844 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002845 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002846 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002847 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002848 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002849 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002850 e->start, e->length,
2851 e->has_offset ? e->offset : 0,
2852 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002853 }
2854 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2855 * Modify the flags here to allow more coalescing.
2856 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002857 if (next && (!next->data || next->zero)) {
2858 next->data = false;
2859 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002860 }
2861 break;
2862 case OFORMAT_JSON:
Fam Zheng16b0d552016-01-26 11:59:02 +08002863 printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
2864 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002865 (e->start == 0 ? "[" : ",\n"),
2866 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002867 e->zero ? "true" : "false",
2868 e->data ? "true" : "false");
2869 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002870 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002871 }
2872 putchar('}');
2873
2874 if (!next) {
2875 printf("]\n");
2876 }
2877 break;
2878 }
Eric Blake30065d12019-03-26 13:40:43 -05002879 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002880}
2881
Eric Blake5e344dd2017-10-11 22:47:02 -05002882static int get_block_status(BlockDriverState *bs, int64_t offset,
2883 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002884{
Eric Blake237d78f2017-10-11 22:47:03 -05002885 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002886 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002887 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002888 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002889 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002890 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002891
2892 /* As an optimization, we could cache the current range of unallocated
2893 * clusters in each file of the chain, and avoid querying the same
2894 * range repeatedly.
2895 */
2896
2897 depth = 0;
2898 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002899 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002900 if (ret < 0) {
2901 return ret;
2902 }
Eric Blake237d78f2017-10-11 22:47:03 -05002903 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002904 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2905 break;
2906 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002907 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002908 if (bs == NULL) {
2909 ret = 0;
2910 break;
2911 }
2912
2913 depth++;
2914 }
2915
John Snow28756452016-02-05 13:12:33 -05002916 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
2917
Max Reitzf30c66b2019-02-01 20:29:05 +01002918 if (file && has_offset) {
2919 bdrv_refresh_filename(file);
2920 filename = file->filename;
2921 }
2922
John Snow28756452016-02-05 13:12:33 -05002923 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05002924 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05002925 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05002926 .data = !!(ret & BDRV_BLOCK_DATA),
2927 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05002928 .offset = map,
John Snow28756452016-02-05 13:12:33 -05002929 .has_offset = has_offset,
2930 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01002931 .has_filename = filename,
2932 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05002933 };
2934
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002935 return 0;
2936}
2937
Fam Zheng16b0d552016-01-26 11:59:02 +08002938static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
2939{
2940 if (curr->length == 0) {
2941 return false;
2942 }
2943 if (curr->zero != next->zero ||
2944 curr->data != next->data ||
2945 curr->depth != next->depth ||
2946 curr->has_filename != next->has_filename ||
2947 curr->has_offset != next->has_offset) {
2948 return false;
2949 }
2950 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
2951 return false;
2952 }
2953 if (curr->has_offset && curr->offset + curr->length != next->offset) {
2954 return false;
2955 }
2956 return true;
2957}
2958
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002959static int img_map(int argc, char **argv)
2960{
2961 int c;
2962 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02002963 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002964 BlockDriverState *bs;
2965 const char *filename, *fmt, *output;
2966 int64_t length;
2967 MapEntry curr = { .length = 0 }, next;
2968 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002969 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002970 bool force_share = false;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002971
2972 fmt = NULL;
2973 output = NULL;
2974 for (;;) {
2975 int option_index = 0;
2976 static const struct option long_options[] = {
2977 {"help", no_argument, 0, 'h'},
2978 {"format", required_argument, 0, 'f'},
2979 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002980 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002981 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002982 {"force-share", no_argument, 0, 'U'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002983 {0, 0, 0, 0}
2984 };
Fam Zheng335e9932017-05-03 00:35:39 +08002985 c = getopt_long(argc, argv, ":f:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002986 long_options, &option_index);
2987 if (c == -1) {
2988 break;
2989 }
2990 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002991 case ':':
2992 missing_argument(argv[optind - 1]);
2993 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002994 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002995 unrecognized_option(argv[optind - 1]);
2996 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002997 case 'h':
2998 help();
2999 break;
3000 case 'f':
3001 fmt = optarg;
3002 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003003 case 'U':
3004 force_share = true;
3005 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003006 case OPTION_OUTPUT:
3007 output = optarg;
3008 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003009 case OPTION_OBJECT: {
3010 QemuOpts *opts;
3011 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3012 optarg, true);
3013 if (!opts) {
3014 return 1;
3015 }
3016 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003017 case OPTION_IMAGE_OPTS:
3018 image_opts = true;
3019 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003020 }
3021 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003022 if (optind != argc - 1) {
3023 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003024 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003025 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003026
3027 if (output && !strcmp(output, "json")) {
3028 output_format = OFORMAT_JSON;
3029 } else if (output && !strcmp(output, "human")) {
3030 output_format = OFORMAT_HUMAN;
3031 } else if (output) {
3032 error_report("--output must be used with human or json as argument.");
3033 return 1;
3034 }
3035
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003036 if (qemu_opts_foreach(&qemu_object_opts,
3037 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003038 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003039 return 1;
3040 }
3041
Fam Zheng335e9932017-05-03 00:35:39 +08003042 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003043 if (!blk) {
3044 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003046 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003047
3048 if (output_format == OFORMAT_HUMAN) {
3049 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
3050 }
3051
Max Reitzf1d3cd72015-02-05 13:58:18 -05003052 length = blk_getlength(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003053 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003054 int64_t offset = curr.start + curr.length;
3055 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003056
3057 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003058 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003059 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003060
3061 if (ret < 0) {
3062 error_report("Could not read file metadata: %s", strerror(-ret));
3063 goto out;
3064 }
3065
Fam Zheng16b0d552016-01-26 11:59:02 +08003066 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003067 curr.length += next.length;
3068 continue;
3069 }
3070
3071 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003072 ret = dump_map_entry(output_format, &curr, &next);
3073 if (ret < 0) {
3074 goto out;
3075 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003076 }
3077 curr = next;
3078 }
3079
Eric Blake30065d12019-03-26 13:40:43 -05003080 ret = dump_map_entry(output_format, &curr, NULL);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003081
3082out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003083 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003084 return ret < 0;
3085}
3086
aliguorif7b4a942009-01-07 17:40:15 +00003087#define SNAPSHOT_LIST 1
3088#define SNAPSHOT_CREATE 2
3089#define SNAPSHOT_APPLY 3
3090#define SNAPSHOT_DELETE 4
3091
Stuart Brady153859b2009-06-07 00:42:17 +01003092static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003093{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003094 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003095 BlockDriverState *bs;
3096 QEMUSnapshotInfo sn;
3097 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003098 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003099 int action = 0;
3100 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003101 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003102 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003103 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003104 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003105
Kevin Wolfce099542016-03-15 13:01:04 +01003106 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003107 /* Parse commandline parameters */
3108 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003109 static const struct option long_options[] = {
3110 {"help", no_argument, 0, 'h'},
3111 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003112 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003113 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003114 {0, 0, 0, 0}
3115 };
Fam Zheng335e9932017-05-03 00:35:39 +08003116 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003117 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003118 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003119 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003120 }
aliguorif7b4a942009-01-07 17:40:15 +00003121 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003122 case ':':
3123 missing_argument(argv[optind - 1]);
3124 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003125 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003126 unrecognized_option(argv[optind - 1]);
3127 break;
aliguorif7b4a942009-01-07 17:40:15 +00003128 case 'h':
3129 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003130 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003131 case 'l':
3132 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003133 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003134 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003135 }
3136 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003137 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003138 break;
3139 case 'a':
3140 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003141 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003142 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003143 }
3144 action = SNAPSHOT_APPLY;
3145 snapshot_name = optarg;
3146 break;
3147 case 'c':
3148 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003149 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003150 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003151 }
3152 action = SNAPSHOT_CREATE;
3153 snapshot_name = optarg;
3154 break;
3155 case 'd':
3156 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003157 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003158 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003159 }
3160 action = SNAPSHOT_DELETE;
3161 snapshot_name = optarg;
3162 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003163 case 'q':
3164 quiet = true;
3165 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003166 case 'U':
3167 force_share = true;
3168 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003169 case OPTION_OBJECT: {
3170 QemuOpts *opts;
3171 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3172 optarg, true);
3173 if (!opts) {
3174 return 1;
3175 }
3176 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003177 case OPTION_IMAGE_OPTS:
3178 image_opts = true;
3179 break;
aliguorif7b4a942009-01-07 17:40:15 +00003180 }
3181 }
3182
Kevin Wolffc11eb22013-08-05 10:53:04 +02003183 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003184 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003185 }
aliguorif7b4a942009-01-07 17:40:15 +00003186 filename = argv[optind++];
3187
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003188 if (qemu_opts_foreach(&qemu_object_opts,
3189 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003190 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003191 return 1;
3192 }
3193
aliguorif7b4a942009-01-07 17:40:15 +00003194 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003195 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3196 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003197 if (!blk) {
3198 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003199 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003200 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003201
3202 /* Perform the requested action */
3203 switch(action) {
3204 case SNAPSHOT_LIST:
3205 dump_snapshots(bs);
3206 break;
3207
3208 case SNAPSHOT_CREATE:
3209 memset(&sn, 0, sizeof(sn));
3210 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3211
3212 qemu_gettimeofday(&tv);
3213 sn.date_sec = tv.tv_sec;
3214 sn.date_nsec = tv.tv_usec * 1000;
3215
3216 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003217 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003218 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003219 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003220 }
aliguorif7b4a942009-01-07 17:40:15 +00003221 break;
3222
3223 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003224 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003225 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003226 error_reportf_err(err, "Could not apply snapshot '%s': ",
3227 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003228 }
aliguorif7b4a942009-01-07 17:40:15 +00003229 break;
3230
3231 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003232 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3233 if (ret < 0) {
3234 error_report("Could not delete snapshot '%s': snapshot not "
3235 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003236 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003237 } else {
3238 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3239 if (ret < 0) {
3240 error_reportf_err(err, "Could not delete snapshot '%s': ",
3241 snapshot_name);
3242 ret = 1;
3243 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003244 }
aliguorif7b4a942009-01-07 17:40:15 +00003245 break;
3246 }
3247
3248 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003249 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003250 if (ret) {
3251 return 1;
3252 }
Stuart Brady153859b2009-06-07 00:42:17 +01003253 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003254}
3255
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003256static int img_rebase(int argc, char **argv)
3257{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003258 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003259 uint8_t *buf_old = NULL;
3260 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003261 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003262 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003263 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3264 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003265 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003266 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003267 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003268 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003269 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003270 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003271 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003272
3273 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003274 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003275 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003276 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003277 out_baseimg = NULL;
3278 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003279 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003280 static const struct option long_options[] = {
3281 {"help", no_argument, 0, 'h'},
3282 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003283 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003284 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003285 {0, 0, 0, 0}
3286 };
Fam Zheng335e9932017-05-03 00:35:39 +08003287 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003288 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003289 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003290 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003291 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003292 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003293 case ':':
3294 missing_argument(argv[optind - 1]);
3295 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003296 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003297 unrecognized_option(argv[optind - 1]);
3298 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003299 case 'h':
3300 help();
3301 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003302 case 'f':
3303 fmt = optarg;
3304 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003305 case 'F':
3306 out_basefmt = optarg;
3307 break;
3308 case 'b':
3309 out_baseimg = optarg;
3310 break;
3311 case 'u':
3312 unsafe = 1;
3313 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003314 case 'p':
3315 progress = 1;
3316 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003317 case 't':
3318 cache = optarg;
3319 break;
Max Reitz40055952014-07-22 22:58:42 +02003320 case 'T':
3321 src_cache = optarg;
3322 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003323 case 'q':
3324 quiet = true;
3325 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003326 case OPTION_OBJECT: {
3327 QemuOpts *opts;
3328 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3329 optarg, true);
3330 if (!opts) {
3331 return 1;
3332 }
3333 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003334 case OPTION_IMAGE_OPTS:
3335 image_opts = true;
3336 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003337 case 'U':
3338 force_share = true;
3339 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003340 }
3341 }
3342
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003343 if (quiet) {
3344 progress = 0;
3345 }
3346
Fam Zhengac1307a2014-04-22 13:36:11 +08003347 if (optind != argc - 1) {
3348 error_exit("Expecting one image file name");
3349 }
3350 if (!unsafe && !out_baseimg) {
3351 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003352 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003353 filename = argv[optind++];
3354
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003355 if (qemu_opts_foreach(&qemu_object_opts,
3356 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003357 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003358 return 1;
3359 }
3360
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003361 qemu_progress_init(progress, 2.0);
3362 qemu_progress_print(0, 100);
3363
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003364 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003365 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003366 if (ret < 0) {
3367 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003368 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003369 }
3370
Kevin Wolfce099542016-03-15 13:01:04 +01003371 src_flags = 0;
3372 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003373 if (ret < 0) {
3374 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003375 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003376 }
3377
Kevin Wolfce099542016-03-15 13:01:04 +01003378 /* The source files are opened read-only, don't care about WCE */
3379 assert((src_flags & BDRV_O_RDWR) == 0);
3380 (void) src_writethrough;
3381
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003382 /*
3383 * Open the images.
3384 *
3385 * Ignore the old backing file for unsafe rebase in case we want to correct
3386 * the reference to a renamed or moved backing file.
3387 */
Fam Zheng335e9932017-05-03 00:35:39 +08003388 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3389 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003390 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003391 ret = -1;
3392 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003393 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003394 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003395
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003396 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003397 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003398 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003399 ret = -1;
3400 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003401 }
3402 }
3403
3404 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003405 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003406 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003407 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003408
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003409 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003410 blk_old_backing = blk_new(qemu_get_aio_context(),
3411 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003412 BLK_PERM_ALL);
3413 ret = blk_insert_bs(blk_old_backing, base_bs,
3414 &local_err);
3415 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003416 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003417 "Could not reuse old backing file '%s': ",
3418 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003419 goto out;
3420 }
3421 } else {
3422 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003423 }
Max Reitz644483d2015-02-05 13:58:17 -05003424
Alex Bligha6166732012-10-16 13:46:18 +01003425 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003426 const char *overlay_filename;
3427 char *out_real_path;
3428
Fam Zheng335e9932017-05-03 00:35:39 +08003429 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003430 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003431 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003432 }
3433 if (force_share) {
3434 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003435 }
3436
Max Reitzf30c66b2019-02-01 20:29:05 +01003437 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003438 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3439 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003440 out_real_path =
3441 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3442 out_baseimg,
3443 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003444 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003445 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003446 error_reportf_err(local_err,
3447 "Could not resolve backing filename: ");
3448 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003449 goto out;
3450 }
3451
Sam Eiderman863cc782019-05-23 19:33:36 +03003452 /*
3453 * Find out whether we rebase an image on top of a previous image
3454 * in its chain.
3455 */
3456 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003457 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003458 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003459 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003460
Kevin Wolfd861ab32019-04-25 14:25:10 +02003461 blk_new_backing = blk_new(qemu_get_aio_context(),
3462 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003463 BLK_PERM_ALL);
3464 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3465 &local_err);
3466 if (ret < 0) {
3467 error_reportf_err(local_err,
3468 "Could not reuse backing file '%s': ",
3469 out_baseimg);
3470 goto out;
3471 }
3472 } else {
3473 blk_new_backing = blk_new_open(out_real_path, NULL,
3474 options, src_flags, &local_err);
3475 g_free(out_real_path);
3476 if (!blk_new_backing) {
3477 error_reportf_err(local_err,
3478 "Could not open new backing file '%s': ",
3479 out_baseimg);
3480 ret = -1;
3481 goto out;
3482 }
Alex Bligha6166732012-10-16 13:46:18 +01003483 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003484 }
3485 }
3486
3487 /*
3488 * Check each unallocated cluster in the COW file. If it is unallocated,
3489 * accesses go to the backing file. We must therefore compare this cluster
3490 * in the old and new backing file, and if they differ we need to copy it
3491 * from the old backing file into the COW file.
3492 *
3493 * If qemu-img crashes during this step, no harm is done. The content of
3494 * the image is the same as the original one at any time.
3495 */
3496 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003497 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003498 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003499 int64_t new_backing_size = 0;
3500 uint64_t offset;
3501 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003502 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003503
Max Reitzf1d3cd72015-02-05 13:58:18 -05003504 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3505 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003506
Eric Blake41536282017-10-11 22:47:15 -05003507 size = blk_getlength(blk);
3508 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003509 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003510 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003511 ret = -1;
3512 goto out;
3513 }
Max Reitz35ddd932019-05-09 19:52:35 +02003514 if (blk_old_backing) {
3515 old_backing_size = blk_getlength(blk_old_backing);
3516 if (old_backing_size < 0) {
3517 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003518
Max Reitz35ddd932019-05-09 19:52:35 +02003519 bdrv_get_backing_filename(bs, backing_name,
3520 sizeof(backing_name));
3521 error_report("Could not get size of '%s': %s",
3522 backing_name, strerror(-old_backing_size));
3523 ret = -1;
3524 goto out;
3525 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003526 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003527 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003528 new_backing_size = blk_getlength(blk_new_backing);
3529 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003530 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003531 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003532 ret = -1;
3533 goto out;
3534 }
Alex Bligha6166732012-10-16 13:46:18 +01003535 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003536
Eric Blake41536282017-10-11 22:47:15 -05003537 if (size != 0) {
3538 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003539 }
3540
Eric Blake41536282017-10-11 22:47:15 -05003541 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003542 bool buf_old_is_zero = false;
3543
Eric Blake41536282017-10-11 22:47:15 -05003544 /* How many bytes can we handle with the next read? */
3545 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003546
3547 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003548 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003549 if (ret < 0) {
3550 error_report("error while reading image metadata: %s",
3551 strerror(-ret));
3552 goto out;
3553 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003554 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003555 continue;
3556 }
3557
Sam Eiderman863cc782019-05-23 19:33:36 +03003558 if (prefix_chain_bs) {
3559 /*
3560 * If cluster wasn't changed since prefix_chain, we don't need
3561 * to take action
3562 */
3563 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003564 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003565 if (ret < 0) {
3566 error_report("error while reading image metadata: %s",
3567 strerror(-ret));
3568 goto out;
3569 }
3570 if (!ret) {
3571 continue;
3572 }
3573 }
3574
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003575 /*
3576 * Read old and new backing file and take into consideration that
3577 * backing files may be smaller than the COW image.
3578 */
Eric Blake41536282017-10-11 22:47:15 -05003579 if (offset >= old_backing_size) {
3580 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003581 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003582 } else {
Eric Blake41536282017-10-11 22:47:15 -05003583 if (offset + n > old_backing_size) {
3584 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003585 }
3586
Eric Blake41536282017-10-11 22:47:15 -05003587 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003588 if (ret < 0) {
3589 error_report("error while reading from old backing file");
3590 goto out;
3591 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003592 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003593
Eric Blake41536282017-10-11 22:47:15 -05003594 if (offset >= new_backing_size || !blk_new_backing) {
3595 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003596 } else {
Eric Blake41536282017-10-11 22:47:15 -05003597 if (offset + n > new_backing_size) {
3598 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003599 }
3600
Eric Blake41536282017-10-11 22:47:15 -05003601 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003602 if (ret < 0) {
3603 error_report("error while reading from new backing file");
3604 goto out;
3605 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003606 }
3607
3608 /* If they differ, we need to write to the COW file */
3609 uint64_t written = 0;
3610
Eric Blake41536282017-10-11 22:47:15 -05003611 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003612 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003613
Eric Blake41536282017-10-11 22:47:15 -05003614 if (compare_buffers(buf_old + written, buf_new + written,
3615 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003616 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003617 if (buf_old_is_zero) {
3618 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3619 } else {
3620 ret = blk_pwrite(blk, offset + written,
3621 buf_old + written, pnum, 0);
3622 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003623 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003624 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003625 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003626 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003627 }
3628 }
3629
3630 written += pnum;
3631 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003632 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003633 }
3634 }
3635
3636 /*
3637 * Change the backing file. All clusters that are different from the old
3638 * backing file are overwritten in the COW file now, so the visible content
3639 * doesn't change when we switch the backing file.
3640 */
Alex Bligha6166732012-10-16 13:46:18 +01003641 if (out_baseimg && *out_baseimg) {
3642 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3643 } else {
3644 ret = bdrv_change_backing_file(bs, NULL, NULL);
3645 }
3646
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003647 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003648 error_report("Could not change the backing file to '%s': No "
3649 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003650 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003651 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003652 out_baseimg, strerror(-ret));
3653 }
3654
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003655 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003656 /*
3657 * TODO At this point it is possible to check if any clusters that are
3658 * allocated in the COW file are the same in the backing file. If so, they
3659 * could be dropped from the COW file. Don't do this before switching the
3660 * backing file, in case of a crash this would lead to corruption.
3661 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003662out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003663 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003664 /* Cleanup */
3665 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003666 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003667 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003668 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003669 qemu_vfree(buf_old);
3670 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003671
Markus Armbruster26f54e92014-10-07 13:59:04 +02003672 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003673 if (ret) {
3674 return 1;
3675 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003676 return 0;
3677}
3678
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003679static int img_resize(int argc, char **argv)
3680{
Markus Armbruster6750e792015-02-12 17:43:08 +01003681 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003682 int c, ret, relative;
3683 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003684 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003685 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003686 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003687 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003688 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003689
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003690 static QemuOptsList resize_options = {
3691 .name = "resize_options",
3692 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3693 .desc = {
3694 {
3695 .name = BLOCK_OPT_SIZE,
3696 .type = QEMU_OPT_SIZE,
3697 .help = "Virtual disk size"
3698 }, {
3699 /* end of list */
3700 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003701 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003702 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003703 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003704 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003705
Kevin Wolfe80fec72011-04-29 10:58:12 +02003706 /* Remove size from argv manually so that negative numbers are not treated
3707 * as options by getopt. */
3708 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003709 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003710 return 1;
3711 }
3712
3713 size = argv[--argc];
3714
3715 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003716 fmt = NULL;
3717 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003718 static const struct option long_options[] = {
3719 {"help", no_argument, 0, 'h'},
3720 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003721 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003722 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003723 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003724 {0, 0, 0, 0}
3725 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003726 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003727 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003728 if (c == -1) {
3729 break;
3730 }
3731 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003732 case ':':
3733 missing_argument(argv[optind - 1]);
3734 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003735 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003736 unrecognized_option(argv[optind - 1]);
3737 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003738 case 'h':
3739 help();
3740 break;
3741 case 'f':
3742 fmt = optarg;
3743 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003744 case 'q':
3745 quiet = true;
3746 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003747 case OPTION_OBJECT: {
3748 QemuOpts *opts;
3749 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3750 optarg, true);
3751 if (!opts) {
3752 return 1;
3753 }
3754 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003755 case OPTION_IMAGE_OPTS:
3756 image_opts = true;
3757 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003758 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003759 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003760 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003761 if (prealloc == PREALLOC_MODE__MAX) {
3762 error_report("Invalid preallocation mode '%s'", optarg);
3763 return 1;
3764 }
3765 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003766 case OPTION_SHRINK:
3767 shrink = true;
3768 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003769 }
3770 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003771 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003772 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003773 }
3774 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003775
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003776 if (qemu_opts_foreach(&qemu_object_opts,
3777 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003778 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003779 return 1;
3780 }
3781
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003782 /* Choose grow, shrink, or absolute resize mode */
3783 switch (size[0]) {
3784 case '+':
3785 relative = 1;
3786 size++;
3787 break;
3788 case '-':
3789 relative = -1;
3790 size++;
3791 break;
3792 default:
3793 relative = 0;
3794 break;
3795 }
3796
3797 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003798 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003799 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003800 if (err) {
3801 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003802 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003803 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003804 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003805 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003806 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3807 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003808
Max Reitzefaa7c42016-03-16 19:54:38 +01003809 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003810 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3811 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003812 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003813 ret = -1;
3814 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003815 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003816
Max Reitzdc5f6902017-06-13 22:20:55 +02003817 current_size = blk_getlength(blk);
3818 if (current_size < 0) {
3819 error_report("Failed to inquire current image length: %s",
3820 strerror(-current_size));
3821 ret = -1;
3822 goto out;
3823 }
3824
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003825 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003826 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003827 } else {
3828 total_size = n;
3829 }
3830 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003831 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003832 ret = -1;
3833 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003834 }
3835
Max Reitzdc5f6902017-06-13 22:20:55 +02003836 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3837 error_report("Preallocation can only be used for growing images");
3838 ret = -1;
3839 goto out;
3840 }
3841
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003842 if (total_size < current_size && !shrink) {
3843 warn_report("Shrinking an image will delete all data beyond the "
3844 "shrunken image's end. Before performing such an "
3845 "operation, make sure there is no important data there.");
3846
3847 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3848 error_report(
3849 "Use the --shrink option to perform a shrink operation.");
3850 ret = -1;
3851 goto out;
3852 } else {
3853 warn_report("Using the --shrink option will suppress this message. "
3854 "Note that future versions of qemu-img may refuse to "
3855 "shrink images without this option.");
3856 }
3857 }
3858
Max Reitze8d04f92019-09-18 11:51:43 +02003859 /*
3860 * The user expects the image to have the desired size after
3861 * resizing, so pass @exact=true. It is of no use to report
3862 * success when the image has not actually been resized.
3863 */
3864 ret = blk_truncate(blk, total_size, true, prealloc, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02003865 if (!ret) {
3866 qprintf(quiet, "Image resized.\n");
3867 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003868 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003869 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003870out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003871 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003872 if (ret) {
3873 return 1;
3874 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003875 return 0;
3876}
3877
Max Reitz76a3a342014-10-27 11:12:51 +01003878static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003879 int64_t offset, int64_t total_work_size,
3880 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003881{
3882 qemu_progress_print(100.f * offset / total_work_size, 0);
3883}
3884
Max Reitz51641352018-05-09 23:00:20 +02003885static int print_amend_option_help(const char *format)
3886{
3887 BlockDriver *drv;
3888
3889 /* Find driver and parse its options */
3890 drv = bdrv_find_format(format);
3891 if (!drv) {
3892 error_report("Unknown file format '%s'", format);
3893 return 1;
3894 }
3895
3896 if (!drv->bdrv_amend_options) {
3897 error_report("Format driver '%s' does not support option amendment",
3898 format);
3899 return 1;
3900 }
3901
3902 /* Every driver supporting amendment must have create_opts */
3903 assert(drv->create_opts);
3904
3905 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02003906 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02003907 printf("\nNote that not all of these options may be amendable.\n");
3908 return 0;
3909}
3910
Max Reitz6f176b42013-09-03 10:09:50 +02003911static int img_amend(int argc, char **argv)
3912{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01003913 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003914 int c, ret = 0;
3915 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08003916 QemuOptsList *create_opts = NULL;
3917 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02003918 const char *fmt = NULL, *filename, *cache;
3919 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01003920 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01003921 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003922 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02003923 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003924 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02003925
Max Reitzbd39e6e2014-07-22 22:58:43 +02003926 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02003927 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003928 static const struct option long_options[] = {
3929 {"help", no_argument, 0, 'h'},
3930 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003931 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003932 {0, 0, 0, 0}
3933 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003934 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003935 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02003936 if (c == -1) {
3937 break;
3938 }
3939
3940 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003941 case ':':
3942 missing_argument(argv[optind - 1]);
3943 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003944 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003945 unrecognized_option(argv[optind - 1]);
3946 break;
3947 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08003948 help();
3949 break;
3950 case 'o':
3951 if (!is_valid_option_list(optarg)) {
3952 error_report("Invalid option list: %s", optarg);
3953 ret = -1;
3954 goto out_no_progress;
3955 }
3956 if (!options) {
3957 options = g_strdup(optarg);
3958 } else {
3959 char *old_options = options;
3960 options = g_strdup_printf("%s,%s", options, optarg);
3961 g_free(old_options);
3962 }
3963 break;
3964 case 'f':
3965 fmt = optarg;
3966 break;
3967 case 't':
3968 cache = optarg;
3969 break;
3970 case 'p':
3971 progress = true;
3972 break;
3973 case 'q':
3974 quiet = true;
3975 break;
3976 case OPTION_OBJECT:
3977 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3978 optarg, true);
3979 if (!opts) {
3980 ret = -1;
3981 goto out_no_progress;
3982 }
3983 break;
3984 case OPTION_IMAGE_OPTS:
3985 image_opts = true;
3986 break;
Max Reitz6f176b42013-09-03 10:09:50 +02003987 }
3988 }
3989
Max Reitz6f176b42013-09-03 10:09:50 +02003990 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003991 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02003992 }
3993
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003994 if (qemu_opts_foreach(&qemu_object_opts,
3995 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003996 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003997 ret = -1;
3998 goto out_no_progress;
3999 }
4000
Max Reitz76a3a342014-10-27 11:12:51 +01004001 if (quiet) {
4002 progress = false;
4003 }
4004 qemu_progress_init(progress, 1.0);
4005
Kevin Wolfa283cb62014-02-21 16:24:07 +01004006 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4007 if (fmt && has_help_option(options)) {
4008 /* If a format is explicitly specified (and possibly no filename is
4009 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004010 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004011 goto out;
4012 }
4013
4014 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004015 error_report("Expecting one image file name");
4016 ret = -1;
4017 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004018 }
Max Reitz6f176b42013-09-03 10:09:50 +02004019
Kevin Wolfce099542016-03-15 13:01:04 +01004020 flags = BDRV_O_RDWR;
4021 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004022 if (ret < 0) {
4023 error_report("Invalid cache option: %s", cache);
4024 goto out;
4025 }
4026
Fam Zheng335e9932017-05-03 00:35:39 +08004027 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4028 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004029 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004030 ret = -1;
4031 goto out;
4032 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004033 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004034
4035 fmt = bs->drv->format_name;
4036
Kevin Wolf626f84f2014-02-21 16:24:06 +01004037 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004038 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004039 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004040 goto out;
4041 }
4042
Max Reitz1f996682018-05-09 23:00:17 +02004043 if (!bs->drv->bdrv_amend_options) {
4044 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004045 fmt);
4046 ret = -1;
4047 goto out;
4048 }
4049
Max Reitz1f996682018-05-09 23:00:17 +02004050 /* Every driver supporting amendment must have create_opts */
4051 assert(bs->drv->create_opts);
4052
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004053 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004054 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004055 qemu_opts_do_parse(opts, options, NULL, &err);
4056 if (err) {
4057 error_report_err(err);
4058 ret = -1;
4059 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004060 }
4061
Max Reitz76a3a342014-10-27 11:12:51 +01004062 /* In case the driver does not call amend_status_cb() */
4063 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004064 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004065 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004066 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004067 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004068 goto out;
4069 }
4070
4071out:
Max Reitz76a3a342014-10-27 11:12:51 +01004072 qemu_progress_end();
4073
Max Reitze814dff2015-08-20 16:00:38 -07004074out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004075 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004076 qemu_opts_del(opts);
4077 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004078 g_free(options);
4079
Max Reitz6f176b42013-09-03 10:09:50 +02004080 if (ret) {
4081 return 1;
4082 }
4083 return 0;
4084}
4085
Kevin Wolfb6133b82014-08-05 14:17:13 +02004086typedef struct BenchData {
4087 BlockBackend *blk;
4088 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004089 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004090 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004091 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004092 int nrreq;
4093 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004094 int flush_interval;
4095 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004096 uint8_t *buf;
4097 QEMUIOVector *qiov;
4098
4099 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004100 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004101 uint64_t offset;
4102} BenchData;
4103
Kevin Wolf55d539c2016-06-03 13:59:41 +02004104static void bench_undrained_flush_cb(void *opaque, int ret)
4105{
4106 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004107 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004108 exit(EXIT_FAILURE);
4109 }
4110}
4111
Kevin Wolfb6133b82014-08-05 14:17:13 +02004112static void bench_cb(void *opaque, int ret)
4113{
4114 BenchData *b = opaque;
4115 BlockAIOCB *acb;
4116
4117 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004118 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004119 exit(EXIT_FAILURE);
4120 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004121
4122 if (b->in_flush) {
4123 /* Just finished a flush with drained queue: Start next requests */
4124 assert(b->in_flight == 0);
4125 b->in_flush = false;
4126 } else if (b->in_flight > 0) {
4127 int remaining = b->n - b->in_flight;
4128
Kevin Wolfb6133b82014-08-05 14:17:13 +02004129 b->n--;
4130 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004131
4132 /* Time for flush? Drain queue if requested, then flush */
4133 if (b->flush_interval && remaining % b->flush_interval == 0) {
4134 if (!b->in_flight || !b->drain_on_flush) {
4135 BlockCompletionFunc *cb;
4136
4137 if (b->drain_on_flush) {
4138 b->in_flush = true;
4139 cb = bench_cb;
4140 } else {
4141 cb = bench_undrained_flush_cb;
4142 }
4143
4144 acb = blk_aio_flush(b->blk, cb, b);
4145 if (!acb) {
4146 error_report("Failed to issue flush request");
4147 exit(EXIT_FAILURE);
4148 }
4149 }
4150 if (b->drain_on_flush) {
4151 return;
4152 }
4153 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004154 }
4155
4156 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004157 int64_t offset = b->offset;
4158 /* blk_aio_* might look for completed I/Os and kick bench_cb
4159 * again, so make sure this operation is counted by in_flight
4160 * and b->offset is ready for the next submission.
4161 */
4162 b->in_flight++;
4163 b->offset += b->step;
4164 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004165 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004166 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004167 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004168 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004169 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004170 if (!acb) {
4171 error_report("Failed to issue request");
4172 exit(EXIT_FAILURE);
4173 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004174 }
4175}
4176
4177static int img_bench(int argc, char **argv)
4178{
4179 int c, ret = 0;
4180 const char *fmt = NULL, *filename;
4181 bool quiet = false;
4182 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004183 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004184 int count = 75000;
4185 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004186 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004187 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004188 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004189 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004190 int flush_interval = 0;
4191 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004192 int64_t image_size;
4193 BlockBackend *blk = NULL;
4194 BenchData data = {};
4195 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004196 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004197 struct timeval t1, t2;
4198 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004199 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004200 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004201
4202 for (;;) {
4203 static const struct option long_options[] = {
4204 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004205 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004206 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004207 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004208 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004209 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004210 {0, 0, 0, 0}
4211 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004212 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4213 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004214 if (c == -1) {
4215 break;
4216 }
4217
4218 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004219 case ':':
4220 missing_argument(argv[optind - 1]);
4221 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004222 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004223 unrecognized_option(argv[optind - 1]);
4224 break;
4225 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004226 help();
4227 break;
4228 case 'c':
4229 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004230 unsigned long res;
4231
4232 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004233 error_report("Invalid request count specified");
4234 return 1;
4235 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004236 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004237 break;
4238 }
4239 case 'd':
4240 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004241 unsigned long res;
4242
4243 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004244 error_report("Invalid queue depth specified");
4245 return 1;
4246 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004247 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004248 break;
4249 }
4250 case 'f':
4251 fmt = optarg;
4252 break;
4253 case 'n':
4254 flags |= BDRV_O_NATIVE_AIO;
4255 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004256 case 'i':
4257 ret = bdrv_parse_aio(optarg, &flags);
4258 if (ret < 0) {
4259 error_report("Invalid aio option: %s", optarg);
4260 ret = -1;
4261 goto out;
4262 }
4263 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004264 case 'o':
4265 {
Markus Armbruster606caa02017-02-21 21:14:04 +01004266 offset = cvtnum(optarg);
4267 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004268 error_report("Invalid offset specified");
4269 return 1;
4270 }
4271 break;
4272 }
4273 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004274 case 'q':
4275 quiet = true;
4276 break;
4277 case 's':
4278 {
4279 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004280
Markus Armbruster606caa02017-02-21 21:14:04 +01004281 sval = cvtnum(optarg);
4282 if (sval < 0 || sval > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004283 error_report("Invalid buffer size specified");
4284 return 1;
4285 }
4286
4287 bufsize = sval;
4288 break;
4289 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004290 case 'S':
4291 {
4292 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004293
Markus Armbruster606caa02017-02-21 21:14:04 +01004294 sval = cvtnum(optarg);
4295 if (sval < 0 || sval > INT_MAX) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004296 error_report("Invalid step size specified");
4297 return 1;
4298 }
4299
4300 step = sval;
4301 break;
4302 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004303 case 't':
4304 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4305 if (ret < 0) {
4306 error_report("Invalid cache mode");
4307 ret = -1;
4308 goto out;
4309 }
4310 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004311 case 'w':
4312 flags |= BDRV_O_RDWR;
4313 is_write = true;
4314 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004315 case 'U':
4316 force_share = true;
4317 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004318 case OPTION_PATTERN:
4319 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004320 unsigned long res;
4321
4322 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004323 error_report("Invalid pattern byte specified");
4324 return 1;
4325 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004326 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004327 break;
4328 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004329 case OPTION_FLUSH_INTERVAL:
4330 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004331 unsigned long res;
4332
4333 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004334 error_report("Invalid flush interval specified");
4335 return 1;
4336 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004337 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004338 break;
4339 }
4340 case OPTION_NO_DRAIN:
4341 drain_on_flush = false;
4342 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004343 case OPTION_IMAGE_OPTS:
4344 image_opts = true;
4345 break;
4346 }
4347 }
4348
4349 if (optind != argc - 1) {
4350 error_exit("Expecting one image file name");
4351 }
4352 filename = argv[argc - 1];
4353
Kevin Wolf55d539c2016-06-03 13:59:41 +02004354 if (!is_write && flush_interval) {
4355 error_report("--flush-interval is only available in write tests");
4356 ret = -1;
4357 goto out;
4358 }
4359 if (flush_interval && flush_interval < depth) {
4360 error_report("Flush interval can't be smaller than depth");
4361 ret = -1;
4362 goto out;
4363 }
4364
Fam Zheng335e9932017-05-03 00:35:39 +08004365 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4366 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004367 if (!blk) {
4368 ret = -1;
4369 goto out;
4370 }
4371
4372 image_size = blk_getlength(blk);
4373 if (image_size < 0) {
4374 ret = image_size;
4375 goto out;
4376 }
4377
4378 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004379 .blk = blk,
4380 .image_size = image_size,
4381 .bufsize = bufsize,
4382 .step = step ?: bufsize,
4383 .nrreq = depth,
4384 .n = count,
4385 .offset = offset,
4386 .write = is_write,
4387 .flush_interval = flush_interval,
4388 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004389 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004390 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004391 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004392 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004393 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004394 if (flush_interval) {
4395 printf("Sending flush every %d requests\n", flush_interval);
4396 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004397
Fam Zheng79d46582018-01-16 14:08:58 +08004398 buf_size = data.nrreq * data.bufsize;
4399 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004400 memset(data.buf, pattern, data.nrreq * data.bufsize);
4401
Fam Zheng79d46582018-01-16 14:08:58 +08004402 blk_register_buf(blk, data.buf, buf_size);
4403
Kevin Wolfb6133b82014-08-05 14:17:13 +02004404 data.qiov = g_new(QEMUIOVector, data.nrreq);
4405 for (i = 0; i < data.nrreq; i++) {
4406 qemu_iovec_init(&data.qiov[i], 1);
4407 qemu_iovec_add(&data.qiov[i],
4408 data.buf + i * data.bufsize, data.bufsize);
4409 }
4410
4411 gettimeofday(&t1, NULL);
4412 bench_cb(&data, 0);
4413
4414 while (data.n > 0) {
4415 main_loop_wait(false);
4416 }
4417 gettimeofday(&t2, NULL);
4418
4419 printf("Run completed in %3.3f seconds.\n",
4420 (t2.tv_sec - t1.tv_sec)
4421 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4422
4423out:
Fam Zheng79d46582018-01-16 14:08:58 +08004424 if (data.buf) {
4425 blk_unregister_buf(blk, data.buf);
4426 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004427 qemu_vfree(data.buf);
4428 blk_unref(blk);
4429
4430 if (ret) {
4431 return 1;
4432 }
4433 return 0;
4434}
4435
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004436#define C_BS 01
4437#define C_COUNT 02
4438#define C_IF 04
4439#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004440#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004441
4442struct DdInfo {
4443 unsigned int flags;
4444 int64_t count;
4445};
4446
4447struct DdIo {
4448 int bsz; /* Block size */
4449 char *filename;
4450 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004451 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004452};
4453
4454struct DdOpts {
4455 const char *name;
4456 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4457 unsigned int flag;
4458};
4459
4460static int img_dd_bs(const char *arg,
4461 struct DdIo *in, struct DdIo *out,
4462 struct DdInfo *dd)
4463{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004464 int64_t res;
4465
Markus Armbruster606caa02017-02-21 21:14:04 +01004466 res = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004467
Markus Armbruster606caa02017-02-21 21:14:04 +01004468 if (res <= 0 || res > INT_MAX) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004469 error_report("invalid number: '%s'", arg);
4470 return 1;
4471 }
4472 in->bsz = out->bsz = res;
4473
4474 return 0;
4475}
4476
4477static int img_dd_count(const char *arg,
4478 struct DdIo *in, struct DdIo *out,
4479 struct DdInfo *dd)
4480{
Markus Armbruster606caa02017-02-21 21:14:04 +01004481 dd->count = cvtnum(arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004482
Markus Armbruster606caa02017-02-21 21:14:04 +01004483 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004484 error_report("invalid number: '%s'", arg);
4485 return 1;
4486 }
4487
4488 return 0;
4489}
4490
4491static int img_dd_if(const char *arg,
4492 struct DdIo *in, struct DdIo *out,
4493 struct DdInfo *dd)
4494{
4495 in->filename = g_strdup(arg);
4496
4497 return 0;
4498}
4499
4500static int img_dd_of(const char *arg,
4501 struct DdIo *in, struct DdIo *out,
4502 struct DdInfo *dd)
4503{
4504 out->filename = g_strdup(arg);
4505
4506 return 0;
4507}
4508
Reda Sallahif7c15532016-08-10 16:16:09 +02004509static int img_dd_skip(const char *arg,
4510 struct DdIo *in, struct DdIo *out,
4511 struct DdInfo *dd)
4512{
Markus Armbruster606caa02017-02-21 21:14:04 +01004513 in->offset = cvtnum(arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004514
Markus Armbruster606caa02017-02-21 21:14:04 +01004515 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004516 error_report("invalid number: '%s'", arg);
4517 return 1;
4518 }
4519
4520 return 0;
4521}
4522
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004523static int img_dd(int argc, char **argv)
4524{
4525 int ret = 0;
4526 char *arg = NULL;
4527 char *tmp;
4528 BlockDriver *drv = NULL, *proto_drv = NULL;
4529 BlockBackend *blk1 = NULL, *blk2 = NULL;
4530 QemuOpts *opts = NULL;
4531 QemuOptsList *create_opts = NULL;
4532 Error *local_err = NULL;
4533 bool image_opts = false;
4534 int c, i;
4535 const char *out_fmt = "raw";
4536 const char *fmt = NULL;
4537 int64_t size = 0;
4538 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004539 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004540 struct DdInfo dd = {
4541 .flags = 0,
4542 .count = 0,
4543 };
4544 struct DdIo in = {
4545 .bsz = 512, /* Block size is by default 512 bytes */
4546 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004547 .buf = NULL,
4548 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004549 };
4550 struct DdIo out = {
4551 .bsz = 512,
4552 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004553 .buf = NULL,
4554 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004555 };
4556
4557 const struct DdOpts options[] = {
4558 { "bs", img_dd_bs, C_BS },
4559 { "count", img_dd_count, C_COUNT },
4560 { "if", img_dd_if, C_IF },
4561 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004562 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004563 { NULL, NULL, 0 }
4564 };
4565 const struct option long_options[] = {
4566 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004567 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004568 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004569 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004570 { 0, 0, 0, 0 }
4571 };
4572
Fam Zheng335e9932017-05-03 00:35:39 +08004573 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004574 if (c == EOF) {
4575 break;
4576 }
4577 switch (c) {
4578 case 'O':
4579 out_fmt = optarg;
4580 break;
4581 case 'f':
4582 fmt = optarg;
4583 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004584 case ':':
4585 missing_argument(argv[optind - 1]);
4586 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004587 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004588 unrecognized_option(argv[optind - 1]);
4589 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004590 case 'h':
4591 help();
4592 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004593 case 'U':
4594 force_share = true;
4595 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004596 case OPTION_OBJECT:
4597 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004598 ret = -1;
4599 goto out;
4600 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004601 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004602 case OPTION_IMAGE_OPTS:
4603 image_opts = true;
4604 break;
4605 }
4606 }
4607
4608 for (i = optind; i < argc; i++) {
4609 int j;
4610 arg = g_strdup(argv[i]);
4611
4612 tmp = strchr(arg, '=');
4613 if (tmp == NULL) {
4614 error_report("unrecognized operand %s", arg);
4615 ret = -1;
4616 goto out;
4617 }
4618
4619 *tmp++ = '\0';
4620
4621 for (j = 0; options[j].name != NULL; j++) {
4622 if (!strcmp(arg, options[j].name)) {
4623 break;
4624 }
4625 }
4626 if (options[j].name == NULL) {
4627 error_report("unrecognized operand %s", arg);
4628 ret = -1;
4629 goto out;
4630 }
4631
4632 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4633 ret = -1;
4634 goto out;
4635 }
4636 dd.flags |= options[j].flag;
4637 g_free(arg);
4638 arg = NULL;
4639 }
4640
4641 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4642 error_report("Must specify both input and output files");
4643 ret = -1;
4644 goto out;
4645 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004646
4647 if (qemu_opts_foreach(&qemu_object_opts,
4648 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004649 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004650 ret = -1;
4651 goto out;
4652 }
4653
Fam Zheng335e9932017-05-03 00:35:39 +08004654 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4655 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004656
4657 if (!blk1) {
4658 ret = -1;
4659 goto out;
4660 }
4661
4662 drv = bdrv_find_format(out_fmt);
4663 if (!drv) {
4664 error_report("Unknown file format");
4665 ret = -1;
4666 goto out;
4667 }
4668 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4669
4670 if (!proto_drv) {
4671 error_report_err(local_err);
4672 ret = -1;
4673 goto out;
4674 }
4675 if (!drv->create_opts) {
4676 error_report("Format driver '%s' does not support image creation",
4677 drv->format_name);
4678 ret = -1;
4679 goto out;
4680 }
4681 if (!proto_drv->create_opts) {
4682 error_report("Protocol driver '%s' does not support image creation",
4683 proto_drv->format_name);
4684 ret = -1;
4685 goto out;
4686 }
4687 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4688 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4689
4690 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4691
4692 size = blk_getlength(blk1);
4693 if (size < 0) {
4694 error_report("Failed to get size for '%s'", in.filename);
4695 ret = -1;
4696 goto out;
4697 }
4698
4699 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4700 dd.count * in.bsz < size) {
4701 size = dd.count * in.bsz;
4702 }
4703
Reda Sallahif7c15532016-08-10 16:16:09 +02004704 /* Overflow means the specified offset is beyond input image's size */
4705 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4706 size < in.bsz * in.offset)) {
4707 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4708 } else {
4709 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
4710 size - in.bsz * in.offset, &error_abort);
4711 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004712
4713 ret = bdrv_create(drv, out.filename, opts, &local_err);
4714 if (ret < 0) {
4715 error_reportf_err(local_err,
4716 "%s: error while creating output image: ",
4717 out.filename);
4718 ret = -1;
4719 goto out;
4720 }
4721
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004722 /* TODO, we can't honour --image-opts for the target,
4723 * since it needs to be given in a format compatible
4724 * with the bdrv_create() call above which does not
4725 * support image-opts style.
4726 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01004727 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01004728 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004729
4730 if (!blk2) {
4731 ret = -1;
4732 goto out;
4733 }
4734
Reda Sallahif7c15532016-08-10 16:16:09 +02004735 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4736 size < in.offset * in.bsz)) {
4737 /* We give a warning if the skip option is bigger than the input
4738 * size and create an empty output disk image (i.e. like dd(1)).
4739 */
4740 error_report("%s: cannot skip to specified offset", in.filename);
4741 in_pos = size;
4742 } else {
4743 in_pos = in.offset * in.bsz;
4744 }
4745
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004746 in.buf = g_new(uint8_t, in.bsz);
4747
Reda Sallahif7c15532016-08-10 16:16:09 +02004748 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004749 int in_ret, out_ret;
4750
4751 if (in_pos + in.bsz > size) {
4752 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
4753 } else {
4754 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
4755 }
4756 if (in_ret < 0) {
4757 error_report("error while reading from input image file: %s",
4758 strerror(-in_ret));
4759 ret = -1;
4760 goto out;
4761 }
4762 in_pos += in_ret;
4763
4764 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
4765
4766 if (out_ret < 0) {
4767 error_report("error while writing to output image file: %s",
4768 strerror(-out_ret));
4769 ret = -1;
4770 goto out;
4771 }
4772 out_pos += out_ret;
4773 }
4774
4775out:
4776 g_free(arg);
4777 qemu_opts_del(opts);
4778 qemu_opts_free(create_opts);
4779 blk_unref(blk1);
4780 blk_unref(blk2);
4781 g_free(in.filename);
4782 g_free(out.filename);
4783 g_free(in.buf);
4784 g_free(out.buf);
4785
4786 if (ret) {
4787 return 1;
4788 }
4789 return 0;
4790}
4791
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004792static void dump_json_block_measure_info(BlockMeasureInfo *info)
4793{
4794 QString *str;
4795 QObject *obj;
4796 Visitor *v = qobject_output_visitor_new(&obj);
4797
4798 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
4799 visit_complete(v, &obj);
4800 str = qobject_to_json_pretty(obj);
4801 assert(str != NULL);
4802 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004803 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004804 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004805 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004806}
4807
4808static int img_measure(int argc, char **argv)
4809{
4810 static const struct option long_options[] = {
4811 {"help", no_argument, 0, 'h'},
4812 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4813 {"object", required_argument, 0, OPTION_OBJECT},
4814 {"output", required_argument, 0, OPTION_OUTPUT},
4815 {"size", required_argument, 0, OPTION_SIZE},
4816 {"force-share", no_argument, 0, 'U'},
4817 {0, 0, 0, 0}
4818 };
4819 OutputFormat output_format = OFORMAT_HUMAN;
4820 BlockBackend *in_blk = NULL;
4821 BlockDriver *drv;
4822 const char *filename = NULL;
4823 const char *fmt = NULL;
4824 const char *out_fmt = "raw";
4825 char *options = NULL;
4826 char *snapshot_name = NULL;
4827 bool force_share = false;
4828 QemuOpts *opts = NULL;
4829 QemuOpts *object_opts = NULL;
4830 QemuOpts *sn_opts = NULL;
4831 QemuOptsList *create_opts = NULL;
4832 bool image_opts = false;
4833 uint64_t img_size = UINT64_MAX;
4834 BlockMeasureInfo *info = NULL;
4835 Error *local_err = NULL;
4836 int ret = 1;
4837 int c;
4838
4839 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
4840 long_options, NULL)) != -1) {
4841 switch (c) {
4842 case '?':
4843 case 'h':
4844 help();
4845 break;
4846 case 'f':
4847 fmt = optarg;
4848 break;
4849 case 'O':
4850 out_fmt = optarg;
4851 break;
4852 case 'o':
4853 if (!is_valid_option_list(optarg)) {
4854 error_report("Invalid option list: %s", optarg);
4855 goto out;
4856 }
4857 if (!options) {
4858 options = g_strdup(optarg);
4859 } else {
4860 char *old_options = options;
4861 options = g_strdup_printf("%s,%s", options, optarg);
4862 g_free(old_options);
4863 }
4864 break;
4865 case 'l':
4866 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
4867 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
4868 optarg, false);
4869 if (!sn_opts) {
4870 error_report("Failed in parsing snapshot param '%s'",
4871 optarg);
4872 goto out;
4873 }
4874 } else {
4875 snapshot_name = optarg;
4876 }
4877 break;
4878 case 'U':
4879 force_share = true;
4880 break;
4881 case OPTION_OBJECT:
4882 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
4883 optarg, true);
4884 if (!object_opts) {
4885 goto out;
4886 }
4887 break;
4888 case OPTION_IMAGE_OPTS:
4889 image_opts = true;
4890 break;
4891 case OPTION_OUTPUT:
4892 if (!strcmp(optarg, "json")) {
4893 output_format = OFORMAT_JSON;
4894 } else if (!strcmp(optarg, "human")) {
4895 output_format = OFORMAT_HUMAN;
4896 } else {
4897 error_report("--output must be used with human or json "
4898 "as argument.");
4899 goto out;
4900 }
4901 break;
4902 case OPTION_SIZE:
4903 {
4904 int64_t sval;
4905
4906 sval = cvtnum(optarg);
4907 if (sval < 0) {
4908 if (sval == -ERANGE) {
4909 error_report("Image size must be less than 8 EiB!");
4910 } else {
4911 error_report("Invalid image size specified! You may use "
4912 "k, M, G, T, P or E suffixes for ");
4913 error_report("kilobytes, megabytes, gigabytes, terabytes, "
4914 "petabytes and exabytes.");
4915 }
4916 goto out;
4917 }
4918 img_size = (uint64_t)sval;
4919 }
4920 break;
4921 }
4922 }
4923
4924 if (qemu_opts_foreach(&qemu_object_opts,
4925 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004926 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004927 goto out;
4928 }
4929
4930 if (argc - optind > 1) {
4931 error_report("At most one filename argument is allowed.");
4932 goto out;
4933 } else if (argc - optind == 1) {
4934 filename = argv[optind];
4935 }
4936
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00004937 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
4938 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01004939 goto out;
4940 }
4941 if (filename && img_size != UINT64_MAX) {
4942 error_report("--size N cannot be used together with a filename.");
4943 goto out;
4944 }
4945 if (!filename && img_size == UINT64_MAX) {
4946 error_report("Either --size N or one filename must be specified.");
4947 goto out;
4948 }
4949
4950 if (filename) {
4951 in_blk = img_open(image_opts, filename, fmt, 0,
4952 false, false, force_share);
4953 if (!in_blk) {
4954 goto out;
4955 }
4956
4957 if (sn_opts) {
4958 bdrv_snapshot_load_tmp(blk_bs(in_blk),
4959 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
4960 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
4961 &local_err);
4962 } else if (snapshot_name != NULL) {
4963 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
4964 snapshot_name, &local_err);
4965 }
4966 if (local_err) {
4967 error_reportf_err(local_err, "Failed to load snapshot: ");
4968 goto out;
4969 }
4970 }
4971
4972 drv = bdrv_find_format(out_fmt);
4973 if (!drv) {
4974 error_report("Unknown file format '%s'", out_fmt);
4975 goto out;
4976 }
4977 if (!drv->create_opts) {
4978 error_report("Format driver '%s' does not support image creation",
4979 drv->format_name);
4980 goto out;
4981 }
4982
4983 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4984 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
4985 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4986 if (options) {
4987 qemu_opts_do_parse(opts, options, NULL, &local_err);
4988 if (local_err) {
4989 error_report_err(local_err);
4990 error_report("Invalid options for file format '%s'", out_fmt);
4991 goto out;
4992 }
4993 }
4994 if (img_size != UINT64_MAX) {
4995 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4996 }
4997
4998 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
4999 if (local_err) {
5000 error_report_err(local_err);
5001 goto out;
5002 }
5003
5004 if (output_format == OFORMAT_HUMAN) {
5005 printf("required size: %" PRIu64 "\n", info->required);
5006 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
5007 } else {
5008 dump_json_block_measure_info(info);
5009 }
5010
5011 ret = 0;
5012
5013out:
5014 qapi_free_BlockMeasureInfo(info);
5015 qemu_opts_del(object_opts);
5016 qemu_opts_del(opts);
5017 qemu_opts_del(sn_opts);
5018 qemu_opts_free(create_opts);
5019 g_free(options);
5020 blk_unref(in_blk);
5021 return ret;
5022}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005023
Anthony Liguoric227f092009-10-01 16:12:16 -05005024static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005025#define DEF(option, callback, arg_string) \
5026 { option, callback },
5027#include "qemu-img-cmds.h"
5028#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005029 { NULL, NULL, },
5030};
5031
bellardea2384d2004-08-01 21:59:26 +00005032int main(int argc, char **argv)
5033{
Anthony Liguoric227f092009-10-01 16:12:16 -05005034 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005035 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005036 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005037 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005038 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005039 static const struct option long_options[] = {
5040 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005041 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005042 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005043 {0, 0, 0, 0}
5044 };
bellardea2384d2004-08-01 21:59:26 +00005045
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005046#ifdef CONFIG_POSIX
5047 signal(SIGPIPE, SIG_IGN);
5048#endif
5049
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005050 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005051 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005052 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005053
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005054 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005055 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005056 exit(EXIT_FAILURE);
5057 }
5058
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005059 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005060
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005061 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005062 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005063 if (argc < 2) {
5064 error_exit("Not enough arguments");
5065 }
Stuart Brady153859b2009-06-07 00:42:17 +01005066
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005067 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005068 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005069 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005070
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005071 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005072 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005073 case ':':
5074 missing_argument(argv[optind - 1]);
5075 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005076 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005077 unrecognized_option(argv[optind - 1]);
5078 return 0;
5079 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005080 help();
5081 return 0;
5082 case 'V':
5083 printf(QEMU_IMG_VERSION);
5084 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005085 case 'T':
5086 g_free(trace_file);
5087 trace_file = trace_opt_parse(optarg);
5088 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005089 }
bellardea2384d2004-08-01 21:59:26 +00005090 }
Stuart Brady153859b2009-06-07 00:42:17 +01005091
Denis V. Lunev10985132016-06-17 17:44:13 +03005092 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005093
Denis V. Lunev10985132016-06-17 17:44:13 +03005094 /* reset getopt_long scanning */
5095 argc -= optind;
5096 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005097 return 0;
5098 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005099 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005100 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005101
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005102 if (!trace_init_backends()) {
5103 exit(1);
5104 }
5105 trace_init_file(trace_file);
5106 qemu_set_log(LOG_TRACE);
5107
Denis V. Lunev10985132016-06-17 17:44:13 +03005108 /* find the command */
5109 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5110 if (!strcmp(cmdname, cmd->name)) {
5111 return cmd->handler(argc, argv);
5112 }
5113 }
Jeff Cody7db16892014-04-25 17:02:32 -04005114
Stuart Brady153859b2009-06-07 00:42:17 +01005115 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005116 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005117}