blob: 7e73c5c1da289ec415572c63458cfbfdce52937a [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
Marc-André Lureau49f95222022-04-20 17:25:49 +040028#include "qemu/help-texts.h"
Marc-André Lureau16a18f22022-03-23 19:57:35 +040029#include "qemu/qemu-progress.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080030#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010031#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050032#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010033#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010034#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010035#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010036#include "qapi/qmp/qdict.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010044#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020045#include "qemu/units.h"
Peter Maydell5df022c2022-02-26 18:07:23 +000046#include "qemu/memalign.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000047#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020048#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010049#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020050#include "block/blockjob.h"
Markus Armbrustere2c1c342022-12-21 14:35:49 +010051#include "block/dirty-bitmap.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080052#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010053#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030054#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000055#include "qemu/throttle.h"
56#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000057
Thomas Huth7e563bf2018-02-15 12:06:47 +010058#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020059 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040060
Anthony Liguoric227f092009-10-01 16:12:16 -050061typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010062 const char *name;
63 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050064} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010065
Federico Simoncelli8599ea42013-01-28 06:59:47 -050066enum {
67 OPTION_OUTPUT = 256,
68 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000069 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000070 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020071 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020072 OPTION_FLUSH_INTERVAL = 261,
73 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010074 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010075 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020076 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030077 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020078 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000079 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050080 OPTION_ADD = 269,
81 OPTION_REMOVE = 270,
82 OPTION_CLEAR = 271,
83 OPTION_ENABLE = 272,
84 OPTION_DISABLE = 273,
85 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050086 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020087 OPTION_FORCE = 276,
Eric Blake955171e2021-07-21 10:53:48 -050088 OPTION_SKIP_BROKEN = 277,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050089};
90
91typedef enum OutputFormat {
92 OFORMAT_JSON,
93 OFORMAT_HUMAN,
94} OutputFormat;
95
Kevin Wolfe6996142016-03-15 13:03:11 +010096/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040097#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000098
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010099static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +0000100{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100101 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +0000102}
103
Marc-André Lureau89057702022-04-20 17:26:02 +0400104static G_NORETURN G_GNUC_PRINTF(1, 2)
105void error_exit(const char *fmt, ...)
Fam Zhengac1307a2014-04-22 13:36:11 +0800106{
107 va_list ap;
108
Fam Zhengac1307a2014-04-22 13:36:11 +0800109 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200110 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800111 va_end(ap);
112
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200113 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800114 exit(EXIT_FAILURE);
115}
116
Marc-André Lureau89057702022-04-20 17:26:02 +0400117static G_NORETURN
118void missing_argument(const char *option)
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800119{
120 error_exit("missing argument for option '%s'", option);
121}
122
Marc-André Lureau89057702022-04-20 17:26:02 +0400123static G_NORETURN
124void unrecognized_option(const char *option)
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800125{
126 error_exit("unrecognized option '%s'", option);
127}
128
Eric Blake0562adf2020-05-12 20:16:41 -0500129/* Please keep in synch with docs/tools/qemu-img.rst */
Marc-André Lureau89057702022-04-20 17:26:02 +0400130static G_NORETURN
131void help(void)
bellardea2384d2004-08-01 21:59:26 +0000132{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100133 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400134 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300135 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300136 "QEMU disk image utility\n"
137 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300138 " '-h', '--help' display this help and exit\n"
139 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300140 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
141 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300142 "\n"
malc3f020d72010-02-08 12:04:56 +0300143 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100144#define DEF(option, callback, arg_string) \
145 " " arg_string "\n"
146#include "qemu-img-cmds.h"
147#undef DEF
malc3f020d72010-02-08 12:04:56 +0300148 "\n"
149 "Command parameters:\n"
150 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000151 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
152 " manual page for a description of the object properties. The most common\n"
153 " object type is a 'secret', which is used to supply passwords and/or\n"
154 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300155 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400156 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800157 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
158 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100159 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
160 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300161 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200162 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
163 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
164 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300165 " 'output_filename' is the destination disk image filename\n"
166 " 'output_fmt' is the destination format\n"
167 " 'options' is a comma separated list of format specific options in a\n"
Markus Armbruster7f118b42022-09-08 15:08:42 +0200168 " name=value format. Use -o help for an overview of the options supported by\n"
169 " the used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800170 " 'snapshot_param' is param used for internal snapshot, format\n"
171 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
172 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300173 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400174 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
175 " new backing file match exactly. The image doesn't need a working\n"
176 " backing file before rebasing in this case (useful for renaming the\n"
177 " backing file). For image creation, allow creating without attempting\n"
178 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300179 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200180 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100181 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200182 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
183 " contain only zeros for qemu-img to create a sparse image during\n"
184 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
185 " unallocated or zero sectors, and the destination image will always be\n"
186 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200187 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100188 " '-n' skips the target volume creation (useful if the volume is created\n"
189 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300190 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500191 "Parameters to bitmap subcommand:\n"
192 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
193 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
194 " or '--merge source'\n"
195 " '-g granularity' sets the granularity for '--add' actions\n"
196 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
197 " bitmaps from an alternative file\n"
198 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200199 "Parameters to check subcommand:\n"
200 " '-r' tries to repair any inconsistencies that are found during the check.\n"
201 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
202 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200203 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200204 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100205 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500206 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100207 " '-m' specifies how many coroutines work in parallel during the convert\n"
208 " process (defaults to 8)\n"
209 " '-W' allow to write to the target out of order rather than sequential\n"
210 "\n"
malc3f020d72010-02-08 12:04:56 +0300211 "Parameters to snapshot subcommand:\n"
212 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
213 " '-a' applies a snapshot (revert disk to saved state)\n"
214 " '-c' creates a snapshot\n"
215 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100216 " '-l' lists all snapshots in the given image\n"
217 "\n"
218 "Parameters to compare subcommand:\n"
219 " '-f' first image format\n"
220 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200221 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
222 "\n"
223 "Parameters to dd subcommand:\n"
224 " 'bs=BYTES' read and write up to BYTES bytes at a time "
225 "(default: 512)\n"
226 " 'count=N' copy only N input blocks\n"
227 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200228 " 'of=FILE' write to FILE\n"
229 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100230
231 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300232 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500233 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800234 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000235}
236
Markus Armbruster80c710c2020-04-15 09:49:26 +0200237/*
238 * Is @optarg safe for accumulate_options()?
239 * It is when multiple of them can be joined together separated by ','.
240 * To make that work, @optarg must not start with ',' (or else a
241 * separating ',' preceding it gets escaped), and it must not end with
242 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200243 * escaped), or be empty (or else a separating ',' preceding it can
244 * escape a separating ',' following it).
245 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200246 */
247static bool is_valid_option_list(const char *optarg)
248{
249 size_t len = strlen(optarg);
250 size_t i;
251
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200252 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200253 return false;
254 }
255
256 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
257 }
258 if ((len - i) % 2) {
259 return false;
260 }
261
262 return true;
263}
264
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200265static int accumulate_options(char **options, char *optarg)
266{
267 char *new_options;
268
269 if (!is_valid_option_list(optarg)) {
270 error_report("Invalid option list: %s", optarg);
271 return -1;
272 }
273
274 if (!*options) {
275 *options = g_strdup(optarg);
276 } else {
277 new_options = g_strdup_printf("%s,%s", *options, optarg);
278 g_free(*options);
279 *options = new_options;
280 }
281 return 0;
282}
283
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000284static QemuOptsList qemu_source_opts = {
285 .name = "source",
286 .implied_opt_name = "file",
287 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
288 .desc = {
289 { }
290 },
291};
292
Marc-André Lureau9edc6312022-02-20 20:39:25 +0400293static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100294{
295 int ret = 0;
296 if (!quiet) {
297 va_list args;
298 va_start(args, fmt);
299 ret = vprintf(fmt, args);
300 va_end(args);
301 }
302 return ret;
303}
304
bellardea2384d2004-08-01 21:59:26 +0000305
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100306static int print_block_option_help(const char *filename, const char *fmt)
307{
308 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800309 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500310 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100311
312 /* Find driver and parse its options */
313 drv = bdrv_find_format(fmt);
314 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100315 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100316 return 1;
317 }
318
Max Reitzd402b6a2018-05-09 23:00:21 +0200319 if (!drv->create_opts) {
320 error_report("Format driver '%s' does not support image creation", fmt);
321 return 1;
322 }
323
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800324 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100325 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500326 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100327 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100328 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800329 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100330 return 1;
331 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200332 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100333 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200334 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100335 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200336 return 1;
337 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800338 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100339 }
340
Max Reitzf4619af2019-04-13 17:20:37 +0200341 if (filename) {
342 printf("Supported options:\n");
343 } else {
344 printf("Supported %s options:\n", fmt);
345 }
Max Reitz63898712018-10-19 18:49:25 +0200346 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800347 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200348
349 if (!filename) {
350 printf("\n"
351 "The protocol level may support further options.\n"
352 "Specify the target filename to include those options.\n");
353 }
354
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100355 return 0;
356}
357
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000358
Max Reitzefaa7c42016-03-16 19:54:38 +0100359static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100360 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800361 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000362{
363 QDict *options;
364 Error *local_err = NULL;
365 BlockBackend *blk;
366 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800367 if (force_share) {
368 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200369 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800370 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200371 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800372 return NULL;
373 }
Max Reitz4615f872018-05-02 22:20:50 +0200374 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800375 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100376 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000377 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100378 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000379 return NULL;
380 }
Kevin Wolfce099542016-03-15 13:01:04 +0100381 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000382
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 return blk;
384}
385
Max Reitzefaa7c42016-03-16 19:54:38 +0100386static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100387 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000388 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800389 bool writethrough, bool quiet,
390 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000391{
392 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200393 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100394
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100395 if (!options) {
396 options = qdict_new();
397 }
bellard75c23802004-08-27 21:28:58 +0000398 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500399 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000400 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100401
Fam Zheng335e9932017-05-03 00:35:39 +0800402 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500403 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800404 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100405 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500406 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100407 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000408 return NULL;
bellard75c23802004-08-27 21:28:58 +0000409 }
Kevin Wolfce099542016-03-15 13:01:04 +0100410 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100411
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200412 return blk;
bellard75c23802004-08-27 21:28:58 +0000413}
414
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000415
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100416static int img_add_key_secrets(void *opaque,
417 const char *name, const char *value,
418 Error **errp)
419{
420 QDict *options = opaque;
421
422 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600423 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100424 }
425
426 return 0;
427}
428
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100429
Max Reitzefaa7c42016-03-16 19:54:38 +0100430static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000431 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100432 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800433 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000434{
435 BlockBackend *blk;
436 if (image_opts) {
437 QemuOpts *opts;
438 if (fmt) {
439 error_report("--image-opts and --format are mutually exclusive");
440 return NULL;
441 }
442 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
443 filename, true);
444 if (!opts) {
445 return NULL;
446 }
Fam Zheng335e9932017-05-03 00:35:39 +0800447 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
448 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000449 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100450 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800451 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000452 }
453 return blk;
454}
455
456
Chunyan Liu83d05212014-06-05 17:20:51 +0800457static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100458 const char *base_filename,
459 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200460{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200461 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200462 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200463 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100464 error_report("Backing file not supported for file format '%s'",
465 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900466 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200467 }
468 }
469 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200470 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100471 error_report("Backing file format not supported for file "
472 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900473 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200474 }
475 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900476 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200477}
478
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300479static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
480 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100481{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100482 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300483 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100484
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300485 err = qemu_strtosz(value, NULL, &res);
486 if (err < 0 && err != -ERANGE) {
487 error_report("Invalid %s specified. You may use "
488 "k, M, G, T, P or E suffixes for", name);
489 error_report("kilobytes, megabytes, gigabytes, terabytes, "
490 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100491 return err;
492 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300493 if (err == -ERANGE || res > max || res < min) {
494 error_report("Invalid %s specified. Must be between %" PRId64
495 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100496 return -ERANGE;
497 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300498 return res;
499}
500
501static int64_t cvtnum(const char *name, const char *value)
502{
503 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100504}
505
bellardea2384d2004-08-01 21:59:26 +0000506static int img_create(int argc, char **argv)
507{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200508 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100509 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000510 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000511 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000512 const char *filename;
513 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200514 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200515 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100516 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400517 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000518
bellardea2384d2004-08-01 21:59:26 +0000519 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000520 static const struct option long_options[] = {
521 {"help", no_argument, 0, 'h'},
522 {"object", required_argument, 0, OPTION_OBJECT},
523 {0, 0, 0, 0}
524 };
John Snow6e6e55f2017-07-17 20:34:22 -0400525 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000526 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100527 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000528 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100529 }
bellardea2384d2004-08-01 21:59:26 +0000530 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800531 case ':':
532 missing_argument(argv[optind - 1]);
533 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100534 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800535 unrecognized_option(argv[optind - 1]);
536 break;
bellardea2384d2004-08-01 21:59:26 +0000537 case 'h':
538 help();
539 break;
aliguori9230eaf2009-03-28 17:55:19 +0000540 case 'F':
541 base_fmt = optarg;
542 break;
bellardea2384d2004-08-01 21:59:26 +0000543 case 'b':
544 base_filename = optarg;
545 break;
546 case 'f':
547 fmt = optarg;
548 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200549 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200550 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100551 goto fail;
552 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200553 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100554 case 'q':
555 quiet = true;
556 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400557 case 'u':
558 flags |= BDRV_O_NO_BACKING;
559 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100560 case OPTION_OBJECT:
561 user_creatable_process_cmdline(optarg);
562 break;
bellardea2384d2004-08-01 21:59:26 +0000563 }
564 }
aliguori9230eaf2009-03-28 17:55:19 +0000565
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900566 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100567 filename = (optind < argc) ? argv[optind] : NULL;
568 if (options && has_help_option(options)) {
569 g_free(options);
570 return print_block_option_help(filename, fmt);
571 }
572
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100573 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800574 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100575 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100576 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900577
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100578 /* Get image size, if specified */
579 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100580 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100581
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300582 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100583 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100584 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100585 }
586 img_size = (uint64_t)sval;
587 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200588 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800589 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200590 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100591
Luiz Capitulino9b375252012-11-30 10:52:05 -0200592 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400593 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100594 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100595 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100596 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900597 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200598
Kevin Wolf77386bf2014-02-21 16:24:04 +0100599 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000600 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100601
602fail:
603 g_free(options);
604 return 1;
bellardea2384d2004-08-01 21:59:26 +0000605}
606
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100607static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100609 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500610 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100611 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600612
613 visit_type_ImageCheck(v, NULL, &check, &error_abort);
614 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100615 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500616 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100617 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200618 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600619 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100620 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500621}
622
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100623static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500624{
625 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100626 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500627 } else {
628 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
630 "Data may be corrupted, or further writes to the image "
631 "may corrupt it.\n",
632 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500633 }
634
635 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100636 qprintf(quiet,
637 "\n%" PRId64 " leaked clusters were found on the image.\n"
638 "This means waste of disk space, but no harm to data.\n",
639 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500640 }
641
642 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100643 qprintf(quiet,
644 "\n%" PRId64
645 " internal errors have occurred during the check.\n",
646 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647 }
648 }
649
650 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100651 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
652 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
653 check->allocated_clusters, check->total_clusters,
654 check->allocated_clusters * 100.0 / check->total_clusters,
655 check->fragmented_clusters * 100.0 / check->allocated_clusters,
656 check->compressed_clusters * 100.0 /
657 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500658 }
659
660 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100661 qprintf(quiet,
662 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500663 }
664}
665
666static int collect_image_check(BlockDriverState *bs,
667 ImageCheck *check,
668 const char *filename,
669 const char *fmt,
670 int fix)
671{
672 int ret;
673 BdrvCheckResult result;
674
675 ret = bdrv_check(bs, &result, fix);
676 if (ret < 0) {
677 return ret;
678 }
679
680 check->filename = g_strdup(filename);
681 check->format = g_strdup(bdrv_get_format_name(bs));
682 check->check_errors = result.check_errors;
683 check->corruptions = result.corruptions;
684 check->has_corruptions = result.corruptions != 0;
685 check->leaks = result.leaks;
686 check->has_leaks = result.leaks != 0;
687 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100688 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500689 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100690 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500691 check->image_end_offset = result.image_end_offset;
692 check->has_image_end_offset = result.image_end_offset != 0;
693 check->total_clusters = result.bfi.total_clusters;
694 check->has_total_clusters = result.bfi.total_clusters != 0;
695 check->allocated_clusters = result.bfi.allocated_clusters;
696 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
697 check->fragmented_clusters = result.bfi.fragmented_clusters;
698 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100699 check->compressed_clusters = result.bfi.compressed_clusters;
700 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500701
702 return 0;
703}
704
Kevin Wolfe076f332010-06-29 11:43:13 +0200705/*
706 * Checks an image for consistency. Exit codes:
707 *
Max Reitzd6635c42014-06-02 22:15:21 +0200708 * 0 - Check completed, image is good
709 * 1 - Check not completed because of internal errors
710 * 2 - Check completed, image is corrupted
711 * 3 - Check completed, image has leaked clusters, but is good otherwise
712 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200713 */
aliguori15859692009-04-21 23:11:53 +0000714static int img_check(int argc, char **argv)
715{
716 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500717 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200718 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200719 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000720 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200721 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100722 int flags = BDRV_O_CHECK;
723 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200724 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100725 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000726 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800727 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000728
729 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500730 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200731 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100732
aliguori15859692009-04-21 23:11:53 +0000733 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500734 int option_index = 0;
735 static const struct option long_options[] = {
736 {"help", no_argument, 0, 'h'},
737 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530738 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500739 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000740 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000741 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800742 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500743 {0, 0, 0, 0}
744 };
Fam Zheng335e9932017-05-03 00:35:39 +0800745 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500746 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100747 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000748 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100749 }
aliguori15859692009-04-21 23:11:53 +0000750 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800751 case ':':
752 missing_argument(argv[optind - 1]);
753 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100754 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800755 unrecognized_option(argv[optind - 1]);
756 break;
aliguori15859692009-04-21 23:11:53 +0000757 case 'h':
758 help();
759 break;
760 case 'f':
761 fmt = optarg;
762 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200763 case 'r':
764 flags |= BDRV_O_RDWR;
765
766 if (!strcmp(optarg, "leaks")) {
767 fix = BDRV_FIX_LEAKS;
768 } else if (!strcmp(optarg, "all")) {
769 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
770 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800771 error_exit("Unknown option value for -r "
772 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200773 }
774 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500775 case OPTION_OUTPUT:
776 output = optarg;
777 break;
Max Reitz40055952014-07-22 22:58:42 +0200778 case 'T':
779 cache = optarg;
780 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100781 case 'q':
782 quiet = true;
783 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800784 case 'U':
785 force_share = true;
786 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100787 case OPTION_OBJECT:
788 user_creatable_process_cmdline(optarg);
789 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000790 case OPTION_IMAGE_OPTS:
791 image_opts = true;
792 break;
aliguori15859692009-04-21 23:11:53 +0000793 }
794 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200795 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800796 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100797 }
aliguori15859692009-04-21 23:11:53 +0000798 filename = argv[optind++];
799
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500800 if (output && !strcmp(output, "json")) {
801 output_format = OFORMAT_JSON;
802 } else if (output && !strcmp(output, "human")) {
803 output_format = OFORMAT_HUMAN;
804 } else if (output) {
805 error_report("--output must be used with human or json as argument.");
806 return 1;
807 }
808
Kevin Wolfce099542016-03-15 13:01:04 +0100809 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200810 if (ret < 0) {
811 error_report("Invalid source cache option: %s", cache);
812 return 1;
813 }
814
Fam Zheng335e9932017-05-03 00:35:39 +0800815 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
816 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200817 if (!blk) {
818 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900819 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200820 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500821
822 check = g_new0(ImageCheck, 1);
823 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200824
825 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200826 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200827 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500828 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200829 }
830
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500831 if (check->corruptions_fixed || check->leaks_fixed) {
832 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100833 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834
835 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100836 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500837 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100838 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500839
840 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100841 qprintf(quiet,
842 "The following inconsistencies were found and repaired:\n\n"
843 " %" PRId64 " leaked clusters\n"
844 " %" PRId64 " corruptions\n\n"
845 "Double checking the fixed image now...\n",
846 check->leaks_fixed,
847 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500848 }
849
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800850 qapi_free_ImageCheck(check);
851 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500852 ret = collect_image_check(bs, check, filename, fmt, 0);
853
854 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100855 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500856 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100857 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200858 }
859
Max Reitz832390a2014-10-23 15:29:12 +0200860 if (!ret) {
861 switch (output_format) {
862 case OFORMAT_HUMAN:
863 dump_human_image_check(check, quiet);
864 break;
865 case OFORMAT_JSON:
866 dump_json_image_check(check, quiet);
867 break;
868 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500869 }
870
871 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200872 if (ret) {
873 error_report("Check failed: %s", strerror(-ret));
874 } else {
875 error_report("Check failed");
876 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500877 ret = 1;
878 goto fail;
879 }
880
881 if (check->corruptions) {
882 ret = 2;
883 } else if (check->leaks) {
884 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200885 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500886 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000887 }
888
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500889fail:
890 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200891 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500892 return ret;
aliguori15859692009-04-21 23:11:53 +0000893}
894
Max Reitzd4a32382014-10-24 15:57:37 +0200895typedef struct CommonBlockJobCBInfo {
896 BlockDriverState *bs;
897 Error **errp;
898} CommonBlockJobCBInfo;
899
900static void common_block_job_cb(void *opaque, int ret)
901{
902 CommonBlockJobCBInfo *cbi = opaque;
903
904 if (ret < 0) {
905 error_setg_errno(cbi->errp, -ret, "Block job failed");
906 }
Max Reitzd4a32382014-10-24 15:57:37 +0200907}
908
909static void run_block_job(BlockJob *job, Error **errp)
910{
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200911 uint64_t progress_current, progress_total;
Vladimir Sementsov-Ogievskiydf9a3162021-05-06 17:13:53 +0300912 AioContext *aio_context = block_job_get_aio_context(job);
sochin.jiang4172a002017-06-15 14:47:33 +0800913 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200914
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400915 job_lock();
916 job_ref_locked(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200917 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200918 float progress = 0.0f;
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400919 job_unlock();
Max Reitzd4a32382014-10-24 15:57:37 +0200920 aio_poll(aio_context, true);
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200921
922 progress_get_snapshot(&job->job.progress, &progress_current,
923 &progress_total);
924 if (progress_total) {
925 progress = (float)progress_current / progress_total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200926 }
927 qemu_progress_print(progress, 0);
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400928 job_lock();
929 } while (!job_is_ready_locked(&job->job) &&
930 !job_is_completed_locked(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200931
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400932 if (!job_is_completed_locked(&job->job)) {
933 ret = job_complete_sync_locked(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800934 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200935 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800936 }
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400937 job_unref_locked(&job->job);
938 job_unlock();
Max Reitz687fa1d2014-10-24 15:57:39 +0200939
sochin.jiang4172a002017-06-15 14:47:33 +0800940 /* publish completion progress only when success */
941 if (!ret) {
942 qemu_progress_print(100.f, 0);
943 }
Max Reitzd4a32382014-10-24 15:57:37 +0200944}
945
bellardea2384d2004-08-01 21:59:26 +0000946static int img_commit(int argc, char **argv)
947{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400948 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200949 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200950 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200951 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100952 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200953 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100954 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200955 Error *local_err = NULL;
956 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000957 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200958 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000959 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000960
961 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400962 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200963 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000964 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000965 static const struct option long_options[] = {
966 {"help", no_argument, 0, 'h'},
967 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000968 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000969 {0, 0, 0, 0}
970 };
Zhenguia0441b62020-10-20 14:47:43 +0000971 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000972 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100973 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000974 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100975 }
bellardea2384d2004-08-01 21:59:26 +0000976 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800977 case ':':
978 missing_argument(argv[optind - 1]);
979 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100980 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800981 unrecognized_option(argv[optind - 1]);
982 break;
bellardea2384d2004-08-01 21:59:26 +0000983 case 'h':
984 help();
985 break;
986 case 'f':
987 fmt = optarg;
988 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400989 case 't':
990 cache = optarg;
991 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200992 case 'b':
993 base = optarg;
994 /* -b implies -d */
995 drop = true;
996 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200997 case 'd':
998 drop = true;
999 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001000 case 'p':
1001 progress = true;
1002 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001003 case 'q':
1004 quiet = true;
1005 break;
Zhenguia0441b62020-10-20 14:47:43 +00001006 case 'r':
1007 rate_limit = cvtnum("rate limit", optarg);
1008 if (rate_limit < 0) {
1009 return 1;
1010 }
1011 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001012 case OPTION_OBJECT:
1013 user_creatable_process_cmdline(optarg);
1014 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001015 case OPTION_IMAGE_OPTS:
1016 image_opts = true;
1017 break;
bellardea2384d2004-08-01 21:59:26 +00001018 }
1019 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001020
1021 /* Progress is not shown in Quiet mode */
1022 if (quiet) {
1023 progress = false;
1024 }
1025
Kevin Wolffc11eb22013-08-05 10:53:04 +02001026 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001027 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001028 }
bellardea2384d2004-08-01 21:59:26 +00001029 filename = argv[optind++];
1030
Max Reitz9a86fe42014-10-24 15:57:38 +02001031 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001032 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001033 if (ret < 0) {
1034 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001035 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001036 }
1037
Fam Zheng335e9932017-05-03 00:35:39 +08001038 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1039 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001040 if (!blk) {
1041 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001042 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001043 bs = blk_bs(blk);
1044
Max Reitz687fa1d2014-10-24 15:57:39 +02001045 qemu_progress_init(progress, 1.f);
1046 qemu_progress_print(0.f, 100);
1047
Max Reitz1b22bff2014-10-24 15:57:40 +02001048 if (base) {
1049 base_bs = bdrv_find_backing_image(bs, base);
1050 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001051 error_setg(&local_err,
1052 "Did not find '%s' in the backing chain of '%s'",
1053 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001054 goto done;
1055 }
1056 } else {
1057 /* This is different from QMP, which by default uses the deepest file in
1058 * the backing chain (i.e., the very base); however, the traditional
1059 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001060 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001061 if (!base_bs) {
1062 error_setg(&local_err, "Image does not have a backing file");
1063 goto done;
1064 }
bellardea2384d2004-08-01 21:59:26 +00001065 }
1066
Max Reitzd4a32382014-10-24 15:57:37 +02001067 cbi = (CommonBlockJobCBInfo){
1068 .errp = &local_err,
1069 .bs = bs,
1070 };
1071
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001072 aio_context = bdrv_get_aio_context(bs);
1073 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001074 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001075 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001076 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001077 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001078 if (local_err) {
1079 goto done;
1080 }
1081
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001082 /* When the block job completes, the BlockBackend reference will point to
1083 * the old backing file. In order to avoid that the top image is already
1084 * deleted, so we can still empty it afterwards, increment the reference
1085 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001086 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001087 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001088 }
1089
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001090 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001091 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001092 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001093 if (local_err) {
1094 goto unref_backing;
1095 }
1096
Max Reitz2d97fde2020-04-29 16:11:26 +02001097 if (!drop) {
1098 BlockBackend *old_backing_blk;
1099
1100 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1101 &local_err);
1102 if (!old_backing_blk) {
1103 goto unref_backing;
1104 }
1105 ret = blk_make_empty(old_backing_blk, &local_err);
1106 blk_unref(old_backing_blk);
1107 if (ret == -ENOTSUP) {
1108 error_free(local_err);
1109 local_err = NULL;
1110 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001111 goto unref_backing;
1112 }
1113 }
1114
1115unref_backing:
1116 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001117 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001118 }
Max Reitzd4a32382014-10-24 15:57:37 +02001119
1120done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001121 qemu_progress_end();
1122
Markus Armbruster26f54e92014-10-07 13:59:04 +02001123 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001124
1125 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001126 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001127 return 1;
1128 }
Max Reitzd4a32382014-10-24 15:57:37 +02001129
1130 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001131 return 0;
1132}
1133
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001134/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001135 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1136 * of the first sector boundary within buf where the sector contains a
1137 * non-zero byte. This function is robust to a buffer that is not
1138 * sector-aligned.
1139 */
1140static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1141{
1142 int64_t i;
1143 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1144
1145 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1146 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1147 return i;
1148 }
1149 }
1150 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1151 return i;
1152 }
1153 return -1;
1154}
1155
1156/*
thsf58c7b32008-06-05 21:53:49 +00001157 * Returns true iff the first sector pointed to by 'buf' contains at least
1158 * a non-NUL byte.
1159 *
1160 * 'pnum' is set to the number of sectors (including and immediately following
1161 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001162 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001163 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001164 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001165 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001166static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1167 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001168{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001169 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001170 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001171
1172 if (n <= 0) {
1173 *pnum = 0;
1174 return 0;
1175 }
Yi Lic075c422020-08-19 09:36:07 +08001176 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001177 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001178 buf += BDRV_SECTOR_SIZE;
1179 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001180 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001181 }
bellardea2384d2004-08-01 21:59:26 +00001182 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001183
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001184 if (i == n) {
1185 /*
1186 * The whole buf is the same.
1187 * No reason to split it into chunks, so return now.
1188 */
1189 *pnum = i;
1190 return !is_zero;
1191 }
1192
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001193 tail = (sector_num + i) & (alignment - 1);
1194 if (tail) {
1195 if (is_zero && i <= tail) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001196 /*
1197 * For sure next sector after i is data, and it will rewrite this
1198 * tail anyway due to RMW. So, let's just write data now.
1199 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001200 is_zero = false;
1201 }
1202 if (!is_zero) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001203 /* If possible, align up end offset of allocated areas. */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001204 i += alignment - tail;
1205 i = MIN(i, n);
1206 } else {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001207 /*
1208 * For sure next sector after i is data, and it will rewrite this
1209 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1210 * to aligned bound.
1211 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001212 i -= tail;
1213 }
1214 }
bellardea2384d2004-08-01 21:59:26 +00001215 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001216 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001217}
1218
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001219/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001220 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1221 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1222 * breaking up write requests for only small sparse areas.
1223 */
1224static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001225 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001226{
1227 int ret;
1228 int num_checked, num_used;
1229
1230 if (n < min) {
1231 min = n;
1232 }
1233
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001234 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001235 if (!ret) {
1236 return ret;
1237 }
1238
1239 num_used = *pnum;
1240 buf += BDRV_SECTOR_SIZE * *pnum;
1241 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001242 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001243 num_checked = num_used;
1244
1245 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001246 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001247
1248 buf += BDRV_SECTOR_SIZE * *pnum;
1249 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001250 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001251 num_checked += *pnum;
1252 if (ret) {
1253 num_used = num_checked;
1254 } else if (*pnum >= min) {
1255 break;
1256 }
1257 }
1258
1259 *pnum = num_used;
1260 return 1;
1261}
1262
1263/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001264 * Compares two buffers sector by sector. Returns 0 if the first
1265 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001266 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001267 * pnum is set to the sector-aligned size of the buffer prefix that
1268 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001269 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001270static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1271 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001272{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001273 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001274 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001275
Eric Blakedc61cd32017-10-11 22:47:14 -05001276 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001277
Eric Blakedc61cd32017-10-11 22:47:14 -05001278 res = !!memcmp(buf1, buf2, i);
1279 while (i < bytes) {
1280 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001281
Eric Blakedc61cd32017-10-11 22:47:14 -05001282 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001283 break;
1284 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001285 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001286 }
1287
1288 *pnum = i;
1289 return res;
1290}
1291
Stefano Garzarella97ede572019-05-08 12:43:24 +02001292#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001293
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001294/*
1295 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1296 *
Eric Blake0608e402017-10-11 22:47:12 -05001297 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1298 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1299 * failure), and 4 on error (the exit status for read errors), after emitting
1300 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001301 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001302 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001303 * @param offset: Starting offset to check
1304 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001305 * @param filename: Name of disk file we are checking (logging purpose)
1306 * @param buffer: Allocated buffer for storing read data
1307 * @param quiet: Flag for quiet mode
1308 */
Eric Blakec41508e2017-10-11 22:47:13 -05001309static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1310 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311 uint8_t *buffer, bool quiet)
1312{
Eric Blakedebb38a2017-10-11 22:47:11 -05001313 int ret = 0;
1314 int64_t idx;
1315
Alberto Fariaa9262f52022-07-05 17:15:11 +01001316 ret = blk_pread(blk, offset, bytes, buffer, 0);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001317 if (ret < 0) {
1318 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001319 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001320 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001321 }
Eric Blakec41508e2017-10-11 22:47:13 -05001322 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001323 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001324 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001325 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001326 return 1;
1327 }
1328
1329 return 0;
1330}
1331
1332/*
1333 * Compares two images. Exit codes:
1334 *
Kevin Wolf99b1e642021-02-17 12:56:45 +01001335 * 0 - Images are identical or the requested help was printed
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001336 * 1 - Images differ
1337 * >1 - Error occurred
1338 */
1339static int img_compare(int argc, char **argv)
1340{
Max Reitz40055952014-07-22 22:58:42 +02001341 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001342 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001343 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001344 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001346 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001347 int allocated1, allocated2;
1348 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1349 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001350 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001351 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001352 int64_t total_size;
1353 int64_t offset = 0;
1354 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001355 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001356 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001357 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001358 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359
Max Reitz40055952014-07-22 22:58:42 +02001360 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001361 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001362 static const struct option long_options[] = {
1363 {"help", no_argument, 0, 'h'},
1364 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001365 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001366 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001367 {0, 0, 0, 0}
1368 };
Fam Zheng335e9932017-05-03 00:35:39 +08001369 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001370 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001371 if (c == -1) {
1372 break;
1373 }
1374 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001375 case ':':
1376 missing_argument(argv[optind - 1]);
1377 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001379 unrecognized_option(argv[optind - 1]);
1380 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381 case 'h':
1382 help();
1383 break;
1384 case 'f':
1385 fmt1 = optarg;
1386 break;
1387 case 'F':
1388 fmt2 = optarg;
1389 break;
Max Reitz40055952014-07-22 22:58:42 +02001390 case 'T':
1391 cache = optarg;
1392 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 case 'p':
1394 progress = true;
1395 break;
1396 case 'q':
1397 quiet = true;
1398 break;
1399 case 's':
1400 strict = true;
1401 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001402 case 'U':
1403 force_share = true;
1404 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001405 case OPTION_OBJECT:
1406 {
1407 Error *local_err = NULL;
1408
1409 if (!user_creatable_add_from_str(optarg, &local_err)) {
1410 if (local_err) {
1411 error_report_err(local_err);
1412 exit(2);
1413 } else {
1414 /* Help was printed */
1415 exit(EXIT_SUCCESS);
1416 }
1417 }
1418 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001419 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001420 case OPTION_IMAGE_OPTS:
1421 image_opts = true;
1422 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001423 }
1424 }
1425
1426 /* Progress is not shown in Quiet mode */
1427 if (quiet) {
1428 progress = false;
1429 }
1430
1431
Kevin Wolffc11eb22013-08-05 10:53:04 +02001432 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001433 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434 }
1435 filename1 = argv[optind++];
1436 filename2 = argv[optind++];
1437
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001438 /* Initialize before goto out */
1439 qemu_progress_init(progress, 2.0);
1440
Kevin Wolfce099542016-03-15 13:01:04 +01001441 flags = 0;
1442 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001443 if (ret < 0) {
1444 error_report("Invalid source cache option: %s", cache);
1445 ret = 2;
1446 goto out3;
1447 }
1448
Fam Zheng335e9932017-05-03 00:35:39 +08001449 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1450 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001451 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001452 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001453 goto out3;
1454 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001455
Fam Zheng335e9932017-05-03 00:35:39 +08001456 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1457 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001458 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001459 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001460 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001461 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001462 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001463 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001464
Max Reitzf1d3cd72015-02-05 13:58:18 -05001465 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1466 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001467 total_size1 = blk_getlength(blk1);
1468 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001469 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001470 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001471 ret = 4;
1472 goto out;
1473 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001474 total_size2 = blk_getlength(blk2);
1475 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001476 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001477 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001478 ret = 4;
1479 goto out;
1480 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001481 total_size = MIN(total_size1, total_size2);
1482 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483
1484 qemu_progress_print(0, 100);
1485
Eric Blake033d9fc2017-10-11 22:47:16 -05001486 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487 ret = 1;
1488 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1489 goto out;
1490 }
1491
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001493 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001494
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 status1 = bdrv_block_status_above(bs1, NULL, offset,
1496 total_size1 - offset, &pnum1, NULL,
1497 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001498 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001499 ret = 3;
1500 error_report("Sector allocation test failed for %s", filename1);
1501 goto out;
1502 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001503 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504
Eric Blake033d9fc2017-10-11 22:47:16 -05001505 status2 = bdrv_block_status_above(bs2, NULL, offset,
1506 total_size2 - offset, &pnum2, NULL,
1507 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001508 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 ret = 3;
1510 error_report("Sector allocation test failed for %s", filename2);
1511 goto out;
1512 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001513 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001514
1515 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001516 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001517
Fam Zheng25ad8e62016-01-13 16:37:41 +08001518 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001519 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001520 ret = 1;
1521 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001522 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001523 goto out;
1524 }
1525 }
1526 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001527 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001528 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001529 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001530 int64_t pnum;
1531
Eric Blake033d9fc2017-10-11 22:47:16 -05001532 chunk = MIN(chunk, IO_BUF_SIZE);
Alberto Fariaa9262f52022-07-05 17:15:11 +01001533 ret = blk_pread(blk1, offset, chunk, buf1, 0);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534 if (ret < 0) {
1535 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001536 " of %s: %s",
1537 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001538 ret = 4;
1539 goto out;
1540 }
Alberto Fariaa9262f52022-07-05 17:15:11 +01001541 ret = blk_pread(blk2, offset, chunk, buf2, 0);
Eric Blake033d9fc2017-10-11 22:47:16 -05001542 if (ret < 0) {
1543 error_report("Error while reading offset %" PRId64
1544 " of %s: %s",
1545 offset, filename2, strerror(-ret));
1546 ret = 4;
1547 goto out;
1548 }
1549 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1550 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001552 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001553 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001554 goto out;
1555 }
1556 }
1557 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001558 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001559 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001560 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001561 filename1, buf1, quiet);
1562 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001563 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001564 filename2, buf1, quiet);
1565 }
1566 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001567 goto out;
1568 }
1569 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001570 offset += chunk;
1571 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001572 }
1573
Eric Blake033d9fc2017-10-11 22:47:16 -05001574 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001575 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001576 const char *filename_over;
1577
1578 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001579 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001580 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001581 filename_over = filename1;
1582 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001583 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001584 filename_over = filename2;
1585 }
1586
Eric Blake033d9fc2017-10-11 22:47:16 -05001587 while (offset < progress_base) {
1588 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1589 progress_base - offset, &chunk,
1590 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001591 if (ret < 0) {
1592 ret = 3;
1593 error_report("Sector allocation test failed for %s",
1594 filename_over);
1595 goto out;
1596
1597 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001598 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001599 chunk = MIN(chunk, IO_BUF_SIZE);
1600 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001601 filename_over, buf1, quiet);
1602 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001603 goto out;
1604 }
1605 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001606 offset += chunk;
1607 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001608 }
1609 }
1610
1611 qprintf(quiet, "Images are identical.\n");
1612 ret = 0;
1613
1614out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001615 qemu_vfree(buf1);
1616 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001617 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001618out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001619 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001620out3:
1621 qemu_progress_end();
1622 return ret;
1623}
1624
Eric Blake6c729dd2020-05-21 14:21:35 -05001625/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1626static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1627 const char *src_node, const char *src_name,
1628 Error **errp)
1629{
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001630 BlockDirtyBitmapOrStr *merge_src;
1631 BlockDirtyBitmapOrStrList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001632
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001633 merge_src = g_new0(BlockDirtyBitmapOrStr, 1);
Eric Blake6c729dd2020-05-21 14:21:35 -05001634 merge_src->type = QTYPE_QDICT;
1635 merge_src->u.external.node = g_strdup(src_node);
1636 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001637 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001638 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001639 qapi_free_BlockDirtyBitmapOrStrList(list);
Eric Blake6c729dd2020-05-21 14:21:35 -05001640}
1641
Kevin Wolf690c7302015-03-19 13:33:32 +01001642enum ImgConvertBlockStatus {
1643 BLK_DATA,
1644 BLK_ZERO,
1645 BLK_BACKING_FILE,
1646};
1647
Peter Lieven2d9187b2017-02-28 13:40:07 +01001648#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001649#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001650
Kevin Wolf690c7302015-03-19 13:33:32 +01001651typedef struct ImgConvertState {
1652 BlockBackend **src;
1653 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001654 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001655 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001656 int64_t total_sectors;
1657 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001658 int64_t allocated_done;
1659 int64_t sector_num;
1660 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001661 enum ImgConvertBlockStatus status;
1662 int64_t sector_next_status;
1663 BlockBackend *target;
1664 bool has_zero_init;
1665 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001666 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001667 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001668 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001669 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001670 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001671 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001672 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001674 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001675 size_t cluster_sectors;
1676 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001677 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001678 int running_coroutines;
1679 Coroutine *co[MAX_COROUTINES];
1680 int64_t wait_sector_num[MAX_COROUTINES];
1681 CoMutex lock;
1682 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001683} ImgConvertState;
1684
Peter Lieven2d9187b2017-02-28 13:40:07 +01001685static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1686 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001687{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001688 *src_cur = 0;
1689 *src_cur_offset = 0;
1690 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1691 *src_cur_offset += s->src_sectors[*src_cur];
1692 (*src_cur)++;
1693 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001694 }
1695}
1696
1697static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1698{
Eric Blake31826642017-10-11 22:47:08 -05001699 int64_t src_cur_offset;
1700 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001701 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001702
Peter Lieven2d9187b2017-02-28 13:40:07 +01001703 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001704
1705 assert(s->total_sectors > sector_num);
1706 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1707
Max Reitz351c8ef2018-05-01 18:57:49 +02001708 if (s->target_backing_sectors >= 0) {
1709 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001710 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001711 } else if (sector_num + n > s->target_backing_sectors) {
1712 /* Split requests around target_backing_sectors (because
1713 * starting from there, zeros are handled differently) */
1714 n = s->target_backing_sectors - sector_num;
1715 }
1716 }
1717
Kevin Wolf690c7302015-03-19 13:33:32 +01001718 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001719 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1720 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001721 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001722 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1723 BlockDriverState *base;
1724
1725 if (s->target_has_backing) {
1726 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1727 } else {
1728 base = NULL;
1729 }
Eric Blake31826642017-10-11 22:47:08 -05001730
Max Reitz8eaac022019-05-07 22:35:03 +02001731 do {
1732 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001733
Max Reitz4a2061e2019-06-12 19:00:30 +02001734 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1735 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001736
1737 if (ret < 0) {
1738 if (s->salvage) {
1739 if (n == 1) {
1740 if (!s->quiet) {
1741 warn_report("error while reading block status at "
1742 "offset %" PRIu64 ": %s", offset,
1743 strerror(-ret));
1744 }
1745 /* Just try to read the data, then */
1746 ret = BDRV_BLOCK_DATA;
1747 count = BDRV_SECTOR_SIZE;
1748 } else {
1749 /* Retry on a shorter range */
1750 n = DIV_ROUND_UP(n, 4);
1751 }
1752 } else {
1753 error_report("error while reading block status at offset "
1754 "%" PRIu64 ": %s", offset, strerror(-ret));
1755 return ret;
1756 }
1757 }
1758 } while (ret < 0);
1759
Eric Blake31826642017-10-11 22:47:08 -05001760 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001761
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001762 /*
1763 * Avoid that s->sector_next_status becomes unaligned to the source
1764 * request alignment and/or cluster size to avoid unnecessary read
1765 * cycles.
1766 */
1767 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1768 if (n > tail) {
1769 n -= tail;
1770 }
1771
Kevin Wolf690c7302015-03-19 13:33:32 +01001772 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001773 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001774 } else if (ret & BDRV_BLOCK_DATA) {
1775 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001776 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001777 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001778 }
1779
1780 s->sector_next_status = sector_num + n;
1781 }
1782
1783 n = MIN(n, s->sector_next_status - sector_num);
1784 if (s->status == BLK_DATA) {
1785 n = MIN(n, s->buf_sectors);
1786 }
1787
1788 /* We need to write complete clusters for compressed images, so if an
1789 * unallocated area is shorter than that, we must consider the whole
1790 * cluster allocated. */
1791 if (s->compressed) {
1792 if (n < s->cluster_sectors) {
1793 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1794 s->status = BLK_DATA;
1795 } else {
1796 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1797 }
1798 }
1799
1800 return n;
1801}
1802
Peter Lieven2d9187b2017-02-28 13:40:07 +01001803static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1804 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001805{
Max Reitz8eaac022019-05-07 22:35:03 +02001806 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001807 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001808
Kevin Wolf690c7302015-03-19 13:33:32 +01001809 assert(nb_sectors <= s->buf_sectors);
1810 while (nb_sectors > 0) {
1811 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001812 int src_cur;
1813 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001814 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001815
1816 /* In the case of compression with multiple source files, we can get a
1817 * nb_sectors that spreads into the next part. So we must be able to
1818 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001819 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1820 blk = s->src[src_cur];
1821 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001822
Max Reitz8eaac022019-05-07 22:35:03 +02001823 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001824
Max Reitz8eaac022019-05-07 22:35:03 +02001825 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1826 if (single_read_until > offset) {
1827 n = 1;
1828 }
1829
1830 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001831 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001832 if (s->salvage) {
1833 if (n > 1) {
1834 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1835 continue;
1836 } else {
1837 if (!s->quiet) {
1838 warn_report("error while reading offset %" PRIu64
1839 ": %s", offset, strerror(-ret));
1840 }
1841 memset(buf, 0, BDRV_SECTOR_SIZE);
1842 }
1843 } else {
1844 return ret;
1845 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001846 }
1847
1848 sector_num += n;
1849 nb_sectors -= n;
1850 buf += n * BDRV_SECTOR_SIZE;
1851 }
1852
1853 return 0;
1854}
1855
Peter Lieven2d9187b2017-02-28 13:40:07 +01001856
1857static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1858 int nb_sectors, uint8_t *buf,
1859 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001860{
1861 int ret;
1862
1863 while (nb_sectors > 0) {
1864 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001865 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1866
Peter Lieven2d9187b2017-02-28 13:40:07 +01001867 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001868 case BLK_BACKING_FILE:
1869 /* If we have a backing file, leave clusters unallocated that are
1870 * unallocated in the source image, so that the backing file is
1871 * visible at the respective offset. */
1872 assert(s->target_has_backing);
1873 break;
1874
1875 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001876 /* If we're told to keep the target fully allocated (-S 0) or there
1877 * is real non-zero data, we must write it. Otherwise we can treat
1878 * it as zero sectors.
1879 * Compressed clusters need to be written as a whole, so in that
1880 * case we can only save the write if the buffer is completely
1881 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001882 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001883 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001884 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1885 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001886 (s->compressed &&
1887 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001888 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001889 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1890 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001891 if (ret < 0) {
1892 return ret;
1893 }
1894 break;
1895 }
1896 /* fall-through */
1897
1898 case BLK_ZERO:
1899 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001900 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001901 break;
1902 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001903 ret = blk_co_pwrite_zeroes(s->target,
1904 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001905 n << BDRV_SECTOR_BITS,
1906 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001907 if (ret < 0) {
1908 return ret;
1909 }
1910 break;
1911 }
1912
1913 sector_num += n;
1914 nb_sectors -= n;
1915 buf += n * BDRV_SECTOR_SIZE;
1916 }
1917
1918 return 0;
1919}
1920
Fam Zhengee5306d2018-06-01 17:26:48 +08001921static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1922 int nb_sectors)
1923{
1924 int n, ret;
1925
1926 while (nb_sectors > 0) {
1927 BlockBackend *blk;
1928 int src_cur;
1929 int64_t bs_sectors, src_cur_offset;
1930 int64_t offset;
1931
1932 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1933 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1934 blk = s->src[src_cur];
1935 bs_sectors = s->src_sectors[src_cur];
1936
1937 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1938
1939 ret = blk_co_copy_range(blk, offset, s->target,
1940 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001941 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001942 if (ret < 0) {
1943 return ret;
1944 }
1945
1946 sector_num += n;
1947 nb_sectors -= n;
1948 }
1949 return 0;
1950}
1951
Peter Lieven2d9187b2017-02-28 13:40:07 +01001952static void coroutine_fn convert_co_do_copy(void *opaque)
1953{
1954 ImgConvertState *s = opaque;
1955 uint8_t *buf = NULL;
1956 int ret, i;
1957 int index = -1;
1958
1959 for (i = 0; i < s->num_coroutines; i++) {
1960 if (s->co[i] == qemu_coroutine_self()) {
1961 index = i;
1962 break;
1963 }
1964 }
1965 assert(index >= 0);
1966
1967 s->running_coroutines++;
1968 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1969
1970 while (1) {
1971 int n;
1972 int64_t sector_num;
1973 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001974 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975
1976 qemu_co_mutex_lock(&s->lock);
1977 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1978 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001979 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001980 }
1981 n = convert_iteration_sectors(s, s->sector_num);
1982 if (n < 0) {
1983 qemu_co_mutex_unlock(&s->lock);
1984 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001985 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001986 }
1987 /* save current sector and allocation status to local variables */
1988 sector_num = s->sector_num;
1989 status = s->status;
1990 if (!s->min_sparse && s->status == BLK_ZERO) {
1991 n = MIN(n, s->buf_sectors);
1992 }
1993 /* increment global sector counter so that other coroutines can
1994 * already continue reading beyond this request */
1995 s->sector_num += n;
1996 qemu_co_mutex_unlock(&s->lock);
1997
1998 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1999 s->allocated_done += n;
2000 qemu_progress_print(100.0 * s->allocated_done /
2001 s->allocated_sectors, 0);
2002 }
2003
Fam Zhengee5306d2018-06-01 17:26:48 +08002004retry:
2005 copy_range = s->copy_range && s->status == BLK_DATA;
2006 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002007 ret = convert_co_read(s, sector_num, n, buf);
2008 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002009 error_report("error while reading at byte %lld: %s",
2010 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002011 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002012 }
2013 } else if (!s->min_sparse && status == BLK_ZERO) {
2014 status = BLK_DATA;
2015 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2016 }
2017
2018 if (s->wr_in_order) {
2019 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002020 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002021 s->wait_sector_num[index] = sector_num;
2022 qemu_coroutine_yield();
2023 }
2024 s->wait_sector_num[index] = -1;
2025 }
2026
Anton Nefedovb91127e2017-04-26 11:33:15 +03002027 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002028 if (copy_range) {
2029 ret = convert_co_copy_range(s, sector_num, n);
2030 if (ret) {
2031 s->copy_range = false;
2032 goto retry;
2033 }
2034 } else {
2035 ret = convert_co_write(s, sector_num, n, buf, status);
2036 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002037 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002038 error_report("error while writing at byte %lld: %s",
2039 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002040 s->ret = ret;
2041 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002042 }
2043
2044 if (s->wr_in_order) {
2045 /* reenter the coroutine that might have waited
2046 * for this write to complete */
2047 s->wr_offs = sector_num + n;
2048 for (i = 0; i < s->num_coroutines; i++) {
2049 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2050 /*
2051 * A -> B -> A cannot occur because A has
2052 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2053 * B will never enter A during this time window.
2054 */
2055 qemu_coroutine_enter(s->co[i]);
2056 break;
2057 }
2058 }
2059 }
2060 }
2061
Peter Lieven2d9187b2017-02-28 13:40:07 +01002062 qemu_vfree(buf);
2063 s->co[index] = NULL;
2064 s->running_coroutines--;
2065 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2066 /* the convert job finished successfully */
2067 s->ret = 0;
2068 }
2069}
2070
Kevin Wolf690c7302015-03-19 13:33:32 +01002071static int convert_do_copy(ImgConvertState *s)
2072{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002073 int ret, i, n;
2074 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002075
2076 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002077 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2078 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002079 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002080 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002081
Kevin Wolf690c7302015-03-19 13:33:32 +01002082 /* Allocate buffer for copied data. For compressed images, only one cluster
2083 * can be copied at a time. */
2084 if (s->compressed) {
2085 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2086 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002087 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002088 }
2089 s->buf_sectors = s->cluster_sectors;
2090 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002091
Kevin Wolf690c7302015-03-19 13:33:32 +01002092 while (sector_num < s->total_sectors) {
2093 n = convert_iteration_sectors(s, sector_num);
2094 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002095 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002096 }
Max Reitzaad15de2016-03-24 23:33:57 +01002097 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2098 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002099 s->allocated_sectors += n;
2100 }
2101 sector_num += n;
2102 }
2103
2104 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002105 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002106 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002107
Peter Lieven2d9187b2017-02-28 13:40:07 +01002108 qemu_co_mutex_init(&s->lock);
2109 for (i = 0; i < s->num_coroutines; i++) {
2110 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2111 s->wait_sector_num[i] = -1;
2112 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002113 }
2114
Anton Nefedovb91127e2017-04-26 11:33:15 +03002115 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002116 main_loop_wait(false);
2117 }
2118
2119 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002120 /* signal EOF to align */
Alberto Faria0cadf2c2022-07-05 17:15:18 +01002121 ret = blk_pwrite_compressed(s->target, 0, 0, NULL);
Kevin Wolf690c7302015-03-19 13:33:32 +01002122 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002123 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002124 }
2125 }
2126
Peter Lieven2d9187b2017-02-28 13:40:07 +01002127 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002128}
2129
Eric Blake74a43202021-07-09 10:39:50 -05002130/* Check that bitmaps can be copied, or output an error */
Eric Blake955171e2021-07-21 10:53:48 -05002131static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
Eric Blake74a43202021-07-09 10:39:50 -05002132{
2133 BdrvDirtyBitmap *bm;
2134
2135 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2136 error_report("Source lacks bitmap support");
2137 return -1;
2138 }
2139 FOR_EACH_DIRTY_BITMAP(src, bm) {
2140 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2141 continue;
2142 }
Eric Blake955171e2021-07-21 10:53:48 -05002143 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
Eric Blake74a43202021-07-09 10:39:50 -05002144 error_report("Cannot copy inconsistent bitmap '%s'",
2145 bdrv_dirty_bitmap_name(bm));
Eric Blake955171e2021-07-21 10:53:48 -05002146 error_printf("Try --skip-broken-bitmaps, or "
2147 "use 'qemu-img bitmap --remove' to delete it\n");
Eric Blake74a43202021-07-09 10:39:50 -05002148 return -1;
2149 }
2150 }
2151 return 0;
2152}
2153
Eric Blake955171e2021-07-21 10:53:48 -05002154static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2155 bool skip_broken)
Eric Blake15e39ad2020-05-21 14:21:36 -05002156{
2157 BdrvDirtyBitmap *bm;
2158 Error *err = NULL;
2159
2160 FOR_EACH_DIRTY_BITMAP(src, bm) {
2161 const char *name;
2162
2163 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2164 continue;
2165 }
2166 name = bdrv_dirty_bitmap_name(bm);
Eric Blake955171e2021-07-21 10:53:48 -05002167 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2168 warn_report("Skipping inconsistent bitmap '%s'", name);
2169 continue;
2170 }
Eric Blake15e39ad2020-05-21 14:21:36 -05002171 qmp_block_dirty_bitmap_add(dst->node_name, name,
2172 true, bdrv_dirty_bitmap_granularity(bm),
2173 true, true,
2174 true, !bdrv_dirty_bitmap_enabled(bm),
2175 &err);
2176 if (err) {
2177 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2178 return -1;
2179 }
2180
2181 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2182 &err);
2183 if (err) {
2184 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
Eric Blake74a43202021-07-09 10:39:50 -05002185 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
Eric Blake15e39ad2020-05-21 14:21:36 -05002186 return -1;
2187 }
2188 }
2189
2190 return 0;
2191}
2192
Peter Lieven6360ab22018-07-13 09:15:39 +02002193#define MAX_BUF_SECTORS 32768
2194
Zhengui0c8c4892020-10-20 14:47:44 +00002195static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2196{
2197 ThrottleConfig cfg;
2198
2199 throttle_config_init(&cfg);
2200 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2201
2202 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2203 blk_set_io_limits(blk, &cfg);
2204}
2205
bellardea2384d2004-08-01 21:59:26 +00002206static int img_convert(int argc, char **argv)
2207{
Kevin Wolf0b8fb552021-04-22 18:43:44 +02002208 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002209 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002210 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
Eric Blake1899bf42021-09-13 08:17:35 -05002211 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2212 *backing_fmt = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002213 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002214 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002215 BlockDriverState *out_bs;
2216 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002217 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002218 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002219 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002220 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002221 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002222 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002223 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002224 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002225 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002226 bool bitmaps = false;
Eric Blake955171e2021-07-21 10:53:48 -05002227 bool skip_broken = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002228 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002229
Peter Lieven9fd77f92017-04-21 11:11:55 +02002230 ImgConvertState s = (ImgConvertState) {
2231 /* Need at least 4k of zeros for sparse detection */
2232 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002233 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002234 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2235 .wr_in_order = true,
2236 .num_coroutines = 8,
2237 };
2238
bellardea2384d2004-08-01 21:59:26 +00002239 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002240 static const struct option long_options[] = {
2241 {"help", no_argument, 0, 'h'},
2242 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002243 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002244 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002245 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002246 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002247 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002248 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Eric Blake955171e2021-07-21 10:53:48 -05002249 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002250 {0, 0, 0, 0}
2251 };
Eric Blake1899bf42021-09-13 08:17:35 -05002252 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002253 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002254 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002255 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002256 }
bellardea2384d2004-08-01 21:59:26 +00002257 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002258 case ':':
2259 missing_argument(argv[optind - 1]);
2260 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002261 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002262 unrecognized_option(argv[optind - 1]);
2263 break;
bellardea2384d2004-08-01 21:59:26 +00002264 case 'h':
2265 help();
2266 break;
2267 case 'f':
2268 fmt = optarg;
2269 break;
2270 case 'O':
2271 out_fmt = optarg;
2272 break;
thsf58c7b32008-06-05 21:53:49 +00002273 case 'B':
2274 out_baseimg = optarg;
2275 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002276 case 'C':
2277 s.copy_range = true;
2278 break;
bellardea2384d2004-08-01 21:59:26 +00002279 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002280 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002281 break;
Eric Blake1899bf42021-09-13 08:17:35 -05002282 case 'F':
2283 backing_fmt = optarg;
2284 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002285 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002286 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002287 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002288 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002289 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002290 case 'l':
2291 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002292 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2293 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002294 if (!sn_opts) {
2295 error_report("Failed in parsing snapshot param '%s'",
2296 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002297 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002298 }
2299 } else {
2300 snapshot_name = optarg;
2301 }
2302 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002303 case 'S':
2304 {
2305 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002306
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002307 sval = cvtnum("buffer size for sparse output", optarg);
2308 if (sval < 0) {
2309 goto fail_getopt;
2310 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002311 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2312 error_report("Invalid buffer size for sparse output specified. "
2313 "Valid sizes are multiples of %llu up to %llu. Select "
2314 "0 to disable sparse detection (fully allocates output).",
2315 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002316 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002317 }
2318
Peter Lieven9fd77f92017-04-21 11:11:55 +02002319 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002320 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002321 break;
2322 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002323 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002325 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002326 case 't':
2327 cache = optarg;
2328 break;
Max Reitz40055952014-07-22 22:58:42 +02002329 case 'T':
2330 src_cache = optarg;
2331 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002332 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002333 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002334 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002335 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002336 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002337 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002338 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002339 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2340 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002341 error_report("Invalid number of coroutines. Allowed number of"
2342 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002343 goto fail_getopt;
2344 }
2345 break;
2346 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002347 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002348 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002349 case 'U':
2350 force_share = true;
2351 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002352 case 'r':
2353 rate_limit = cvtnum("rate limit", optarg);
2354 if (rate_limit < 0) {
2355 goto fail_getopt;
2356 }
2357 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002358 case OPTION_OBJECT:
2359 user_creatable_process_cmdline(optarg);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002360 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002361 case OPTION_IMAGE_OPTS:
2362 image_opts = true;
2363 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002364 case OPTION_SALVAGE:
2365 s.salvage = true;
2366 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002367 case OPTION_TARGET_IMAGE_OPTS:
2368 tgt_image_opts = true;
2369 break;
David Edmondson168468f2020-02-05 11:02:48 +00002370 case OPTION_TARGET_IS_ZERO:
2371 /*
2372 * The user asserting that the target is blank has the
2373 * same effect as the target driver supporting zero
2374 * initialisation.
2375 */
2376 s.has_zero_init = true;
2377 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002378 case OPTION_BITMAPS:
2379 bitmaps = true;
2380 break;
Eric Blake955171e2021-07-21 10:53:48 -05002381 case OPTION_SKIP_BROKEN:
2382 skip_broken = true;
2383 break;
bellardea2384d2004-08-01 21:59:26 +00002384 }
2385 }
ths3b46e622007-09-17 08:09:54 +00002386
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002387 if (!out_fmt && !tgt_image_opts) {
2388 out_fmt = "raw";
2389 }
2390
Eric Blake955171e2021-07-21 10:53:48 -05002391 if (skip_broken && !bitmaps) {
2392 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2393 goto fail_getopt;
2394 }
2395
Fam Zhenge11ce122018-07-27 11:34:01 +08002396 if (s.compressed && s.copy_range) {
2397 error_report("Cannot enable copy offloading when -c is used");
2398 goto fail_getopt;
2399 }
2400
2401 if (explict_min_sparse && s.copy_range) {
2402 error_report("Cannot enable copy offloading when -S is used");
2403 goto fail_getopt;
2404 }
2405
Max Reitz8eaac022019-05-07 22:35:03 +02002406 if (s.copy_range && s.salvage) {
2407 error_report("Cannot use copy offloading in salvaging mode");
2408 goto fail_getopt;
2409 }
2410
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002411 if (tgt_image_opts && !skip_create) {
2412 error_report("--target-image-opts requires use of -n flag");
2413 goto fail_getopt;
2414 }
2415
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002416 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002417 error_report("-o has no effect when skipping image creation");
2418 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002419 }
2420
David Edmondson168468f2020-02-05 11:02:48 +00002421 if (s.has_zero_init && !skip_create) {
2422 error_report("--target-is-zero requires use of -n flag");
2423 goto fail_getopt;
2424 }
2425
Peter Lieven9fd77f92017-04-21 11:11:55 +02002426 s.src_num = argc - optind - 1;
2427 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2428
2429 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002430 if (out_fmt) {
2431 ret = print_block_option_help(out_filename, out_fmt);
2432 goto fail_getopt;
2433 } else {
2434 error_report("Option help requires a format be specified");
2435 goto fail_getopt;
2436 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002437 }
2438
2439 if (s.src_num < 1) {
2440 error_report("Must specify image file name");
2441 goto fail_getopt;
2442 }
2443
Peter Lieven9fd77f92017-04-21 11:11:55 +02002444 /* ret is still -EINVAL until here */
2445 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2446 if (ret < 0) {
2447 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002448 goto fail_getopt;
2449 }
2450
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002451 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002452 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002453 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002454 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002455 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002456 qemu_progress_print(0, 100);
2457
Peter Lieven9fd77f92017-04-21 11:11:55 +02002458 s.src = g_new0(BlockBackend *, s.src_num);
2459 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002460 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002461
Peter Lieven9fd77f92017-04-21 11:11:55 +02002462 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002463 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002464 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002465 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002466 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002467 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002468 ret = -1;
2469 goto out;
2470 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002471 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2472 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002473 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002474 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002475 ret = -1;
2476 goto out;
2477 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002478 src_bs = blk_bs(s.src[bs_i]);
2479 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2480 BDRV_SECTOR_SIZE);
2481 if (!bdrv_get_info(src_bs, &bdi)) {
2482 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2483 bdi.cluster_size / BDRV_SECTOR_SIZE);
2484 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002485 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002486 }
bellardea2384d2004-08-01 21:59:26 +00002487
Wenchao Xiaef806542013-12-04 17:10:57 +08002488 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002489 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002490 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2491 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2492 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002493 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002494 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002495 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002496 ret = -1;
2497 goto out;
2498 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002499
Peter Lieven9fd77f92017-04-21 11:11:55 +02002500 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2501 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002502 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002503 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002504 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002505 ret = -1;
2506 goto out;
edison51ef6722010-09-21 19:58:41 -07002507 }
2508
Max Reitz2e024cd2015-02-11 09:58:46 -05002509 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002510 /* Find driver and parse its options */
2511 drv = bdrv_find_format(out_fmt);
2512 if (!drv) {
2513 error_report("Unknown file format '%s'", out_fmt);
2514 ret = -1;
2515 goto out;
2516 }
2517
2518 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2519 if (!proto_drv) {
2520 error_report_err(local_err);
2521 ret = -1;
2522 goto out;
2523 }
2524
Max Reitz2e024cd2015-02-11 09:58:46 -05002525 if (!drv->create_opts) {
2526 error_report("Format driver '%s' does not support image creation",
2527 drv->format_name);
2528 ret = -1;
2529 goto out;
2530 }
Max Reitzf75613c2014-12-02 18:32:46 +01002531
Max Reitz2e024cd2015-02-11 09:58:46 -05002532 if (!proto_drv->create_opts) {
2533 error_report("Protocol driver '%s' does not support image creation",
2534 proto_drv->format_name);
2535 ret = -1;
2536 goto out;
2537 }
Max Reitzf75613c2014-12-02 18:32:46 +01002538
Max Reitz2e024cd2015-02-11 09:58:46 -05002539 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2540 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002541
Max Reitz2e024cd2015-02-11 09:58:46 -05002542 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002543 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002544 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002545 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002546 ret = -1;
2547 goto out;
2548 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002549 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002550
Yi Lic075c422020-08-19 09:36:07 +08002551 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2552 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Eric Blake1899bf42021-09-13 08:17:35 -05002553 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
Max Reitz2e024cd2015-02-11 09:58:46 -05002554 if (ret < 0) {
2555 goto out;
2556 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002557 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002558
Kevin Wolfa18953f2010-10-14 15:46:04 +02002559 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002560 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002561 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002562 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002563 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002564 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002565
David Edmondson168468f2020-02-05 11:02:48 +00002566 if (s.has_zero_init && s.target_has_backing) {
2567 error_report("Cannot use --target-is-zero when the destination "
2568 "image has a backing file");
2569 goto out;
2570 }
2571
Max Reitz48758a82017-04-26 15:46:48 +02002572 if (s.src_num > 1 && out_baseimg) {
2573 error_report("Having a backing file for the target makes no sense when "
2574 "concatenating multiple input images");
2575 ret = -1;
2576 goto out;
2577 }
2578
Eric Blaked9f059a2020-07-06 15:39:54 -05002579 if (out_baseimg_param) {
2580 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
Eric Blake497a30d2021-05-03 14:36:00 -07002581 error_report("Use of backing file requires explicit "
2582 "backing format");
2583 ret = -1;
2584 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05002585 }
2586 }
2587
Kevin Wolfefa84d42009-05-18 16:42:12 +02002588 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002589 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002590 bool encryption =
2591 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002592 const char *encryptfmt =
2593 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002594 const char *preallocation =
2595 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002596
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002597 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002598 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002599 ret = -1;
2600 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002601 }
2602
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002603 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002604 error_report("Compression and encryption not supported at "
2605 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002606 ret = -1;
2607 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002608 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002609
Chunyan Liu83d05212014-06-05 17:20:51 +08002610 if (preallocation
2611 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002612 {
2613 error_report("Compression and preallocation not supported at "
2614 "the same time");
2615 ret = -1;
2616 goto out;
2617 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002618 }
2619
Eric Blake15e39ad2020-05-21 14:21:36 -05002620 /* Determine if bitmaps need copying */
2621 if (bitmaps) {
2622 if (s.src_num > 1) {
2623 error_report("Copying bitmaps only possible with single source");
2624 ret = -1;
2625 goto out;
2626 }
Eric Blake955171e2021-07-21 10:53:48 -05002627 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
Eric Blake74a43202021-07-09 10:39:50 -05002628 if (ret < 0) {
Eric Blake15e39ad2020-05-21 14:21:36 -05002629 goto out;
2630 }
2631 }
2632
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002633 /*
2634 * The later open call will need any decryption secrets, and
2635 * bdrv_create() will purge "opts", so extract them now before
2636 * they are lost.
2637 */
2638 if (!skip_create) {
2639 open_opts = qdict_new();
2640 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002641
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002642 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002643 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002644 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002645 error_reportf_err(local_err, "%s: error while converting %s: ",
2646 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002647 goto out;
bellardea2384d2004-08-01 21:59:26 +00002648 }
2649 }
ths3b46e622007-09-17 08:09:54 +00002650
Max Reitz4d7c4872019-07-24 19:12:29 +02002651 s.target_is_new = !skip_create;
2652
Peter Lieven9fd77f92017-04-21 11:11:55 +02002653 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002654 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002655 if (ret < 0) {
2656 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002657 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002658 }
2659
Hanna Reitza1c62432021-08-19 12:12:00 +02002660 if (flags & BDRV_O_NOCACHE) {
2661 /*
2662 * If we open the target with O_DIRECT, it may be necessary to
2663 * extend its size to align to the physical sector size.
2664 */
2665 flags |= BDRV_O_RESIZE;
2666 }
2667
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002668 if (skip_create) {
2669 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002670 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002671 } else {
2672 /* TODO ultimately we should allow --target-image-opts
2673 * to be used even when -n is not given.
2674 * That has to wait for bdrv_create to be improved
2675 * to allow filenames in option syntax
2676 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002677 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002678 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002679 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002680 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002681 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002682 ret = -1;
2683 goto out;
2684 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002685 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002686
Eric Blake15e39ad2020-05-21 14:21:36 -05002687 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2688 error_report("Format driver '%s' does not support bitmaps",
2689 out_bs->drv->format_name);
2690 ret = -1;
2691 goto out;
2692 }
2693
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002694 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002695 error_report("Compression not supported for this file format");
2696 ret = -1;
2697 goto out;
2698 }
2699
Eric Blake5def6b82016-06-23 16:37:19 -06002700 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002701 * or discard_alignment of the out_bs is greater. Limit to
2702 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2703 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002704 MAX(s.buf_sectors,
2705 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2706 out_bs->bl.pdiscard_alignment >>
2707 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002708
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002709 /* try to align the write requests to the destination to avoid unnecessary
2710 * RMW cycles. */
2711 s.alignment = MAX(pow2floor(s.min_sparse),
2712 DIV_ROUND_UP(out_bs->bl.request_alignment,
2713 BDRV_SECTOR_SIZE));
2714 assert(is_power_of_2(s.alignment));
2715
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002716 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002717 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002718 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002719 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002720 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002721 ret = -1;
2722 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002723 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002724 error_report("output file is smaller than input file");
2725 ret = -1;
2726 goto out;
2727 }
2728 }
2729
Max Reitzc69291e2020-01-21 16:59:14 +01002730 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002731 /* Errors are treated as "backing length unknown" (which means
2732 * s.target_backing_sectors has to be negative, which it will
2733 * be automatically). The backing file length is used only
2734 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002735 s.target_backing_sectors =
2736 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002737 } else {
2738 s.target_backing_sectors = -1;
2739 }
2740
Peter Lieven24f833c2013-11-27 11:07:07 +01002741 ret = bdrv_get_info(out_bs, &bdi);
2742 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002743 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002744 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002745 goto out;
2746 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002747 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002748 s.compressed = s.compressed || bdi.needs_compressed_writes;
2749 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002750 }
2751
Zhengui0c8c4892020-10-20 14:47:44 +00002752 if (rate_limit) {
2753 set_rate_limit(s.target, rate_limit);
2754 }
2755
Peter Lieven9fd77f92017-04-21 11:11:55 +02002756 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002757
2758 /* Now copy the bitmaps */
2759 if (bitmaps && ret == 0) {
Eric Blake955171e2021-07-21 10:53:48 -05002760 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
Eric Blake15e39ad2020-05-21 14:21:36 -05002761 }
2762
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002763out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002764 if (!ret) {
2765 qemu_progress_print(100, 0);
2766 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002767 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002768 qemu_opts_del(opts);
2769 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002770 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002771 blk_unref(s.target);
2772 if (s.src) {
2773 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2774 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002775 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002776 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002777 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002778 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002779 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002780fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002781 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002782 g_free(options);
2783
Peter Lieven9fd77f92017-04-21 11:11:55 +02002784 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002785}
2786
bellard57d1a2b2004-08-03 21:15:11 +00002787
bellardfaea38e2006-08-05 21:31:00 +00002788static void dump_snapshots(BlockDriverState *bs)
2789{
2790 QEMUSnapshotInfo *sn_tab, *sn;
2791 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002792
2793 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2794 if (nb_sns <= 0)
2795 return;
2796 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002797 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002798 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002799 for(i = 0; i < nb_sns; i++) {
2800 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002801 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002802 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002803 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002804 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002805}
2806
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002807static void dump_json_image_info_list(ImageInfoList *list)
2808{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002809 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002810 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002811 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002812
2813 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2814 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002815 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002816 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002817 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002818 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002819 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002820 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002821}
2822
Benoît Canetc054b3f2012-09-05 13:09:02 +02002823static void dump_json_image_info(ImageInfo *info)
2824{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002825 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002826 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002827 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002828
2829 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2830 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002831 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002832 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002833 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002834 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002835 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002836 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002837}
2838
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002839static void dump_human_image_info_list(ImageInfoList *list)
2840{
2841 ImageInfoList *elem;
2842 bool delim = false;
2843
2844 for (elem = list; elem; elem = elem->next) {
2845 if (delim) {
2846 printf("\n");
2847 }
2848 delim = true;
2849
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002850 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002851 }
2852}
2853
2854static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2855{
2856 return strcmp(a, b) == 0;
2857}
2858
2859/**
2860 * Open an image file chain and return an ImageInfoList
2861 *
2862 * @filename: topmost image filename
2863 * @fmt: topmost image format (may be NULL to autodetect)
2864 * @chain: true - enumerate entire backing file chain
2865 * false - only topmost image file
2866 *
2867 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2868 * image file. If there was an error a message will have been printed to
2869 * stderr.
2870 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002871static ImageInfoList *collect_image_info_list(bool image_opts,
2872 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002873 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002874 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002875{
2876 ImageInfoList *head = NULL;
Eric Blakec3033fd2021-01-13 16:10:12 -06002877 ImageInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002878 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002879 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002880
2881 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2882
2883 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002884 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002885 BlockDriverState *bs;
2886 ImageInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002887
2888 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2889 error_report("Backing file '%s' creates an infinite loop.",
2890 filename);
2891 goto err;
2892 }
2893 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2894
Max Reitzefaa7c42016-03-16 19:54:38 +01002895 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002896 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2897 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002898 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002899 goto err;
2900 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002901 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002902
Wenchao Xia43526ec2013-06-06 12:27:58 +08002903 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002904 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002905 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002906 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002907 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002908 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002909
Eric Blakec3033fd2021-01-13 16:10:12 -06002910 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002911
Markus Armbruster26f54e92014-10-07 13:59:04 +02002912 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002913
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002914 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002915 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002916 image_opts = false;
2917
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002918 if (chain) {
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002919 if (info->full_backing_filename) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002920 filename = info->full_backing_filename;
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002921 } else if (info->backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002922 error_report("Could not determine absolute backing filename,"
2923 " but backing filename '%s' present",
2924 info->backing_filename);
2925 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002926 }
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002927 if (info->backing_filename_format) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002928 fmt = info->backing_filename_format;
2929 }
2930 }
2931 }
2932 g_hash_table_destroy(filenames);
2933 return head;
2934
2935err:
2936 qapi_free_ImageInfoList(head);
2937 g_hash_table_destroy(filenames);
2938 return NULL;
2939}
2940
Benoît Canetc054b3f2012-09-05 13:09:02 +02002941static int img_info(int argc, char **argv)
2942{
2943 int c;
2944 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002945 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002946 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002947 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002948 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002949 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002950
bellardea2384d2004-08-01 21:59:26 +00002951 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002952 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002953 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002954 int option_index = 0;
2955 static const struct option long_options[] = {
2956 {"help", no_argument, 0, 'h'},
2957 {"format", required_argument, 0, 'f'},
2958 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002959 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002960 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002961 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002962 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002963 {0, 0, 0, 0}
2964 };
Fam Zheng335e9932017-05-03 00:35:39 +08002965 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002966 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002967 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002968 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002969 }
bellardea2384d2004-08-01 21:59:26 +00002970 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002971 case ':':
2972 missing_argument(argv[optind - 1]);
2973 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002974 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002975 unrecognized_option(argv[optind - 1]);
2976 break;
bellardea2384d2004-08-01 21:59:26 +00002977 case 'h':
2978 help();
2979 break;
2980 case 'f':
2981 fmt = optarg;
2982 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002983 case 'U':
2984 force_share = true;
2985 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002986 case OPTION_OUTPUT:
2987 output = optarg;
2988 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002989 case OPTION_BACKING_CHAIN:
2990 chain = true;
2991 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002992 case OPTION_OBJECT:
2993 user_creatable_process_cmdline(optarg);
2994 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002995 case OPTION_IMAGE_OPTS:
2996 image_opts = true;
2997 break;
bellardea2384d2004-08-01 21:59:26 +00002998 }
2999 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003000 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003001 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003002 }
bellardea2384d2004-08-01 21:59:26 +00003003 filename = argv[optind++];
3004
Benoît Canetc054b3f2012-09-05 13:09:02 +02003005 if (output && !strcmp(output, "json")) {
3006 output_format = OFORMAT_JSON;
3007 } else if (output && !strcmp(output, "human")) {
3008 output_format = OFORMAT_HUMAN;
3009 } else if (output) {
3010 error_report("--output must be used with human or json as argument.");
3011 return 1;
3012 }
3013
Fam Zheng335e9932017-05-03 00:35:39 +08003014 list = collect_image_info_list(image_opts, filename, fmt, chain,
3015 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003016 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003017 return 1;
3018 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003019
Benoît Canetc054b3f2012-09-05 13:09:02 +02003020 switch (output_format) {
3021 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003022 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003023 break;
3024 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003025 if (chain) {
3026 dump_json_image_info_list(list);
3027 } else {
3028 dump_json_image_info(list->value);
3029 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003030 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003031 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003032
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003033 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003034 return 0;
3035}
3036
Eric Blake30065d12019-03-26 13:40:43 -05003037static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3038 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003039{
3040 switch (output_format) {
3041 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003042 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003043 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003044 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003046 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003047 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003048 e->start, e->length,
3049 e->has_offset ? e->offset : 0,
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003050 e->filename ?: "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 }
3052 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3053 * Modify the flags here to allow more coalescing.
3054 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003055 if (next && (!next->data || next->zero)) {
3056 next->data = false;
3057 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003058 }
3059 break;
3060 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003061 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Eric Blake8417e132021-07-01 14:06:55 -05003062 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3063 " \"data\": %s", e->start, e->length, e->depth,
3064 e->present ? "true" : "false",
Fam Zheng16b0d552016-01-26 11:59:02 +08003065 e->zero ? "true" : "false",
3066 e->data ? "true" : "false");
3067 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003068 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003069 }
3070 putchar('}');
3071
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003072 if (next) {
3073 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003074 }
3075 break;
3076 }
Eric Blake30065d12019-03-26 13:40:43 -05003077 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003078}
3079
Eric Blake5e344dd2017-10-11 22:47:02 -05003080static int get_block_status(BlockDriverState *bs, int64_t offset,
3081 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003082{
Eric Blake237d78f2017-10-11 22:47:03 -05003083 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003084 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003085 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003086 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003087 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003088 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003089
3090 /* As an optimization, we could cache the current range of unallocated
3091 * clusters in each file of the chain, and avoid querying the same
3092 * range repeatedly.
3093 */
3094
3095 depth = 0;
3096 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003097 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003098 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003099 if (ret < 0) {
3100 return ret;
3101 }
Eric Blake237d78f2017-10-11 22:47:03 -05003102 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003103 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3104 break;
3105 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003106 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003107 if (bs == NULL) {
3108 ret = 0;
3109 break;
3110 }
3111
3112 depth++;
3113 }
3114
John Snow28756452016-02-05 13:12:33 -05003115 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3116
Max Reitzf30c66b2019-02-01 20:29:05 +01003117 if (file && has_offset) {
3118 bdrv_refresh_filename(file);
3119 filename = file->filename;
3120 }
3121
John Snow28756452016-02-05 13:12:33 -05003122 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003123 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003124 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003125 .data = !!(ret & BDRV_BLOCK_DATA),
3126 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003127 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003128 .has_offset = has_offset,
3129 .depth = depth,
Eric Blake8417e132021-07-01 14:06:55 -05003130 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
Max Reitzf30c66b2019-02-01 20:29:05 +01003131 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003132 };
3133
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003134 return 0;
3135}
3136
Fam Zheng16b0d552016-01-26 11:59:02 +08003137static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3138{
3139 if (curr->length == 0) {
3140 return false;
3141 }
3142 if (curr->zero != next->zero ||
3143 curr->data != next->data ||
3144 curr->depth != next->depth ||
Eric Blake8417e132021-07-01 14:06:55 -05003145 curr->present != next->present ||
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003146 !curr->filename != !next->filename ||
Fam Zheng16b0d552016-01-26 11:59:02 +08003147 curr->has_offset != next->has_offset) {
3148 return false;
3149 }
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003150 if (curr->filename && strcmp(curr->filename, next->filename)) {
Fam Zheng16b0d552016-01-26 11:59:02 +08003151 return false;
3152 }
3153 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3154 return false;
3155 }
3156 return true;
3157}
3158
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003159static int img_map(int argc, char **argv)
3160{
3161 int c;
3162 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003163 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003164 BlockDriverState *bs;
3165 const char *filename, *fmt, *output;
3166 int64_t length;
3167 MapEntry curr = { .length = 0 }, next;
3168 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003169 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003170 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003171 int64_t start_offset = 0;
3172 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003173
3174 fmt = NULL;
3175 output = NULL;
3176 for (;;) {
3177 int option_index = 0;
3178 static const struct option long_options[] = {
3179 {"help", no_argument, 0, 'h'},
3180 {"format", required_argument, 0, 'f'},
3181 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003182 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003183 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003184 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003185 {"start-offset", required_argument, 0, 's'},
3186 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003187 {0, 0, 0, 0}
3188 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003189 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003190 long_options, &option_index);
3191 if (c == -1) {
3192 break;
3193 }
3194 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003195 case ':':
3196 missing_argument(argv[optind - 1]);
3197 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003198 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003199 unrecognized_option(argv[optind - 1]);
3200 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003201 case 'h':
3202 help();
3203 break;
3204 case 'f':
3205 fmt = optarg;
3206 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003207 case 'U':
3208 force_share = true;
3209 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003210 case OPTION_OUTPUT:
3211 output = optarg;
3212 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003213 case 's':
3214 start_offset = cvtnum("start offset", optarg);
3215 if (start_offset < 0) {
3216 return 1;
3217 }
3218 break;
3219 case 'l':
3220 max_length = cvtnum("max length", optarg);
3221 if (max_length < 0) {
3222 return 1;
3223 }
3224 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003225 case OPTION_OBJECT:
3226 user_creatable_process_cmdline(optarg);
3227 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003228 case OPTION_IMAGE_OPTS:
3229 image_opts = true;
3230 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003231 }
3232 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003233 if (optind != argc - 1) {
3234 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003235 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003236 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003237
3238 if (output && !strcmp(output, "json")) {
3239 output_format = OFORMAT_JSON;
3240 } else if (output && !strcmp(output, "human")) {
3241 output_format = OFORMAT_HUMAN;
3242 } else if (output) {
3243 error_report("--output must be used with human or json as argument.");
3244 return 1;
3245 }
3246
Fam Zheng335e9932017-05-03 00:35:39 +08003247 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003248 if (!blk) {
3249 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003250 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003251 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003252
3253 if (output_format == OFORMAT_HUMAN) {
3254 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003255 } else if (output_format == OFORMAT_JSON) {
3256 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003257 }
3258
Max Reitzf1d3cd72015-02-05 13:58:18 -05003259 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003260 if (length < 0) {
3261 error_report("Failed to get size for '%s'", filename);
3262 return 1;
3263 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003264 if (max_length != -1) {
3265 length = MIN(start_offset + max_length, length);
3266 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003267
Eyal Moscovicic0469492020-05-13 16:36:29 +03003268 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003269 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003270 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003271 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003272
Eric Blake5e344dd2017-10-11 22:47:02 -05003273 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003274 if (ret < 0) {
3275 error_report("Could not read file metadata: %s", strerror(-ret));
3276 goto out;
3277 }
3278
Fam Zheng16b0d552016-01-26 11:59:02 +08003279 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003280 curr.length += next.length;
3281 continue;
3282 }
3283
3284 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003285 ret = dump_map_entry(output_format, &curr, &next);
3286 if (ret < 0) {
3287 goto out;
3288 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003289 }
3290 curr = next;
3291 }
3292
Eric Blake30065d12019-03-26 13:40:43 -05003293 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003294 if (output_format == OFORMAT_JSON) {
3295 puts("]");
3296 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003297
3298out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003299 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003300 return ret < 0;
3301}
3302
aliguorif7b4a942009-01-07 17:40:15 +00003303#define SNAPSHOT_LIST 1
3304#define SNAPSHOT_CREATE 2
3305#define SNAPSHOT_APPLY 3
3306#define SNAPSHOT_DELETE 4
3307
Stuart Brady153859b2009-06-07 00:42:17 +01003308static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003309{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003310 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003311 BlockDriverState *bs;
3312 QEMUSnapshotInfo sn;
3313 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003314 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003315 int action = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003316 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003317 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003318 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003319 bool force_share = false;
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003320 int64_t rt;
aliguorif7b4a942009-01-07 17:40:15 +00003321
Kevin Wolfce099542016-03-15 13:01:04 +01003322 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003323 /* Parse commandline parameters */
3324 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003325 static const struct option long_options[] = {
3326 {"help", no_argument, 0, 'h'},
3327 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003328 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003329 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003330 {0, 0, 0, 0}
3331 };
Fam Zheng335e9932017-05-03 00:35:39 +08003332 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003333 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003334 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003335 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003336 }
aliguorif7b4a942009-01-07 17:40:15 +00003337 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003338 case ':':
3339 missing_argument(argv[optind - 1]);
3340 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003341 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003342 unrecognized_option(argv[optind - 1]);
3343 break;
aliguorif7b4a942009-01-07 17:40:15 +00003344 case 'h':
3345 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003346 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003347 case 'l':
3348 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003349 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003350 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003351 }
3352 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003353 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003354 break;
3355 case 'a':
3356 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003357 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003358 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003359 }
3360 action = SNAPSHOT_APPLY;
3361 snapshot_name = optarg;
3362 break;
3363 case 'c':
3364 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003365 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003366 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003367 }
3368 action = SNAPSHOT_CREATE;
3369 snapshot_name = optarg;
3370 break;
3371 case 'd':
3372 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003373 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003374 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003375 }
3376 action = SNAPSHOT_DELETE;
3377 snapshot_name = optarg;
3378 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003379 case 'q':
3380 quiet = true;
3381 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003382 case 'U':
3383 force_share = true;
3384 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003385 case OPTION_OBJECT:
3386 user_creatable_process_cmdline(optarg);
3387 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003388 case OPTION_IMAGE_OPTS:
3389 image_opts = true;
3390 break;
aliguorif7b4a942009-01-07 17:40:15 +00003391 }
3392 }
3393
Kevin Wolffc11eb22013-08-05 10:53:04 +02003394 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003395 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003396 }
aliguorif7b4a942009-01-07 17:40:15 +00003397 filename = argv[optind++];
3398
3399 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003400 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3401 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003402 if (!blk) {
3403 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003404 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003405 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003406
3407 /* Perform the requested action */
3408 switch(action) {
3409 case SNAPSHOT_LIST:
3410 dump_snapshots(bs);
3411 break;
3412
3413 case SNAPSHOT_CREATE:
3414 memset(&sn, 0, sizeof(sn));
3415 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3416
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003417 rt = g_get_real_time();
3418 sn.date_sec = rt / G_USEC_PER_SEC;
3419 sn.date_nsec = (rt % G_USEC_PER_SEC) * 1000;
aliguorif7b4a942009-01-07 17:40:15 +00003420
3421 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003422 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003423 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003424 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003425 }
aliguorif7b4a942009-01-07 17:40:15 +00003426 break;
3427
3428 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003429 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003430 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003431 error_reportf_err(err, "Could not apply snapshot '%s': ",
3432 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003433 }
aliguorif7b4a942009-01-07 17:40:15 +00003434 break;
3435
3436 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003437 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3438 if (ret < 0) {
3439 error_report("Could not delete snapshot '%s': snapshot not "
3440 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003441 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003442 } else {
3443 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3444 if (ret < 0) {
3445 error_reportf_err(err, "Could not delete snapshot '%s': ",
3446 snapshot_name);
3447 ret = 1;
3448 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003449 }
aliguorif7b4a942009-01-07 17:40:15 +00003450 break;
3451 }
3452
3453 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003454 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003455 if (ret) {
3456 return 1;
3457 }
Stuart Brady153859b2009-06-07 00:42:17 +01003458 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003459}
3460
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003461static int img_rebase(int argc, char **argv)
3462{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003463 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003464 uint8_t *buf_old = NULL;
3465 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003466 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003467 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003468 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003469 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3470 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003471 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003472 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003473 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003474 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003475 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003476 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003477 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478
3479 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003480 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003481 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003482 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003483 out_baseimg = NULL;
3484 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003485 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003486 static const struct option long_options[] = {
3487 {"help", no_argument, 0, 'h'},
3488 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003489 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003490 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003491 {0, 0, 0, 0}
3492 };
Fam Zheng335e9932017-05-03 00:35:39 +08003493 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003494 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003495 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003497 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003498 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003499 case ':':
3500 missing_argument(argv[optind - 1]);
3501 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003502 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003503 unrecognized_option(argv[optind - 1]);
3504 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003505 case 'h':
3506 help();
3507 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003508 case 'f':
3509 fmt = optarg;
3510 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003511 case 'F':
3512 out_basefmt = optarg;
3513 break;
3514 case 'b':
3515 out_baseimg = optarg;
3516 break;
3517 case 'u':
3518 unsafe = 1;
3519 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003520 case 'p':
3521 progress = 1;
3522 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003523 case 't':
3524 cache = optarg;
3525 break;
Max Reitz40055952014-07-22 22:58:42 +02003526 case 'T':
3527 src_cache = optarg;
3528 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003529 case 'q':
3530 quiet = true;
3531 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003532 case OPTION_OBJECT:
3533 user_creatable_process_cmdline(optarg);
3534 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003535 case OPTION_IMAGE_OPTS:
3536 image_opts = true;
3537 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003538 case 'U':
3539 force_share = true;
3540 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003541 }
3542 }
3543
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003544 if (quiet) {
3545 progress = 0;
3546 }
3547
Fam Zhengac1307a2014-04-22 13:36:11 +08003548 if (optind != argc - 1) {
3549 error_exit("Expecting one image file name");
3550 }
3551 if (!unsafe && !out_baseimg) {
3552 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003553 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003554 filename = argv[optind++];
3555
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003556 qemu_progress_init(progress, 2.0);
3557 qemu_progress_print(0, 100);
3558
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003559 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003560 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003561 if (ret < 0) {
3562 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003563 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003564 }
3565
Kevin Wolfce099542016-03-15 13:01:04 +01003566 src_flags = 0;
3567 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003568 if (ret < 0) {
3569 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003570 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003571 }
3572
Kevin Wolfce099542016-03-15 13:01:04 +01003573 /* The source files are opened read-only, don't care about WCE */
3574 assert((src_flags & BDRV_O_RDWR) == 0);
3575 (void) src_writethrough;
3576
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003577 /*
3578 * Open the images.
3579 *
3580 * Ignore the old backing file for unsafe rebase in case we want to correct
3581 * the reference to a renamed or moved backing file.
3582 */
Fam Zheng335e9932017-05-03 00:35:39 +08003583 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3584 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003585 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003586 ret = -1;
3587 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003588 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003589 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003590
Max Reitz4a2061e2019-06-12 19:00:30 +02003591 unfiltered_bs = bdrv_skip_filters(bs);
3592
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003593 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003594 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003595 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003596 ret = -1;
3597 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003598 }
3599 }
3600
3601 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003602 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003603 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003604 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003605
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003606 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003607 blk_old_backing = blk_new(qemu_get_aio_context(),
3608 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003609 BLK_PERM_ALL);
3610 ret = blk_insert_bs(blk_old_backing, base_bs,
3611 &local_err);
3612 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003613 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003614 "Could not reuse old backing file '%s': ",
3615 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003616 goto out;
3617 }
3618 } else {
3619 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003620 }
Max Reitz644483d2015-02-05 13:58:17 -05003621
Alex Bligha6166732012-10-16 13:46:18 +01003622 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003623 const char *overlay_filename;
3624 char *out_real_path;
3625
Fam Zheng335e9932017-05-03 00:35:39 +08003626 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003627 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003628 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003629 }
3630 if (force_share) {
3631 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003632 }
3633
Max Reitzf30c66b2019-02-01 20:29:05 +01003634 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003635 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3636 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003637 out_real_path =
3638 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3639 out_baseimg,
3640 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003641 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003642 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003643 error_reportf_err(local_err,
3644 "Could not resolve backing filename: ");
3645 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003646 goto out;
3647 }
3648
Sam Eiderman863cc782019-05-23 19:33:36 +03003649 /*
3650 * Find out whether we rebase an image on top of a previous image
3651 * in its chain.
3652 */
3653 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003654 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003655 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003656 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003657
Kevin Wolfd861ab32019-04-25 14:25:10 +02003658 blk_new_backing = blk_new(qemu_get_aio_context(),
3659 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003660 BLK_PERM_ALL);
3661 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3662 &local_err);
3663 if (ret < 0) {
3664 error_reportf_err(local_err,
3665 "Could not reuse backing file '%s': ",
3666 out_baseimg);
3667 goto out;
3668 }
3669 } else {
3670 blk_new_backing = blk_new_open(out_real_path, NULL,
3671 options, src_flags, &local_err);
3672 g_free(out_real_path);
3673 if (!blk_new_backing) {
3674 error_reportf_err(local_err,
3675 "Could not open new backing file '%s': ",
3676 out_baseimg);
3677 ret = -1;
3678 goto out;
3679 }
Alex Bligha6166732012-10-16 13:46:18 +01003680 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003681 }
3682 }
3683
3684 /*
3685 * Check each unallocated cluster in the COW file. If it is unallocated,
3686 * accesses go to the backing file. We must therefore compare this cluster
3687 * in the old and new backing file, and if they differ we need to copy it
3688 * from the old backing file into the COW file.
3689 *
3690 * If qemu-img crashes during this step, no harm is done. The content of
3691 * the image is the same as the original one at any time.
3692 */
3693 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003694 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003695 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003696 int64_t new_backing_size = 0;
3697 uint64_t offset;
3698 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003699 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003700
Max Reitzf1d3cd72015-02-05 13:58:18 -05003701 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3702 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003703
Eric Blake41536282017-10-11 22:47:15 -05003704 size = blk_getlength(blk);
3705 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003706 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003707 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003708 ret = -1;
3709 goto out;
3710 }
Max Reitz35ddd932019-05-09 19:52:35 +02003711 if (blk_old_backing) {
3712 old_backing_size = blk_getlength(blk_old_backing);
3713 if (old_backing_size < 0) {
3714 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003715
Max Reitz35ddd932019-05-09 19:52:35 +02003716 bdrv_get_backing_filename(bs, backing_name,
3717 sizeof(backing_name));
3718 error_report("Could not get size of '%s': %s",
3719 backing_name, strerror(-old_backing_size));
3720 ret = -1;
3721 goto out;
3722 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003723 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003724 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003725 new_backing_size = blk_getlength(blk_new_backing);
3726 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003727 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003728 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003729 ret = -1;
3730 goto out;
3731 }
Alex Bligha6166732012-10-16 13:46:18 +01003732 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003733
Eric Blake41536282017-10-11 22:47:15 -05003734 if (size != 0) {
3735 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003736 }
3737
Eric Blake41536282017-10-11 22:47:15 -05003738 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003739 bool buf_old_is_zero = false;
3740
Eric Blake41536282017-10-11 22:47:15 -05003741 /* How many bytes can we handle with the next read? */
3742 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003743
3744 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003745 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003746 if (ret < 0) {
3747 error_report("error while reading image metadata: %s",
3748 strerror(-ret));
3749 goto out;
3750 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003751 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003752 continue;
3753 }
3754
Sam Eiderman863cc782019-05-23 19:33:36 +03003755 if (prefix_chain_bs) {
3756 /*
3757 * If cluster wasn't changed since prefix_chain, we don't need
3758 * to take action
3759 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003760 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3761 prefix_chain_bs, false,
3762 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003763 if (ret < 0) {
3764 error_report("error while reading image metadata: %s",
3765 strerror(-ret));
3766 goto out;
3767 }
3768 if (!ret) {
3769 continue;
3770 }
3771 }
3772
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003773 /*
3774 * Read old and new backing file and take into consideration that
3775 * backing files may be smaller than the COW image.
3776 */
Eric Blake41536282017-10-11 22:47:15 -05003777 if (offset >= old_backing_size) {
3778 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003779 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003780 } else {
Eric Blake41536282017-10-11 22:47:15 -05003781 if (offset + n > old_backing_size) {
3782 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003783 }
3784
Alberto Fariaa9262f52022-07-05 17:15:11 +01003785 ret = blk_pread(blk_old_backing, offset, n, buf_old, 0);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003786 if (ret < 0) {
3787 error_report("error while reading from old backing file");
3788 goto out;
3789 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003790 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003791
Eric Blake41536282017-10-11 22:47:15 -05003792 if (offset >= new_backing_size || !blk_new_backing) {
3793 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003794 } else {
Eric Blake41536282017-10-11 22:47:15 -05003795 if (offset + n > new_backing_size) {
3796 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003797 }
3798
Alberto Fariaa9262f52022-07-05 17:15:11 +01003799 ret = blk_pread(blk_new_backing, offset, n, buf_new, 0);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003800 if (ret < 0) {
3801 error_report("error while reading from new backing file");
3802 goto out;
3803 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003804 }
3805
3806 /* If they differ, we need to write to the COW file */
3807 uint64_t written = 0;
3808
Eric Blake41536282017-10-11 22:47:15 -05003809 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003810 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003811
Eric Blake41536282017-10-11 22:47:15 -05003812 if (compare_buffers(buf_old + written, buf_new + written,
3813 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003814 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003815 if (buf_old_is_zero) {
3816 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3817 } else {
Alberto Fariaa9262f52022-07-05 17:15:11 +01003818 ret = blk_pwrite(blk, offset + written, pnum,
3819 buf_old + written, 0);
Max Reitz1c6e8772019-05-09 19:52:36 +02003820 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003821 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003822 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003823 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003824 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003825 }
3826 }
3827
3828 written += pnum;
3829 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003830 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003831 }
3832 }
3833
3834 /*
3835 * Change the backing file. All clusters that are different from the old
3836 * backing file are overwritten in the COW file now, so the visible content
3837 * doesn't change when we switch the backing file.
3838 */
Alex Bligha6166732012-10-16 13:46:18 +01003839 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003840 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3841 true);
Alex Bligha6166732012-10-16 13:46:18 +01003842 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003843 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003844 }
3845
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003846 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003847 error_report("Could not change the backing file to '%s': No "
3848 "space left in the file header", out_baseimg);
Eric Blakea7cd44b2021-07-08 10:52:28 -05003849 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3850 error_report("Could not change the backing file to '%s': backing "
3851 "format must be specified", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003852 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003853 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003854 out_baseimg, strerror(-ret));
3855 }
3856
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003857 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003858 /*
3859 * TODO At this point it is possible to check if any clusters that are
3860 * allocated in the COW file are the same in the backing file. If so, they
3861 * could be dropped from the COW file. Don't do this before switching the
3862 * backing file, in case of a crash this would lead to corruption.
3863 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003864out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003865 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003866 /* Cleanup */
3867 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003868 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003869 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003870 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003871 qemu_vfree(buf_old);
3872 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003873
Markus Armbruster26f54e92014-10-07 13:59:04 +02003874 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003875 if (ret) {
3876 return 1;
3877 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003878 return 0;
3879}
3880
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003881static int img_resize(int argc, char **argv)
3882{
Markus Armbruster6750e792015-02-12 17:43:08 +01003883 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003884 int c, ret, relative;
3885 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003886 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003887 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003888 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003889 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003890 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003891
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003892 static QemuOptsList resize_options = {
3893 .name = "resize_options",
3894 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3895 .desc = {
3896 {
3897 .name = BLOCK_OPT_SIZE,
3898 .type = QEMU_OPT_SIZE,
3899 .help = "Virtual disk size"
3900 }, {
3901 /* end of list */
3902 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003903 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003904 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003905 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003906 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003907
Kevin Wolfe80fec72011-04-29 10:58:12 +02003908 /* Remove size from argv manually so that negative numbers are not treated
3909 * as options by getopt. */
3910 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003911 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003912 return 1;
3913 }
3914
3915 size = argv[--argc];
3916
3917 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003918 fmt = NULL;
3919 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003920 static const struct option long_options[] = {
3921 {"help", no_argument, 0, 'h'},
3922 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003923 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003924 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003925 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003926 {0, 0, 0, 0}
3927 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003928 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003929 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003930 if (c == -1) {
3931 break;
3932 }
3933 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003934 case ':':
3935 missing_argument(argv[optind - 1]);
3936 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003937 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003938 unrecognized_option(argv[optind - 1]);
3939 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003940 case 'h':
3941 help();
3942 break;
3943 case 'f':
3944 fmt = optarg;
3945 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003946 case 'q':
3947 quiet = true;
3948 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003949 case OPTION_OBJECT:
3950 user_creatable_process_cmdline(optarg);
3951 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003952 case OPTION_IMAGE_OPTS:
3953 image_opts = true;
3954 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003955 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003956 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003957 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003958 if (prealloc == PREALLOC_MODE__MAX) {
3959 error_report("Invalid preallocation mode '%s'", optarg);
3960 return 1;
3961 }
3962 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003963 case OPTION_SHRINK:
3964 shrink = true;
3965 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003966 }
3967 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003968 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003969 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003970 }
3971 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003972
3973 /* Choose grow, shrink, or absolute resize mode */
3974 switch (size[0]) {
3975 case '+':
3976 relative = 1;
3977 size++;
3978 break;
3979 case '-':
3980 relative = -1;
3981 size++;
3982 break;
3983 default:
3984 relative = 0;
3985 break;
3986 }
3987
3988 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003989 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02003990 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01003991 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003992 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003993 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003994 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003995 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003996 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3997 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003998
Max Reitzefaa7c42016-03-16 19:54:38 +01003999 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08004000 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4001 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004002 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01004003 ret = -1;
4004 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004005 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004006
Max Reitzdc5f6902017-06-13 22:20:55 +02004007 current_size = blk_getlength(blk);
4008 if (current_size < 0) {
4009 error_report("Failed to inquire current image length: %s",
4010 strerror(-current_size));
4011 ret = -1;
4012 goto out;
4013 }
4014
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004015 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004016 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004017 } else {
4018 total_size = n;
4019 }
4020 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004021 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004022 ret = -1;
4023 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004024 }
4025
Max Reitzdc5f6902017-06-13 22:20:55 +02004026 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4027 error_report("Preallocation can only be used for growing images");
4028 ret = -1;
4029 goto out;
4030 }
4031
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004032 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004033 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004034 warn_report("Shrinking an image will delete all data beyond the "
4035 "shrunken image's end. Before performing such an "
4036 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004037 ret = -1;
4038 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004039 }
4040
Max Reitze8d04f92019-09-18 11:51:43 +02004041 /*
4042 * The user expects the image to have the desired size after
4043 * resizing, so pass @exact=true. It is of no use to report
4044 * success when the image has not actually been resized.
4045 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004046 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004047 if (!ret) {
4048 qprintf(quiet, "Image resized.\n");
4049 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004050 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004051 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004052out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004053 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004054 if (ret) {
4055 return 1;
4056 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004057 return 0;
4058}
4059
Max Reitz76a3a342014-10-27 11:12:51 +01004060static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004061 int64_t offset, int64_t total_work_size,
4062 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004063{
4064 qemu_progress_print(100.f * offset / total_work_size, 0);
4065}
4066
Max Reitz51641352018-05-09 23:00:20 +02004067static int print_amend_option_help(const char *format)
4068{
4069 BlockDriver *drv;
4070
4071 /* Find driver and parse its options */
4072 drv = bdrv_find_format(format);
4073 if (!drv) {
4074 error_report("Unknown file format '%s'", format);
4075 return 1;
4076 }
4077
4078 if (!drv->bdrv_amend_options) {
4079 error_report("Format driver '%s' does not support option amendment",
4080 format);
4081 return 1;
4082 }
4083
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004084 /* Every driver supporting amendment must have amend_opts */
4085 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004086
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004087 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004088 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004089 return 0;
4090}
4091
Max Reitz6f176b42013-09-03 10:09:50 +02004092static int img_amend(int argc, char **argv)
4093{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004094 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004095 int c, ret = 0;
4096 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004097 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004098 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004099 const char *fmt = NULL, *filename, *cache;
4100 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004101 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004102 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004103 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004104 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004105 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004106 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004107
Max Reitzbd39e6e2014-07-22 22:58:43 +02004108 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004109 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004110 static const struct option long_options[] = {
4111 {"help", no_argument, 0, 'h'},
4112 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004113 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004114 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004115 {0, 0, 0, 0}
4116 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004117 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004118 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004119 if (c == -1) {
4120 break;
4121 }
4122
4123 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004124 case ':':
4125 missing_argument(argv[optind - 1]);
4126 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004127 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004128 unrecognized_option(argv[optind - 1]);
4129 break;
4130 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004131 help();
4132 break;
4133 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004134 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004135 ret = -1;
4136 goto out_no_progress;
4137 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004138 break;
4139 case 'f':
4140 fmt = optarg;
4141 break;
4142 case 't':
4143 cache = optarg;
4144 break;
4145 case 'p':
4146 progress = true;
4147 break;
4148 case 'q':
4149 quiet = true;
4150 break;
4151 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004152 user_creatable_process_cmdline(optarg);
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004153 break;
4154 case OPTION_IMAGE_OPTS:
4155 image_opts = true;
4156 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004157 case OPTION_FORCE:
4158 force = true;
4159 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004160 }
4161 }
4162
Max Reitz6f176b42013-09-03 10:09:50 +02004163 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004164 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004165 }
4166
Max Reitz76a3a342014-10-27 11:12:51 +01004167 if (quiet) {
4168 progress = false;
4169 }
4170 qemu_progress_init(progress, 1.0);
4171
Kevin Wolfa283cb62014-02-21 16:24:07 +01004172 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4173 if (fmt && has_help_option(options)) {
4174 /* If a format is explicitly specified (and possibly no filename is
4175 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004176 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004177 goto out;
4178 }
4179
4180 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004181 error_report("Expecting one image file name");
4182 ret = -1;
4183 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004184 }
Max Reitz6f176b42013-09-03 10:09:50 +02004185
Kevin Wolfce099542016-03-15 13:01:04 +01004186 flags = BDRV_O_RDWR;
4187 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004188 if (ret < 0) {
4189 error_report("Invalid cache option: %s", cache);
4190 goto out;
4191 }
4192
Fam Zheng335e9932017-05-03 00:35:39 +08004193 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4194 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004195 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004196 ret = -1;
4197 goto out;
4198 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004199 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004200
4201 fmt = bs->drv->format_name;
4202
Kevin Wolf626f84f2014-02-21 16:24:06 +01004203 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004204 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004205 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004206 goto out;
4207 }
4208
Max Reitz1f996682018-05-09 23:00:17 +02004209 if (!bs->drv->bdrv_amend_options) {
4210 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004211 fmt);
4212 ret = -1;
4213 goto out;
4214 }
4215
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004216 /* Every driver supporting amendment must have amend_opts */
4217 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004218
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004219 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4220 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004221 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004222 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004223 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4224 qemu_opts_del(opts);
4225 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004226 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004227 error_append_hint(&err,
4228 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004229 }
4230
Paolo Bonziniece90862017-01-04 15:56:24 +01004231 error_report_err(err);
4232 ret = -1;
4233 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004234 }
4235
Max Reitz76a3a342014-10-27 11:12:51 +01004236 /* In case the driver does not call amend_status_cb() */
4237 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004238 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004239 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004240 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004241 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004242 goto out;
4243 }
4244
4245out:
Max Reitz76a3a342014-10-27 11:12:51 +01004246 qemu_progress_end();
4247
Max Reitze814dff2015-08-20 16:00:38 -07004248out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004249 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004250 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004251 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004252 g_free(options);
4253
Max Reitz6f176b42013-09-03 10:09:50 +02004254 if (ret) {
4255 return 1;
4256 }
4257 return 0;
4258}
4259
Kevin Wolfb6133b82014-08-05 14:17:13 +02004260typedef struct BenchData {
4261 BlockBackend *blk;
4262 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004263 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004264 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004265 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004266 int nrreq;
4267 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004268 int flush_interval;
4269 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004270 uint8_t *buf;
4271 QEMUIOVector *qiov;
4272
4273 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004274 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004275 uint64_t offset;
4276} BenchData;
4277
Kevin Wolf55d539c2016-06-03 13:59:41 +02004278static void bench_undrained_flush_cb(void *opaque, int ret)
4279{
4280 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004281 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004282 exit(EXIT_FAILURE);
4283 }
4284}
4285
Kevin Wolfb6133b82014-08-05 14:17:13 +02004286static void bench_cb(void *opaque, int ret)
4287{
4288 BenchData *b = opaque;
4289 BlockAIOCB *acb;
4290
4291 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004292 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004293 exit(EXIT_FAILURE);
4294 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004295
4296 if (b->in_flush) {
4297 /* Just finished a flush with drained queue: Start next requests */
4298 assert(b->in_flight == 0);
4299 b->in_flush = false;
4300 } else if (b->in_flight > 0) {
4301 int remaining = b->n - b->in_flight;
4302
Kevin Wolfb6133b82014-08-05 14:17:13 +02004303 b->n--;
4304 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004305
4306 /* Time for flush? Drain queue if requested, then flush */
4307 if (b->flush_interval && remaining % b->flush_interval == 0) {
4308 if (!b->in_flight || !b->drain_on_flush) {
4309 BlockCompletionFunc *cb;
4310
4311 if (b->drain_on_flush) {
4312 b->in_flush = true;
4313 cb = bench_cb;
4314 } else {
4315 cb = bench_undrained_flush_cb;
4316 }
4317
4318 acb = blk_aio_flush(b->blk, cb, b);
4319 if (!acb) {
4320 error_report("Failed to issue flush request");
4321 exit(EXIT_FAILURE);
4322 }
4323 }
4324 if (b->drain_on_flush) {
4325 return;
4326 }
4327 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004328 }
4329
4330 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004331 int64_t offset = b->offset;
4332 /* blk_aio_* might look for completed I/Os and kick bench_cb
4333 * again, so make sure this operation is counted by in_flight
4334 * and b->offset is ready for the next submission.
4335 */
4336 b->in_flight++;
4337 b->offset += b->step;
4338 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004339 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004340 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004341 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004342 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004343 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004344 if (!acb) {
4345 error_report("Failed to issue request");
4346 exit(EXIT_FAILURE);
4347 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004348 }
4349}
4350
4351static int img_bench(int argc, char **argv)
4352{
4353 int c, ret = 0;
4354 const char *fmt = NULL, *filename;
4355 bool quiet = false;
4356 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004357 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004358 int count = 75000;
4359 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004360 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004361 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004362 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004363 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004364 int flush_interval = 0;
4365 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004366 int64_t image_size;
4367 BlockBackend *blk = NULL;
4368 BenchData data = {};
4369 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004370 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004371 struct timeval t1, t2;
4372 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004373 bool force_share = false;
Stefan Hajnoczi4f384012022-10-13 14:58:59 -04004374 size_t buf_size = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004375
4376 for (;;) {
4377 static const struct option long_options[] = {
4378 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004379 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004380 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004381 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004382 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004383 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004384 {0, 0, 0, 0}
4385 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004386 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4387 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004388 if (c == -1) {
4389 break;
4390 }
4391
4392 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004393 case ':':
4394 missing_argument(argv[optind - 1]);
4395 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004396 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004397 unrecognized_option(argv[optind - 1]);
4398 break;
4399 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004400 help();
4401 break;
4402 case 'c':
4403 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004404 unsigned long res;
4405
4406 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004407 error_report("Invalid request count specified");
4408 return 1;
4409 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004410 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004411 break;
4412 }
4413 case 'd':
4414 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004415 unsigned long res;
4416
4417 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004418 error_report("Invalid queue depth specified");
4419 return 1;
4420 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004421 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004422 break;
4423 }
4424 case 'f':
4425 fmt = optarg;
4426 break;
4427 case 'n':
4428 flags |= BDRV_O_NATIVE_AIO;
4429 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004430 case 'i':
4431 ret = bdrv_parse_aio(optarg, &flags);
4432 if (ret < 0) {
4433 error_report("Invalid aio option: %s", optarg);
4434 ret = -1;
4435 goto out;
4436 }
4437 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004438 case 'o':
4439 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004440 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004441 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004442 return 1;
4443 }
4444 break;
4445 }
4446 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004447 case 'q':
4448 quiet = true;
4449 break;
4450 case 's':
4451 {
4452 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004453
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004454 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4455 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004456 return 1;
4457 }
4458
4459 bufsize = sval;
4460 break;
4461 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004462 case 'S':
4463 {
4464 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004465
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004466 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4467 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004468 return 1;
4469 }
4470
4471 step = sval;
4472 break;
4473 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004474 case 't':
4475 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4476 if (ret < 0) {
4477 error_report("Invalid cache mode");
4478 ret = -1;
4479 goto out;
4480 }
4481 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004482 case 'w':
4483 flags |= BDRV_O_RDWR;
4484 is_write = true;
4485 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004486 case 'U':
4487 force_share = true;
4488 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004489 case OPTION_PATTERN:
4490 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004491 unsigned long res;
4492
4493 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004494 error_report("Invalid pattern byte specified");
4495 return 1;
4496 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004497 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004498 break;
4499 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004500 case OPTION_FLUSH_INTERVAL:
4501 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004502 unsigned long res;
4503
4504 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004505 error_report("Invalid flush interval specified");
4506 return 1;
4507 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004508 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004509 break;
4510 }
4511 case OPTION_NO_DRAIN:
4512 drain_on_flush = false;
4513 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004514 case OPTION_IMAGE_OPTS:
4515 image_opts = true;
4516 break;
4517 }
4518 }
4519
4520 if (optind != argc - 1) {
4521 error_exit("Expecting one image file name");
4522 }
4523 filename = argv[argc - 1];
4524
Kevin Wolf55d539c2016-06-03 13:59:41 +02004525 if (!is_write && flush_interval) {
4526 error_report("--flush-interval is only available in write tests");
4527 ret = -1;
4528 goto out;
4529 }
4530 if (flush_interval && flush_interval < depth) {
4531 error_report("Flush interval can't be smaller than depth");
4532 ret = -1;
4533 goto out;
4534 }
4535
Fam Zheng335e9932017-05-03 00:35:39 +08004536 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4537 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004538 if (!blk) {
4539 ret = -1;
4540 goto out;
4541 }
4542
4543 image_size = blk_getlength(blk);
4544 if (image_size < 0) {
4545 ret = image_size;
4546 goto out;
4547 }
4548
4549 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004550 .blk = blk,
4551 .image_size = image_size,
4552 .bufsize = bufsize,
4553 .step = step ?: bufsize,
4554 .nrreq = depth,
4555 .n = count,
4556 .offset = offset,
4557 .write = is_write,
4558 .flush_interval = flush_interval,
4559 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004560 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004561 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004562 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004563 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004564 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004565 if (flush_interval) {
4566 printf("Sending flush every %d requests\n", flush_interval);
4567 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004568
Fam Zheng79d46582018-01-16 14:08:58 +08004569 buf_size = data.nrreq * data.bufsize;
4570 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004571 memset(data.buf, pattern, data.nrreq * data.bufsize);
4572
Stefan Hajnoczif4ec04b2022-10-13 14:59:02 -04004573 blk_register_buf(blk, data.buf, buf_size, &error_fatal);
Fam Zheng79d46582018-01-16 14:08:58 +08004574
Kevin Wolfb6133b82014-08-05 14:17:13 +02004575 data.qiov = g_new(QEMUIOVector, data.nrreq);
4576 for (i = 0; i < data.nrreq; i++) {
4577 qemu_iovec_init(&data.qiov[i], 1);
4578 qemu_iovec_add(&data.qiov[i],
4579 data.buf + i * data.bufsize, data.bufsize);
4580 }
4581
4582 gettimeofday(&t1, NULL);
4583 bench_cb(&data, 0);
4584
4585 while (data.n > 0) {
4586 main_loop_wait(false);
4587 }
4588 gettimeofday(&t2, NULL);
4589
4590 printf("Run completed in %3.3f seconds.\n",
4591 (t2.tv_sec - t1.tv_sec)
4592 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4593
4594out:
Fam Zheng79d46582018-01-16 14:08:58 +08004595 if (data.buf) {
Stefan Hajnoczi4f384012022-10-13 14:58:59 -04004596 blk_unregister_buf(blk, data.buf, buf_size);
Fam Zheng79d46582018-01-16 14:08:58 +08004597 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004598 qemu_vfree(data.buf);
4599 blk_unref(blk);
4600
4601 if (ret) {
4602 return 1;
4603 }
4604 return 0;
4605}
4606
Eric Blake3b51ab42020-05-12 20:16:45 -05004607enum ImgBitmapAct {
4608 BITMAP_ADD,
4609 BITMAP_REMOVE,
4610 BITMAP_CLEAR,
4611 BITMAP_ENABLE,
4612 BITMAP_DISABLE,
4613 BITMAP_MERGE,
4614};
4615typedef struct ImgBitmapAction {
4616 enum ImgBitmapAct act;
4617 const char *src; /* only used for merge */
4618 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4619} ImgBitmapAction;
4620
4621static int img_bitmap(int argc, char **argv)
4622{
4623 Error *err = NULL;
4624 int c, ret = 1;
4625 QemuOpts *opts = NULL;
4626 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4627 const char *filename, *bitmap;
4628 BlockBackend *blk = NULL, *src = NULL;
4629 BlockDriverState *bs = NULL, *src_bs = NULL;
4630 bool image_opts = false;
4631 int64_t granularity = 0;
4632 bool add = false, merge = false;
4633 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4634 ImgBitmapAction *act, *act_next;
4635 const char *op;
4636
4637 QSIMPLEQ_INIT(&actions);
4638
4639 for (;;) {
4640 static const struct option long_options[] = {
4641 {"help", no_argument, 0, 'h'},
4642 {"object", required_argument, 0, OPTION_OBJECT},
4643 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4644 {"add", no_argument, 0, OPTION_ADD},
4645 {"remove", no_argument, 0, OPTION_REMOVE},
4646 {"clear", no_argument, 0, OPTION_CLEAR},
4647 {"enable", no_argument, 0, OPTION_ENABLE},
4648 {"disable", no_argument, 0, OPTION_DISABLE},
4649 {"merge", required_argument, 0, OPTION_MERGE},
4650 {"granularity", required_argument, 0, 'g'},
4651 {"source-file", required_argument, 0, 'b'},
4652 {"source-format", required_argument, 0, 'F'},
4653 {0, 0, 0, 0}
4654 };
4655 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4656 if (c == -1) {
4657 break;
4658 }
4659
4660 switch (c) {
4661 case ':':
4662 missing_argument(argv[optind - 1]);
4663 break;
4664 case '?':
4665 unrecognized_option(argv[optind - 1]);
4666 break;
4667 case 'h':
4668 help();
4669 break;
4670 case 'b':
4671 src_filename = optarg;
4672 break;
4673 case 'f':
4674 fmt = optarg;
4675 break;
4676 case 'F':
4677 src_fmt = optarg;
4678 break;
4679 case 'g':
4680 granularity = cvtnum("granularity", optarg);
4681 if (granularity < 0) {
4682 return 1;
4683 }
4684 break;
4685 case OPTION_ADD:
4686 act = g_new0(ImgBitmapAction, 1);
4687 act->act = BITMAP_ADD;
4688 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4689 add = true;
4690 break;
4691 case OPTION_REMOVE:
4692 act = g_new0(ImgBitmapAction, 1);
4693 act->act = BITMAP_REMOVE;
4694 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4695 break;
4696 case OPTION_CLEAR:
4697 act = g_new0(ImgBitmapAction, 1);
4698 act->act = BITMAP_CLEAR;
4699 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4700 break;
4701 case OPTION_ENABLE:
4702 act = g_new0(ImgBitmapAction, 1);
4703 act->act = BITMAP_ENABLE;
4704 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4705 break;
4706 case OPTION_DISABLE:
4707 act = g_new0(ImgBitmapAction, 1);
4708 act->act = BITMAP_DISABLE;
4709 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4710 break;
4711 case OPTION_MERGE:
4712 act = g_new0(ImgBitmapAction, 1);
4713 act->act = BITMAP_MERGE;
4714 act->src = optarg;
4715 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4716 merge = true;
4717 break;
4718 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004719 user_creatable_process_cmdline(optarg);
Eric Blake3b51ab42020-05-12 20:16:45 -05004720 break;
4721 case OPTION_IMAGE_OPTS:
4722 image_opts = true;
4723 break;
4724 }
4725 }
4726
Eric Blake3b51ab42020-05-12 20:16:45 -05004727 if (QSIMPLEQ_EMPTY(&actions)) {
4728 error_report("Need at least one of --add, --remove, --clear, "
4729 "--enable, --disable, or --merge");
4730 goto out;
4731 }
4732
4733 if (granularity && !add) {
4734 error_report("granularity only supported with --add");
4735 goto out;
4736 }
4737 if (src_fmt && !src_filename) {
4738 error_report("-F only supported with -b");
4739 goto out;
4740 }
4741 if (src_filename && !merge) {
4742 error_report("Merge bitmap source file only supported with "
4743 "--merge");
4744 goto out;
4745 }
4746
4747 if (optind != argc - 2) {
4748 error_report("Expecting filename and bitmap name");
4749 goto out;
4750 }
4751
4752 filename = argv[optind];
4753 bitmap = argv[optind + 1];
4754
Eric Blake14f16bf2020-09-14 14:10:09 -05004755 /*
4756 * No need to open backing chains; we will be manipulating bitmaps
4757 * directly in this image without reference to image contents.
4758 */
4759 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4760 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004761 if (!blk) {
4762 goto out;
4763 }
4764 bs = blk_bs(blk);
4765 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004766 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4767 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004768 if (!src) {
4769 goto out;
4770 }
4771 src_bs = blk_bs(src);
4772 } else {
4773 src_bs = bs;
4774 }
4775
4776 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4777 switch (act->act) {
4778 case BITMAP_ADD:
4779 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4780 !!granularity, granularity, true, true,
4781 false, false, &err);
4782 op = "add";
4783 break;
4784 case BITMAP_REMOVE:
4785 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4786 op = "remove";
4787 break;
4788 case BITMAP_CLEAR:
4789 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4790 op = "clear";
4791 break;
4792 case BITMAP_ENABLE:
4793 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4794 op = "enable";
4795 break;
4796 case BITMAP_DISABLE:
4797 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4798 op = "disable";
4799 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004800 case BITMAP_MERGE:
4801 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4802 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004803 op = "merge";
4804 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004805 default:
4806 g_assert_not_reached();
4807 }
4808
4809 if (err) {
4810 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4811 op, bitmap);
4812 goto out;
4813 }
4814 g_free(act);
4815 }
4816
4817 ret = 0;
4818
4819 out:
4820 blk_unref(src);
4821 blk_unref(blk);
4822 qemu_opts_del(opts);
4823 return ret;
4824}
4825
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004826#define C_BS 01
4827#define C_COUNT 02
4828#define C_IF 04
4829#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004830#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004831
4832struct DdInfo {
4833 unsigned int flags;
4834 int64_t count;
4835};
4836
4837struct DdIo {
4838 int bsz; /* Block size */
4839 char *filename;
4840 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004841 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004842};
4843
4844struct DdOpts {
4845 const char *name;
4846 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4847 unsigned int flag;
4848};
4849
4850static int img_dd_bs(const char *arg,
4851 struct DdIo *in, struct DdIo *out,
4852 struct DdInfo *dd)
4853{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004854 int64_t res;
4855
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004856 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004857
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004858 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004859 return 1;
4860 }
4861 in->bsz = out->bsz = res;
4862
4863 return 0;
4864}
4865
4866static int img_dd_count(const char *arg,
4867 struct DdIo *in, struct DdIo *out,
4868 struct DdInfo *dd)
4869{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004870 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004871
Markus Armbruster606caa02017-02-21 21:14:04 +01004872 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004873 return 1;
4874 }
4875
4876 return 0;
4877}
4878
4879static int img_dd_if(const char *arg,
4880 struct DdIo *in, struct DdIo *out,
4881 struct DdInfo *dd)
4882{
4883 in->filename = g_strdup(arg);
4884
4885 return 0;
4886}
4887
4888static int img_dd_of(const char *arg,
4889 struct DdIo *in, struct DdIo *out,
4890 struct DdInfo *dd)
4891{
4892 out->filename = g_strdup(arg);
4893
4894 return 0;
4895}
4896
Reda Sallahif7c15532016-08-10 16:16:09 +02004897static int img_dd_skip(const char *arg,
4898 struct DdIo *in, struct DdIo *out,
4899 struct DdInfo *dd)
4900{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004901 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004902
Markus Armbruster606caa02017-02-21 21:14:04 +01004903 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004904 return 1;
4905 }
4906
4907 return 0;
4908}
4909
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004910static int img_dd(int argc, char **argv)
4911{
4912 int ret = 0;
4913 char *arg = NULL;
4914 char *tmp;
4915 BlockDriver *drv = NULL, *proto_drv = NULL;
4916 BlockBackend *blk1 = NULL, *blk2 = NULL;
4917 QemuOpts *opts = NULL;
4918 QemuOptsList *create_opts = NULL;
4919 Error *local_err = NULL;
4920 bool image_opts = false;
4921 int c, i;
4922 const char *out_fmt = "raw";
4923 const char *fmt = NULL;
4924 int64_t size = 0;
Miroslav Rezanina0f48c472022-11-09 10:57:13 -05004925 int64_t out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004926 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004927 struct DdInfo dd = {
4928 .flags = 0,
4929 .count = 0,
4930 };
4931 struct DdIo in = {
4932 .bsz = 512, /* Block size is by default 512 bytes */
4933 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004934 .buf = NULL,
4935 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004936 };
4937 struct DdIo out = {
4938 .bsz = 512,
4939 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004940 .buf = NULL,
4941 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004942 };
4943
4944 const struct DdOpts options[] = {
4945 { "bs", img_dd_bs, C_BS },
4946 { "count", img_dd_count, C_COUNT },
4947 { "if", img_dd_if, C_IF },
4948 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004949 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004950 { NULL, NULL, 0 }
4951 };
4952 const struct option long_options[] = {
4953 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004954 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004955 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004956 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004957 { 0, 0, 0, 0 }
4958 };
4959
Fam Zheng335e9932017-05-03 00:35:39 +08004960 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004961 if (c == EOF) {
4962 break;
4963 }
4964 switch (c) {
4965 case 'O':
4966 out_fmt = optarg;
4967 break;
4968 case 'f':
4969 fmt = optarg;
4970 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004971 case ':':
4972 missing_argument(argv[optind - 1]);
4973 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004974 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004975 unrecognized_option(argv[optind - 1]);
4976 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004977 case 'h':
4978 help();
4979 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004980 case 'U':
4981 force_share = true;
4982 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004983 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004984 user_creatable_process_cmdline(optarg);
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004985 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004986 case OPTION_IMAGE_OPTS:
4987 image_opts = true;
4988 break;
4989 }
4990 }
4991
4992 for (i = optind; i < argc; i++) {
4993 int j;
4994 arg = g_strdup(argv[i]);
4995
4996 tmp = strchr(arg, '=');
4997 if (tmp == NULL) {
4998 error_report("unrecognized operand %s", arg);
4999 ret = -1;
5000 goto out;
5001 }
5002
5003 *tmp++ = '\0';
5004
5005 for (j = 0; options[j].name != NULL; j++) {
5006 if (!strcmp(arg, options[j].name)) {
5007 break;
5008 }
5009 }
5010 if (options[j].name == NULL) {
5011 error_report("unrecognized operand %s", arg);
5012 ret = -1;
5013 goto out;
5014 }
5015
5016 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5017 ret = -1;
5018 goto out;
5019 }
5020 dd.flags |= options[j].flag;
5021 g_free(arg);
5022 arg = NULL;
5023 }
5024
5025 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5026 error_report("Must specify both input and output files");
5027 ret = -1;
5028 goto out;
5029 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005030
Fam Zheng335e9932017-05-03 00:35:39 +08005031 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5032 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005033
5034 if (!blk1) {
5035 ret = -1;
5036 goto out;
5037 }
5038
5039 drv = bdrv_find_format(out_fmt);
5040 if (!drv) {
5041 error_report("Unknown file format");
5042 ret = -1;
5043 goto out;
5044 }
5045 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5046
5047 if (!proto_drv) {
5048 error_report_err(local_err);
5049 ret = -1;
5050 goto out;
5051 }
5052 if (!drv->create_opts) {
5053 error_report("Format driver '%s' does not support image creation",
5054 drv->format_name);
5055 ret = -1;
5056 goto out;
5057 }
5058 if (!proto_drv->create_opts) {
5059 error_report("Protocol driver '%s' does not support image creation",
5060 proto_drv->format_name);
5061 ret = -1;
5062 goto out;
5063 }
5064 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5065 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5066
5067 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5068
5069 size = blk_getlength(blk1);
5070 if (size < 0) {
5071 error_report("Failed to get size for '%s'", in.filename);
5072 ret = -1;
5073 goto out;
5074 }
5075
5076 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5077 dd.count * in.bsz < size) {
5078 size = dd.count * in.bsz;
5079 }
5080
Reda Sallahif7c15532016-08-10 16:16:09 +02005081 /* Overflow means the specified offset is beyond input image's size */
5082 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5083 size < in.bsz * in.offset)) {
5084 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5085 } else {
5086 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5087 size - in.bsz * in.offset, &error_abort);
5088 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005089
5090 ret = bdrv_create(drv, out.filename, opts, &local_err);
5091 if (ret < 0) {
5092 error_reportf_err(local_err,
5093 "%s: error while creating output image: ",
5094 out.filename);
5095 ret = -1;
5096 goto out;
5097 }
5098
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005099 /* TODO, we can't honour --image-opts for the target,
5100 * since it needs to be given in a format compatible
5101 * with the bdrv_create() call above which does not
5102 * support image-opts style.
5103 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005104 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005105 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005106
5107 if (!blk2) {
5108 ret = -1;
5109 goto out;
5110 }
5111
Reda Sallahif7c15532016-08-10 16:16:09 +02005112 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5113 size < in.offset * in.bsz)) {
5114 /* We give a warning if the skip option is bigger than the input
5115 * size and create an empty output disk image (i.e. like dd(1)).
5116 */
5117 error_report("%s: cannot skip to specified offset", in.filename);
5118 in_pos = size;
5119 } else {
5120 in_pos = in.offset * in.bsz;
5121 }
5122
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005123 in.buf = g_new(uint8_t, in.bsz);
5124
Miroslav Rezanina0f48c472022-11-09 10:57:13 -05005125 for (out_pos = 0; in_pos < size; ) {
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005126 int bytes = (in_pos + in.bsz > size) ? size - in_pos : in.bsz;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005127
Alberto Fariaa9262f52022-07-05 17:15:11 +01005128 ret = blk_pread(blk1, in_pos, bytes, in.buf, 0);
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005129 if (ret < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005130 error_report("error while reading from input image file: %s",
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005131 strerror(-ret));
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005132 goto out;
5133 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005134 in_pos += bytes;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005135
Alberto Fariaa9262f52022-07-05 17:15:11 +01005136 ret = blk_pwrite(blk2, out_pos, bytes, in.buf, 0);
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005137 if (ret < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005138 error_report("error while writing to output image file: %s",
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005139 strerror(-ret));
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005140 goto out;
5141 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005142 out_pos += bytes;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005143 }
5144
5145out:
5146 g_free(arg);
5147 qemu_opts_del(opts);
5148 qemu_opts_free(create_opts);
5149 blk_unref(blk1);
5150 blk_unref(blk2);
5151 g_free(in.filename);
5152 g_free(out.filename);
5153 g_free(in.buf);
5154 g_free(out.buf);
5155
5156 if (ret) {
5157 return 1;
5158 }
5159 return 0;
5160}
5161
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005162static void dump_json_block_measure_info(BlockMeasureInfo *info)
5163{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005164 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005165 QObject *obj;
5166 Visitor *v = qobject_output_visitor_new(&obj);
5167
5168 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5169 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005170 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005171 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005172 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005173 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005174 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005175 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005176}
5177
5178static int img_measure(int argc, char **argv)
5179{
5180 static const struct option long_options[] = {
5181 {"help", no_argument, 0, 'h'},
5182 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5183 {"object", required_argument, 0, OPTION_OBJECT},
5184 {"output", required_argument, 0, OPTION_OUTPUT},
5185 {"size", required_argument, 0, OPTION_SIZE},
5186 {"force-share", no_argument, 0, 'U'},
5187 {0, 0, 0, 0}
5188 };
5189 OutputFormat output_format = OFORMAT_HUMAN;
5190 BlockBackend *in_blk = NULL;
5191 BlockDriver *drv;
5192 const char *filename = NULL;
5193 const char *fmt = NULL;
5194 const char *out_fmt = "raw";
5195 char *options = NULL;
5196 char *snapshot_name = NULL;
5197 bool force_share = false;
5198 QemuOpts *opts = NULL;
5199 QemuOpts *object_opts = NULL;
5200 QemuOpts *sn_opts = NULL;
5201 QemuOptsList *create_opts = NULL;
5202 bool image_opts = false;
5203 uint64_t img_size = UINT64_MAX;
5204 BlockMeasureInfo *info = NULL;
5205 Error *local_err = NULL;
5206 int ret = 1;
5207 int c;
5208
5209 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5210 long_options, NULL)) != -1) {
5211 switch (c) {
5212 case '?':
5213 case 'h':
5214 help();
5215 break;
5216 case 'f':
5217 fmt = optarg;
5218 break;
5219 case 'O':
5220 out_fmt = optarg;
5221 break;
5222 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005223 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005224 goto out;
5225 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005226 break;
5227 case 'l':
5228 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5229 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5230 optarg, false);
5231 if (!sn_opts) {
5232 error_report("Failed in parsing snapshot param '%s'",
5233 optarg);
5234 goto out;
5235 }
5236 } else {
5237 snapshot_name = optarg;
5238 }
5239 break;
5240 case 'U':
5241 force_share = true;
5242 break;
5243 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005244 user_creatable_process_cmdline(optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005245 break;
5246 case OPTION_IMAGE_OPTS:
5247 image_opts = true;
5248 break;
5249 case OPTION_OUTPUT:
5250 if (!strcmp(optarg, "json")) {
5251 output_format = OFORMAT_JSON;
5252 } else if (!strcmp(optarg, "human")) {
5253 output_format = OFORMAT_HUMAN;
5254 } else {
5255 error_report("--output must be used with human or json "
5256 "as argument.");
5257 goto out;
5258 }
5259 break;
5260 case OPTION_SIZE:
5261 {
5262 int64_t sval;
5263
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005264 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005265 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005266 goto out;
5267 }
5268 img_size = (uint64_t)sval;
5269 }
5270 break;
5271 }
5272 }
5273
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005274 if (argc - optind > 1) {
5275 error_report("At most one filename argument is allowed.");
5276 goto out;
5277 } else if (argc - optind == 1) {
5278 filename = argv[optind];
5279 }
5280
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005281 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5282 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005283 goto out;
5284 }
5285 if (filename && img_size != UINT64_MAX) {
5286 error_report("--size N cannot be used together with a filename.");
5287 goto out;
5288 }
5289 if (!filename && img_size == UINT64_MAX) {
5290 error_report("Either --size N or one filename must be specified.");
5291 goto out;
5292 }
5293
5294 if (filename) {
5295 in_blk = img_open(image_opts, filename, fmt, 0,
5296 false, false, force_share);
5297 if (!in_blk) {
5298 goto out;
5299 }
5300
5301 if (sn_opts) {
5302 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5303 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5304 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5305 &local_err);
5306 } else if (snapshot_name != NULL) {
5307 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5308 snapshot_name, &local_err);
5309 }
5310 if (local_err) {
5311 error_reportf_err(local_err, "Failed to load snapshot: ");
5312 goto out;
5313 }
5314 }
5315
5316 drv = bdrv_find_format(out_fmt);
5317 if (!drv) {
5318 error_report("Unknown file format '%s'", out_fmt);
5319 goto out;
5320 }
5321 if (!drv->create_opts) {
5322 error_report("Format driver '%s' does not support image creation",
5323 drv->format_name);
5324 goto out;
5325 }
5326
5327 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5328 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5329 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5330 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005331 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005332 error_report_err(local_err);
5333 error_report("Invalid options for file format '%s'", out_fmt);
5334 goto out;
5335 }
5336 }
5337 if (img_size != UINT64_MAX) {
5338 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5339 }
5340
5341 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5342 if (local_err) {
5343 error_report_err(local_err);
5344 goto out;
5345 }
5346
5347 if (output_format == OFORMAT_HUMAN) {
5348 printf("required size: %" PRIu64 "\n", info->required);
5349 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005350 if (info->has_bitmaps) {
5351 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5352 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005353 } else {
5354 dump_json_block_measure_info(info);
5355 }
5356
5357 ret = 0;
5358
5359out:
5360 qapi_free_BlockMeasureInfo(info);
5361 qemu_opts_del(object_opts);
5362 qemu_opts_del(opts);
5363 qemu_opts_del(sn_opts);
5364 qemu_opts_free(create_opts);
5365 g_free(options);
5366 blk_unref(in_blk);
5367 return ret;
5368}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005369
Anthony Liguoric227f092009-10-01 16:12:16 -05005370static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005371#define DEF(option, callback, arg_string) \
5372 { option, callback },
5373#include "qemu-img-cmds.h"
5374#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005375 { NULL, NULL, },
5376};
5377
bellardea2384d2004-08-01 21:59:26 +00005378int main(int argc, char **argv)
5379{
Anthony Liguoric227f092009-10-01 16:12:16 -05005380 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005381 const char *cmdname;
Jeff Cody7db16892014-04-25 17:02:32 -04005382 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005383 static const struct option long_options[] = {
5384 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005385 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005386 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005387 {0, 0, 0, 0}
5388 };
bellardea2384d2004-08-01 21:59:26 +00005389
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005390#ifdef CONFIG_POSIX
5391 signal(SIGPIPE, SIG_IGN);
5392#endif
5393
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005394 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005395 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005396 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005397 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005398
Markus Armbrusterf9734d52021-07-20 14:53:53 +02005399 qemu_init_main_loop(&error_fatal);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005400
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005401 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005402
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005403 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005404 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005405 if (argc < 2) {
5406 error_exit("Not enough arguments");
5407 }
Stuart Brady153859b2009-06-07 00:42:17 +01005408
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005409 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005410 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005411
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005412 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005413 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005414 case ':':
5415 missing_argument(argv[optind - 1]);
5416 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005417 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005418 unrecognized_option(argv[optind - 1]);
5419 return 0;
5420 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005421 help();
5422 return 0;
5423 case 'V':
5424 printf(QEMU_IMG_VERSION);
5425 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005426 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005427 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005428 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005429 }
bellardea2384d2004-08-01 21:59:26 +00005430 }
Stuart Brady153859b2009-06-07 00:42:17 +01005431
Denis V. Lunev10985132016-06-17 17:44:13 +03005432 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005433
Denis V. Lunev10985132016-06-17 17:44:13 +03005434 /* reset getopt_long scanning */
5435 argc -= optind;
5436 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005437 return 0;
5438 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005439 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005440 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005441
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005442 if (!trace_init_backends()) {
5443 exit(1);
5444 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005445 trace_init_file();
Richard Hendersonc5955f42022-04-17 11:29:44 -07005446 qemu_set_log(LOG_TRACE, &error_fatal);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005447
Denis V. Lunev10985132016-06-17 17:44:13 +03005448 /* find the command */
5449 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5450 if (!strcmp(cmdname, cmd->name)) {
5451 return cmd->handler(argc, argv);
5452 }
5453 }
Jeff Cody7db16892014-04-25 17:02:32 -04005454
Stuart Brady153859b2009-06-07 00:42:17 +01005455 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005456 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005457}