blob: 6fe2466032f95f43ada251f597641fae80a68bdf [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"
Eric Blake3b51ab42020-05-12 20:16:45 -050031#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010032#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010033#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010035#include "qapi/qmp/qdict.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"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010043#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020044#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000045#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020046#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010047#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020048#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080049#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010050#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030051#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000052#include "qemu/throttle.h"
53#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000054
Thomas Huth7e563bf2018-02-15 12:06:47 +010055#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020056 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040057
Anthony Liguoric227f092009-10-01 16:12:16 -050058typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010059 const char *name;
60 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050061} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010062
Federico Simoncelli8599ea42013-01-28 06:59:47 -050063enum {
64 OPTION_OUTPUT = 256,
65 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000066 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000067 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020068 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020069 OPTION_FLUSH_INTERVAL = 261,
70 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010071 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010072 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020073 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030074 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020075 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000076 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050077 OPTION_ADD = 269,
78 OPTION_REMOVE = 270,
79 OPTION_CLEAR = 271,
80 OPTION_ENABLE = 272,
81 OPTION_DISABLE = 273,
82 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050083 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020084 OPTION_FORCE = 276,
Eric Blake955171e2021-07-21 10:53:48 -050085 OPTION_SKIP_BROKEN = 277,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050086};
87
88typedef enum OutputFormat {
89 OFORMAT_JSON,
90 OFORMAT_HUMAN,
91} OutputFormat;
92
Kevin Wolfe6996142016-03-15 13:03:11 +010093/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040094#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000095
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010096static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000097{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010098 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000099}
100
Fam Zhengac1307a2014-04-22 13:36:11 +0800101static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
102{
103 va_list ap;
104
Fam Zhengac1307a2014-04-22 13:36:11 +0800105 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200106 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800107 va_end(ap);
108
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200109 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800110 exit(EXIT_FAILURE);
111}
112
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800113static void QEMU_NORETURN missing_argument(const char *option)
114{
115 error_exit("missing argument for option '%s'", option);
116}
117
118static void QEMU_NORETURN unrecognized_option(const char *option)
119{
120 error_exit("unrecognized option '%s'", option);
121}
122
Eric Blake0562adf2020-05-12 20:16:41 -0500123/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800124static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000125{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100126 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400127 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300128 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300129 "QEMU disk image utility\n"
130 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300131 " '-h', '--help' display this help and exit\n"
132 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300133 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
134 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300135 "\n"
malc3f020d72010-02-08 12:04:56 +0300136 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100137#define DEF(option, callback, arg_string) \
138 " " arg_string "\n"
139#include "qemu-img-cmds.h"
140#undef DEF
malc3f020d72010-02-08 12:04:56 +0300141 "\n"
142 "Command parameters:\n"
143 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000144 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
145 " manual page for a description of the object properties. The most common\n"
146 " object type is a 'secret', which is used to supply passwords and/or\n"
147 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300148 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400149 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800150 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
151 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100152 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
153 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300154 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200155 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
156 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
157 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300158 " 'output_filename' is the destination disk image filename\n"
159 " 'output_fmt' is the destination format\n"
160 " 'options' is a comma separated list of format specific options in a\n"
161 " name=value format. Use -o ? for an overview of the options supported by the\n"
162 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800163 " 'snapshot_param' is param used for internal snapshot, format\n"
164 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
165 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300166 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400167 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
168 " new backing file match exactly. The image doesn't need a working\n"
169 " backing file before rebasing in this case (useful for renaming the\n"
170 " backing file). For image creation, allow creating without attempting\n"
171 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300172 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200173 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100174 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200175 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
176 " contain only zeros for qemu-img to create a sparse image during\n"
177 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
178 " unallocated or zero sectors, and the destination image will always be\n"
179 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200180 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100181 " '-n' skips the target volume creation (useful if the volume is created\n"
182 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300183 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500184 "Parameters to bitmap subcommand:\n"
185 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
186 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
187 " or '--merge source'\n"
188 " '-g granularity' sets the granularity for '--add' actions\n"
189 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
190 " bitmaps from an alternative file\n"
191 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200192 "Parameters to check subcommand:\n"
193 " '-r' tries to repair any inconsistencies that are found during the check.\n"
194 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
195 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200196 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200197 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100198 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500199 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100200 " '-m' specifies how many coroutines work in parallel during the convert\n"
201 " process (defaults to 8)\n"
202 " '-W' allow to write to the target out of order rather than sequential\n"
203 "\n"
malc3f020d72010-02-08 12:04:56 +0300204 "Parameters to snapshot subcommand:\n"
205 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
206 " '-a' applies a snapshot (revert disk to saved state)\n"
207 " '-c' creates a snapshot\n"
208 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100209 " '-l' lists all snapshots in the given image\n"
210 "\n"
211 "Parameters to compare subcommand:\n"
212 " '-f' first image format\n"
213 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200214 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
215 "\n"
216 "Parameters to dd subcommand:\n"
217 " 'bs=BYTES' read and write up to BYTES bytes at a time "
218 "(default: 512)\n"
219 " 'count=N' copy only N input blocks\n"
220 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200221 " 'of=FILE' write to FILE\n"
222 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100223
224 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300225 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500226 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800227 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000228}
229
Markus Armbruster80c710c2020-04-15 09:49:26 +0200230/*
231 * Is @optarg safe for accumulate_options()?
232 * It is when multiple of them can be joined together separated by ','.
233 * To make that work, @optarg must not start with ',' (or else a
234 * separating ',' preceding it gets escaped), and it must not end with
235 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200236 * escaped), or be empty (or else a separating ',' preceding it can
237 * escape a separating ',' following it).
238 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200239 */
240static bool is_valid_option_list(const char *optarg)
241{
242 size_t len = strlen(optarg);
243 size_t i;
244
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200245 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200246 return false;
247 }
248
249 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
250 }
251 if ((len - i) % 2) {
252 return false;
253 }
254
255 return true;
256}
257
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200258static int accumulate_options(char **options, char *optarg)
259{
260 char *new_options;
261
262 if (!is_valid_option_list(optarg)) {
263 error_report("Invalid option list: %s", optarg);
264 return -1;
265 }
266
267 if (!*options) {
268 *options = g_strdup(optarg);
269 } else {
270 new_options = g_strdup_printf("%s,%s", *options, optarg);
271 g_free(*options);
272 *options = new_options;
273 }
274 return 0;
275}
276
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000277static QemuOptsList qemu_source_opts = {
278 .name = "source",
279 .implied_opt_name = "file",
280 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
281 .desc = {
282 { }
283 },
284};
285
Stefan Weil7c30f652013-06-16 17:01:05 +0200286static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100287{
288 int ret = 0;
289 if (!quiet) {
290 va_list args;
291 va_start(args, fmt);
292 ret = vprintf(fmt, args);
293 va_end(args);
294 }
295 return ret;
296}
297
bellardea2384d2004-08-01 21:59:26 +0000298
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100299static int print_block_option_help(const char *filename, const char *fmt)
300{
301 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800302 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500303 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100304
305 /* Find driver and parse its options */
306 drv = bdrv_find_format(fmt);
307 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100308 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100309 return 1;
310 }
311
Max Reitzd402b6a2018-05-09 23:00:21 +0200312 if (!drv->create_opts) {
313 error_report("Format driver '%s' does not support image creation", fmt);
314 return 1;
315 }
316
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800317 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100318 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500319 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100320 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100321 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800322 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100323 return 1;
324 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200325 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100326 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200327 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100328 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200329 return 1;
330 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800331 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100332 }
333
Max Reitzf4619af2019-04-13 17:20:37 +0200334 if (filename) {
335 printf("Supported options:\n");
336 } else {
337 printf("Supported %s options:\n", fmt);
338 }
Max Reitz63898712018-10-19 18:49:25 +0200339 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800340 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200341
342 if (!filename) {
343 printf("\n"
344 "The protocol level may support further options.\n"
345 "Specify the target filename to include those options.\n");
346 }
347
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100348 return 0;
349}
350
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000351
Max Reitzefaa7c42016-03-16 19:54:38 +0100352static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100353 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800354 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000355{
356 QDict *options;
357 Error *local_err = NULL;
358 BlockBackend *blk;
359 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800360 if (force_share) {
361 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200362 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800363 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200364 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800365 return NULL;
366 }
Max Reitz4615f872018-05-02 22:20:50 +0200367 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800368 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100369 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000370 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100371 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000372 return NULL;
373 }
Kevin Wolfce099542016-03-15 13:01:04 +0100374 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000375
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000376 return blk;
377}
378
Max Reitzefaa7c42016-03-16 19:54:38 +0100379static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100380 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000381 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800382 bool writethrough, bool quiet,
383 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000384{
385 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200386 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100387
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100388 if (!options) {
389 options = qdict_new();
390 }
bellard75c23802004-08-27 21:28:58 +0000391 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500392 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000393 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100394
Fam Zheng335e9932017-05-03 00:35:39 +0800395 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500396 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800397 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100398 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500399 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100400 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000401 return NULL;
bellard75c23802004-08-27 21:28:58 +0000402 }
Kevin Wolfce099542016-03-15 13:01:04 +0100403 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100404
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200405 return blk;
bellard75c23802004-08-27 21:28:58 +0000406}
407
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000408
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100409static int img_add_key_secrets(void *opaque,
410 const char *name, const char *value,
411 Error **errp)
412{
413 QDict *options = opaque;
414
415 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600416 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100417 }
418
419 return 0;
420}
421
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100422
Max Reitzefaa7c42016-03-16 19:54:38 +0100423static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000424 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100425 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800426 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000427{
428 BlockBackend *blk;
429 if (image_opts) {
430 QemuOpts *opts;
431 if (fmt) {
432 error_report("--image-opts and --format are mutually exclusive");
433 return NULL;
434 }
435 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
436 filename, true);
437 if (!opts) {
438 return NULL;
439 }
Fam Zheng335e9932017-05-03 00:35:39 +0800440 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
441 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000442 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100443 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800444 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000445 }
446 return blk;
447}
448
449
Chunyan Liu83d05212014-06-05 17:20:51 +0800450static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100451 const char *base_filename,
452 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200453{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200454 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200455 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200456 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100457 error_report("Backing file not supported for file format '%s'",
458 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900459 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200460 }
461 }
462 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200463 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100464 error_report("Backing file format not supported for file "
465 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900466 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200467 }
468 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900469 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200470}
471
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300472static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
473 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100474{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100475 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300476 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100477
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300478 err = qemu_strtosz(value, NULL, &res);
479 if (err < 0 && err != -ERANGE) {
480 error_report("Invalid %s specified. You may use "
481 "k, M, G, T, P or E suffixes for", name);
482 error_report("kilobytes, megabytes, gigabytes, terabytes, "
483 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100484 return err;
485 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300486 if (err == -ERANGE || res > max || res < min) {
487 error_report("Invalid %s specified. Must be between %" PRId64
488 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100489 return -ERANGE;
490 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300491 return res;
492}
493
494static int64_t cvtnum(const char *name, const char *value)
495{
496 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100497}
498
bellardea2384d2004-08-01 21:59:26 +0000499static int img_create(int argc, char **argv)
500{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200501 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100502 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000503 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000504 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000505 const char *filename;
506 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200507 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200508 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100509 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400510 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000511
bellardea2384d2004-08-01 21:59:26 +0000512 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000513 static const struct option long_options[] = {
514 {"help", no_argument, 0, 'h'},
515 {"object", required_argument, 0, OPTION_OBJECT},
516 {0, 0, 0, 0}
517 };
John Snow6e6e55f2017-07-17 20:34:22 -0400518 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000519 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100520 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000521 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100522 }
bellardea2384d2004-08-01 21:59:26 +0000523 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800524 case ':':
525 missing_argument(argv[optind - 1]);
526 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100527 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800528 unrecognized_option(argv[optind - 1]);
529 break;
bellardea2384d2004-08-01 21:59:26 +0000530 case 'h':
531 help();
532 break;
aliguori9230eaf2009-03-28 17:55:19 +0000533 case 'F':
534 base_fmt = optarg;
535 break;
bellardea2384d2004-08-01 21:59:26 +0000536 case 'b':
537 base_filename = optarg;
538 break;
539 case 'f':
540 fmt = optarg;
541 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200542 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200543 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100544 goto fail;
545 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200546 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100547 case 'q':
548 quiet = true;
549 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400550 case 'u':
551 flags |= BDRV_O_NO_BACKING;
552 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100553 case OPTION_OBJECT:
554 user_creatable_process_cmdline(optarg);
555 break;
bellardea2384d2004-08-01 21:59:26 +0000556 }
557 }
aliguori9230eaf2009-03-28 17:55:19 +0000558
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900559 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100560 filename = (optind < argc) ? argv[optind] : NULL;
561 if (options && has_help_option(options)) {
562 g_free(options);
563 return print_block_option_help(filename, fmt);
564 }
565
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100566 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800567 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100568 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100569 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900570
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100571 /* Get image size, if specified */
572 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100573 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100574
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300575 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100576 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100577 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100578 }
579 img_size = (uint64_t)sval;
580 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200581 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800582 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200583 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100584
Luiz Capitulino9b375252012-11-30 10:52:05 -0200585 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400586 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100587 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100588 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100589 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900590 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200591
Kevin Wolf77386bf2014-02-21 16:24:04 +0100592 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000593 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100594
595fail:
596 g_free(options);
597 return 1;
bellardea2384d2004-08-01 21:59:26 +0000598}
599
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100600static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500601{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100602 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100604 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600605
606 visit_type_ImageCheck(v, NULL, &check, &error_abort);
607 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100608 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500609 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100610 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200611 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600612 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100613 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500614}
615
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100616static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500617{
618 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100619 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500620 } else {
621 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100622 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
623 "Data may be corrupted, or further writes to the image "
624 "may corrupt it.\n",
625 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500626 }
627
628 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 qprintf(quiet,
630 "\n%" PRId64 " leaked clusters were found on the image.\n"
631 "This means waste of disk space, but no harm to data.\n",
632 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500633 }
634
635 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100636 qprintf(quiet,
637 "\n%" PRId64
638 " internal errors have occurred during the check.\n",
639 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500640 }
641 }
642
643 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100644 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
645 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
646 check->allocated_clusters, check->total_clusters,
647 check->allocated_clusters * 100.0 / check->total_clusters,
648 check->fragmented_clusters * 100.0 / check->allocated_clusters,
649 check->compressed_clusters * 100.0 /
650 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500651 }
652
653 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100654 qprintf(quiet,
655 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500656 }
657}
658
659static int collect_image_check(BlockDriverState *bs,
660 ImageCheck *check,
661 const char *filename,
662 const char *fmt,
663 int fix)
664{
665 int ret;
666 BdrvCheckResult result;
667
668 ret = bdrv_check(bs, &result, fix);
669 if (ret < 0) {
670 return ret;
671 }
672
673 check->filename = g_strdup(filename);
674 check->format = g_strdup(bdrv_get_format_name(bs));
675 check->check_errors = result.check_errors;
676 check->corruptions = result.corruptions;
677 check->has_corruptions = result.corruptions != 0;
678 check->leaks = result.leaks;
679 check->has_leaks = result.leaks != 0;
680 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100681 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500682 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100683 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 check->image_end_offset = result.image_end_offset;
685 check->has_image_end_offset = result.image_end_offset != 0;
686 check->total_clusters = result.bfi.total_clusters;
687 check->has_total_clusters = result.bfi.total_clusters != 0;
688 check->allocated_clusters = result.bfi.allocated_clusters;
689 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
690 check->fragmented_clusters = result.bfi.fragmented_clusters;
691 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100692 check->compressed_clusters = result.bfi.compressed_clusters;
693 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500694
695 return 0;
696}
697
Kevin Wolfe076f332010-06-29 11:43:13 +0200698/*
699 * Checks an image for consistency. Exit codes:
700 *
Max Reitzd6635c42014-06-02 22:15:21 +0200701 * 0 - Check completed, image is good
702 * 1 - Check not completed because of internal errors
703 * 2 - Check completed, image is corrupted
704 * 3 - Check completed, image has leaked clusters, but is good otherwise
705 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200706 */
aliguori15859692009-04-21 23:11:53 +0000707static int img_check(int argc, char **argv)
708{
709 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500710 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200711 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200712 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000713 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200714 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100715 int flags = BDRV_O_CHECK;
716 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200717 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100718 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000719 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800720 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000721
722 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500723 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200724 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100725
aliguori15859692009-04-21 23:11:53 +0000726 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500727 int option_index = 0;
728 static const struct option long_options[] = {
729 {"help", no_argument, 0, 'h'},
730 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530731 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500732 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000733 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000734 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800735 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500736 {0, 0, 0, 0}
737 };
Fam Zheng335e9932017-05-03 00:35:39 +0800738 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500739 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100740 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000741 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100742 }
aliguori15859692009-04-21 23:11:53 +0000743 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800744 case ':':
745 missing_argument(argv[optind - 1]);
746 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100747 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800748 unrecognized_option(argv[optind - 1]);
749 break;
aliguori15859692009-04-21 23:11:53 +0000750 case 'h':
751 help();
752 break;
753 case 'f':
754 fmt = optarg;
755 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200756 case 'r':
757 flags |= BDRV_O_RDWR;
758
759 if (!strcmp(optarg, "leaks")) {
760 fix = BDRV_FIX_LEAKS;
761 } else if (!strcmp(optarg, "all")) {
762 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
763 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800764 error_exit("Unknown option value for -r "
765 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200766 }
767 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500768 case OPTION_OUTPUT:
769 output = optarg;
770 break;
Max Reitz40055952014-07-22 22:58:42 +0200771 case 'T':
772 cache = optarg;
773 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100774 case 'q':
775 quiet = true;
776 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800777 case 'U':
778 force_share = true;
779 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100780 case OPTION_OBJECT:
781 user_creatable_process_cmdline(optarg);
782 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000783 case OPTION_IMAGE_OPTS:
784 image_opts = true;
785 break;
aliguori15859692009-04-21 23:11:53 +0000786 }
787 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200788 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800789 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100790 }
aliguori15859692009-04-21 23:11:53 +0000791 filename = argv[optind++];
792
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500793 if (output && !strcmp(output, "json")) {
794 output_format = OFORMAT_JSON;
795 } else if (output && !strcmp(output, "human")) {
796 output_format = OFORMAT_HUMAN;
797 } else if (output) {
798 error_report("--output must be used with human or json as argument.");
799 return 1;
800 }
801
Kevin Wolfce099542016-03-15 13:01:04 +0100802 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200803 if (ret < 0) {
804 error_report("Invalid source cache option: %s", cache);
805 return 1;
806 }
807
Fam Zheng335e9932017-05-03 00:35:39 +0800808 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
809 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200810 if (!blk) {
811 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900812 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200813 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500814
815 check = g_new0(ImageCheck, 1);
816 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200817
818 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200819 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200820 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500821 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200822 }
823
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500824 if (check->corruptions_fixed || check->leaks_fixed) {
825 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100826 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500827
828 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100829 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500830 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100831 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500832
833 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100834 qprintf(quiet,
835 "The following inconsistencies were found and repaired:\n\n"
836 " %" PRId64 " leaked clusters\n"
837 " %" PRId64 " corruptions\n\n"
838 "Double checking the fixed image now...\n",
839 check->leaks_fixed,
840 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500841 }
842
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800843 qapi_free_ImageCheck(check);
844 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500845 ret = collect_image_check(bs, check, filename, fmt, 0);
846
847 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100848 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500849 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100850 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200851 }
852
Max Reitz832390a2014-10-23 15:29:12 +0200853 if (!ret) {
854 switch (output_format) {
855 case OFORMAT_HUMAN:
856 dump_human_image_check(check, quiet);
857 break;
858 case OFORMAT_JSON:
859 dump_json_image_check(check, quiet);
860 break;
861 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500862 }
863
864 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200865 if (ret) {
866 error_report("Check failed: %s", strerror(-ret));
867 } else {
868 error_report("Check failed");
869 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500870 ret = 1;
871 goto fail;
872 }
873
874 if (check->corruptions) {
875 ret = 2;
876 } else if (check->leaks) {
877 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200878 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500879 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000880 }
881
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500882fail:
883 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200884 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500885 return ret;
aliguori15859692009-04-21 23:11:53 +0000886}
887
Max Reitzd4a32382014-10-24 15:57:37 +0200888typedef struct CommonBlockJobCBInfo {
889 BlockDriverState *bs;
890 Error **errp;
891} CommonBlockJobCBInfo;
892
893static void common_block_job_cb(void *opaque, int ret)
894{
895 CommonBlockJobCBInfo *cbi = opaque;
896
897 if (ret < 0) {
898 error_setg_errno(cbi->errp, -ret, "Block job failed");
899 }
Max Reitzd4a32382014-10-24 15:57:37 +0200900}
901
902static void run_block_job(BlockJob *job, Error **errp)
903{
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200904 uint64_t progress_current, progress_total;
Vladimir Sementsov-Ogievskiydf9a3162021-05-06 17:13:53 +0300905 AioContext *aio_context = block_job_get_aio_context(job);
sochin.jiang4172a002017-06-15 14:47:33 +0800906 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200907
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200908 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200909 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200910 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200911 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200912 aio_poll(aio_context, true);
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200913
914 progress_get_snapshot(&job->job.progress, &progress_current,
915 &progress_total);
916 if (progress_total) {
917 progress = (float)progress_current / progress_total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200918 }
919 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200920 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200921
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200922 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200923 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800924 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200925 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800926 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200927 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200928 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200929
sochin.jiang4172a002017-06-15 14:47:33 +0800930 /* publish completion progress only when success */
931 if (!ret) {
932 qemu_progress_print(100.f, 0);
933 }
Max Reitzd4a32382014-10-24 15:57:37 +0200934}
935
bellardea2384d2004-08-01 21:59:26 +0000936static int img_commit(int argc, char **argv)
937{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400938 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200939 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200940 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200941 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100942 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200943 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100944 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200945 Error *local_err = NULL;
946 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000947 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200948 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000949 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000950
951 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400952 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200953 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000954 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000955 static const struct option long_options[] = {
956 {"help", no_argument, 0, 'h'},
957 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000958 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000959 {0, 0, 0, 0}
960 };
Zhenguia0441b62020-10-20 14:47:43 +0000961 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000962 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100963 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000964 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100965 }
bellardea2384d2004-08-01 21:59:26 +0000966 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800967 case ':':
968 missing_argument(argv[optind - 1]);
969 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100970 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800971 unrecognized_option(argv[optind - 1]);
972 break;
bellardea2384d2004-08-01 21:59:26 +0000973 case 'h':
974 help();
975 break;
976 case 'f':
977 fmt = optarg;
978 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400979 case 't':
980 cache = optarg;
981 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200982 case 'b':
983 base = optarg;
984 /* -b implies -d */
985 drop = true;
986 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200987 case 'd':
988 drop = true;
989 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200990 case 'p':
991 progress = true;
992 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100993 case 'q':
994 quiet = true;
995 break;
Zhenguia0441b62020-10-20 14:47:43 +0000996 case 'r':
997 rate_limit = cvtnum("rate limit", optarg);
998 if (rate_limit < 0) {
999 return 1;
1000 }
1001 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001002 case OPTION_OBJECT:
1003 user_creatable_process_cmdline(optarg);
1004 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001005 case OPTION_IMAGE_OPTS:
1006 image_opts = true;
1007 break;
bellardea2384d2004-08-01 21:59:26 +00001008 }
1009 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001010
1011 /* Progress is not shown in Quiet mode */
1012 if (quiet) {
1013 progress = false;
1014 }
1015
Kevin Wolffc11eb22013-08-05 10:53:04 +02001016 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001017 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001018 }
bellardea2384d2004-08-01 21:59:26 +00001019 filename = argv[optind++];
1020
Max Reitz9a86fe42014-10-24 15:57:38 +02001021 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001022 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001023 if (ret < 0) {
1024 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001025 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001026 }
1027
Fam Zheng335e9932017-05-03 00:35:39 +08001028 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1029 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001030 if (!blk) {
1031 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001032 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001033 bs = blk_bs(blk);
1034
Max Reitz687fa1d2014-10-24 15:57:39 +02001035 qemu_progress_init(progress, 1.f);
1036 qemu_progress_print(0.f, 100);
1037
Max Reitz1b22bff2014-10-24 15:57:40 +02001038 if (base) {
1039 base_bs = bdrv_find_backing_image(bs, base);
1040 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001041 error_setg(&local_err,
1042 "Did not find '%s' in the backing chain of '%s'",
1043 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001044 goto done;
1045 }
1046 } else {
1047 /* This is different from QMP, which by default uses the deepest file in
1048 * the backing chain (i.e., the very base); however, the traditional
1049 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001050 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001051 if (!base_bs) {
1052 error_setg(&local_err, "Image does not have a backing file");
1053 goto done;
1054 }
bellardea2384d2004-08-01 21:59:26 +00001055 }
1056
Max Reitzd4a32382014-10-24 15:57:37 +02001057 cbi = (CommonBlockJobCBInfo){
1058 .errp = &local_err,
1059 .bs = bs,
1060 };
1061
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001062 aio_context = bdrv_get_aio_context(bs);
1063 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001064 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001065 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001066 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001067 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001068 if (local_err) {
1069 goto done;
1070 }
1071
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001072 /* When the block job completes, the BlockBackend reference will point to
1073 * the old backing file. In order to avoid that the top image is already
1074 * deleted, so we can still empty it afterwards, increment the reference
1075 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001076 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001077 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001078 }
1079
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001080 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001081 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001082 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001083 if (local_err) {
1084 goto unref_backing;
1085 }
1086
Max Reitz2d97fde2020-04-29 16:11:26 +02001087 if (!drop) {
1088 BlockBackend *old_backing_blk;
1089
1090 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1091 &local_err);
1092 if (!old_backing_blk) {
1093 goto unref_backing;
1094 }
1095 ret = blk_make_empty(old_backing_blk, &local_err);
1096 blk_unref(old_backing_blk);
1097 if (ret == -ENOTSUP) {
1098 error_free(local_err);
1099 local_err = NULL;
1100 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001101 goto unref_backing;
1102 }
1103 }
1104
1105unref_backing:
1106 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001107 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001108 }
Max Reitzd4a32382014-10-24 15:57:37 +02001109
1110done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001111 qemu_progress_end();
1112
Markus Armbruster26f54e92014-10-07 13:59:04 +02001113 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001114
1115 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001116 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001117 return 1;
1118 }
Max Reitzd4a32382014-10-24 15:57:37 +02001119
1120 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001121 return 0;
1122}
1123
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001124/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001125 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1126 * of the first sector boundary within buf where the sector contains a
1127 * non-zero byte. This function is robust to a buffer that is not
1128 * sector-aligned.
1129 */
1130static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1131{
1132 int64_t i;
1133 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1134
1135 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1136 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1137 return i;
1138 }
1139 }
1140 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1141 return i;
1142 }
1143 return -1;
1144}
1145
1146/*
thsf58c7b32008-06-05 21:53:49 +00001147 * Returns true iff the first sector pointed to by 'buf' contains at least
1148 * a non-NUL byte.
1149 *
1150 * 'pnum' is set to the number of sectors (including and immediately following
1151 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001152 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001153 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001154 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001155 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001156static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1157 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001158{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001159 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001160 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001161
1162 if (n <= 0) {
1163 *pnum = 0;
1164 return 0;
1165 }
Yi Lic075c422020-08-19 09:36:07 +08001166 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001167 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001168 buf += BDRV_SECTOR_SIZE;
1169 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001170 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001171 }
bellardea2384d2004-08-01 21:59:26 +00001172 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001173
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001174 if (i == n) {
1175 /*
1176 * The whole buf is the same.
1177 * No reason to split it into chunks, so return now.
1178 */
1179 *pnum = i;
1180 return !is_zero;
1181 }
1182
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001183 tail = (sector_num + i) & (alignment - 1);
1184 if (tail) {
1185 if (is_zero && i <= tail) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001186 /*
1187 * For sure next sector after i is data, and it will rewrite this
1188 * tail anyway due to RMW. So, let's just write data now.
1189 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001190 is_zero = false;
1191 }
1192 if (!is_zero) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001193 /* If possible, align up end offset of allocated areas. */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001194 i += alignment - tail;
1195 i = MIN(i, n);
1196 } else {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001197 /*
1198 * For sure next sector after i is data, and it will rewrite this
1199 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1200 * to aligned bound.
1201 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001202 i -= tail;
1203 }
1204 }
bellardea2384d2004-08-01 21:59:26 +00001205 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001206 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001207}
1208
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001209/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001210 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1211 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1212 * breaking up write requests for only small sparse areas.
1213 */
1214static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001215 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001216{
1217 int ret;
1218 int num_checked, num_used;
1219
1220 if (n < min) {
1221 min = n;
1222 }
1223
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001224 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001225 if (!ret) {
1226 return ret;
1227 }
1228
1229 num_used = *pnum;
1230 buf += BDRV_SECTOR_SIZE * *pnum;
1231 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001232 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001233 num_checked = num_used;
1234
1235 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001236 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001237
1238 buf += BDRV_SECTOR_SIZE * *pnum;
1239 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001240 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001241 num_checked += *pnum;
1242 if (ret) {
1243 num_used = num_checked;
1244 } else if (*pnum >= min) {
1245 break;
1246 }
1247 }
1248
1249 *pnum = num_used;
1250 return 1;
1251}
1252
1253/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001254 * Compares two buffers sector by sector. Returns 0 if the first
1255 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001256 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001257 * pnum is set to the sector-aligned size of the buffer prefix that
1258 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001259 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001260static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1261 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001262{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001263 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001264 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001265
Eric Blakedc61cd32017-10-11 22:47:14 -05001266 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001267
Eric Blakedc61cd32017-10-11 22:47:14 -05001268 res = !!memcmp(buf1, buf2, i);
1269 while (i < bytes) {
1270 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001271
Eric Blakedc61cd32017-10-11 22:47:14 -05001272 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001273 break;
1274 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001275 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001276 }
1277
1278 *pnum = i;
1279 return res;
1280}
1281
Stefano Garzarella97ede572019-05-08 12:43:24 +02001282#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001283
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001284/*
1285 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1286 *
Eric Blake0608e402017-10-11 22:47:12 -05001287 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1288 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1289 * failure), and 4 on error (the exit status for read errors), after emitting
1290 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001291 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001292 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001293 * @param offset: Starting offset to check
1294 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 * @param filename: Name of disk file we are checking (logging purpose)
1296 * @param buffer: Allocated buffer for storing read data
1297 * @param quiet: Flag for quiet mode
1298 */
Eric Blakec41508e2017-10-11 22:47:13 -05001299static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1300 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001301 uint8_t *buffer, bool quiet)
1302{
Eric Blakedebb38a2017-10-11 22:47:11 -05001303 int ret = 0;
1304 int64_t idx;
1305
Eric Blakec41508e2017-10-11 22:47:13 -05001306 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001307 if (ret < 0) {
1308 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001309 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001310 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 }
Eric Blakec41508e2017-10-11 22:47:13 -05001312 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001313 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001314 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001315 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001316 return 1;
1317 }
1318
1319 return 0;
1320}
1321
1322/*
1323 * Compares two images. Exit codes:
1324 *
Kevin Wolf99b1e642021-02-17 12:56:45 +01001325 * 0 - Images are identical or the requested help was printed
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001326 * 1 - Images differ
1327 * >1 - Error occurred
1328 */
1329static int img_compare(int argc, char **argv)
1330{
Max Reitz40055952014-07-22 22:58:42 +02001331 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001332 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001334 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001336 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001337 int allocated1, allocated2;
1338 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1339 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001340 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001341 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001342 int64_t total_size;
1343 int64_t offset = 0;
1344 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001345 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001346 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001347 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001348 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001349
Max Reitz40055952014-07-22 22:58:42 +02001350 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001351 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001352 static const struct option long_options[] = {
1353 {"help", no_argument, 0, 'h'},
1354 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001355 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001356 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001357 {0, 0, 0, 0}
1358 };
Fam Zheng335e9932017-05-03 00:35:39 +08001359 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001360 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001361 if (c == -1) {
1362 break;
1363 }
1364 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001365 case ':':
1366 missing_argument(argv[optind - 1]);
1367 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001368 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001369 unrecognized_option(argv[optind - 1]);
1370 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001371 case 'h':
1372 help();
1373 break;
1374 case 'f':
1375 fmt1 = optarg;
1376 break;
1377 case 'F':
1378 fmt2 = optarg;
1379 break;
Max Reitz40055952014-07-22 22:58:42 +02001380 case 'T':
1381 cache = optarg;
1382 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001383 case 'p':
1384 progress = true;
1385 break;
1386 case 'q':
1387 quiet = true;
1388 break;
1389 case 's':
1390 strict = true;
1391 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001392 case 'U':
1393 force_share = true;
1394 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001395 case OPTION_OBJECT:
1396 {
1397 Error *local_err = NULL;
1398
1399 if (!user_creatable_add_from_str(optarg, &local_err)) {
1400 if (local_err) {
1401 error_report_err(local_err);
1402 exit(2);
1403 } else {
1404 /* Help was printed */
1405 exit(EXIT_SUCCESS);
1406 }
1407 }
1408 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001409 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001410 case OPTION_IMAGE_OPTS:
1411 image_opts = true;
1412 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001413 }
1414 }
1415
1416 /* Progress is not shown in Quiet mode */
1417 if (quiet) {
1418 progress = false;
1419 }
1420
1421
Kevin Wolffc11eb22013-08-05 10:53:04 +02001422 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001423 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001424 }
1425 filename1 = argv[optind++];
1426 filename2 = argv[optind++];
1427
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001428 /* Initialize before goto out */
1429 qemu_progress_init(progress, 2.0);
1430
Kevin Wolfce099542016-03-15 13:01:04 +01001431 flags = 0;
1432 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001433 if (ret < 0) {
1434 error_report("Invalid source cache option: %s", cache);
1435 ret = 2;
1436 goto out3;
1437 }
1438
Fam Zheng335e9932017-05-03 00:35:39 +08001439 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1440 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001441 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001442 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001443 goto out3;
1444 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001445
Fam Zheng335e9932017-05-03 00:35:39 +08001446 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1447 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001448 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001449 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001450 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001451 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001452 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001453 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001454
Max Reitzf1d3cd72015-02-05 13:58:18 -05001455 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1456 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001457 total_size1 = blk_getlength(blk1);
1458 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001459 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001460 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001461 ret = 4;
1462 goto out;
1463 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001464 total_size2 = blk_getlength(blk2);
1465 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001466 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001467 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001468 ret = 4;
1469 goto out;
1470 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001471 total_size = MIN(total_size1, total_size2);
1472 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001473
1474 qemu_progress_print(0, 100);
1475
Eric Blake033d9fc2017-10-11 22:47:16 -05001476 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477 ret = 1;
1478 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1479 goto out;
1480 }
1481
Eric Blake033d9fc2017-10-11 22:47:16 -05001482 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001483 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001484
Eric Blake033d9fc2017-10-11 22:47:16 -05001485 status1 = bdrv_block_status_above(bs1, NULL, offset,
1486 total_size1 - offset, &pnum1, NULL,
1487 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001488 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001489 ret = 3;
1490 error_report("Sector allocation test failed for %s", filename1);
1491 goto out;
1492 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001493 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001494
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 status2 = bdrv_block_status_above(bs2, NULL, offset,
1496 total_size2 - offset, &pnum2, NULL,
1497 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001498 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 ret = 3;
1500 error_report("Sector allocation test failed for %s", filename2);
1501 goto out;
1502 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001503 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001504
1505 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001506 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001507
Fam Zheng25ad8e62016-01-13 16:37:41 +08001508 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001509 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001510 ret = 1;
1511 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001512 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001513 goto out;
1514 }
1515 }
1516 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001517 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001518 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001520 int64_t pnum;
1521
Eric Blake033d9fc2017-10-11 22:47:16 -05001522 chunk = MIN(chunk, IO_BUF_SIZE);
1523 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001524 if (ret < 0) {
1525 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001526 " of %s: %s",
1527 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001528 ret = 4;
1529 goto out;
1530 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001531 ret = blk_pread(blk2, offset, buf2, chunk);
1532 if (ret < 0) {
1533 error_report("Error while reading offset %" PRId64
1534 " of %s: %s",
1535 offset, filename2, strerror(-ret));
1536 ret = 4;
1537 goto out;
1538 }
1539 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1540 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001541 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001542 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001543 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 goto out;
1545 }
1546 }
1547 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001548 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001550 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 filename1, buf1, quiet);
1552 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001553 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001554 filename2, buf1, quiet);
1555 }
1556 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001557 goto out;
1558 }
1559 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001560 offset += chunk;
1561 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001562 }
1563
Eric Blake033d9fc2017-10-11 22:47:16 -05001564 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001565 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001566 const char *filename_over;
1567
1568 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001569 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001570 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001571 filename_over = filename1;
1572 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001573 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001574 filename_over = filename2;
1575 }
1576
Eric Blake033d9fc2017-10-11 22:47:16 -05001577 while (offset < progress_base) {
1578 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1579 progress_base - offset, &chunk,
1580 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001581 if (ret < 0) {
1582 ret = 3;
1583 error_report("Sector allocation test failed for %s",
1584 filename_over);
1585 goto out;
1586
1587 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001588 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001589 chunk = MIN(chunk, IO_BUF_SIZE);
1590 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001591 filename_over, buf1, quiet);
1592 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001593 goto out;
1594 }
1595 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001596 offset += chunk;
1597 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001598 }
1599 }
1600
1601 qprintf(quiet, "Images are identical.\n");
1602 ret = 0;
1603
1604out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001605 qemu_vfree(buf1);
1606 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001607 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001608out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001609 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001610out3:
1611 qemu_progress_end();
1612 return ret;
1613}
1614
Eric Blake6c729dd2020-05-21 14:21:35 -05001615/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1616static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1617 const char *src_node, const char *src_name,
1618 Error **errp)
1619{
1620 BlockDirtyBitmapMergeSource *merge_src;
Eric Blake54aa3de2020-11-12 19:13:37 -06001621 BlockDirtyBitmapMergeSourceList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001622
1623 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1624 merge_src->type = QTYPE_QDICT;
1625 merge_src->u.external.node = g_strdup(src_node);
1626 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001627 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001628 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1629 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1630}
1631
Kevin Wolf690c7302015-03-19 13:33:32 +01001632enum ImgConvertBlockStatus {
1633 BLK_DATA,
1634 BLK_ZERO,
1635 BLK_BACKING_FILE,
1636};
1637
Peter Lieven2d9187b2017-02-28 13:40:07 +01001638#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001639#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001640
Kevin Wolf690c7302015-03-19 13:33:32 +01001641typedef struct ImgConvertState {
1642 BlockBackend **src;
1643 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001644 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001645 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001646 int64_t total_sectors;
1647 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001648 int64_t allocated_done;
1649 int64_t sector_num;
1650 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001651 enum ImgConvertBlockStatus status;
1652 int64_t sector_next_status;
1653 BlockBackend *target;
1654 bool has_zero_init;
1655 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001656 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001657 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001658 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001659 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001660 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001661 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001662 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001663 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001664 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001665 size_t cluster_sectors;
1666 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001667 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001668 int running_coroutines;
1669 Coroutine *co[MAX_COROUTINES];
1670 int64_t wait_sector_num[MAX_COROUTINES];
1671 CoMutex lock;
1672 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673} ImgConvertState;
1674
Peter Lieven2d9187b2017-02-28 13:40:07 +01001675static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1676 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001677{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001678 *src_cur = 0;
1679 *src_cur_offset = 0;
1680 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1681 *src_cur_offset += s->src_sectors[*src_cur];
1682 (*src_cur)++;
1683 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001684 }
1685}
1686
1687static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1688{
Eric Blake31826642017-10-11 22:47:08 -05001689 int64_t src_cur_offset;
1690 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001691 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001692
Peter Lieven2d9187b2017-02-28 13:40:07 +01001693 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001694
1695 assert(s->total_sectors > sector_num);
1696 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1697
Max Reitz351c8ef2018-05-01 18:57:49 +02001698 if (s->target_backing_sectors >= 0) {
1699 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001700 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001701 } else if (sector_num + n > s->target_backing_sectors) {
1702 /* Split requests around target_backing_sectors (because
1703 * starting from there, zeros are handled differently) */
1704 n = s->target_backing_sectors - sector_num;
1705 }
1706 }
1707
Kevin Wolf690c7302015-03-19 13:33:32 +01001708 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001709 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1710 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001711 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001712 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1713 BlockDriverState *base;
1714
1715 if (s->target_has_backing) {
1716 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1717 } else {
1718 base = NULL;
1719 }
Eric Blake31826642017-10-11 22:47:08 -05001720
Max Reitz8eaac022019-05-07 22:35:03 +02001721 do {
1722 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001723
Max Reitz4a2061e2019-06-12 19:00:30 +02001724 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1725 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001726
1727 if (ret < 0) {
1728 if (s->salvage) {
1729 if (n == 1) {
1730 if (!s->quiet) {
1731 warn_report("error while reading block status at "
1732 "offset %" PRIu64 ": %s", offset,
1733 strerror(-ret));
1734 }
1735 /* Just try to read the data, then */
1736 ret = BDRV_BLOCK_DATA;
1737 count = BDRV_SECTOR_SIZE;
1738 } else {
1739 /* Retry on a shorter range */
1740 n = DIV_ROUND_UP(n, 4);
1741 }
1742 } else {
1743 error_report("error while reading block status at offset "
1744 "%" PRIu64 ": %s", offset, strerror(-ret));
1745 return ret;
1746 }
1747 }
1748 } while (ret < 0);
1749
Eric Blake31826642017-10-11 22:47:08 -05001750 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001751
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001752 /*
1753 * Avoid that s->sector_next_status becomes unaligned to the source
1754 * request alignment and/or cluster size to avoid unnecessary read
1755 * cycles.
1756 */
1757 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1758 if (n > tail) {
1759 n -= tail;
1760 }
1761
Kevin Wolf690c7302015-03-19 13:33:32 +01001762 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001763 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001764 } else if (ret & BDRV_BLOCK_DATA) {
1765 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001766 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001767 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001768 }
1769
1770 s->sector_next_status = sector_num + n;
1771 }
1772
1773 n = MIN(n, s->sector_next_status - sector_num);
1774 if (s->status == BLK_DATA) {
1775 n = MIN(n, s->buf_sectors);
1776 }
1777
1778 /* We need to write complete clusters for compressed images, so if an
1779 * unallocated area is shorter than that, we must consider the whole
1780 * cluster allocated. */
1781 if (s->compressed) {
1782 if (n < s->cluster_sectors) {
1783 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1784 s->status = BLK_DATA;
1785 } else {
1786 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1787 }
1788 }
1789
1790 return n;
1791}
1792
Peter Lieven2d9187b2017-02-28 13:40:07 +01001793static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1794 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001795{
Max Reitz8eaac022019-05-07 22:35:03 +02001796 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001797 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001798
Kevin Wolf690c7302015-03-19 13:33:32 +01001799 assert(nb_sectors <= s->buf_sectors);
1800 while (nb_sectors > 0) {
1801 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001802 int src_cur;
1803 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001804 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001805
1806 /* In the case of compression with multiple source files, we can get a
1807 * nb_sectors that spreads into the next part. So we must be able to
1808 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001809 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1810 blk = s->src[src_cur];
1811 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001812
Max Reitz8eaac022019-05-07 22:35:03 +02001813 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001814
Max Reitz8eaac022019-05-07 22:35:03 +02001815 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1816 if (single_read_until > offset) {
1817 n = 1;
1818 }
1819
1820 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001821 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001822 if (s->salvage) {
1823 if (n > 1) {
1824 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1825 continue;
1826 } else {
1827 if (!s->quiet) {
1828 warn_report("error while reading offset %" PRIu64
1829 ": %s", offset, strerror(-ret));
1830 }
1831 memset(buf, 0, BDRV_SECTOR_SIZE);
1832 }
1833 } else {
1834 return ret;
1835 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001836 }
1837
1838 sector_num += n;
1839 nb_sectors -= n;
1840 buf += n * BDRV_SECTOR_SIZE;
1841 }
1842
1843 return 0;
1844}
1845
Peter Lieven2d9187b2017-02-28 13:40:07 +01001846
1847static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1848 int nb_sectors, uint8_t *buf,
1849 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001850{
1851 int ret;
1852
1853 while (nb_sectors > 0) {
1854 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001855 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1856
Peter Lieven2d9187b2017-02-28 13:40:07 +01001857 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001858 case BLK_BACKING_FILE:
1859 /* If we have a backing file, leave clusters unallocated that are
1860 * unallocated in the source image, so that the backing file is
1861 * visible at the respective offset. */
1862 assert(s->target_has_backing);
1863 break;
1864
1865 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001866 /* If we're told to keep the target fully allocated (-S 0) or there
1867 * is real non-zero data, we must write it. Otherwise we can treat
1868 * it as zero sectors.
1869 * Compressed clusters need to be written as a whole, so in that
1870 * case we can only save the write if the buffer is completely
1871 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001872 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001873 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001874 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1875 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001876 (s->compressed &&
1877 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001878 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001879 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1880 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001881 if (ret < 0) {
1882 return ret;
1883 }
1884 break;
1885 }
1886 /* fall-through */
1887
1888 case BLK_ZERO:
1889 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001890 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001891 break;
1892 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001893 ret = blk_co_pwrite_zeroes(s->target,
1894 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001895 n << BDRV_SECTOR_BITS,
1896 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001897 if (ret < 0) {
1898 return ret;
1899 }
1900 break;
1901 }
1902
1903 sector_num += n;
1904 nb_sectors -= n;
1905 buf += n * BDRV_SECTOR_SIZE;
1906 }
1907
1908 return 0;
1909}
1910
Fam Zhengee5306d2018-06-01 17:26:48 +08001911static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1912 int nb_sectors)
1913{
1914 int n, ret;
1915
1916 while (nb_sectors > 0) {
1917 BlockBackend *blk;
1918 int src_cur;
1919 int64_t bs_sectors, src_cur_offset;
1920 int64_t offset;
1921
1922 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1923 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1924 blk = s->src[src_cur];
1925 bs_sectors = s->src_sectors[src_cur];
1926
1927 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1928
1929 ret = blk_co_copy_range(blk, offset, s->target,
1930 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001931 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001932 if (ret < 0) {
1933 return ret;
1934 }
1935
1936 sector_num += n;
1937 nb_sectors -= n;
1938 }
1939 return 0;
1940}
1941
Peter Lieven2d9187b2017-02-28 13:40:07 +01001942static void coroutine_fn convert_co_do_copy(void *opaque)
1943{
1944 ImgConvertState *s = opaque;
1945 uint8_t *buf = NULL;
1946 int ret, i;
1947 int index = -1;
1948
1949 for (i = 0; i < s->num_coroutines; i++) {
1950 if (s->co[i] == qemu_coroutine_self()) {
1951 index = i;
1952 break;
1953 }
1954 }
1955 assert(index >= 0);
1956
1957 s->running_coroutines++;
1958 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1959
1960 while (1) {
1961 int n;
1962 int64_t sector_num;
1963 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001964 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001965
1966 qemu_co_mutex_lock(&s->lock);
1967 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1968 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001969 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001970 }
1971 n = convert_iteration_sectors(s, s->sector_num);
1972 if (n < 0) {
1973 qemu_co_mutex_unlock(&s->lock);
1974 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001975 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001976 }
1977 /* save current sector and allocation status to local variables */
1978 sector_num = s->sector_num;
1979 status = s->status;
1980 if (!s->min_sparse && s->status == BLK_ZERO) {
1981 n = MIN(n, s->buf_sectors);
1982 }
1983 /* increment global sector counter so that other coroutines can
1984 * already continue reading beyond this request */
1985 s->sector_num += n;
1986 qemu_co_mutex_unlock(&s->lock);
1987
1988 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1989 s->allocated_done += n;
1990 qemu_progress_print(100.0 * s->allocated_done /
1991 s->allocated_sectors, 0);
1992 }
1993
Fam Zhengee5306d2018-06-01 17:26:48 +08001994retry:
1995 copy_range = s->copy_range && s->status == BLK_DATA;
1996 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001997 ret = convert_co_read(s, sector_num, n, buf);
1998 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05001999 error_report("error while reading at byte %lld: %s",
2000 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002001 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002002 }
2003 } else if (!s->min_sparse && status == BLK_ZERO) {
2004 status = BLK_DATA;
2005 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2006 }
2007
2008 if (s->wr_in_order) {
2009 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002010 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002011 s->wait_sector_num[index] = sector_num;
2012 qemu_coroutine_yield();
2013 }
2014 s->wait_sector_num[index] = -1;
2015 }
2016
Anton Nefedovb91127e2017-04-26 11:33:15 +03002017 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002018 if (copy_range) {
2019 ret = convert_co_copy_range(s, sector_num, n);
2020 if (ret) {
2021 s->copy_range = false;
2022 goto retry;
2023 }
2024 } else {
2025 ret = convert_co_write(s, sector_num, n, buf, status);
2026 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002027 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002028 error_report("error while writing at byte %lld: %s",
2029 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002030 s->ret = ret;
2031 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002032 }
2033
2034 if (s->wr_in_order) {
2035 /* reenter the coroutine that might have waited
2036 * for this write to complete */
2037 s->wr_offs = sector_num + n;
2038 for (i = 0; i < s->num_coroutines; i++) {
2039 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2040 /*
2041 * A -> B -> A cannot occur because A has
2042 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2043 * B will never enter A during this time window.
2044 */
2045 qemu_coroutine_enter(s->co[i]);
2046 break;
2047 }
2048 }
2049 }
2050 }
2051
Peter Lieven2d9187b2017-02-28 13:40:07 +01002052 qemu_vfree(buf);
2053 s->co[index] = NULL;
2054 s->running_coroutines--;
2055 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2056 /* the convert job finished successfully */
2057 s->ret = 0;
2058 }
2059}
2060
Kevin Wolf690c7302015-03-19 13:33:32 +01002061static int convert_do_copy(ImgConvertState *s)
2062{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002063 int ret, i, n;
2064 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002065
2066 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002067 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2068 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002069 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002070 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002071
Kevin Wolf690c7302015-03-19 13:33:32 +01002072 /* Allocate buffer for copied data. For compressed images, only one cluster
2073 * can be copied at a time. */
2074 if (s->compressed) {
2075 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2076 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002077 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002078 }
2079 s->buf_sectors = s->cluster_sectors;
2080 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002081
Kevin Wolf690c7302015-03-19 13:33:32 +01002082 while (sector_num < s->total_sectors) {
2083 n = convert_iteration_sectors(s, sector_num);
2084 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002085 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002086 }
Max Reitzaad15de2016-03-24 23:33:57 +01002087 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2088 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002089 s->allocated_sectors += n;
2090 }
2091 sector_num += n;
2092 }
2093
2094 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002095 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002096 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002097
Peter Lieven2d9187b2017-02-28 13:40:07 +01002098 qemu_co_mutex_init(&s->lock);
2099 for (i = 0; i < s->num_coroutines; i++) {
2100 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2101 s->wait_sector_num[i] = -1;
2102 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002103 }
2104
Anton Nefedovb91127e2017-04-26 11:33:15 +03002105 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002106 main_loop_wait(false);
2107 }
2108
2109 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002110 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002111 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002112 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002113 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002114 }
2115 }
2116
Peter Lieven2d9187b2017-02-28 13:40:07 +01002117 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002118}
2119
Eric Blake74a43202021-07-09 10:39:50 -05002120/* Check that bitmaps can be copied, or output an error */
Eric Blake955171e2021-07-21 10:53:48 -05002121static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
Eric Blake74a43202021-07-09 10:39:50 -05002122{
2123 BdrvDirtyBitmap *bm;
2124
2125 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2126 error_report("Source lacks bitmap support");
2127 return -1;
2128 }
2129 FOR_EACH_DIRTY_BITMAP(src, bm) {
2130 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2131 continue;
2132 }
Eric Blake955171e2021-07-21 10:53:48 -05002133 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
Eric Blake74a43202021-07-09 10:39:50 -05002134 error_report("Cannot copy inconsistent bitmap '%s'",
2135 bdrv_dirty_bitmap_name(bm));
Eric Blake955171e2021-07-21 10:53:48 -05002136 error_printf("Try --skip-broken-bitmaps, or "
2137 "use 'qemu-img bitmap --remove' to delete it\n");
Eric Blake74a43202021-07-09 10:39:50 -05002138 return -1;
2139 }
2140 }
2141 return 0;
2142}
2143
Eric Blake955171e2021-07-21 10:53:48 -05002144static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2145 bool skip_broken)
Eric Blake15e39ad2020-05-21 14:21:36 -05002146{
2147 BdrvDirtyBitmap *bm;
2148 Error *err = NULL;
2149
2150 FOR_EACH_DIRTY_BITMAP(src, bm) {
2151 const char *name;
2152
2153 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2154 continue;
2155 }
2156 name = bdrv_dirty_bitmap_name(bm);
Eric Blake955171e2021-07-21 10:53:48 -05002157 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2158 warn_report("Skipping inconsistent bitmap '%s'", name);
2159 continue;
2160 }
Eric Blake15e39ad2020-05-21 14:21:36 -05002161 qmp_block_dirty_bitmap_add(dst->node_name, name,
2162 true, bdrv_dirty_bitmap_granularity(bm),
2163 true, true,
2164 true, !bdrv_dirty_bitmap_enabled(bm),
2165 &err);
2166 if (err) {
2167 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2168 return -1;
2169 }
2170
2171 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2172 &err);
2173 if (err) {
2174 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
Eric Blake74a43202021-07-09 10:39:50 -05002175 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
Eric Blake15e39ad2020-05-21 14:21:36 -05002176 return -1;
2177 }
2178 }
2179
2180 return 0;
2181}
2182
Peter Lieven6360ab22018-07-13 09:15:39 +02002183#define MAX_BUF_SECTORS 32768
2184
Zhengui0c8c4892020-10-20 14:47:44 +00002185static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2186{
2187 ThrottleConfig cfg;
2188
2189 throttle_config_init(&cfg);
2190 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2191
2192 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2193 blk_set_io_limits(blk, &cfg);
2194}
2195
bellardea2384d2004-08-01 21:59:26 +00002196static int img_convert(int argc, char **argv)
2197{
Kevin Wolf0b8fb552021-04-22 18:43:44 +02002198 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002199 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002200 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
Eric Blake1899bf42021-09-13 08:17:35 -05002201 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2202 *backing_fmt = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002203 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002204 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002205 BlockDriverState *out_bs;
2206 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002207 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002208 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002209 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002210 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002211 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002212 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002213 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002214 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002215 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002216 bool bitmaps = false;
Eric Blake955171e2021-07-21 10:53:48 -05002217 bool skip_broken = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002218 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002219
Peter Lieven9fd77f92017-04-21 11:11:55 +02002220 ImgConvertState s = (ImgConvertState) {
2221 /* Need at least 4k of zeros for sparse detection */
2222 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002223 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002224 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2225 .wr_in_order = true,
2226 .num_coroutines = 8,
2227 };
2228
bellardea2384d2004-08-01 21:59:26 +00002229 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002230 static const struct option long_options[] = {
2231 {"help", no_argument, 0, 'h'},
2232 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002233 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002234 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002235 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002236 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002237 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002238 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Eric Blake955171e2021-07-21 10:53:48 -05002239 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002240 {0, 0, 0, 0}
2241 };
Eric Blake1899bf42021-09-13 08:17:35 -05002242 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002243 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002244 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002245 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002246 }
bellardea2384d2004-08-01 21:59:26 +00002247 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002248 case ':':
2249 missing_argument(argv[optind - 1]);
2250 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002251 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002252 unrecognized_option(argv[optind - 1]);
2253 break;
bellardea2384d2004-08-01 21:59:26 +00002254 case 'h':
2255 help();
2256 break;
2257 case 'f':
2258 fmt = optarg;
2259 break;
2260 case 'O':
2261 out_fmt = optarg;
2262 break;
thsf58c7b32008-06-05 21:53:49 +00002263 case 'B':
2264 out_baseimg = optarg;
2265 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002266 case 'C':
2267 s.copy_range = true;
2268 break;
bellardea2384d2004-08-01 21:59:26 +00002269 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002270 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002271 break;
Eric Blake1899bf42021-09-13 08:17:35 -05002272 case 'F':
2273 backing_fmt = optarg;
2274 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002275 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002276 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002277 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002278 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002279 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002280 case 'l':
2281 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002282 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2283 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002284 if (!sn_opts) {
2285 error_report("Failed in parsing snapshot param '%s'",
2286 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002287 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002288 }
2289 } else {
2290 snapshot_name = optarg;
2291 }
2292 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002293 case 'S':
2294 {
2295 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002296
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002297 sval = cvtnum("buffer size for sparse output", optarg);
2298 if (sval < 0) {
2299 goto fail_getopt;
2300 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002301 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2302 error_report("Invalid buffer size for sparse output specified. "
2303 "Valid sizes are multiples of %llu up to %llu. Select "
2304 "0 to disable sparse detection (fully allocates output).",
2305 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002306 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002307 }
2308
Peter Lieven9fd77f92017-04-21 11:11:55 +02002309 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002310 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002311 break;
2312 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002313 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002314 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002315 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002316 case 't':
2317 cache = optarg;
2318 break;
Max Reitz40055952014-07-22 22:58:42 +02002319 case 'T':
2320 src_cache = optarg;
2321 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002322 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002323 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002324 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002325 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002326 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002327 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002328 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002329 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2330 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002331 error_report("Invalid number of coroutines. Allowed number of"
2332 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002333 goto fail_getopt;
2334 }
2335 break;
2336 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002337 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002338 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002339 case 'U':
2340 force_share = true;
2341 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002342 case 'r':
2343 rate_limit = cvtnum("rate limit", optarg);
2344 if (rate_limit < 0) {
2345 goto fail_getopt;
2346 }
2347 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002348 case OPTION_OBJECT:
2349 user_creatable_process_cmdline(optarg);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002350 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002351 case OPTION_IMAGE_OPTS:
2352 image_opts = true;
2353 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002354 case OPTION_SALVAGE:
2355 s.salvage = true;
2356 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002357 case OPTION_TARGET_IMAGE_OPTS:
2358 tgt_image_opts = true;
2359 break;
David Edmondson168468f2020-02-05 11:02:48 +00002360 case OPTION_TARGET_IS_ZERO:
2361 /*
2362 * The user asserting that the target is blank has the
2363 * same effect as the target driver supporting zero
2364 * initialisation.
2365 */
2366 s.has_zero_init = true;
2367 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002368 case OPTION_BITMAPS:
2369 bitmaps = true;
2370 break;
Eric Blake955171e2021-07-21 10:53:48 -05002371 case OPTION_SKIP_BROKEN:
2372 skip_broken = true;
2373 break;
bellardea2384d2004-08-01 21:59:26 +00002374 }
2375 }
ths3b46e622007-09-17 08:09:54 +00002376
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002377 if (!out_fmt && !tgt_image_opts) {
2378 out_fmt = "raw";
2379 }
2380
Eric Blake955171e2021-07-21 10:53:48 -05002381 if (skip_broken && !bitmaps) {
2382 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2383 goto fail_getopt;
2384 }
2385
Fam Zhenge11ce122018-07-27 11:34:01 +08002386 if (s.compressed && s.copy_range) {
2387 error_report("Cannot enable copy offloading when -c is used");
2388 goto fail_getopt;
2389 }
2390
2391 if (explict_min_sparse && s.copy_range) {
2392 error_report("Cannot enable copy offloading when -S is used");
2393 goto fail_getopt;
2394 }
2395
Max Reitz8eaac022019-05-07 22:35:03 +02002396 if (s.copy_range && s.salvage) {
2397 error_report("Cannot use copy offloading in salvaging mode");
2398 goto fail_getopt;
2399 }
2400
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002401 if (tgt_image_opts && !skip_create) {
2402 error_report("--target-image-opts requires use of -n flag");
2403 goto fail_getopt;
2404 }
2405
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002406 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002407 error_report("-o has no effect when skipping image creation");
2408 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002409 }
2410
David Edmondson168468f2020-02-05 11:02:48 +00002411 if (s.has_zero_init && !skip_create) {
2412 error_report("--target-is-zero requires use of -n flag");
2413 goto fail_getopt;
2414 }
2415
Peter Lieven9fd77f92017-04-21 11:11:55 +02002416 s.src_num = argc - optind - 1;
2417 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2418
2419 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002420 if (out_fmt) {
2421 ret = print_block_option_help(out_filename, out_fmt);
2422 goto fail_getopt;
2423 } else {
2424 error_report("Option help requires a format be specified");
2425 goto fail_getopt;
2426 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002427 }
2428
2429 if (s.src_num < 1) {
2430 error_report("Must specify image file name");
2431 goto fail_getopt;
2432 }
2433
Peter Lieven9fd77f92017-04-21 11:11:55 +02002434 /* ret is still -EINVAL until here */
2435 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2436 if (ret < 0) {
2437 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002438 goto fail_getopt;
2439 }
2440
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002441 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002442 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002443 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002444 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002445 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002446 qemu_progress_print(0, 100);
2447
Peter Lieven9fd77f92017-04-21 11:11:55 +02002448 s.src = g_new0(BlockBackend *, s.src_num);
2449 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002450 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002451
Peter Lieven9fd77f92017-04-21 11:11:55 +02002452 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002453 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002455 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002456 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002457 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002458 ret = -1;
2459 goto out;
2460 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002461 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2462 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002463 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002464 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002465 ret = -1;
2466 goto out;
2467 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002468 src_bs = blk_bs(s.src[bs_i]);
2469 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2470 BDRV_SECTOR_SIZE);
2471 if (!bdrv_get_info(src_bs, &bdi)) {
2472 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2473 bdi.cluster_size / BDRV_SECTOR_SIZE);
2474 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002475 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002476 }
bellardea2384d2004-08-01 21:59:26 +00002477
Wenchao Xiaef806542013-12-04 17:10:57 +08002478 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002479 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002480 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2481 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2482 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002483 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002484 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002485 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002486 ret = -1;
2487 goto out;
2488 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002489
Peter Lieven9fd77f92017-04-21 11:11:55 +02002490 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2491 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002492 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002493 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002494 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002495 ret = -1;
2496 goto out;
edison51ef6722010-09-21 19:58:41 -07002497 }
2498
Max Reitz2e024cd2015-02-11 09:58:46 -05002499 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002500 /* Find driver and parse its options */
2501 drv = bdrv_find_format(out_fmt);
2502 if (!drv) {
2503 error_report("Unknown file format '%s'", out_fmt);
2504 ret = -1;
2505 goto out;
2506 }
2507
2508 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2509 if (!proto_drv) {
2510 error_report_err(local_err);
2511 ret = -1;
2512 goto out;
2513 }
2514
Max Reitz2e024cd2015-02-11 09:58:46 -05002515 if (!drv->create_opts) {
2516 error_report("Format driver '%s' does not support image creation",
2517 drv->format_name);
2518 ret = -1;
2519 goto out;
2520 }
Max Reitzf75613c2014-12-02 18:32:46 +01002521
Max Reitz2e024cd2015-02-11 09:58:46 -05002522 if (!proto_drv->create_opts) {
2523 error_report("Protocol driver '%s' does not support image creation",
2524 proto_drv->format_name);
2525 ret = -1;
2526 goto out;
2527 }
Max Reitzf75613c2014-12-02 18:32:46 +01002528
Max Reitz2e024cd2015-02-11 09:58:46 -05002529 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2530 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002531
Max Reitz2e024cd2015-02-11 09:58:46 -05002532 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002533 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002534 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002535 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002536 ret = -1;
2537 goto out;
2538 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002539 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002540
Yi Lic075c422020-08-19 09:36:07 +08002541 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2542 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Eric Blake1899bf42021-09-13 08:17:35 -05002543 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
Max Reitz2e024cd2015-02-11 09:58:46 -05002544 if (ret < 0) {
2545 goto out;
2546 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002547 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002548
Kevin Wolfa18953f2010-10-14 15:46:04 +02002549 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002550 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002551 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002552 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002553 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002554 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002555
David Edmondson168468f2020-02-05 11:02:48 +00002556 if (s.has_zero_init && s.target_has_backing) {
2557 error_report("Cannot use --target-is-zero when the destination "
2558 "image has a backing file");
2559 goto out;
2560 }
2561
Max Reitz48758a82017-04-26 15:46:48 +02002562 if (s.src_num > 1 && out_baseimg) {
2563 error_report("Having a backing file for the target makes no sense when "
2564 "concatenating multiple input images");
2565 ret = -1;
2566 goto out;
2567 }
2568
Eric Blaked9f059a2020-07-06 15:39:54 -05002569 if (out_baseimg_param) {
2570 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
Eric Blake497a30d2021-05-03 14:36:00 -07002571 error_report("Use of backing file requires explicit "
2572 "backing format");
2573 ret = -1;
2574 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05002575 }
2576 }
2577
Kevin Wolfefa84d42009-05-18 16:42:12 +02002578 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002579 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002580 bool encryption =
2581 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002582 const char *encryptfmt =
2583 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002584 const char *preallocation =
2585 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002586
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002587 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002588 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002589 ret = -1;
2590 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002591 }
2592
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002593 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002594 error_report("Compression and encryption not supported at "
2595 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002596 ret = -1;
2597 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002598 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002599
Chunyan Liu83d05212014-06-05 17:20:51 +08002600 if (preallocation
2601 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002602 {
2603 error_report("Compression and preallocation not supported at "
2604 "the same time");
2605 ret = -1;
2606 goto out;
2607 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002608 }
2609
Eric Blake15e39ad2020-05-21 14:21:36 -05002610 /* Determine if bitmaps need copying */
2611 if (bitmaps) {
2612 if (s.src_num > 1) {
2613 error_report("Copying bitmaps only possible with single source");
2614 ret = -1;
2615 goto out;
2616 }
Eric Blake955171e2021-07-21 10:53:48 -05002617 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
Eric Blake74a43202021-07-09 10:39:50 -05002618 if (ret < 0) {
Eric Blake15e39ad2020-05-21 14:21:36 -05002619 goto out;
2620 }
2621 }
2622
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002623 /*
2624 * The later open call will need any decryption secrets, and
2625 * bdrv_create() will purge "opts", so extract them now before
2626 * they are lost.
2627 */
2628 if (!skip_create) {
2629 open_opts = qdict_new();
2630 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002631
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002632 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002633 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002634 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002635 error_reportf_err(local_err, "%s: error while converting %s: ",
2636 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002637 goto out;
bellardea2384d2004-08-01 21:59:26 +00002638 }
2639 }
ths3b46e622007-09-17 08:09:54 +00002640
Max Reitz4d7c4872019-07-24 19:12:29 +02002641 s.target_is_new = !skip_create;
2642
Peter Lieven9fd77f92017-04-21 11:11:55 +02002643 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002644 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002645 if (ret < 0) {
2646 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002647 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002648 }
2649
Hanna Reitza1c62432021-08-19 12:12:00 +02002650 if (flags & BDRV_O_NOCACHE) {
2651 /*
2652 * If we open the target with O_DIRECT, it may be necessary to
2653 * extend its size to align to the physical sector size.
2654 */
2655 flags |= BDRV_O_RESIZE;
2656 }
2657
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002658 if (skip_create) {
2659 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002660 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002661 } else {
2662 /* TODO ultimately we should allow --target-image-opts
2663 * to be used even when -n is not given.
2664 * That has to wait for bdrv_create to be improved
2665 * to allow filenames in option syntax
2666 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002667 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002668 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002669 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002670 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002671 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002672 ret = -1;
2673 goto out;
2674 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002675 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002676
Eric Blake15e39ad2020-05-21 14:21:36 -05002677 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2678 error_report("Format driver '%s' does not support bitmaps",
2679 out_bs->drv->format_name);
2680 ret = -1;
2681 goto out;
2682 }
2683
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002684 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002685 error_report("Compression not supported for this file format");
2686 ret = -1;
2687 goto out;
2688 }
2689
Eric Blake5def6b82016-06-23 16:37:19 -06002690 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002691 * or discard_alignment of the out_bs is greater. Limit to
2692 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2693 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002694 MAX(s.buf_sectors,
2695 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2696 out_bs->bl.pdiscard_alignment >>
2697 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002698
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002699 /* try to align the write requests to the destination to avoid unnecessary
2700 * RMW cycles. */
2701 s.alignment = MAX(pow2floor(s.min_sparse),
2702 DIV_ROUND_UP(out_bs->bl.request_alignment,
2703 BDRV_SECTOR_SIZE));
2704 assert(is_power_of_2(s.alignment));
2705
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002706 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002707 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002708 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002709 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002710 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002711 ret = -1;
2712 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002713 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002714 error_report("output file is smaller than input file");
2715 ret = -1;
2716 goto out;
2717 }
2718 }
2719
Max Reitzc69291e2020-01-21 16:59:14 +01002720 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002721 /* Errors are treated as "backing length unknown" (which means
2722 * s.target_backing_sectors has to be negative, which it will
2723 * be automatically). The backing file length is used only
2724 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002725 s.target_backing_sectors =
2726 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002727 } else {
2728 s.target_backing_sectors = -1;
2729 }
2730
Peter Lieven24f833c2013-11-27 11:07:07 +01002731 ret = bdrv_get_info(out_bs, &bdi);
2732 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002733 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002734 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002735 goto out;
2736 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002737 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002738 s.compressed = s.compressed || bdi.needs_compressed_writes;
2739 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002740 }
2741
Zhengui0c8c4892020-10-20 14:47:44 +00002742 if (rate_limit) {
2743 set_rate_limit(s.target, rate_limit);
2744 }
2745
Peter Lieven9fd77f92017-04-21 11:11:55 +02002746 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002747
2748 /* Now copy the bitmaps */
2749 if (bitmaps && ret == 0) {
Eric Blake955171e2021-07-21 10:53:48 -05002750 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
Eric Blake15e39ad2020-05-21 14:21:36 -05002751 }
2752
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002753out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002754 if (!ret) {
2755 qemu_progress_print(100, 0);
2756 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002757 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002758 qemu_opts_del(opts);
2759 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002760 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002761 blk_unref(s.target);
2762 if (s.src) {
2763 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2764 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002765 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002766 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002767 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002768 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002769 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002770fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002771 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002772 g_free(options);
2773
Peter Lieven9fd77f92017-04-21 11:11:55 +02002774 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002775}
2776
bellard57d1a2b2004-08-03 21:15:11 +00002777
bellardfaea38e2006-08-05 21:31:00 +00002778static void dump_snapshots(BlockDriverState *bs)
2779{
2780 QEMUSnapshotInfo *sn_tab, *sn;
2781 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002782
2783 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2784 if (nb_sns <= 0)
2785 return;
2786 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002787 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002788 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002789 for(i = 0; i < nb_sns; i++) {
2790 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002791 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002792 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002793 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002794 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002795}
2796
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002797static void dump_json_image_info_list(ImageInfoList *list)
2798{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002799 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002800 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002801 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002802
2803 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2804 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002805 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002806 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002807 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002808 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002809 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002810 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002811}
2812
Benoît Canetc054b3f2012-09-05 13:09:02 +02002813static void dump_json_image_info(ImageInfo *info)
2814{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002815 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002816 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002817 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002818
2819 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2820 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002821 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002822 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002823 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002824 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002825 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002826 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002827}
2828
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002829static void dump_human_image_info_list(ImageInfoList *list)
2830{
2831 ImageInfoList *elem;
2832 bool delim = false;
2833
2834 for (elem = list; elem; elem = elem->next) {
2835 if (delim) {
2836 printf("\n");
2837 }
2838 delim = true;
2839
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002840 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002841 }
2842}
2843
2844static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2845{
2846 return strcmp(a, b) == 0;
2847}
2848
2849/**
2850 * Open an image file chain and return an ImageInfoList
2851 *
2852 * @filename: topmost image filename
2853 * @fmt: topmost image format (may be NULL to autodetect)
2854 * @chain: true - enumerate entire backing file chain
2855 * false - only topmost image file
2856 *
2857 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2858 * image file. If there was an error a message will have been printed to
2859 * stderr.
2860 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002861static ImageInfoList *collect_image_info_list(bool image_opts,
2862 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002863 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002864 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002865{
2866 ImageInfoList *head = NULL;
Eric Blakec3033fd2021-01-13 16:10:12 -06002867 ImageInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002868 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002869 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002870
2871 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2872
2873 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002874 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002875 BlockDriverState *bs;
2876 ImageInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002877
2878 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2879 error_report("Backing file '%s' creates an infinite loop.",
2880 filename);
2881 goto err;
2882 }
2883 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2884
Max Reitzefaa7c42016-03-16 19:54:38 +01002885 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002886 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2887 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002888 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002889 goto err;
2890 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002891 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002892
Wenchao Xia43526ec2013-06-06 12:27:58 +08002893 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002894 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002895 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002896 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002897 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002898 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002899
Eric Blakec3033fd2021-01-13 16:10:12 -06002900 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002901
Markus Armbruster26f54e92014-10-07 13:59:04 +02002902 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002903
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002904 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002905 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002906 image_opts = false;
2907
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002908 if (chain) {
2909 if (info->has_full_backing_filename) {
2910 filename = info->full_backing_filename;
2911 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002912 error_report("Could not determine absolute backing filename,"
2913 " but backing filename '%s' present",
2914 info->backing_filename);
2915 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002916 }
2917 if (info->has_backing_filename_format) {
2918 fmt = info->backing_filename_format;
2919 }
2920 }
2921 }
2922 g_hash_table_destroy(filenames);
2923 return head;
2924
2925err:
2926 qapi_free_ImageInfoList(head);
2927 g_hash_table_destroy(filenames);
2928 return NULL;
2929}
2930
Benoît Canetc054b3f2012-09-05 13:09:02 +02002931static int img_info(int argc, char **argv)
2932{
2933 int c;
2934 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002935 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002936 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002937 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002938 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002939 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002940
bellardea2384d2004-08-01 21:59:26 +00002941 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002942 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002943 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002944 int option_index = 0;
2945 static const struct option long_options[] = {
2946 {"help", no_argument, 0, 'h'},
2947 {"format", required_argument, 0, 'f'},
2948 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002949 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002950 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002951 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002952 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002953 {0, 0, 0, 0}
2954 };
Fam Zheng335e9932017-05-03 00:35:39 +08002955 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002956 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002957 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002958 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002959 }
bellardea2384d2004-08-01 21:59:26 +00002960 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002961 case ':':
2962 missing_argument(argv[optind - 1]);
2963 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002964 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002965 unrecognized_option(argv[optind - 1]);
2966 break;
bellardea2384d2004-08-01 21:59:26 +00002967 case 'h':
2968 help();
2969 break;
2970 case 'f':
2971 fmt = optarg;
2972 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002973 case 'U':
2974 force_share = true;
2975 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002976 case OPTION_OUTPUT:
2977 output = optarg;
2978 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002979 case OPTION_BACKING_CHAIN:
2980 chain = true;
2981 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002982 case OPTION_OBJECT:
2983 user_creatable_process_cmdline(optarg);
2984 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002985 case OPTION_IMAGE_OPTS:
2986 image_opts = true;
2987 break;
bellardea2384d2004-08-01 21:59:26 +00002988 }
2989 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002990 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002991 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002992 }
bellardea2384d2004-08-01 21:59:26 +00002993 filename = argv[optind++];
2994
Benoît Canetc054b3f2012-09-05 13:09:02 +02002995 if (output && !strcmp(output, "json")) {
2996 output_format = OFORMAT_JSON;
2997 } else if (output && !strcmp(output, "human")) {
2998 output_format = OFORMAT_HUMAN;
2999 } else if (output) {
3000 error_report("--output must be used with human or json as argument.");
3001 return 1;
3002 }
3003
Fam Zheng335e9932017-05-03 00:35:39 +08003004 list = collect_image_info_list(image_opts, filename, fmt, chain,
3005 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003006 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003007 return 1;
3008 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003009
Benoît Canetc054b3f2012-09-05 13:09:02 +02003010 switch (output_format) {
3011 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003012 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003013 break;
3014 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003015 if (chain) {
3016 dump_json_image_info_list(list);
3017 } else {
3018 dump_json_image_info(list->value);
3019 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003020 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003021 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003022
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003023 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003024 return 0;
3025}
3026
Eric Blake30065d12019-03-26 13:40:43 -05003027static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3028 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003029{
3030 switch (output_format) {
3031 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003032 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003033 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003034 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003035 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003036 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003037 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003038 e->start, e->length,
3039 e->has_offset ? e->offset : 0,
3040 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003041 }
3042 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3043 * Modify the flags here to allow more coalescing.
3044 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003045 if (next && (!next->data || next->zero)) {
3046 next->data = false;
3047 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003048 }
3049 break;
3050 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003051 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Eric Blake8417e132021-07-01 14:06:55 -05003052 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3053 " \"data\": %s", e->start, e->length, e->depth,
3054 e->present ? "true" : "false",
Fam Zheng16b0d552016-01-26 11:59:02 +08003055 e->zero ? "true" : "false",
3056 e->data ? "true" : "false");
3057 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003058 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003059 }
3060 putchar('}');
3061
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003062 if (next) {
3063 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003064 }
3065 break;
3066 }
Eric Blake30065d12019-03-26 13:40:43 -05003067 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003068}
3069
Eric Blake5e344dd2017-10-11 22:47:02 -05003070static int get_block_status(BlockDriverState *bs, int64_t offset,
3071 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003072{
Eric Blake237d78f2017-10-11 22:47:03 -05003073 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003074 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003075 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003076 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003077 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003078 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003079
3080 /* As an optimization, we could cache the current range of unallocated
3081 * clusters in each file of the chain, and avoid querying the same
3082 * range repeatedly.
3083 */
3084
3085 depth = 0;
3086 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003087 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003088 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003089 if (ret < 0) {
3090 return ret;
3091 }
Eric Blake237d78f2017-10-11 22:47:03 -05003092 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003093 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3094 break;
3095 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003096 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003097 if (bs == NULL) {
3098 ret = 0;
3099 break;
3100 }
3101
3102 depth++;
3103 }
3104
John Snow28756452016-02-05 13:12:33 -05003105 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3106
Max Reitzf30c66b2019-02-01 20:29:05 +01003107 if (file && has_offset) {
3108 bdrv_refresh_filename(file);
3109 filename = file->filename;
3110 }
3111
John Snow28756452016-02-05 13:12:33 -05003112 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003113 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003114 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003115 .data = !!(ret & BDRV_BLOCK_DATA),
3116 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003117 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003118 .has_offset = has_offset,
3119 .depth = depth,
Eric Blake8417e132021-07-01 14:06:55 -05003120 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
Max Reitzf30c66b2019-02-01 20:29:05 +01003121 .has_filename = filename,
3122 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003123 };
3124
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003125 return 0;
3126}
3127
Fam Zheng16b0d552016-01-26 11:59:02 +08003128static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3129{
3130 if (curr->length == 0) {
3131 return false;
3132 }
3133 if (curr->zero != next->zero ||
3134 curr->data != next->data ||
3135 curr->depth != next->depth ||
Eric Blake8417e132021-07-01 14:06:55 -05003136 curr->present != next->present ||
Fam Zheng16b0d552016-01-26 11:59:02 +08003137 curr->has_filename != next->has_filename ||
3138 curr->has_offset != next->has_offset) {
3139 return false;
3140 }
3141 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3142 return false;
3143 }
3144 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3145 return false;
3146 }
3147 return true;
3148}
3149
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003150static int img_map(int argc, char **argv)
3151{
3152 int c;
3153 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003154 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003155 BlockDriverState *bs;
3156 const char *filename, *fmt, *output;
3157 int64_t length;
3158 MapEntry curr = { .length = 0 }, next;
3159 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003160 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003161 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003162 int64_t start_offset = 0;
3163 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003164
3165 fmt = NULL;
3166 output = NULL;
3167 for (;;) {
3168 int option_index = 0;
3169 static const struct option long_options[] = {
3170 {"help", no_argument, 0, 'h'},
3171 {"format", required_argument, 0, 'f'},
3172 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003173 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003174 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003175 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003176 {"start-offset", required_argument, 0, 's'},
3177 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003178 {0, 0, 0, 0}
3179 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003180 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003181 long_options, &option_index);
3182 if (c == -1) {
3183 break;
3184 }
3185 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003186 case ':':
3187 missing_argument(argv[optind - 1]);
3188 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003189 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003190 unrecognized_option(argv[optind - 1]);
3191 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003192 case 'h':
3193 help();
3194 break;
3195 case 'f':
3196 fmt = optarg;
3197 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003198 case 'U':
3199 force_share = true;
3200 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003201 case OPTION_OUTPUT:
3202 output = optarg;
3203 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003204 case 's':
3205 start_offset = cvtnum("start offset", optarg);
3206 if (start_offset < 0) {
3207 return 1;
3208 }
3209 break;
3210 case 'l':
3211 max_length = cvtnum("max length", optarg);
3212 if (max_length < 0) {
3213 return 1;
3214 }
3215 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003216 case OPTION_OBJECT:
3217 user_creatable_process_cmdline(optarg);
3218 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003219 case OPTION_IMAGE_OPTS:
3220 image_opts = true;
3221 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003222 }
3223 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003224 if (optind != argc - 1) {
3225 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003226 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003227 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003228
3229 if (output && !strcmp(output, "json")) {
3230 output_format = OFORMAT_JSON;
3231 } else if (output && !strcmp(output, "human")) {
3232 output_format = OFORMAT_HUMAN;
3233 } else if (output) {
3234 error_report("--output must be used with human or json as argument.");
3235 return 1;
3236 }
3237
Fam Zheng335e9932017-05-03 00:35:39 +08003238 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003239 if (!blk) {
3240 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003241 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003242 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003243
3244 if (output_format == OFORMAT_HUMAN) {
3245 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003246 } else if (output_format == OFORMAT_JSON) {
3247 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003248 }
3249
Max Reitzf1d3cd72015-02-05 13:58:18 -05003250 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003251 if (length < 0) {
3252 error_report("Failed to get size for '%s'", filename);
3253 return 1;
3254 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003255 if (max_length != -1) {
3256 length = MIN(start_offset + max_length, length);
3257 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003258
Eyal Moscovicic0469492020-05-13 16:36:29 +03003259 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003260 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003261 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003262 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003263
Eric Blake5e344dd2017-10-11 22:47:02 -05003264 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003265 if (ret < 0) {
3266 error_report("Could not read file metadata: %s", strerror(-ret));
3267 goto out;
3268 }
3269
Fam Zheng16b0d552016-01-26 11:59:02 +08003270 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003271 curr.length += next.length;
3272 continue;
3273 }
3274
3275 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003276 ret = dump_map_entry(output_format, &curr, &next);
3277 if (ret < 0) {
3278 goto out;
3279 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003280 }
3281 curr = next;
3282 }
3283
Eric Blake30065d12019-03-26 13:40:43 -05003284 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003285 if (output_format == OFORMAT_JSON) {
3286 puts("]");
3287 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003288
3289out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003290 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003291 return ret < 0;
3292}
3293
aliguorif7b4a942009-01-07 17:40:15 +00003294#define SNAPSHOT_LIST 1
3295#define SNAPSHOT_CREATE 2
3296#define SNAPSHOT_APPLY 3
3297#define SNAPSHOT_DELETE 4
3298
Stuart Brady153859b2009-06-07 00:42:17 +01003299static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003300{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003301 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003302 BlockDriverState *bs;
3303 QEMUSnapshotInfo sn;
3304 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003305 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003306 int action = 0;
3307 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003308 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003309 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003310 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003311 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003312
Kevin Wolfce099542016-03-15 13:01:04 +01003313 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003314 /* Parse commandline parameters */
3315 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003316 static const struct option long_options[] = {
3317 {"help", no_argument, 0, 'h'},
3318 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003319 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003320 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003321 {0, 0, 0, 0}
3322 };
Fam Zheng335e9932017-05-03 00:35:39 +08003323 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003324 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003325 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003326 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003327 }
aliguorif7b4a942009-01-07 17:40:15 +00003328 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003329 case ':':
3330 missing_argument(argv[optind - 1]);
3331 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003332 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003333 unrecognized_option(argv[optind - 1]);
3334 break;
aliguorif7b4a942009-01-07 17:40:15 +00003335 case 'h':
3336 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003337 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003338 case 'l':
3339 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003340 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003341 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003342 }
3343 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003344 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003345 break;
3346 case 'a':
3347 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003348 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003349 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003350 }
3351 action = SNAPSHOT_APPLY;
3352 snapshot_name = optarg;
3353 break;
3354 case 'c':
3355 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003356 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003357 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003358 }
3359 action = SNAPSHOT_CREATE;
3360 snapshot_name = optarg;
3361 break;
3362 case 'd':
3363 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003364 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003365 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003366 }
3367 action = SNAPSHOT_DELETE;
3368 snapshot_name = optarg;
3369 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003370 case 'q':
3371 quiet = true;
3372 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003373 case 'U':
3374 force_share = true;
3375 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003376 case OPTION_OBJECT:
3377 user_creatable_process_cmdline(optarg);
3378 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003379 case OPTION_IMAGE_OPTS:
3380 image_opts = true;
3381 break;
aliguorif7b4a942009-01-07 17:40:15 +00003382 }
3383 }
3384
Kevin Wolffc11eb22013-08-05 10:53:04 +02003385 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003386 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003387 }
aliguorif7b4a942009-01-07 17:40:15 +00003388 filename = argv[optind++];
3389
3390 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003391 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3392 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003393 if (!blk) {
3394 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003395 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003396 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003397
3398 /* Perform the requested action */
3399 switch(action) {
3400 case SNAPSHOT_LIST:
3401 dump_snapshots(bs);
3402 break;
3403
3404 case SNAPSHOT_CREATE:
3405 memset(&sn, 0, sizeof(sn));
3406 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3407
3408 qemu_gettimeofday(&tv);
3409 sn.date_sec = tv.tv_sec;
3410 sn.date_nsec = tv.tv_usec * 1000;
3411
3412 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003413 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003414 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003415 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003416 }
aliguorif7b4a942009-01-07 17:40:15 +00003417 break;
3418
3419 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003420 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003421 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003422 error_reportf_err(err, "Could not apply snapshot '%s': ",
3423 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003424 }
aliguorif7b4a942009-01-07 17:40:15 +00003425 break;
3426
3427 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003428 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3429 if (ret < 0) {
3430 error_report("Could not delete snapshot '%s': snapshot not "
3431 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003432 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003433 } else {
3434 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3435 if (ret < 0) {
3436 error_reportf_err(err, "Could not delete snapshot '%s': ",
3437 snapshot_name);
3438 ret = 1;
3439 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003440 }
aliguorif7b4a942009-01-07 17:40:15 +00003441 break;
3442 }
3443
3444 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003445 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003446 if (ret) {
3447 return 1;
3448 }
Stuart Brady153859b2009-06-07 00:42:17 +01003449 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003450}
3451
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003452static int img_rebase(int argc, char **argv)
3453{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003454 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003455 uint8_t *buf_old = NULL;
3456 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003457 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003458 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003459 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003460 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3461 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003462 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003463 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003464 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003465 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003466 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003467 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003468 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003469
3470 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003471 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003472 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003473 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003474 out_baseimg = NULL;
3475 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003476 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003477 static const struct option long_options[] = {
3478 {"help", no_argument, 0, 'h'},
3479 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003480 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003481 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003482 {0, 0, 0, 0}
3483 };
Fam Zheng335e9932017-05-03 00:35:39 +08003484 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003485 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003486 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003487 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003488 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003489 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003490 case ':':
3491 missing_argument(argv[optind - 1]);
3492 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003493 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003494 unrecognized_option(argv[optind - 1]);
3495 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496 case 'h':
3497 help();
3498 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003499 case 'f':
3500 fmt = optarg;
3501 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003502 case 'F':
3503 out_basefmt = optarg;
3504 break;
3505 case 'b':
3506 out_baseimg = optarg;
3507 break;
3508 case 'u':
3509 unsafe = 1;
3510 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003511 case 'p':
3512 progress = 1;
3513 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003514 case 't':
3515 cache = optarg;
3516 break;
Max Reitz40055952014-07-22 22:58:42 +02003517 case 'T':
3518 src_cache = optarg;
3519 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003520 case 'q':
3521 quiet = true;
3522 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003523 case OPTION_OBJECT:
3524 user_creatable_process_cmdline(optarg);
3525 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003526 case OPTION_IMAGE_OPTS:
3527 image_opts = true;
3528 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003529 case 'U':
3530 force_share = true;
3531 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003532 }
3533 }
3534
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003535 if (quiet) {
3536 progress = 0;
3537 }
3538
Fam Zhengac1307a2014-04-22 13:36:11 +08003539 if (optind != argc - 1) {
3540 error_exit("Expecting one image file name");
3541 }
3542 if (!unsafe && !out_baseimg) {
3543 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003544 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003545 filename = argv[optind++];
3546
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003547 qemu_progress_init(progress, 2.0);
3548 qemu_progress_print(0, 100);
3549
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003550 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003551 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003552 if (ret < 0) {
3553 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003554 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003555 }
3556
Kevin Wolfce099542016-03-15 13:01:04 +01003557 src_flags = 0;
3558 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003559 if (ret < 0) {
3560 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003561 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003562 }
3563
Kevin Wolfce099542016-03-15 13:01:04 +01003564 /* The source files are opened read-only, don't care about WCE */
3565 assert((src_flags & BDRV_O_RDWR) == 0);
3566 (void) src_writethrough;
3567
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003568 /*
3569 * Open the images.
3570 *
3571 * Ignore the old backing file for unsafe rebase in case we want to correct
3572 * the reference to a renamed or moved backing file.
3573 */
Fam Zheng335e9932017-05-03 00:35:39 +08003574 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3575 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003576 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003577 ret = -1;
3578 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003579 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003580 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003581
Max Reitz4a2061e2019-06-12 19:00:30 +02003582 unfiltered_bs = bdrv_skip_filters(bs);
3583
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003584 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003585 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003586 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003587 ret = -1;
3588 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003589 }
3590 }
3591
3592 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003593 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003594 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003595 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003596
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003597 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003598 blk_old_backing = blk_new(qemu_get_aio_context(),
3599 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003600 BLK_PERM_ALL);
3601 ret = blk_insert_bs(blk_old_backing, base_bs,
3602 &local_err);
3603 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003604 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003605 "Could not reuse old backing file '%s': ",
3606 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003607 goto out;
3608 }
3609 } else {
3610 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003611 }
Max Reitz644483d2015-02-05 13:58:17 -05003612
Alex Bligha6166732012-10-16 13:46:18 +01003613 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003614 const char *overlay_filename;
3615 char *out_real_path;
3616
Fam Zheng335e9932017-05-03 00:35:39 +08003617 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003618 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003619 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003620 }
3621 if (force_share) {
3622 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003623 }
3624
Max Reitzf30c66b2019-02-01 20:29:05 +01003625 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003626 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3627 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003628 out_real_path =
3629 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3630 out_baseimg,
3631 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003632 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003633 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003634 error_reportf_err(local_err,
3635 "Could not resolve backing filename: ");
3636 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003637 goto out;
3638 }
3639
Sam Eiderman863cc782019-05-23 19:33:36 +03003640 /*
3641 * Find out whether we rebase an image on top of a previous image
3642 * in its chain.
3643 */
3644 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003645 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003646 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003647 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003648
Kevin Wolfd861ab32019-04-25 14:25:10 +02003649 blk_new_backing = blk_new(qemu_get_aio_context(),
3650 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003651 BLK_PERM_ALL);
3652 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3653 &local_err);
3654 if (ret < 0) {
3655 error_reportf_err(local_err,
3656 "Could not reuse backing file '%s': ",
3657 out_baseimg);
3658 goto out;
3659 }
3660 } else {
3661 blk_new_backing = blk_new_open(out_real_path, NULL,
3662 options, src_flags, &local_err);
3663 g_free(out_real_path);
3664 if (!blk_new_backing) {
3665 error_reportf_err(local_err,
3666 "Could not open new backing file '%s': ",
3667 out_baseimg);
3668 ret = -1;
3669 goto out;
3670 }
Alex Bligha6166732012-10-16 13:46:18 +01003671 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003672 }
3673 }
3674
3675 /*
3676 * Check each unallocated cluster in the COW file. If it is unallocated,
3677 * accesses go to the backing file. We must therefore compare this cluster
3678 * in the old and new backing file, and if they differ we need to copy it
3679 * from the old backing file into the COW file.
3680 *
3681 * If qemu-img crashes during this step, no harm is done. The content of
3682 * the image is the same as the original one at any time.
3683 */
3684 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003685 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003686 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003687 int64_t new_backing_size = 0;
3688 uint64_t offset;
3689 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003690 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003691
Max Reitzf1d3cd72015-02-05 13:58:18 -05003692 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3693 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003694
Eric Blake41536282017-10-11 22:47:15 -05003695 size = blk_getlength(blk);
3696 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003697 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003698 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003699 ret = -1;
3700 goto out;
3701 }
Max Reitz35ddd932019-05-09 19:52:35 +02003702 if (blk_old_backing) {
3703 old_backing_size = blk_getlength(blk_old_backing);
3704 if (old_backing_size < 0) {
3705 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003706
Max Reitz35ddd932019-05-09 19:52:35 +02003707 bdrv_get_backing_filename(bs, backing_name,
3708 sizeof(backing_name));
3709 error_report("Could not get size of '%s': %s",
3710 backing_name, strerror(-old_backing_size));
3711 ret = -1;
3712 goto out;
3713 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003714 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003715 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003716 new_backing_size = blk_getlength(blk_new_backing);
3717 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003718 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003719 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003720 ret = -1;
3721 goto out;
3722 }
Alex Bligha6166732012-10-16 13:46:18 +01003723 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003724
Eric Blake41536282017-10-11 22:47:15 -05003725 if (size != 0) {
3726 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003727 }
3728
Eric Blake41536282017-10-11 22:47:15 -05003729 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003730 bool buf_old_is_zero = false;
3731
Eric Blake41536282017-10-11 22:47:15 -05003732 /* How many bytes can we handle with the next read? */
3733 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003734
3735 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003736 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003737 if (ret < 0) {
3738 error_report("error while reading image metadata: %s",
3739 strerror(-ret));
3740 goto out;
3741 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003742 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003743 continue;
3744 }
3745
Sam Eiderman863cc782019-05-23 19:33:36 +03003746 if (prefix_chain_bs) {
3747 /*
3748 * If cluster wasn't changed since prefix_chain, we don't need
3749 * to take action
3750 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003751 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3752 prefix_chain_bs, false,
3753 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003754 if (ret < 0) {
3755 error_report("error while reading image metadata: %s",
3756 strerror(-ret));
3757 goto out;
3758 }
3759 if (!ret) {
3760 continue;
3761 }
3762 }
3763
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003764 /*
3765 * Read old and new backing file and take into consideration that
3766 * backing files may be smaller than the COW image.
3767 */
Eric Blake41536282017-10-11 22:47:15 -05003768 if (offset >= old_backing_size) {
3769 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003770 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003771 } else {
Eric Blake41536282017-10-11 22:47:15 -05003772 if (offset + n > old_backing_size) {
3773 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003774 }
3775
Eric Blake41536282017-10-11 22:47:15 -05003776 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003777 if (ret < 0) {
3778 error_report("error while reading from old backing file");
3779 goto out;
3780 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003781 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003782
Eric Blake41536282017-10-11 22:47:15 -05003783 if (offset >= new_backing_size || !blk_new_backing) {
3784 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003785 } else {
Eric Blake41536282017-10-11 22:47:15 -05003786 if (offset + n > new_backing_size) {
3787 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003788 }
3789
Eric Blake41536282017-10-11 22:47:15 -05003790 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003791 if (ret < 0) {
3792 error_report("error while reading from new backing file");
3793 goto out;
3794 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003795 }
3796
3797 /* If they differ, we need to write to the COW file */
3798 uint64_t written = 0;
3799
Eric Blake41536282017-10-11 22:47:15 -05003800 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003801 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003802
Eric Blake41536282017-10-11 22:47:15 -05003803 if (compare_buffers(buf_old + written, buf_new + written,
3804 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003805 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003806 if (buf_old_is_zero) {
3807 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3808 } else {
3809 ret = blk_pwrite(blk, offset + written,
3810 buf_old + written, pnum, 0);
3811 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003812 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003813 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003814 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003815 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003816 }
3817 }
3818
3819 written += pnum;
3820 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003821 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003822 }
3823 }
3824
3825 /*
3826 * Change the backing file. All clusters that are different from the old
3827 * backing file are overwritten in the COW file now, so the visible content
3828 * doesn't change when we switch the backing file.
3829 */
Alex Bligha6166732012-10-16 13:46:18 +01003830 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003831 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3832 true);
Alex Bligha6166732012-10-16 13:46:18 +01003833 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003834 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003835 }
3836
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003837 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003838 error_report("Could not change the backing file to '%s': No "
3839 "space left in the file header", out_baseimg);
Eric Blakea7cd44b2021-07-08 10:52:28 -05003840 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3841 error_report("Could not change the backing file to '%s': backing "
3842 "format must be specified", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003843 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003844 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003845 out_baseimg, strerror(-ret));
3846 }
3847
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003848 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003849 /*
3850 * TODO At this point it is possible to check if any clusters that are
3851 * allocated in the COW file are the same in the backing file. If so, they
3852 * could be dropped from the COW file. Don't do this before switching the
3853 * backing file, in case of a crash this would lead to corruption.
3854 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003855out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003856 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003857 /* Cleanup */
3858 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003859 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003860 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003861 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003862 qemu_vfree(buf_old);
3863 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003864
Markus Armbruster26f54e92014-10-07 13:59:04 +02003865 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003866 if (ret) {
3867 return 1;
3868 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003869 return 0;
3870}
3871
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003872static int img_resize(int argc, char **argv)
3873{
Markus Armbruster6750e792015-02-12 17:43:08 +01003874 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003875 int c, ret, relative;
3876 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003877 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003878 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003879 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003880 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003881 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003882
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003883 static QemuOptsList resize_options = {
3884 .name = "resize_options",
3885 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3886 .desc = {
3887 {
3888 .name = BLOCK_OPT_SIZE,
3889 .type = QEMU_OPT_SIZE,
3890 .help = "Virtual disk size"
3891 }, {
3892 /* end of list */
3893 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003894 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003895 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003896 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003897 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003898
Kevin Wolfe80fec72011-04-29 10:58:12 +02003899 /* Remove size from argv manually so that negative numbers are not treated
3900 * as options by getopt. */
3901 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003902 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003903 return 1;
3904 }
3905
3906 size = argv[--argc];
3907
3908 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003909 fmt = NULL;
3910 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003911 static const struct option long_options[] = {
3912 {"help", no_argument, 0, 'h'},
3913 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003914 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003915 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003916 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003917 {0, 0, 0, 0}
3918 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003919 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003920 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003921 if (c == -1) {
3922 break;
3923 }
3924 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003925 case ':':
3926 missing_argument(argv[optind - 1]);
3927 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003928 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003929 unrecognized_option(argv[optind - 1]);
3930 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003931 case 'h':
3932 help();
3933 break;
3934 case 'f':
3935 fmt = optarg;
3936 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003937 case 'q':
3938 quiet = true;
3939 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003940 case OPTION_OBJECT:
3941 user_creatable_process_cmdline(optarg);
3942 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003943 case OPTION_IMAGE_OPTS:
3944 image_opts = true;
3945 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003946 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003947 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003948 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003949 if (prealloc == PREALLOC_MODE__MAX) {
3950 error_report("Invalid preallocation mode '%s'", optarg);
3951 return 1;
3952 }
3953 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003954 case OPTION_SHRINK:
3955 shrink = true;
3956 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003957 }
3958 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003959 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003960 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003961 }
3962 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003963
3964 /* Choose grow, shrink, or absolute resize mode */
3965 switch (size[0]) {
3966 case '+':
3967 relative = 1;
3968 size++;
3969 break;
3970 case '-':
3971 relative = -1;
3972 size++;
3973 break;
3974 default:
3975 relative = 0;
3976 break;
3977 }
3978
3979 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003980 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02003981 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01003982 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003983 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003984 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003985 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003986 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003987 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3988 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003989
Max Reitzefaa7c42016-03-16 19:54:38 +01003990 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003991 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3992 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003993 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003994 ret = -1;
3995 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003996 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003997
Max Reitzdc5f6902017-06-13 22:20:55 +02003998 current_size = blk_getlength(blk);
3999 if (current_size < 0) {
4000 error_report("Failed to inquire current image length: %s",
4001 strerror(-current_size));
4002 ret = -1;
4003 goto out;
4004 }
4005
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004006 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004007 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004008 } else {
4009 total_size = n;
4010 }
4011 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004012 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004013 ret = -1;
4014 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004015 }
4016
Max Reitzdc5f6902017-06-13 22:20:55 +02004017 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4018 error_report("Preallocation can only be used for growing images");
4019 ret = -1;
4020 goto out;
4021 }
4022
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004023 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004024 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004025 warn_report("Shrinking an image will delete all data beyond the "
4026 "shrunken image's end. Before performing such an "
4027 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004028 ret = -1;
4029 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004030 }
4031
Max Reitze8d04f92019-09-18 11:51:43 +02004032 /*
4033 * The user expects the image to have the desired size after
4034 * resizing, so pass @exact=true. It is of no use to report
4035 * success when the image has not actually been resized.
4036 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004037 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004038 if (!ret) {
4039 qprintf(quiet, "Image resized.\n");
4040 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004041 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004042 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004043out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004044 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004045 if (ret) {
4046 return 1;
4047 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004048 return 0;
4049}
4050
Max Reitz76a3a342014-10-27 11:12:51 +01004051static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004052 int64_t offset, int64_t total_work_size,
4053 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004054{
4055 qemu_progress_print(100.f * offset / total_work_size, 0);
4056}
4057
Max Reitz51641352018-05-09 23:00:20 +02004058static int print_amend_option_help(const char *format)
4059{
4060 BlockDriver *drv;
4061
4062 /* Find driver and parse its options */
4063 drv = bdrv_find_format(format);
4064 if (!drv) {
4065 error_report("Unknown file format '%s'", format);
4066 return 1;
4067 }
4068
4069 if (!drv->bdrv_amend_options) {
4070 error_report("Format driver '%s' does not support option amendment",
4071 format);
4072 return 1;
4073 }
4074
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004075 /* Every driver supporting amendment must have amend_opts */
4076 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004077
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004078 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004079 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004080 return 0;
4081}
4082
Max Reitz6f176b42013-09-03 10:09:50 +02004083static int img_amend(int argc, char **argv)
4084{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004085 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004086 int c, ret = 0;
4087 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004088 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004089 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004090 const char *fmt = NULL, *filename, *cache;
4091 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004092 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004093 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004094 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004095 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004096 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004097 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004098
Max Reitzbd39e6e2014-07-22 22:58:43 +02004099 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004100 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004101 static const struct option long_options[] = {
4102 {"help", no_argument, 0, 'h'},
4103 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004104 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004105 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004106 {0, 0, 0, 0}
4107 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004108 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004109 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004110 if (c == -1) {
4111 break;
4112 }
4113
4114 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004115 case ':':
4116 missing_argument(argv[optind - 1]);
4117 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004118 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004119 unrecognized_option(argv[optind - 1]);
4120 break;
4121 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004122 help();
4123 break;
4124 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004125 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004126 ret = -1;
4127 goto out_no_progress;
4128 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004129 break;
4130 case 'f':
4131 fmt = optarg;
4132 break;
4133 case 't':
4134 cache = optarg;
4135 break;
4136 case 'p':
4137 progress = true;
4138 break;
4139 case 'q':
4140 quiet = true;
4141 break;
4142 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004143 user_creatable_process_cmdline(optarg);
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004144 break;
4145 case OPTION_IMAGE_OPTS:
4146 image_opts = true;
4147 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004148 case OPTION_FORCE:
4149 force = true;
4150 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004151 }
4152 }
4153
Max Reitz6f176b42013-09-03 10:09:50 +02004154 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004155 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004156 }
4157
Max Reitz76a3a342014-10-27 11:12:51 +01004158 if (quiet) {
4159 progress = false;
4160 }
4161 qemu_progress_init(progress, 1.0);
4162
Kevin Wolfa283cb62014-02-21 16:24:07 +01004163 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4164 if (fmt && has_help_option(options)) {
4165 /* If a format is explicitly specified (and possibly no filename is
4166 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004167 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004168 goto out;
4169 }
4170
4171 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004172 error_report("Expecting one image file name");
4173 ret = -1;
4174 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004175 }
Max Reitz6f176b42013-09-03 10:09:50 +02004176
Kevin Wolfce099542016-03-15 13:01:04 +01004177 flags = BDRV_O_RDWR;
4178 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004179 if (ret < 0) {
4180 error_report("Invalid cache option: %s", cache);
4181 goto out;
4182 }
4183
Fam Zheng335e9932017-05-03 00:35:39 +08004184 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4185 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004186 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004187 ret = -1;
4188 goto out;
4189 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004190 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004191
4192 fmt = bs->drv->format_name;
4193
Kevin Wolf626f84f2014-02-21 16:24:06 +01004194 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004195 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004196 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004197 goto out;
4198 }
4199
Max Reitz1f996682018-05-09 23:00:17 +02004200 if (!bs->drv->bdrv_amend_options) {
4201 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004202 fmt);
4203 ret = -1;
4204 goto out;
4205 }
4206
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004207 /* Every driver supporting amendment must have amend_opts */
4208 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004209
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004210 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4211 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004212 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004213 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004214 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4215 qemu_opts_del(opts);
4216 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004217 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004218 error_append_hint(&err,
4219 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004220 }
4221
Paolo Bonziniece90862017-01-04 15:56:24 +01004222 error_report_err(err);
4223 ret = -1;
4224 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004225 }
4226
Max Reitz76a3a342014-10-27 11:12:51 +01004227 /* In case the driver does not call amend_status_cb() */
4228 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004229 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004230 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004231 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004232 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004233 goto out;
4234 }
4235
4236out:
Max Reitz76a3a342014-10-27 11:12:51 +01004237 qemu_progress_end();
4238
Max Reitze814dff2015-08-20 16:00:38 -07004239out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004240 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004241 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004242 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004243 g_free(options);
4244
Max Reitz6f176b42013-09-03 10:09:50 +02004245 if (ret) {
4246 return 1;
4247 }
4248 return 0;
4249}
4250
Kevin Wolfb6133b82014-08-05 14:17:13 +02004251typedef struct BenchData {
4252 BlockBackend *blk;
4253 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004254 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004255 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004256 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004257 int nrreq;
4258 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004259 int flush_interval;
4260 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004261 uint8_t *buf;
4262 QEMUIOVector *qiov;
4263
4264 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004265 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004266 uint64_t offset;
4267} BenchData;
4268
Kevin Wolf55d539c2016-06-03 13:59:41 +02004269static void bench_undrained_flush_cb(void *opaque, int ret)
4270{
4271 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004272 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004273 exit(EXIT_FAILURE);
4274 }
4275}
4276
Kevin Wolfb6133b82014-08-05 14:17:13 +02004277static void bench_cb(void *opaque, int ret)
4278{
4279 BenchData *b = opaque;
4280 BlockAIOCB *acb;
4281
4282 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004283 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004284 exit(EXIT_FAILURE);
4285 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004286
4287 if (b->in_flush) {
4288 /* Just finished a flush with drained queue: Start next requests */
4289 assert(b->in_flight == 0);
4290 b->in_flush = false;
4291 } else if (b->in_flight > 0) {
4292 int remaining = b->n - b->in_flight;
4293
Kevin Wolfb6133b82014-08-05 14:17:13 +02004294 b->n--;
4295 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004296
4297 /* Time for flush? Drain queue if requested, then flush */
4298 if (b->flush_interval && remaining % b->flush_interval == 0) {
4299 if (!b->in_flight || !b->drain_on_flush) {
4300 BlockCompletionFunc *cb;
4301
4302 if (b->drain_on_flush) {
4303 b->in_flush = true;
4304 cb = bench_cb;
4305 } else {
4306 cb = bench_undrained_flush_cb;
4307 }
4308
4309 acb = blk_aio_flush(b->blk, cb, b);
4310 if (!acb) {
4311 error_report("Failed to issue flush request");
4312 exit(EXIT_FAILURE);
4313 }
4314 }
4315 if (b->drain_on_flush) {
4316 return;
4317 }
4318 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004319 }
4320
4321 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004322 int64_t offset = b->offset;
4323 /* blk_aio_* might look for completed I/Os and kick bench_cb
4324 * again, so make sure this operation is counted by in_flight
4325 * and b->offset is ready for the next submission.
4326 */
4327 b->in_flight++;
4328 b->offset += b->step;
4329 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004330 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004331 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004332 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004333 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004334 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004335 if (!acb) {
4336 error_report("Failed to issue request");
4337 exit(EXIT_FAILURE);
4338 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004339 }
4340}
4341
4342static int img_bench(int argc, char **argv)
4343{
4344 int c, ret = 0;
4345 const char *fmt = NULL, *filename;
4346 bool quiet = false;
4347 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004348 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004349 int count = 75000;
4350 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004351 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004352 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004353 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004354 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004355 int flush_interval = 0;
4356 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004357 int64_t image_size;
4358 BlockBackend *blk = NULL;
4359 BenchData data = {};
4360 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004361 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004362 struct timeval t1, t2;
4363 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004364 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004365 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004366
4367 for (;;) {
4368 static const struct option long_options[] = {
4369 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004370 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004371 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004372 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004373 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004374 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004375 {0, 0, 0, 0}
4376 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004377 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4378 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004379 if (c == -1) {
4380 break;
4381 }
4382
4383 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004384 case ':':
4385 missing_argument(argv[optind - 1]);
4386 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004387 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004388 unrecognized_option(argv[optind - 1]);
4389 break;
4390 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004391 help();
4392 break;
4393 case 'c':
4394 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004395 unsigned long res;
4396
4397 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004398 error_report("Invalid request count specified");
4399 return 1;
4400 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004401 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004402 break;
4403 }
4404 case 'd':
4405 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004406 unsigned long res;
4407
4408 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004409 error_report("Invalid queue depth specified");
4410 return 1;
4411 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004412 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004413 break;
4414 }
4415 case 'f':
4416 fmt = optarg;
4417 break;
4418 case 'n':
4419 flags |= BDRV_O_NATIVE_AIO;
4420 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004421 case 'i':
4422 ret = bdrv_parse_aio(optarg, &flags);
4423 if (ret < 0) {
4424 error_report("Invalid aio option: %s", optarg);
4425 ret = -1;
4426 goto out;
4427 }
4428 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004429 case 'o':
4430 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004431 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004432 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004433 return 1;
4434 }
4435 break;
4436 }
4437 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004438 case 'q':
4439 quiet = true;
4440 break;
4441 case 's':
4442 {
4443 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004444
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004445 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4446 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004447 return 1;
4448 }
4449
4450 bufsize = sval;
4451 break;
4452 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004453 case 'S':
4454 {
4455 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004456
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004457 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4458 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004459 return 1;
4460 }
4461
4462 step = sval;
4463 break;
4464 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004465 case 't':
4466 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4467 if (ret < 0) {
4468 error_report("Invalid cache mode");
4469 ret = -1;
4470 goto out;
4471 }
4472 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004473 case 'w':
4474 flags |= BDRV_O_RDWR;
4475 is_write = true;
4476 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004477 case 'U':
4478 force_share = true;
4479 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004480 case OPTION_PATTERN:
4481 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004482 unsigned long res;
4483
4484 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004485 error_report("Invalid pattern byte specified");
4486 return 1;
4487 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004488 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004489 break;
4490 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004491 case OPTION_FLUSH_INTERVAL:
4492 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004493 unsigned long res;
4494
4495 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004496 error_report("Invalid flush interval specified");
4497 return 1;
4498 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004499 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004500 break;
4501 }
4502 case OPTION_NO_DRAIN:
4503 drain_on_flush = false;
4504 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004505 case OPTION_IMAGE_OPTS:
4506 image_opts = true;
4507 break;
4508 }
4509 }
4510
4511 if (optind != argc - 1) {
4512 error_exit("Expecting one image file name");
4513 }
4514 filename = argv[argc - 1];
4515
Kevin Wolf55d539c2016-06-03 13:59:41 +02004516 if (!is_write && flush_interval) {
4517 error_report("--flush-interval is only available in write tests");
4518 ret = -1;
4519 goto out;
4520 }
4521 if (flush_interval && flush_interval < depth) {
4522 error_report("Flush interval can't be smaller than depth");
4523 ret = -1;
4524 goto out;
4525 }
4526
Fam Zheng335e9932017-05-03 00:35:39 +08004527 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4528 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004529 if (!blk) {
4530 ret = -1;
4531 goto out;
4532 }
4533
4534 image_size = blk_getlength(blk);
4535 if (image_size < 0) {
4536 ret = image_size;
4537 goto out;
4538 }
4539
4540 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004541 .blk = blk,
4542 .image_size = image_size,
4543 .bufsize = bufsize,
4544 .step = step ?: bufsize,
4545 .nrreq = depth,
4546 .n = count,
4547 .offset = offset,
4548 .write = is_write,
4549 .flush_interval = flush_interval,
4550 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004551 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004552 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004553 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004554 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004555 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004556 if (flush_interval) {
4557 printf("Sending flush every %d requests\n", flush_interval);
4558 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004559
Fam Zheng79d46582018-01-16 14:08:58 +08004560 buf_size = data.nrreq * data.bufsize;
4561 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004562 memset(data.buf, pattern, data.nrreq * data.bufsize);
4563
Fam Zheng79d46582018-01-16 14:08:58 +08004564 blk_register_buf(blk, data.buf, buf_size);
4565
Kevin Wolfb6133b82014-08-05 14:17:13 +02004566 data.qiov = g_new(QEMUIOVector, data.nrreq);
4567 for (i = 0; i < data.nrreq; i++) {
4568 qemu_iovec_init(&data.qiov[i], 1);
4569 qemu_iovec_add(&data.qiov[i],
4570 data.buf + i * data.bufsize, data.bufsize);
4571 }
4572
4573 gettimeofday(&t1, NULL);
4574 bench_cb(&data, 0);
4575
4576 while (data.n > 0) {
4577 main_loop_wait(false);
4578 }
4579 gettimeofday(&t2, NULL);
4580
4581 printf("Run completed in %3.3f seconds.\n",
4582 (t2.tv_sec - t1.tv_sec)
4583 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4584
4585out:
Fam Zheng79d46582018-01-16 14:08:58 +08004586 if (data.buf) {
4587 blk_unregister_buf(blk, data.buf);
4588 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004589 qemu_vfree(data.buf);
4590 blk_unref(blk);
4591
4592 if (ret) {
4593 return 1;
4594 }
4595 return 0;
4596}
4597
Eric Blake3b51ab42020-05-12 20:16:45 -05004598enum ImgBitmapAct {
4599 BITMAP_ADD,
4600 BITMAP_REMOVE,
4601 BITMAP_CLEAR,
4602 BITMAP_ENABLE,
4603 BITMAP_DISABLE,
4604 BITMAP_MERGE,
4605};
4606typedef struct ImgBitmapAction {
4607 enum ImgBitmapAct act;
4608 const char *src; /* only used for merge */
4609 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4610} ImgBitmapAction;
4611
4612static int img_bitmap(int argc, char **argv)
4613{
4614 Error *err = NULL;
4615 int c, ret = 1;
4616 QemuOpts *opts = NULL;
4617 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4618 const char *filename, *bitmap;
4619 BlockBackend *blk = NULL, *src = NULL;
4620 BlockDriverState *bs = NULL, *src_bs = NULL;
4621 bool image_opts = false;
4622 int64_t granularity = 0;
4623 bool add = false, merge = false;
4624 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4625 ImgBitmapAction *act, *act_next;
4626 const char *op;
4627
4628 QSIMPLEQ_INIT(&actions);
4629
4630 for (;;) {
4631 static const struct option long_options[] = {
4632 {"help", no_argument, 0, 'h'},
4633 {"object", required_argument, 0, OPTION_OBJECT},
4634 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4635 {"add", no_argument, 0, OPTION_ADD},
4636 {"remove", no_argument, 0, OPTION_REMOVE},
4637 {"clear", no_argument, 0, OPTION_CLEAR},
4638 {"enable", no_argument, 0, OPTION_ENABLE},
4639 {"disable", no_argument, 0, OPTION_DISABLE},
4640 {"merge", required_argument, 0, OPTION_MERGE},
4641 {"granularity", required_argument, 0, 'g'},
4642 {"source-file", required_argument, 0, 'b'},
4643 {"source-format", required_argument, 0, 'F'},
4644 {0, 0, 0, 0}
4645 };
4646 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4647 if (c == -1) {
4648 break;
4649 }
4650
4651 switch (c) {
4652 case ':':
4653 missing_argument(argv[optind - 1]);
4654 break;
4655 case '?':
4656 unrecognized_option(argv[optind - 1]);
4657 break;
4658 case 'h':
4659 help();
4660 break;
4661 case 'b':
4662 src_filename = optarg;
4663 break;
4664 case 'f':
4665 fmt = optarg;
4666 break;
4667 case 'F':
4668 src_fmt = optarg;
4669 break;
4670 case 'g':
4671 granularity = cvtnum("granularity", optarg);
4672 if (granularity < 0) {
4673 return 1;
4674 }
4675 break;
4676 case OPTION_ADD:
4677 act = g_new0(ImgBitmapAction, 1);
4678 act->act = BITMAP_ADD;
4679 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4680 add = true;
4681 break;
4682 case OPTION_REMOVE:
4683 act = g_new0(ImgBitmapAction, 1);
4684 act->act = BITMAP_REMOVE;
4685 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4686 break;
4687 case OPTION_CLEAR:
4688 act = g_new0(ImgBitmapAction, 1);
4689 act->act = BITMAP_CLEAR;
4690 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4691 break;
4692 case OPTION_ENABLE:
4693 act = g_new0(ImgBitmapAction, 1);
4694 act->act = BITMAP_ENABLE;
4695 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4696 break;
4697 case OPTION_DISABLE:
4698 act = g_new0(ImgBitmapAction, 1);
4699 act->act = BITMAP_DISABLE;
4700 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4701 break;
4702 case OPTION_MERGE:
4703 act = g_new0(ImgBitmapAction, 1);
4704 act->act = BITMAP_MERGE;
4705 act->src = optarg;
4706 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4707 merge = true;
4708 break;
4709 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004710 user_creatable_process_cmdline(optarg);
Eric Blake3b51ab42020-05-12 20:16:45 -05004711 break;
4712 case OPTION_IMAGE_OPTS:
4713 image_opts = true;
4714 break;
4715 }
4716 }
4717
Eric Blake3b51ab42020-05-12 20:16:45 -05004718 if (QSIMPLEQ_EMPTY(&actions)) {
4719 error_report("Need at least one of --add, --remove, --clear, "
4720 "--enable, --disable, or --merge");
4721 goto out;
4722 }
4723
4724 if (granularity && !add) {
4725 error_report("granularity only supported with --add");
4726 goto out;
4727 }
4728 if (src_fmt && !src_filename) {
4729 error_report("-F only supported with -b");
4730 goto out;
4731 }
4732 if (src_filename && !merge) {
4733 error_report("Merge bitmap source file only supported with "
4734 "--merge");
4735 goto out;
4736 }
4737
4738 if (optind != argc - 2) {
4739 error_report("Expecting filename and bitmap name");
4740 goto out;
4741 }
4742
4743 filename = argv[optind];
4744 bitmap = argv[optind + 1];
4745
Eric Blake14f16bf2020-09-14 14:10:09 -05004746 /*
4747 * No need to open backing chains; we will be manipulating bitmaps
4748 * directly in this image without reference to image contents.
4749 */
4750 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4751 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004752 if (!blk) {
4753 goto out;
4754 }
4755 bs = blk_bs(blk);
4756 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004757 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4758 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004759 if (!src) {
4760 goto out;
4761 }
4762 src_bs = blk_bs(src);
4763 } else {
4764 src_bs = bs;
4765 }
4766
4767 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4768 switch (act->act) {
4769 case BITMAP_ADD:
4770 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4771 !!granularity, granularity, true, true,
4772 false, false, &err);
4773 op = "add";
4774 break;
4775 case BITMAP_REMOVE:
4776 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4777 op = "remove";
4778 break;
4779 case BITMAP_CLEAR:
4780 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4781 op = "clear";
4782 break;
4783 case BITMAP_ENABLE:
4784 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4785 op = "enable";
4786 break;
4787 case BITMAP_DISABLE:
4788 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4789 op = "disable";
4790 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004791 case BITMAP_MERGE:
4792 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4793 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004794 op = "merge";
4795 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004796 default:
4797 g_assert_not_reached();
4798 }
4799
4800 if (err) {
4801 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4802 op, bitmap);
4803 goto out;
4804 }
4805 g_free(act);
4806 }
4807
4808 ret = 0;
4809
4810 out:
4811 blk_unref(src);
4812 blk_unref(blk);
4813 qemu_opts_del(opts);
4814 return ret;
4815}
4816
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004817#define C_BS 01
4818#define C_COUNT 02
4819#define C_IF 04
4820#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004821#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004822
4823struct DdInfo {
4824 unsigned int flags;
4825 int64_t count;
4826};
4827
4828struct DdIo {
4829 int bsz; /* Block size */
4830 char *filename;
4831 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004832 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004833};
4834
4835struct DdOpts {
4836 const char *name;
4837 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4838 unsigned int flag;
4839};
4840
4841static int img_dd_bs(const char *arg,
4842 struct DdIo *in, struct DdIo *out,
4843 struct DdInfo *dd)
4844{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004845 int64_t res;
4846
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004847 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004848
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004849 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004850 return 1;
4851 }
4852 in->bsz = out->bsz = res;
4853
4854 return 0;
4855}
4856
4857static int img_dd_count(const char *arg,
4858 struct DdIo *in, struct DdIo *out,
4859 struct DdInfo *dd)
4860{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004861 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004862
Markus Armbruster606caa02017-02-21 21:14:04 +01004863 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004864 return 1;
4865 }
4866
4867 return 0;
4868}
4869
4870static int img_dd_if(const char *arg,
4871 struct DdIo *in, struct DdIo *out,
4872 struct DdInfo *dd)
4873{
4874 in->filename = g_strdup(arg);
4875
4876 return 0;
4877}
4878
4879static int img_dd_of(const char *arg,
4880 struct DdIo *in, struct DdIo *out,
4881 struct DdInfo *dd)
4882{
4883 out->filename = g_strdup(arg);
4884
4885 return 0;
4886}
4887
Reda Sallahif7c15532016-08-10 16:16:09 +02004888static int img_dd_skip(const char *arg,
4889 struct DdIo *in, struct DdIo *out,
4890 struct DdInfo *dd)
4891{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004892 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004893
Markus Armbruster606caa02017-02-21 21:14:04 +01004894 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004895 return 1;
4896 }
4897
4898 return 0;
4899}
4900
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004901static int img_dd(int argc, char **argv)
4902{
4903 int ret = 0;
4904 char *arg = NULL;
4905 char *tmp;
4906 BlockDriver *drv = NULL, *proto_drv = NULL;
4907 BlockBackend *blk1 = NULL, *blk2 = NULL;
4908 QemuOpts *opts = NULL;
4909 QemuOptsList *create_opts = NULL;
4910 Error *local_err = NULL;
4911 bool image_opts = false;
4912 int c, i;
4913 const char *out_fmt = "raw";
4914 const char *fmt = NULL;
4915 int64_t size = 0;
4916 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004917 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004918 struct DdInfo dd = {
4919 .flags = 0,
4920 .count = 0,
4921 };
4922 struct DdIo in = {
4923 .bsz = 512, /* Block size is by default 512 bytes */
4924 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004925 .buf = NULL,
4926 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004927 };
4928 struct DdIo out = {
4929 .bsz = 512,
4930 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004931 .buf = NULL,
4932 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004933 };
4934
4935 const struct DdOpts options[] = {
4936 { "bs", img_dd_bs, C_BS },
4937 { "count", img_dd_count, C_COUNT },
4938 { "if", img_dd_if, C_IF },
4939 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004940 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004941 { NULL, NULL, 0 }
4942 };
4943 const struct option long_options[] = {
4944 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004945 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004946 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004947 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004948 { 0, 0, 0, 0 }
4949 };
4950
Fam Zheng335e9932017-05-03 00:35:39 +08004951 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004952 if (c == EOF) {
4953 break;
4954 }
4955 switch (c) {
4956 case 'O':
4957 out_fmt = optarg;
4958 break;
4959 case 'f':
4960 fmt = optarg;
4961 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004962 case ':':
4963 missing_argument(argv[optind - 1]);
4964 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004965 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004966 unrecognized_option(argv[optind - 1]);
4967 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004968 case 'h':
4969 help();
4970 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004971 case 'U':
4972 force_share = true;
4973 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004974 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004975 user_creatable_process_cmdline(optarg);
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004976 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004977 case OPTION_IMAGE_OPTS:
4978 image_opts = true;
4979 break;
4980 }
4981 }
4982
4983 for (i = optind; i < argc; i++) {
4984 int j;
4985 arg = g_strdup(argv[i]);
4986
4987 tmp = strchr(arg, '=');
4988 if (tmp == NULL) {
4989 error_report("unrecognized operand %s", arg);
4990 ret = -1;
4991 goto out;
4992 }
4993
4994 *tmp++ = '\0';
4995
4996 for (j = 0; options[j].name != NULL; j++) {
4997 if (!strcmp(arg, options[j].name)) {
4998 break;
4999 }
5000 }
5001 if (options[j].name == NULL) {
5002 error_report("unrecognized operand %s", arg);
5003 ret = -1;
5004 goto out;
5005 }
5006
5007 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5008 ret = -1;
5009 goto out;
5010 }
5011 dd.flags |= options[j].flag;
5012 g_free(arg);
5013 arg = NULL;
5014 }
5015
5016 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5017 error_report("Must specify both input and output files");
5018 ret = -1;
5019 goto out;
5020 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005021
Fam Zheng335e9932017-05-03 00:35:39 +08005022 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5023 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005024
5025 if (!blk1) {
5026 ret = -1;
5027 goto out;
5028 }
5029
5030 drv = bdrv_find_format(out_fmt);
5031 if (!drv) {
5032 error_report("Unknown file format");
5033 ret = -1;
5034 goto out;
5035 }
5036 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5037
5038 if (!proto_drv) {
5039 error_report_err(local_err);
5040 ret = -1;
5041 goto out;
5042 }
5043 if (!drv->create_opts) {
5044 error_report("Format driver '%s' does not support image creation",
5045 drv->format_name);
5046 ret = -1;
5047 goto out;
5048 }
5049 if (!proto_drv->create_opts) {
5050 error_report("Protocol driver '%s' does not support image creation",
5051 proto_drv->format_name);
5052 ret = -1;
5053 goto out;
5054 }
5055 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5056 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5057
5058 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5059
5060 size = blk_getlength(blk1);
5061 if (size < 0) {
5062 error_report("Failed to get size for '%s'", in.filename);
5063 ret = -1;
5064 goto out;
5065 }
5066
5067 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5068 dd.count * in.bsz < size) {
5069 size = dd.count * in.bsz;
5070 }
5071
Reda Sallahif7c15532016-08-10 16:16:09 +02005072 /* Overflow means the specified offset is beyond input image's size */
5073 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5074 size < in.bsz * in.offset)) {
5075 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5076 } else {
5077 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5078 size - in.bsz * in.offset, &error_abort);
5079 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005080
5081 ret = bdrv_create(drv, out.filename, opts, &local_err);
5082 if (ret < 0) {
5083 error_reportf_err(local_err,
5084 "%s: error while creating output image: ",
5085 out.filename);
5086 ret = -1;
5087 goto out;
5088 }
5089
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005090 /* TODO, we can't honour --image-opts for the target,
5091 * since it needs to be given in a format compatible
5092 * with the bdrv_create() call above which does not
5093 * support image-opts style.
5094 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005095 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005096 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005097
5098 if (!blk2) {
5099 ret = -1;
5100 goto out;
5101 }
5102
Reda Sallahif7c15532016-08-10 16:16:09 +02005103 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5104 size < in.offset * in.bsz)) {
5105 /* We give a warning if the skip option is bigger than the input
5106 * size and create an empty output disk image (i.e. like dd(1)).
5107 */
5108 error_report("%s: cannot skip to specified offset", in.filename);
5109 in_pos = size;
5110 } else {
5111 in_pos = in.offset * in.bsz;
5112 }
5113
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005114 in.buf = g_new(uint8_t, in.bsz);
5115
Reda Sallahif7c15532016-08-10 16:16:09 +02005116 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005117 int in_ret, out_ret;
5118
5119 if (in_pos + in.bsz > size) {
5120 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5121 } else {
5122 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5123 }
5124 if (in_ret < 0) {
5125 error_report("error while reading from input image file: %s",
5126 strerror(-in_ret));
5127 ret = -1;
5128 goto out;
5129 }
5130 in_pos += in_ret;
5131
5132 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5133
5134 if (out_ret < 0) {
5135 error_report("error while writing to output image file: %s",
5136 strerror(-out_ret));
5137 ret = -1;
5138 goto out;
5139 }
5140 out_pos += out_ret;
5141 }
5142
5143out:
5144 g_free(arg);
5145 qemu_opts_del(opts);
5146 qemu_opts_free(create_opts);
5147 blk_unref(blk1);
5148 blk_unref(blk2);
5149 g_free(in.filename);
5150 g_free(out.filename);
5151 g_free(in.buf);
5152 g_free(out.buf);
5153
5154 if (ret) {
5155 return 1;
5156 }
5157 return 0;
5158}
5159
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005160static void dump_json_block_measure_info(BlockMeasureInfo *info)
5161{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005162 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005163 QObject *obj;
5164 Visitor *v = qobject_output_visitor_new(&obj);
5165
5166 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5167 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005168 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005169 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005170 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005171 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005172 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005173 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005174}
5175
5176static int img_measure(int argc, char **argv)
5177{
5178 static const struct option long_options[] = {
5179 {"help", no_argument, 0, 'h'},
5180 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5181 {"object", required_argument, 0, OPTION_OBJECT},
5182 {"output", required_argument, 0, OPTION_OUTPUT},
5183 {"size", required_argument, 0, OPTION_SIZE},
5184 {"force-share", no_argument, 0, 'U'},
5185 {0, 0, 0, 0}
5186 };
5187 OutputFormat output_format = OFORMAT_HUMAN;
5188 BlockBackend *in_blk = NULL;
5189 BlockDriver *drv;
5190 const char *filename = NULL;
5191 const char *fmt = NULL;
5192 const char *out_fmt = "raw";
5193 char *options = NULL;
5194 char *snapshot_name = NULL;
5195 bool force_share = false;
5196 QemuOpts *opts = NULL;
5197 QemuOpts *object_opts = NULL;
5198 QemuOpts *sn_opts = NULL;
5199 QemuOptsList *create_opts = NULL;
5200 bool image_opts = false;
5201 uint64_t img_size = UINT64_MAX;
5202 BlockMeasureInfo *info = NULL;
5203 Error *local_err = NULL;
5204 int ret = 1;
5205 int c;
5206
5207 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5208 long_options, NULL)) != -1) {
5209 switch (c) {
5210 case '?':
5211 case 'h':
5212 help();
5213 break;
5214 case 'f':
5215 fmt = optarg;
5216 break;
5217 case 'O':
5218 out_fmt = optarg;
5219 break;
5220 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005221 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005222 goto out;
5223 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005224 break;
5225 case 'l':
5226 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5227 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5228 optarg, false);
5229 if (!sn_opts) {
5230 error_report("Failed in parsing snapshot param '%s'",
5231 optarg);
5232 goto out;
5233 }
5234 } else {
5235 snapshot_name = optarg;
5236 }
5237 break;
5238 case 'U':
5239 force_share = true;
5240 break;
5241 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005242 user_creatable_process_cmdline(optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005243 break;
5244 case OPTION_IMAGE_OPTS:
5245 image_opts = true;
5246 break;
5247 case OPTION_OUTPUT:
5248 if (!strcmp(optarg, "json")) {
5249 output_format = OFORMAT_JSON;
5250 } else if (!strcmp(optarg, "human")) {
5251 output_format = OFORMAT_HUMAN;
5252 } else {
5253 error_report("--output must be used with human or json "
5254 "as argument.");
5255 goto out;
5256 }
5257 break;
5258 case OPTION_SIZE:
5259 {
5260 int64_t sval;
5261
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005262 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005263 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005264 goto out;
5265 }
5266 img_size = (uint64_t)sval;
5267 }
5268 break;
5269 }
5270 }
5271
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005272 if (argc - optind > 1) {
5273 error_report("At most one filename argument is allowed.");
5274 goto out;
5275 } else if (argc - optind == 1) {
5276 filename = argv[optind];
5277 }
5278
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005279 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5280 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005281 goto out;
5282 }
5283 if (filename && img_size != UINT64_MAX) {
5284 error_report("--size N cannot be used together with a filename.");
5285 goto out;
5286 }
5287 if (!filename && img_size == UINT64_MAX) {
5288 error_report("Either --size N or one filename must be specified.");
5289 goto out;
5290 }
5291
5292 if (filename) {
5293 in_blk = img_open(image_opts, filename, fmt, 0,
5294 false, false, force_share);
5295 if (!in_blk) {
5296 goto out;
5297 }
5298
5299 if (sn_opts) {
5300 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5301 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5302 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5303 &local_err);
5304 } else if (snapshot_name != NULL) {
5305 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5306 snapshot_name, &local_err);
5307 }
5308 if (local_err) {
5309 error_reportf_err(local_err, "Failed to load snapshot: ");
5310 goto out;
5311 }
5312 }
5313
5314 drv = bdrv_find_format(out_fmt);
5315 if (!drv) {
5316 error_report("Unknown file format '%s'", out_fmt);
5317 goto out;
5318 }
5319 if (!drv->create_opts) {
5320 error_report("Format driver '%s' does not support image creation",
5321 drv->format_name);
5322 goto out;
5323 }
5324
5325 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5326 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5327 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5328 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005329 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005330 error_report_err(local_err);
5331 error_report("Invalid options for file format '%s'", out_fmt);
5332 goto out;
5333 }
5334 }
5335 if (img_size != UINT64_MAX) {
5336 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5337 }
5338
5339 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5340 if (local_err) {
5341 error_report_err(local_err);
5342 goto out;
5343 }
5344
5345 if (output_format == OFORMAT_HUMAN) {
5346 printf("required size: %" PRIu64 "\n", info->required);
5347 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005348 if (info->has_bitmaps) {
5349 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5350 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005351 } else {
5352 dump_json_block_measure_info(info);
5353 }
5354
5355 ret = 0;
5356
5357out:
5358 qapi_free_BlockMeasureInfo(info);
5359 qemu_opts_del(object_opts);
5360 qemu_opts_del(opts);
5361 qemu_opts_del(sn_opts);
5362 qemu_opts_free(create_opts);
5363 g_free(options);
5364 blk_unref(in_blk);
5365 return ret;
5366}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005367
Anthony Liguoric227f092009-10-01 16:12:16 -05005368static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005369#define DEF(option, callback, arg_string) \
5370 { option, callback },
5371#include "qemu-img-cmds.h"
5372#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005373 { NULL, NULL, },
5374};
5375
bellardea2384d2004-08-01 21:59:26 +00005376int main(int argc, char **argv)
5377{
Anthony Liguoric227f092009-10-01 16:12:16 -05005378 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005379 const char *cmdname;
Jeff Cody7db16892014-04-25 17:02:32 -04005380 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005381 static const struct option long_options[] = {
5382 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005383 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005384 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005385 {0, 0, 0, 0}
5386 };
bellardea2384d2004-08-01 21:59:26 +00005387
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005388#ifdef CONFIG_POSIX
5389 signal(SIGPIPE, SIG_IGN);
5390#endif
5391
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005392 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005393 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005394 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005395 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005396
Markus Armbrusterf9734d52021-07-20 14:53:53 +02005397 qemu_init_main_loop(&error_fatal);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005398
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005399 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005400
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005401 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005402 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005403 if (argc < 2) {
5404 error_exit("Not enough arguments");
5405 }
Stuart Brady153859b2009-06-07 00:42:17 +01005406
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005407 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005408 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005409
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005410 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005411 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005412 case ':':
5413 missing_argument(argv[optind - 1]);
5414 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005415 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005416 unrecognized_option(argv[optind - 1]);
5417 return 0;
5418 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005419 help();
5420 return 0;
5421 case 'V':
5422 printf(QEMU_IMG_VERSION);
5423 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005424 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005425 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005426 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005427 }
bellardea2384d2004-08-01 21:59:26 +00005428 }
Stuart Brady153859b2009-06-07 00:42:17 +01005429
Denis V. Lunev10985132016-06-17 17:44:13 +03005430 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005431
Denis V. Lunev10985132016-06-17 17:44:13 +03005432 /* reset getopt_long scanning */
5433 argc -= optind;
5434 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005435 return 0;
5436 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005437 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005438 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005439
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005440 if (!trace_init_backends()) {
5441 exit(1);
5442 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005443 trace_init_file();
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005444 qemu_set_log(LOG_TRACE);
5445
Denis V. Lunev10985132016-06-17 17:44:13 +03005446 /* find the command */
5447 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5448 if (!strcmp(cmdname, cmd->name)) {
5449 return cmd->handler(argc, argv);
5450 }
5451 }
Jeff Cody7db16892014-04-25 17:02:32 -04005452
Stuart Brady153859b2009-06-07 00:42:17 +01005453 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005454 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005455}