blob: babb5573ab61016effa97347409c814776901cba [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050031#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010032#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010033#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010035#include "qapi/qmp/qdict.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020036#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000037#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010038#include "qemu/option.h"
39#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030040#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020041#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020042#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010043#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020044#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000045#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020046#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010047#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020048#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080049#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010050#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030051#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000052#include "qemu/throttle.h"
53#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000054
Thomas Huth7e563bf2018-02-15 12:06:47 +010055#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020056 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040057
Anthony Liguoric227f092009-10-01 16:12:16 -050058typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010059 const char *name;
60 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050061} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010062
Federico Simoncelli8599ea42013-01-28 06:59:47 -050063enum {
64 OPTION_OUTPUT = 256,
65 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000066 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000067 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020068 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020069 OPTION_FLUSH_INTERVAL = 261,
70 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010071 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010072 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020073 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030074 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020075 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000076 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050077 OPTION_ADD = 269,
78 OPTION_REMOVE = 270,
79 OPTION_CLEAR = 271,
80 OPTION_ENABLE = 272,
81 OPTION_DISABLE = 273,
82 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050083 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020084 OPTION_FORCE = 276,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050085};
86
87typedef enum OutputFormat {
88 OFORMAT_JSON,
89 OFORMAT_HUMAN,
90} OutputFormat;
91
Kevin Wolfe6996142016-03-15 13:03:11 +010092/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040093#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000094
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010095static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000096{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010097 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000098}
99
Fam Zhengac1307a2014-04-22 13:36:11 +0800100static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
101{
102 va_list ap;
103
Fam Zhengac1307a2014-04-22 13:36:11 +0800104 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200105 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800106 va_end(ap);
107
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200108 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800109 exit(EXIT_FAILURE);
110}
111
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800112static void QEMU_NORETURN missing_argument(const char *option)
113{
114 error_exit("missing argument for option '%s'", option);
115}
116
117static void QEMU_NORETURN unrecognized_option(const char *option)
118{
119 error_exit("unrecognized option '%s'", option);
120}
121
Eric Blake0562adf2020-05-12 20:16:41 -0500122/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800123static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000124{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100125 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400126 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300127 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300128 "QEMU disk image utility\n"
129 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300130 " '-h', '--help' display this help and exit\n"
131 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300132 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
133 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300134 "\n"
malc3f020d72010-02-08 12:04:56 +0300135 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100136#define DEF(option, callback, arg_string) \
137 " " arg_string "\n"
138#include "qemu-img-cmds.h"
139#undef DEF
malc3f020d72010-02-08 12:04:56 +0300140 "\n"
141 "Command parameters:\n"
142 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000143 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
144 " manual page for a description of the object properties. The most common\n"
145 " object type is a 'secret', which is used to supply passwords and/or\n"
146 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300147 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400148 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800149 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
150 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100151 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
152 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300153 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200154 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
155 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
156 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300157 " 'output_filename' is the destination disk image filename\n"
158 " 'output_fmt' is the destination format\n"
159 " 'options' is a comma separated list of format specific options in a\n"
160 " name=value format. Use -o ? for an overview of the options supported by the\n"
161 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800162 " 'snapshot_param' is param used for internal snapshot, format\n"
163 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
164 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300165 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400166 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
167 " new backing file match exactly. The image doesn't need a working\n"
168 " backing file before rebasing in this case (useful for renaming the\n"
169 " backing file). For image creation, allow creating without attempting\n"
170 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300171 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200172 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100173 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200174 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
175 " contain only zeros for qemu-img to create a sparse image during\n"
176 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
177 " unallocated or zero sectors, and the destination image will always be\n"
178 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200179 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100180 " '-n' skips the target volume creation (useful if the volume is created\n"
181 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300182 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500183 "Parameters to bitmap subcommand:\n"
184 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
185 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
186 " or '--merge source'\n"
187 " '-g granularity' sets the granularity for '--add' actions\n"
188 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
189 " bitmaps from an alternative file\n"
190 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200191 "Parameters to check subcommand:\n"
192 " '-r' tries to repair any inconsistencies that are found during the check.\n"
193 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
194 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200195 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200196 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100197 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500198 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100199 " '-m' specifies how many coroutines work in parallel during the convert\n"
200 " process (defaults to 8)\n"
201 " '-W' allow to write to the target out of order rather than sequential\n"
202 "\n"
malc3f020d72010-02-08 12:04:56 +0300203 "Parameters to snapshot subcommand:\n"
204 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
205 " '-a' applies a snapshot (revert disk to saved state)\n"
206 " '-c' creates a snapshot\n"
207 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100208 " '-l' lists all snapshots in the given image\n"
209 "\n"
210 "Parameters to compare subcommand:\n"
211 " '-f' first image format\n"
212 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200213 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
214 "\n"
215 "Parameters to dd subcommand:\n"
216 " 'bs=BYTES' read and write up to BYTES bytes at a time "
217 "(default: 512)\n"
218 " 'count=N' copy only N input blocks\n"
219 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200220 " 'of=FILE' write to FILE\n"
221 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100222
223 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300224 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500225 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800226 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000227}
228
Markus Armbruster80c710c2020-04-15 09:49:26 +0200229/*
230 * Is @optarg safe for accumulate_options()?
231 * It is when multiple of them can be joined together separated by ','.
232 * To make that work, @optarg must not start with ',' (or else a
233 * separating ',' preceding it gets escaped), and it must not end with
234 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200235 * escaped), or be empty (or else a separating ',' preceding it can
236 * escape a separating ',' following it).
237 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200238 */
239static bool is_valid_option_list(const char *optarg)
240{
241 size_t len = strlen(optarg);
242 size_t i;
243
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200244 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200245 return false;
246 }
247
248 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
249 }
250 if ((len - i) % 2) {
251 return false;
252 }
253
254 return true;
255}
256
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200257static int accumulate_options(char **options, char *optarg)
258{
259 char *new_options;
260
261 if (!is_valid_option_list(optarg)) {
262 error_report("Invalid option list: %s", optarg);
263 return -1;
264 }
265
266 if (!*options) {
267 *options = g_strdup(optarg);
268 } else {
269 new_options = g_strdup_printf("%s,%s", *options, optarg);
270 g_free(*options);
271 *options = new_options;
272 }
273 return 0;
274}
275
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000276static QemuOptsList qemu_source_opts = {
277 .name = "source",
278 .implied_opt_name = "file",
279 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
280 .desc = {
281 { }
282 },
283};
284
Stefan Weil7c30f652013-06-16 17:01:05 +0200285static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100286{
287 int ret = 0;
288 if (!quiet) {
289 va_list args;
290 va_start(args, fmt);
291 ret = vprintf(fmt, args);
292 va_end(args);
293 }
294 return ret;
295}
296
bellardea2384d2004-08-01 21:59:26 +0000297
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100298static int print_block_option_help(const char *filename, const char *fmt)
299{
300 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800301 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500302 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100303
304 /* Find driver and parse its options */
305 drv = bdrv_find_format(fmt);
306 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100307 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100308 return 1;
309 }
310
Max Reitzd402b6a2018-05-09 23:00:21 +0200311 if (!drv->create_opts) {
312 error_report("Format driver '%s' does not support image creation", fmt);
313 return 1;
314 }
315
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800316 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100317 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500318 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100319 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100320 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800321 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100322 return 1;
323 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200324 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100325 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200326 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100327 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200328 return 1;
329 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800330 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100331 }
332
Max Reitzf4619af2019-04-13 17:20:37 +0200333 if (filename) {
334 printf("Supported options:\n");
335 } else {
336 printf("Supported %s options:\n", fmt);
337 }
Max Reitz63898712018-10-19 18:49:25 +0200338 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800339 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200340
341 if (!filename) {
342 printf("\n"
343 "The protocol level may support further options.\n"
344 "Specify the target filename to include those options.\n");
345 }
346
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100347 return 0;
348}
349
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000350
Max Reitzefaa7c42016-03-16 19:54:38 +0100351static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100352 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800353 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000354{
355 QDict *options;
356 Error *local_err = NULL;
357 BlockBackend *blk;
358 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800359 if (force_share) {
360 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200361 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800362 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200363 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800364 return NULL;
365 }
Max Reitz4615f872018-05-02 22:20:50 +0200366 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800367 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100368 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000369 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100370 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000371 return NULL;
372 }
Kevin Wolfce099542016-03-15 13:01:04 +0100373 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000374
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000375 return blk;
376}
377
Max Reitzefaa7c42016-03-16 19:54:38 +0100378static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100379 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000380 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800381 bool writethrough, bool quiet,
382 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383{
384 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200385 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100386
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100387 if (!options) {
388 options = qdict_new();
389 }
bellard75c23802004-08-27 21:28:58 +0000390 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500391 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000392 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100393
Fam Zheng335e9932017-05-03 00:35:39 +0800394 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500395 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800396 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100397 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500398 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100399 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000400 return NULL;
bellard75c23802004-08-27 21:28:58 +0000401 }
Kevin Wolfce099542016-03-15 13:01:04 +0100402 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100403
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200404 return blk;
bellard75c23802004-08-27 21:28:58 +0000405}
406
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000407
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100408static int img_add_key_secrets(void *opaque,
409 const char *name, const char *value,
410 Error **errp)
411{
412 QDict *options = opaque;
413
414 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600415 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100416 }
417
418 return 0;
419}
420
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100421
Max Reitzefaa7c42016-03-16 19:54:38 +0100422static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000423 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100424 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800425 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000426{
427 BlockBackend *blk;
428 if (image_opts) {
429 QemuOpts *opts;
430 if (fmt) {
431 error_report("--image-opts and --format are mutually exclusive");
432 return NULL;
433 }
434 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
435 filename, true);
436 if (!opts) {
437 return NULL;
438 }
Fam Zheng335e9932017-05-03 00:35:39 +0800439 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
440 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000441 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100442 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800443 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000444 }
445 return blk;
446}
447
448
Chunyan Liu83d05212014-06-05 17:20:51 +0800449static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100450 const char *base_filename,
451 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200452{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200453 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200454 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200455 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100456 error_report("Backing file not supported for file format '%s'",
457 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900458 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200459 }
460 }
461 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200462 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100463 error_report("Backing file format not supported for file "
464 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900465 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200466 }
467 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900468 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200469}
470
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300471static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
472 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100473{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100474 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300475 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100476
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300477 err = qemu_strtosz(value, NULL, &res);
478 if (err < 0 && err != -ERANGE) {
479 error_report("Invalid %s specified. You may use "
480 "k, M, G, T, P or E suffixes for", name);
481 error_report("kilobytes, megabytes, gigabytes, terabytes, "
482 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100483 return err;
484 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300485 if (err == -ERANGE || res > max || res < min) {
486 error_report("Invalid %s specified. Must be between %" PRId64
487 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100488 return -ERANGE;
489 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300490 return res;
491}
492
493static int64_t cvtnum(const char *name, const char *value)
494{
495 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100496}
497
bellardea2384d2004-08-01 21:59:26 +0000498static int img_create(int argc, char **argv)
499{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200500 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100501 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000502 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000503 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000504 const char *filename;
505 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200506 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200507 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100508 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400509 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000510
bellardea2384d2004-08-01 21:59:26 +0000511 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000512 static const struct option long_options[] = {
513 {"help", no_argument, 0, 'h'},
514 {"object", required_argument, 0, OPTION_OBJECT},
515 {0, 0, 0, 0}
516 };
John Snow6e6e55f2017-07-17 20:34:22 -0400517 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000518 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100519 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000520 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100521 }
bellardea2384d2004-08-01 21:59:26 +0000522 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800523 case ':':
524 missing_argument(argv[optind - 1]);
525 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100526 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800527 unrecognized_option(argv[optind - 1]);
528 break;
bellardea2384d2004-08-01 21:59:26 +0000529 case 'h':
530 help();
531 break;
aliguori9230eaf2009-03-28 17:55:19 +0000532 case 'F':
533 base_fmt = optarg;
534 break;
bellardea2384d2004-08-01 21:59:26 +0000535 case 'b':
536 base_filename = optarg;
537 break;
538 case 'f':
539 fmt = optarg;
540 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200541 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200542 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100543 goto fail;
544 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200545 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100546 case 'q':
547 quiet = true;
548 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400549 case 'u':
550 flags |= BDRV_O_NO_BACKING;
551 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100552 case OPTION_OBJECT:
553 user_creatable_process_cmdline(optarg);
554 break;
bellardea2384d2004-08-01 21:59:26 +0000555 }
556 }
aliguori9230eaf2009-03-28 17:55:19 +0000557
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900558 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100559 filename = (optind < argc) ? argv[optind] : NULL;
560 if (options && has_help_option(options)) {
561 g_free(options);
562 return print_block_option_help(filename, fmt);
563 }
564
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100565 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800566 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100567 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100568 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900569
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100570 /* Get image size, if specified */
571 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100572 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100573
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300574 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100575 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100576 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100577 }
578 img_size = (uint64_t)sval;
579 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200580 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800581 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200582 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100583
Luiz Capitulino9b375252012-11-30 10:52:05 -0200584 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400585 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100586 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100587 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100588 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900589 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200590
Kevin Wolf77386bf2014-02-21 16:24:04 +0100591 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000592 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100593
594fail:
595 g_free(options);
596 return 1;
bellardea2384d2004-08-01 21:59:26 +0000597}
598
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100599static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500600{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100601 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500602 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100603 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600604
605 visit_type_ImageCheck(v, NULL, &check, &error_abort);
606 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100607 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500608 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100609 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200610 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600611 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100612 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613}
614
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100615static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500616{
617 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100618 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500619 } else {
620 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100621 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
622 "Data may be corrupted, or further writes to the image "
623 "may corrupt it.\n",
624 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500625 }
626
627 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100628 qprintf(quiet,
629 "\n%" PRId64 " leaked clusters were found on the image.\n"
630 "This means waste of disk space, but no harm to data.\n",
631 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 }
633
634 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100635 qprintf(quiet,
636 "\n%" PRId64
637 " internal errors have occurred during the check.\n",
638 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500639 }
640 }
641
642 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100643 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
644 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
645 check->allocated_clusters, check->total_clusters,
646 check->allocated_clusters * 100.0 / check->total_clusters,
647 check->fragmented_clusters * 100.0 / check->allocated_clusters,
648 check->compressed_clusters * 100.0 /
649 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500650 }
651
652 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100653 qprintf(quiet,
654 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500655 }
656}
657
658static int collect_image_check(BlockDriverState *bs,
659 ImageCheck *check,
660 const char *filename,
661 const char *fmt,
662 int fix)
663{
664 int ret;
665 BdrvCheckResult result;
666
667 ret = bdrv_check(bs, &result, fix);
668 if (ret < 0) {
669 return ret;
670 }
671
672 check->filename = g_strdup(filename);
673 check->format = g_strdup(bdrv_get_format_name(bs));
674 check->check_errors = result.check_errors;
675 check->corruptions = result.corruptions;
676 check->has_corruptions = result.corruptions != 0;
677 check->leaks = result.leaks;
678 check->has_leaks = result.leaks != 0;
679 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100680 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500681 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100682 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 check->image_end_offset = result.image_end_offset;
684 check->has_image_end_offset = result.image_end_offset != 0;
685 check->total_clusters = result.bfi.total_clusters;
686 check->has_total_clusters = result.bfi.total_clusters != 0;
687 check->allocated_clusters = result.bfi.allocated_clusters;
688 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
689 check->fragmented_clusters = result.bfi.fragmented_clusters;
690 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100691 check->compressed_clusters = result.bfi.compressed_clusters;
692 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500693
694 return 0;
695}
696
Kevin Wolfe076f332010-06-29 11:43:13 +0200697/*
698 * Checks an image for consistency. Exit codes:
699 *
Max Reitzd6635c42014-06-02 22:15:21 +0200700 * 0 - Check completed, image is good
701 * 1 - Check not completed because of internal errors
702 * 2 - Check completed, image is corrupted
703 * 3 - Check completed, image has leaked clusters, but is good otherwise
704 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200705 */
aliguori15859692009-04-21 23:11:53 +0000706static int img_check(int argc, char **argv)
707{
708 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500709 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200710 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200711 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000712 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200713 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100714 int flags = BDRV_O_CHECK;
715 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200716 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100717 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000718 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800719 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000720
721 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500722 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200723 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100724
aliguori15859692009-04-21 23:11:53 +0000725 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500726 int option_index = 0;
727 static const struct option long_options[] = {
728 {"help", no_argument, 0, 'h'},
729 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530730 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500731 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000732 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000733 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800734 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500735 {0, 0, 0, 0}
736 };
Fam Zheng335e9932017-05-03 00:35:39 +0800737 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500738 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100739 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000740 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100741 }
aliguori15859692009-04-21 23:11:53 +0000742 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800743 case ':':
744 missing_argument(argv[optind - 1]);
745 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100746 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800747 unrecognized_option(argv[optind - 1]);
748 break;
aliguori15859692009-04-21 23:11:53 +0000749 case 'h':
750 help();
751 break;
752 case 'f':
753 fmt = optarg;
754 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200755 case 'r':
756 flags |= BDRV_O_RDWR;
757
758 if (!strcmp(optarg, "leaks")) {
759 fix = BDRV_FIX_LEAKS;
760 } else if (!strcmp(optarg, "all")) {
761 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
762 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800763 error_exit("Unknown option value for -r "
764 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200765 }
766 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500767 case OPTION_OUTPUT:
768 output = optarg;
769 break;
Max Reitz40055952014-07-22 22:58:42 +0200770 case 'T':
771 cache = optarg;
772 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100773 case 'q':
774 quiet = true;
775 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800776 case 'U':
777 force_share = true;
778 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100779 case OPTION_OBJECT:
780 user_creatable_process_cmdline(optarg);
781 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000782 case OPTION_IMAGE_OPTS:
783 image_opts = true;
784 break;
aliguori15859692009-04-21 23:11:53 +0000785 }
786 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200787 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800788 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100789 }
aliguori15859692009-04-21 23:11:53 +0000790 filename = argv[optind++];
791
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500792 if (output && !strcmp(output, "json")) {
793 output_format = OFORMAT_JSON;
794 } else if (output && !strcmp(output, "human")) {
795 output_format = OFORMAT_HUMAN;
796 } else if (output) {
797 error_report("--output must be used with human or json as argument.");
798 return 1;
799 }
800
Kevin Wolfce099542016-03-15 13:01:04 +0100801 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200802 if (ret < 0) {
803 error_report("Invalid source cache option: %s", cache);
804 return 1;
805 }
806
Fam Zheng335e9932017-05-03 00:35:39 +0800807 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
808 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200809 if (!blk) {
810 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900811 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200812 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500813
814 check = g_new0(ImageCheck, 1);
815 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200816
817 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200818 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200819 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500820 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200821 }
822
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500823 if (check->corruptions_fixed || check->leaks_fixed) {
824 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100825 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826
827 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100828 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500829 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100830 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500831
832 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100833 qprintf(quiet,
834 "The following inconsistencies were found and repaired:\n\n"
835 " %" PRId64 " leaked clusters\n"
836 " %" PRId64 " corruptions\n\n"
837 "Double checking the fixed image now...\n",
838 check->leaks_fixed,
839 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500840 }
841
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800842 qapi_free_ImageCheck(check);
843 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500844 ret = collect_image_check(bs, check, filename, fmt, 0);
845
846 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100847 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500848 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100849 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200850 }
851
Max Reitz832390a2014-10-23 15:29:12 +0200852 if (!ret) {
853 switch (output_format) {
854 case OFORMAT_HUMAN:
855 dump_human_image_check(check, quiet);
856 break;
857 case OFORMAT_JSON:
858 dump_json_image_check(check, quiet);
859 break;
860 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500861 }
862
863 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200864 if (ret) {
865 error_report("Check failed: %s", strerror(-ret));
866 } else {
867 error_report("Check failed");
868 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500869 ret = 1;
870 goto fail;
871 }
872
873 if (check->corruptions) {
874 ret = 2;
875 } else if (check->leaks) {
876 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200877 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500878 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000879 }
880
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500881fail:
882 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200883 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500884 return ret;
aliguori15859692009-04-21 23:11:53 +0000885}
886
Max Reitzd4a32382014-10-24 15:57:37 +0200887typedef struct CommonBlockJobCBInfo {
888 BlockDriverState *bs;
889 Error **errp;
890} CommonBlockJobCBInfo;
891
892static void common_block_job_cb(void *opaque, int ret)
893{
894 CommonBlockJobCBInfo *cbi = opaque;
895
896 if (ret < 0) {
897 error_setg_errno(cbi->errp, -ret, "Block job failed");
898 }
Max Reitzd4a32382014-10-24 15:57:37 +0200899}
900
901static void run_block_job(BlockJob *job, Error **errp)
902{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200903 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800904 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200905
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200906 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200907 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200908 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200909 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200910 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300911 if (job->job.progress.total) {
912 progress = (float)job->job.progress.current /
913 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200914 }
915 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200916 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200917
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200918 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200919 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800920 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200921 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800922 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200923 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200924 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200925
sochin.jiang4172a002017-06-15 14:47:33 +0800926 /* publish completion progress only when success */
927 if (!ret) {
928 qemu_progress_print(100.f, 0);
929 }
Max Reitzd4a32382014-10-24 15:57:37 +0200930}
931
bellardea2384d2004-08-01 21:59:26 +0000932static int img_commit(int argc, char **argv)
933{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400934 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200935 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200936 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200937 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100938 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200939 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100940 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200941 Error *local_err = NULL;
942 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000943 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200944 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000945 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000946
947 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400948 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200949 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000950 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000951 static const struct option long_options[] = {
952 {"help", no_argument, 0, 'h'},
953 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000954 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000955 {0, 0, 0, 0}
956 };
Zhenguia0441b62020-10-20 14:47:43 +0000957 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000958 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100959 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000960 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100961 }
bellardea2384d2004-08-01 21:59:26 +0000962 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800963 case ':':
964 missing_argument(argv[optind - 1]);
965 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100966 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800967 unrecognized_option(argv[optind - 1]);
968 break;
bellardea2384d2004-08-01 21:59:26 +0000969 case 'h':
970 help();
971 break;
972 case 'f':
973 fmt = optarg;
974 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400975 case 't':
976 cache = optarg;
977 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200978 case 'b':
979 base = optarg;
980 /* -b implies -d */
981 drop = true;
982 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200983 case 'd':
984 drop = true;
985 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200986 case 'p':
987 progress = true;
988 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100989 case 'q':
990 quiet = true;
991 break;
Zhenguia0441b62020-10-20 14:47:43 +0000992 case 'r':
993 rate_limit = cvtnum("rate limit", optarg);
994 if (rate_limit < 0) {
995 return 1;
996 }
997 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100998 case OPTION_OBJECT:
999 user_creatable_process_cmdline(optarg);
1000 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001001 case OPTION_IMAGE_OPTS:
1002 image_opts = true;
1003 break;
bellardea2384d2004-08-01 21:59:26 +00001004 }
1005 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001006
1007 /* Progress is not shown in Quiet mode */
1008 if (quiet) {
1009 progress = false;
1010 }
1011
Kevin Wolffc11eb22013-08-05 10:53:04 +02001012 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001013 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001014 }
bellardea2384d2004-08-01 21:59:26 +00001015 filename = argv[optind++];
1016
Max Reitz9a86fe42014-10-24 15:57:38 +02001017 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001018 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001019 if (ret < 0) {
1020 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001021 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001022 }
1023
Fam Zheng335e9932017-05-03 00:35:39 +08001024 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1025 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001026 if (!blk) {
1027 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001028 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001029 bs = blk_bs(blk);
1030
Max Reitz687fa1d2014-10-24 15:57:39 +02001031 qemu_progress_init(progress, 1.f);
1032 qemu_progress_print(0.f, 100);
1033
Max Reitz1b22bff2014-10-24 15:57:40 +02001034 if (base) {
1035 base_bs = bdrv_find_backing_image(bs, base);
1036 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001037 error_setg(&local_err,
1038 "Did not find '%s' in the backing chain of '%s'",
1039 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001040 goto done;
1041 }
1042 } else {
1043 /* This is different from QMP, which by default uses the deepest file in
1044 * the backing chain (i.e., the very base); however, the traditional
1045 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001046 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001047 if (!base_bs) {
1048 error_setg(&local_err, "Image does not have a backing file");
1049 goto done;
1050 }
bellardea2384d2004-08-01 21:59:26 +00001051 }
1052
Max Reitzd4a32382014-10-24 15:57:37 +02001053 cbi = (CommonBlockJobCBInfo){
1054 .errp = &local_err,
1055 .bs = bs,
1056 };
1057
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001058 aio_context = bdrv_get_aio_context(bs);
1059 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001060 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001061 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001062 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001063 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001064 if (local_err) {
1065 goto done;
1066 }
1067
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001068 /* When the block job completes, the BlockBackend reference will point to
1069 * the old backing file. In order to avoid that the top image is already
1070 * deleted, so we can still empty it afterwards, increment the reference
1071 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001072 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001073 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001074 }
1075
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001076 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001077 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001078 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001079 if (local_err) {
1080 goto unref_backing;
1081 }
1082
Max Reitz2d97fde2020-04-29 16:11:26 +02001083 if (!drop) {
1084 BlockBackend *old_backing_blk;
1085
1086 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1087 &local_err);
1088 if (!old_backing_blk) {
1089 goto unref_backing;
1090 }
1091 ret = blk_make_empty(old_backing_blk, &local_err);
1092 blk_unref(old_backing_blk);
1093 if (ret == -ENOTSUP) {
1094 error_free(local_err);
1095 local_err = NULL;
1096 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001097 goto unref_backing;
1098 }
1099 }
1100
1101unref_backing:
1102 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001103 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001104 }
Max Reitzd4a32382014-10-24 15:57:37 +02001105
1106done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001107 qemu_progress_end();
1108
Markus Armbruster26f54e92014-10-07 13:59:04 +02001109 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001110
1111 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001112 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001113 return 1;
1114 }
Max Reitzd4a32382014-10-24 15:57:37 +02001115
1116 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001117 return 0;
1118}
1119
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001120/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001121 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1122 * of the first sector boundary within buf where the sector contains a
1123 * non-zero byte. This function is robust to a buffer that is not
1124 * sector-aligned.
1125 */
1126static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1127{
1128 int64_t i;
1129 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1130
1131 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1132 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1133 return i;
1134 }
1135 }
1136 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1137 return i;
1138 }
1139 return -1;
1140}
1141
1142/*
thsf58c7b32008-06-05 21:53:49 +00001143 * Returns true iff the first sector pointed to by 'buf' contains at least
1144 * a non-NUL byte.
1145 *
1146 * 'pnum' is set to the number of sectors (including and immediately following
1147 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001148 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001149 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001150 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001151 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001152static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1153 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001154{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001155 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001156 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001157
1158 if (n <= 0) {
1159 *pnum = 0;
1160 return 0;
1161 }
Yi Lic075c422020-08-19 09:36:07 +08001162 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001163 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001164 buf += BDRV_SECTOR_SIZE;
1165 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001166 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001167 }
bellardea2384d2004-08-01 21:59:26 +00001168 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001169
1170 tail = (sector_num + i) & (alignment - 1);
1171 if (tail) {
1172 if (is_zero && i <= tail) {
1173 /* treat unallocated areas which only consist
1174 * of a small tail as allocated. */
1175 is_zero = false;
1176 }
1177 if (!is_zero) {
1178 /* align up end offset of allocated areas. */
1179 i += alignment - tail;
1180 i = MIN(i, n);
1181 } else {
1182 /* align down end offset of zero areas. */
1183 i -= tail;
1184 }
1185 }
bellardea2384d2004-08-01 21:59:26 +00001186 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001187 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001188}
1189
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001190/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001191 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1192 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1193 * breaking up write requests for only small sparse areas.
1194 */
1195static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001196 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001197{
1198 int ret;
1199 int num_checked, num_used;
1200
1201 if (n < min) {
1202 min = n;
1203 }
1204
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001205 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001206 if (!ret) {
1207 return ret;
1208 }
1209
1210 num_used = *pnum;
1211 buf += BDRV_SECTOR_SIZE * *pnum;
1212 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001213 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001214 num_checked = num_used;
1215
1216 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001217 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001218
1219 buf += BDRV_SECTOR_SIZE * *pnum;
1220 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001221 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001222 num_checked += *pnum;
1223 if (ret) {
1224 num_used = num_checked;
1225 } else if (*pnum >= min) {
1226 break;
1227 }
1228 }
1229
1230 *pnum = num_used;
1231 return 1;
1232}
1233
1234/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001235 * Compares two buffers sector by sector. Returns 0 if the first
1236 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001237 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001238 * pnum is set to the sector-aligned size of the buffer prefix that
1239 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001240 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001241static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1242 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001243{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001244 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001245 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001246
Eric Blakedc61cd32017-10-11 22:47:14 -05001247 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001248
Eric Blakedc61cd32017-10-11 22:47:14 -05001249 res = !!memcmp(buf1, buf2, i);
1250 while (i < bytes) {
1251 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001252
Eric Blakedc61cd32017-10-11 22:47:14 -05001253 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001254 break;
1255 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001256 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001257 }
1258
1259 *pnum = i;
1260 return res;
1261}
1262
Stefano Garzarella97ede572019-05-08 12:43:24 +02001263#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001264
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001265/*
1266 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1267 *
Eric Blake0608e402017-10-11 22:47:12 -05001268 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1269 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1270 * failure), and 4 on error (the exit status for read errors), after emitting
1271 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001272 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001273 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001274 * @param offset: Starting offset to check
1275 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001276 * @param filename: Name of disk file we are checking (logging purpose)
1277 * @param buffer: Allocated buffer for storing read data
1278 * @param quiet: Flag for quiet mode
1279 */
Eric Blakec41508e2017-10-11 22:47:13 -05001280static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1281 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001282 uint8_t *buffer, bool quiet)
1283{
Eric Blakedebb38a2017-10-11 22:47:11 -05001284 int ret = 0;
1285 int64_t idx;
1286
Eric Blakec41508e2017-10-11 22:47:13 -05001287 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001288 if (ret < 0) {
1289 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001290 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001291 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001292 }
Eric Blakec41508e2017-10-11 22:47:13 -05001293 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001294 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001295 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001296 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001297 return 1;
1298 }
1299
1300 return 0;
1301}
1302
1303/*
1304 * Compares two images. Exit codes:
1305 *
Kevin Wolf99b1e642021-02-17 12:56:45 +01001306 * 0 - Images are identical or the requested help was printed
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001307 * 1 - Images differ
1308 * >1 - Error occurred
1309 */
1310static int img_compare(int argc, char **argv)
1311{
Max Reitz40055952014-07-22 22:58:42 +02001312 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001313 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001314 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001315 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001316 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001317 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 int allocated1, allocated2;
1319 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1320 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001321 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001322 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001323 int64_t total_size;
1324 int64_t offset = 0;
1325 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001326 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001327 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001328 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001329 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001330
Max Reitz40055952014-07-22 22:58:42 +02001331 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001332 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001333 static const struct option long_options[] = {
1334 {"help", no_argument, 0, 'h'},
1335 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001336 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001337 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001338 {0, 0, 0, 0}
1339 };
Fam Zheng335e9932017-05-03 00:35:39 +08001340 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001341 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001342 if (c == -1) {
1343 break;
1344 }
1345 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001346 case ':':
1347 missing_argument(argv[optind - 1]);
1348 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001349 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001350 unrecognized_option(argv[optind - 1]);
1351 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001352 case 'h':
1353 help();
1354 break;
1355 case 'f':
1356 fmt1 = optarg;
1357 break;
1358 case 'F':
1359 fmt2 = optarg;
1360 break;
Max Reitz40055952014-07-22 22:58:42 +02001361 case 'T':
1362 cache = optarg;
1363 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 case 'p':
1365 progress = true;
1366 break;
1367 case 'q':
1368 quiet = true;
1369 break;
1370 case 's':
1371 strict = true;
1372 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001373 case 'U':
1374 force_share = true;
1375 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001376 case OPTION_OBJECT:
1377 {
1378 Error *local_err = NULL;
1379
1380 if (!user_creatable_add_from_str(optarg, &local_err)) {
1381 if (local_err) {
1382 error_report_err(local_err);
1383 exit(2);
1384 } else {
1385 /* Help was printed */
1386 exit(EXIT_SUCCESS);
1387 }
1388 }
1389 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001390 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001391 case OPTION_IMAGE_OPTS:
1392 image_opts = true;
1393 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394 }
1395 }
1396
1397 /* Progress is not shown in Quiet mode */
1398 if (quiet) {
1399 progress = false;
1400 }
1401
1402
Kevin Wolffc11eb22013-08-05 10:53:04 +02001403 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001404 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001405 }
1406 filename1 = argv[optind++];
1407 filename2 = argv[optind++];
1408
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001409 /* Initialize before goto out */
1410 qemu_progress_init(progress, 2.0);
1411
Kevin Wolfce099542016-03-15 13:01:04 +01001412 flags = 0;
1413 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001414 if (ret < 0) {
1415 error_report("Invalid source cache option: %s", cache);
1416 ret = 2;
1417 goto out3;
1418 }
1419
Fam Zheng335e9932017-05-03 00:35:39 +08001420 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1421 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001422 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001423 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001424 goto out3;
1425 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001426
Fam Zheng335e9932017-05-03 00:35:39 +08001427 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1428 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001429 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001430 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001431 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001432 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001433 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001434 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001435
Max Reitzf1d3cd72015-02-05 13:58:18 -05001436 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1437 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001438 total_size1 = blk_getlength(blk1);
1439 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001440 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001441 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001442 ret = 4;
1443 goto out;
1444 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001445 total_size2 = blk_getlength(blk2);
1446 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001447 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001448 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001449 ret = 4;
1450 goto out;
1451 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001452 total_size = MIN(total_size1, total_size2);
1453 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001454
1455 qemu_progress_print(0, 100);
1456
Eric Blake033d9fc2017-10-11 22:47:16 -05001457 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001458 ret = 1;
1459 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1460 goto out;
1461 }
1462
Eric Blake033d9fc2017-10-11 22:47:16 -05001463 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001464 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001465
Eric Blake033d9fc2017-10-11 22:47:16 -05001466 status1 = bdrv_block_status_above(bs1, NULL, offset,
1467 total_size1 - offset, &pnum1, NULL,
1468 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001469 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 ret = 3;
1471 error_report("Sector allocation test failed for %s", filename1);
1472 goto out;
1473 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001474 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001475
Eric Blake033d9fc2017-10-11 22:47:16 -05001476 status2 = bdrv_block_status_above(bs2, NULL, offset,
1477 total_size2 - offset, &pnum2, NULL,
1478 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001479 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001480 ret = 3;
1481 error_report("Sector allocation test failed for %s", filename2);
1482 goto out;
1483 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001484 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001485
1486 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001488
Fam Zheng25ad8e62016-01-13 16:37:41 +08001489 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001490 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001491 ret = 1;
1492 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001493 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001494 goto out;
1495 }
1496 }
1497 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001498 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001499 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001501 int64_t pnum;
1502
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 chunk = MIN(chunk, IO_BUF_SIZE);
1504 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 if (ret < 0) {
1506 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001507 " of %s: %s",
1508 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 ret = 4;
1510 goto out;
1511 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001512 ret = blk_pread(blk2, offset, buf2, chunk);
1513 if (ret < 0) {
1514 error_report("Error while reading offset %" PRId64
1515 " of %s: %s",
1516 offset, filename2, strerror(-ret));
1517 ret = 4;
1518 goto out;
1519 }
1520 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1521 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001523 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001524 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001525 goto out;
1526 }
1527 }
1528 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001529 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001531 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 filename1, buf1, quiet);
1533 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001534 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535 filename2, buf1, quiet);
1536 }
1537 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001538 goto out;
1539 }
1540 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001541 offset += chunk;
1542 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001543 }
1544
Eric Blake033d9fc2017-10-11 22:47:16 -05001545 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001546 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547 const char *filename_over;
1548
1549 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001550 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001551 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552 filename_over = filename1;
1553 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001554 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001555 filename_over = filename2;
1556 }
1557
Eric Blake033d9fc2017-10-11 22:47:16 -05001558 while (offset < progress_base) {
1559 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1560 progress_base - offset, &chunk,
1561 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001562 if (ret < 0) {
1563 ret = 3;
1564 error_report("Sector allocation test failed for %s",
1565 filename_over);
1566 goto out;
1567
1568 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001569 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001570 chunk = MIN(chunk, IO_BUF_SIZE);
1571 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001572 filename_over, buf1, quiet);
1573 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001574 goto out;
1575 }
1576 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001577 offset += chunk;
1578 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001579 }
1580 }
1581
1582 qprintf(quiet, "Images are identical.\n");
1583 ret = 0;
1584
1585out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001586 qemu_vfree(buf1);
1587 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001588 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001589out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001590 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001591out3:
1592 qemu_progress_end();
1593 return ret;
1594}
1595
Eric Blake6c729dd2020-05-21 14:21:35 -05001596/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1597static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1598 const char *src_node, const char *src_name,
1599 Error **errp)
1600{
1601 BlockDirtyBitmapMergeSource *merge_src;
Eric Blake54aa3de2020-11-12 19:13:37 -06001602 BlockDirtyBitmapMergeSourceList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001603
1604 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1605 merge_src->type = QTYPE_QDICT;
1606 merge_src->u.external.node = g_strdup(src_node);
1607 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001608 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001609 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1610 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1611}
1612
Kevin Wolf690c7302015-03-19 13:33:32 +01001613enum ImgConvertBlockStatus {
1614 BLK_DATA,
1615 BLK_ZERO,
1616 BLK_BACKING_FILE,
1617};
1618
Peter Lieven2d9187b2017-02-28 13:40:07 +01001619#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001620#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001621
Kevin Wolf690c7302015-03-19 13:33:32 +01001622typedef struct ImgConvertState {
1623 BlockBackend **src;
1624 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001625 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001626 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001627 int64_t total_sectors;
1628 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001629 int64_t allocated_done;
1630 int64_t sector_num;
1631 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001632 enum ImgConvertBlockStatus status;
1633 int64_t sector_next_status;
1634 BlockBackend *target;
1635 bool has_zero_init;
1636 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001637 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001638 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001639 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001640 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001641 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001642 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001643 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001644 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001645 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001646 size_t cluster_sectors;
1647 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001648 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001649 int running_coroutines;
1650 Coroutine *co[MAX_COROUTINES];
1651 int64_t wait_sector_num[MAX_COROUTINES];
1652 CoMutex lock;
1653 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001654} ImgConvertState;
1655
Peter Lieven2d9187b2017-02-28 13:40:07 +01001656static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1657 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001658{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001659 *src_cur = 0;
1660 *src_cur_offset = 0;
1661 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1662 *src_cur_offset += s->src_sectors[*src_cur];
1663 (*src_cur)++;
1664 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001665 }
1666}
1667
1668static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1669{
Eric Blake31826642017-10-11 22:47:08 -05001670 int64_t src_cur_offset;
1671 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001672 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673
Peter Lieven2d9187b2017-02-28 13:40:07 +01001674 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001675
1676 assert(s->total_sectors > sector_num);
1677 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1678
Max Reitz351c8ef2018-05-01 18:57:49 +02001679 if (s->target_backing_sectors >= 0) {
1680 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001681 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001682 } else if (sector_num + n > s->target_backing_sectors) {
1683 /* Split requests around target_backing_sectors (because
1684 * starting from there, zeros are handled differently) */
1685 n = s->target_backing_sectors - sector_num;
1686 }
1687 }
1688
Kevin Wolf690c7302015-03-19 13:33:32 +01001689 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001690 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1691 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001692 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001693 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1694 BlockDriverState *base;
1695
1696 if (s->target_has_backing) {
1697 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1698 } else {
1699 base = NULL;
1700 }
Eric Blake31826642017-10-11 22:47:08 -05001701
Max Reitz8eaac022019-05-07 22:35:03 +02001702 do {
1703 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001704
Max Reitz4a2061e2019-06-12 19:00:30 +02001705 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1706 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001707
1708 if (ret < 0) {
1709 if (s->salvage) {
1710 if (n == 1) {
1711 if (!s->quiet) {
1712 warn_report("error while reading block status at "
1713 "offset %" PRIu64 ": %s", offset,
1714 strerror(-ret));
1715 }
1716 /* Just try to read the data, then */
1717 ret = BDRV_BLOCK_DATA;
1718 count = BDRV_SECTOR_SIZE;
1719 } else {
1720 /* Retry on a shorter range */
1721 n = DIV_ROUND_UP(n, 4);
1722 }
1723 } else {
1724 error_report("error while reading block status at offset "
1725 "%" PRIu64 ": %s", offset, strerror(-ret));
1726 return ret;
1727 }
1728 }
1729 } while (ret < 0);
1730
Eric Blake31826642017-10-11 22:47:08 -05001731 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001732
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001733 /*
1734 * Avoid that s->sector_next_status becomes unaligned to the source
1735 * request alignment and/or cluster size to avoid unnecessary read
1736 * cycles.
1737 */
1738 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1739 if (n > tail) {
1740 n -= tail;
1741 }
1742
Kevin Wolf690c7302015-03-19 13:33:32 +01001743 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001744 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001745 } else if (ret & BDRV_BLOCK_DATA) {
1746 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001747 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001748 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001749 }
1750
1751 s->sector_next_status = sector_num + n;
1752 }
1753
1754 n = MIN(n, s->sector_next_status - sector_num);
1755 if (s->status == BLK_DATA) {
1756 n = MIN(n, s->buf_sectors);
1757 }
1758
1759 /* We need to write complete clusters for compressed images, so if an
1760 * unallocated area is shorter than that, we must consider the whole
1761 * cluster allocated. */
1762 if (s->compressed) {
1763 if (n < s->cluster_sectors) {
1764 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1765 s->status = BLK_DATA;
1766 } else {
1767 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1768 }
1769 }
1770
1771 return n;
1772}
1773
Peter Lieven2d9187b2017-02-28 13:40:07 +01001774static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1775 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001776{
Max Reitz8eaac022019-05-07 22:35:03 +02001777 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001778 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001779
Kevin Wolf690c7302015-03-19 13:33:32 +01001780 assert(nb_sectors <= s->buf_sectors);
1781 while (nb_sectors > 0) {
1782 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001783 int src_cur;
1784 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001785 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001786
1787 /* In the case of compression with multiple source files, we can get a
1788 * nb_sectors that spreads into the next part. So we must be able to
1789 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001790 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1791 blk = s->src[src_cur];
1792 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001793
Max Reitz8eaac022019-05-07 22:35:03 +02001794 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001795
Max Reitz8eaac022019-05-07 22:35:03 +02001796 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1797 if (single_read_until > offset) {
1798 n = 1;
1799 }
1800
1801 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001802 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001803 if (s->salvage) {
1804 if (n > 1) {
1805 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1806 continue;
1807 } else {
1808 if (!s->quiet) {
1809 warn_report("error while reading offset %" PRIu64
1810 ": %s", offset, strerror(-ret));
1811 }
1812 memset(buf, 0, BDRV_SECTOR_SIZE);
1813 }
1814 } else {
1815 return ret;
1816 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001817 }
1818
1819 sector_num += n;
1820 nb_sectors -= n;
1821 buf += n * BDRV_SECTOR_SIZE;
1822 }
1823
1824 return 0;
1825}
1826
Peter Lieven2d9187b2017-02-28 13:40:07 +01001827
1828static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1829 int nb_sectors, uint8_t *buf,
1830 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001831{
1832 int ret;
1833
1834 while (nb_sectors > 0) {
1835 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001836 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1837
Peter Lieven2d9187b2017-02-28 13:40:07 +01001838 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001839 case BLK_BACKING_FILE:
1840 /* If we have a backing file, leave clusters unallocated that are
1841 * unallocated in the source image, so that the backing file is
1842 * visible at the respective offset. */
1843 assert(s->target_has_backing);
1844 break;
1845
1846 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001847 /* If we're told to keep the target fully allocated (-S 0) or there
1848 * is real non-zero data, we must write it. Otherwise we can treat
1849 * it as zero sectors.
1850 * Compressed clusters need to be written as a whole, so in that
1851 * case we can only save the write if the buffer is completely
1852 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001853 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001854 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001855 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1856 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001857 (s->compressed &&
1858 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001859 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001860 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1861 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001862 if (ret < 0) {
1863 return ret;
1864 }
1865 break;
1866 }
1867 /* fall-through */
1868
1869 case BLK_ZERO:
1870 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001871 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001872 break;
1873 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001874 ret = blk_co_pwrite_zeroes(s->target,
1875 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001876 n << BDRV_SECTOR_BITS,
1877 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001878 if (ret < 0) {
1879 return ret;
1880 }
1881 break;
1882 }
1883
1884 sector_num += n;
1885 nb_sectors -= n;
1886 buf += n * BDRV_SECTOR_SIZE;
1887 }
1888
1889 return 0;
1890}
1891
Fam Zhengee5306d2018-06-01 17:26:48 +08001892static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1893 int nb_sectors)
1894{
1895 int n, ret;
1896
1897 while (nb_sectors > 0) {
1898 BlockBackend *blk;
1899 int src_cur;
1900 int64_t bs_sectors, src_cur_offset;
1901 int64_t offset;
1902
1903 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1904 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1905 blk = s->src[src_cur];
1906 bs_sectors = s->src_sectors[src_cur];
1907
1908 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1909
1910 ret = blk_co_copy_range(blk, offset, s->target,
1911 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001912 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001913 if (ret < 0) {
1914 return ret;
1915 }
1916
1917 sector_num += n;
1918 nb_sectors -= n;
1919 }
1920 return 0;
1921}
1922
Peter Lieven2d9187b2017-02-28 13:40:07 +01001923static void coroutine_fn convert_co_do_copy(void *opaque)
1924{
1925 ImgConvertState *s = opaque;
1926 uint8_t *buf = NULL;
1927 int ret, i;
1928 int index = -1;
1929
1930 for (i = 0; i < s->num_coroutines; i++) {
1931 if (s->co[i] == qemu_coroutine_self()) {
1932 index = i;
1933 break;
1934 }
1935 }
1936 assert(index >= 0);
1937
1938 s->running_coroutines++;
1939 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1940
1941 while (1) {
1942 int n;
1943 int64_t sector_num;
1944 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001945 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001946
1947 qemu_co_mutex_lock(&s->lock);
1948 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1949 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001950 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001951 }
1952 n = convert_iteration_sectors(s, s->sector_num);
1953 if (n < 0) {
1954 qemu_co_mutex_unlock(&s->lock);
1955 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001956 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001957 }
1958 /* save current sector and allocation status to local variables */
1959 sector_num = s->sector_num;
1960 status = s->status;
1961 if (!s->min_sparse && s->status == BLK_ZERO) {
1962 n = MIN(n, s->buf_sectors);
1963 }
1964 /* increment global sector counter so that other coroutines can
1965 * already continue reading beyond this request */
1966 s->sector_num += n;
1967 qemu_co_mutex_unlock(&s->lock);
1968
1969 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1970 s->allocated_done += n;
1971 qemu_progress_print(100.0 * s->allocated_done /
1972 s->allocated_sectors, 0);
1973 }
1974
Fam Zhengee5306d2018-06-01 17:26:48 +08001975retry:
1976 copy_range = s->copy_range && s->status == BLK_DATA;
1977 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001978 ret = convert_co_read(s, sector_num, n, buf);
1979 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05001980 error_report("error while reading at byte %lld: %s",
1981 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01001982 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 }
1984 } else if (!s->min_sparse && status == BLK_ZERO) {
1985 status = BLK_DATA;
1986 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
1987 }
1988
1989 if (s->wr_in_order) {
1990 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03001991 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001992 s->wait_sector_num[index] = sector_num;
1993 qemu_coroutine_yield();
1994 }
1995 s->wait_sector_num[index] = -1;
1996 }
1997
Anton Nefedovb91127e2017-04-26 11:33:15 +03001998 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08001999 if (copy_range) {
2000 ret = convert_co_copy_range(s, sector_num, n);
2001 if (ret) {
2002 s->copy_range = false;
2003 goto retry;
2004 }
2005 } else {
2006 ret = convert_co_write(s, sector_num, n, buf, status);
2007 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002008 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002009 error_report("error while writing at byte %lld: %s",
2010 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002011 s->ret = ret;
2012 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002013 }
2014
2015 if (s->wr_in_order) {
2016 /* reenter the coroutine that might have waited
2017 * for this write to complete */
2018 s->wr_offs = sector_num + n;
2019 for (i = 0; i < s->num_coroutines; i++) {
2020 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2021 /*
2022 * A -> B -> A cannot occur because A has
2023 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2024 * B will never enter A during this time window.
2025 */
2026 qemu_coroutine_enter(s->co[i]);
2027 break;
2028 }
2029 }
2030 }
2031 }
2032
Peter Lieven2d9187b2017-02-28 13:40:07 +01002033 qemu_vfree(buf);
2034 s->co[index] = NULL;
2035 s->running_coroutines--;
2036 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2037 /* the convert job finished successfully */
2038 s->ret = 0;
2039 }
2040}
2041
Kevin Wolf690c7302015-03-19 13:33:32 +01002042static int convert_do_copy(ImgConvertState *s)
2043{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002044 int ret, i, n;
2045 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002046
2047 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002048 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2049 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002050 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002051 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002052
Kevin Wolf690c7302015-03-19 13:33:32 +01002053 /* Allocate buffer for copied data. For compressed images, only one cluster
2054 * can be copied at a time. */
2055 if (s->compressed) {
2056 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2057 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002058 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002059 }
2060 s->buf_sectors = s->cluster_sectors;
2061 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002062
Kevin Wolf690c7302015-03-19 13:33:32 +01002063 while (sector_num < s->total_sectors) {
2064 n = convert_iteration_sectors(s, sector_num);
2065 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002066 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002067 }
Max Reitzaad15de2016-03-24 23:33:57 +01002068 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2069 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002070 s->allocated_sectors += n;
2071 }
2072 sector_num += n;
2073 }
2074
2075 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002076 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002077 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002078
Peter Lieven2d9187b2017-02-28 13:40:07 +01002079 qemu_co_mutex_init(&s->lock);
2080 for (i = 0; i < s->num_coroutines; i++) {
2081 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2082 s->wait_sector_num[i] = -1;
2083 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002084 }
2085
Anton Nefedovb91127e2017-04-26 11:33:15 +03002086 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002087 main_loop_wait(false);
2088 }
2089
2090 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002091 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002092 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002093 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002094 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002095 }
2096 }
2097
Peter Lieven2d9187b2017-02-28 13:40:07 +01002098 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002099}
2100
Eric Blake15e39ad2020-05-21 14:21:36 -05002101static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2102{
2103 BdrvDirtyBitmap *bm;
2104 Error *err = NULL;
2105
2106 FOR_EACH_DIRTY_BITMAP(src, bm) {
2107 const char *name;
2108
2109 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2110 continue;
2111 }
2112 name = bdrv_dirty_bitmap_name(bm);
2113 qmp_block_dirty_bitmap_add(dst->node_name, name,
2114 true, bdrv_dirty_bitmap_granularity(bm),
2115 true, true,
2116 true, !bdrv_dirty_bitmap_enabled(bm),
2117 &err);
2118 if (err) {
2119 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2120 return -1;
2121 }
2122
2123 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2124 &err);
2125 if (err) {
2126 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2127 return -1;
2128 }
2129 }
2130
2131 return 0;
2132}
2133
Peter Lieven6360ab22018-07-13 09:15:39 +02002134#define MAX_BUF_SECTORS 32768
2135
Zhengui0c8c4892020-10-20 14:47:44 +00002136static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2137{
2138 ThrottleConfig cfg;
2139
2140 throttle_config_init(&cfg);
2141 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2142
2143 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2144 blk_set_io_limits(blk, &cfg);
2145}
2146
bellardea2384d2004-08-01 21:59:26 +00002147static int img_convert(int argc, char **argv)
2148{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002149 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002150 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002151 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2152 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002153 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002154 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002155 BlockDriverState *out_bs;
2156 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002157 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002158 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002159 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002160 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002161 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002162 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002163 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002164 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002165 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002166 bool bitmaps = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002167 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002168
Peter Lieven9fd77f92017-04-21 11:11:55 +02002169 ImgConvertState s = (ImgConvertState) {
2170 /* Need at least 4k of zeros for sparse detection */
2171 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002172 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002173 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2174 .wr_in_order = true,
2175 .num_coroutines = 8,
2176 };
2177
bellardea2384d2004-08-01 21:59:26 +00002178 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002179 static const struct option long_options[] = {
2180 {"help", no_argument, 0, 'h'},
2181 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002182 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002183 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002184 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002185 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002186 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002187 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002188 {0, 0, 0, 0}
2189 };
Zhengui0c8c4892020-10-20 14:47:44 +00002190 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002191 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002192 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002193 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002194 }
bellardea2384d2004-08-01 21:59:26 +00002195 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002196 case ':':
2197 missing_argument(argv[optind - 1]);
2198 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002199 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002200 unrecognized_option(argv[optind - 1]);
2201 break;
bellardea2384d2004-08-01 21:59:26 +00002202 case 'h':
2203 help();
2204 break;
2205 case 'f':
2206 fmt = optarg;
2207 break;
2208 case 'O':
2209 out_fmt = optarg;
2210 break;
thsf58c7b32008-06-05 21:53:49 +00002211 case 'B':
2212 out_baseimg = optarg;
2213 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002214 case 'C':
2215 s.copy_range = true;
2216 break;
bellardea2384d2004-08-01 21:59:26 +00002217 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002218 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002219 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002220 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002221 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002222 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002223 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002224 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002225 case 'l':
2226 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002227 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2228 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002229 if (!sn_opts) {
2230 error_report("Failed in parsing snapshot param '%s'",
2231 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002232 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002233 }
2234 } else {
2235 snapshot_name = optarg;
2236 }
2237 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002238 case 'S':
2239 {
2240 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002241
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002242 sval = cvtnum("buffer size for sparse output", optarg);
2243 if (sval < 0) {
2244 goto fail_getopt;
2245 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002246 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2247 error_report("Invalid buffer size for sparse output specified. "
2248 "Valid sizes are multiples of %llu up to %llu. Select "
2249 "0 to disable sparse detection (fully allocates output).",
2250 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002251 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002252 }
2253
Peter Lieven9fd77f92017-04-21 11:11:55 +02002254 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002255 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002256 break;
2257 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002258 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002259 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002260 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002261 case 't':
2262 cache = optarg;
2263 break;
Max Reitz40055952014-07-22 22:58:42 +02002264 case 'T':
2265 src_cache = optarg;
2266 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002267 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002268 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002269 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002270 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002271 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002272 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002273 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002274 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2275 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002276 error_report("Invalid number of coroutines. Allowed number of"
2277 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002278 goto fail_getopt;
2279 }
2280 break;
2281 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002282 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002283 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002284 case 'U':
2285 force_share = true;
2286 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002287 case 'r':
2288 rate_limit = cvtnum("rate limit", optarg);
2289 if (rate_limit < 0) {
2290 goto fail_getopt;
2291 }
2292 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002293 case OPTION_OBJECT:
2294 user_creatable_process_cmdline(optarg);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002295 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002296 case OPTION_IMAGE_OPTS:
2297 image_opts = true;
2298 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002299 case OPTION_SALVAGE:
2300 s.salvage = true;
2301 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002302 case OPTION_TARGET_IMAGE_OPTS:
2303 tgt_image_opts = true;
2304 break;
David Edmondson168468f2020-02-05 11:02:48 +00002305 case OPTION_TARGET_IS_ZERO:
2306 /*
2307 * The user asserting that the target is blank has the
2308 * same effect as the target driver supporting zero
2309 * initialisation.
2310 */
2311 s.has_zero_init = true;
2312 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002313 case OPTION_BITMAPS:
2314 bitmaps = true;
2315 break;
bellardea2384d2004-08-01 21:59:26 +00002316 }
2317 }
ths3b46e622007-09-17 08:09:54 +00002318
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002319 if (!out_fmt && !tgt_image_opts) {
2320 out_fmt = "raw";
2321 }
2322
Fam Zhenge11ce122018-07-27 11:34:01 +08002323 if (s.compressed && s.copy_range) {
2324 error_report("Cannot enable copy offloading when -c is used");
2325 goto fail_getopt;
2326 }
2327
2328 if (explict_min_sparse && s.copy_range) {
2329 error_report("Cannot enable copy offloading when -S is used");
2330 goto fail_getopt;
2331 }
2332
Max Reitz8eaac022019-05-07 22:35:03 +02002333 if (s.copy_range && s.salvage) {
2334 error_report("Cannot use copy offloading in salvaging mode");
2335 goto fail_getopt;
2336 }
2337
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002338 if (tgt_image_opts && !skip_create) {
2339 error_report("--target-image-opts requires use of -n flag");
2340 goto fail_getopt;
2341 }
2342
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002343 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002344 error_report("-o has no effect when skipping image creation");
2345 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002346 }
2347
David Edmondson168468f2020-02-05 11:02:48 +00002348 if (s.has_zero_init && !skip_create) {
2349 error_report("--target-is-zero requires use of -n flag");
2350 goto fail_getopt;
2351 }
2352
Peter Lieven9fd77f92017-04-21 11:11:55 +02002353 s.src_num = argc - optind - 1;
2354 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2355
2356 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002357 if (out_fmt) {
2358 ret = print_block_option_help(out_filename, out_fmt);
2359 goto fail_getopt;
2360 } else {
2361 error_report("Option help requires a format be specified");
2362 goto fail_getopt;
2363 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002364 }
2365
2366 if (s.src_num < 1) {
2367 error_report("Must specify image file name");
2368 goto fail_getopt;
2369 }
2370
Peter Lieven9fd77f92017-04-21 11:11:55 +02002371 /* ret is still -EINVAL until here */
2372 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2373 if (ret < 0) {
2374 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002375 goto fail_getopt;
2376 }
2377
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002378 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002379 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002380 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002381 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002382 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002383 qemu_progress_print(0, 100);
2384
Peter Lieven9fd77f92017-04-21 11:11:55 +02002385 s.src = g_new0(BlockBackend *, s.src_num);
2386 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002387 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002388
Peter Lieven9fd77f92017-04-21 11:11:55 +02002389 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002390 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002391 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002392 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002393 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002394 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002395 ret = -1;
2396 goto out;
2397 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002398 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2399 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002400 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002401 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002402 ret = -1;
2403 goto out;
2404 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002405 src_bs = blk_bs(s.src[bs_i]);
2406 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2407 BDRV_SECTOR_SIZE);
2408 if (!bdrv_get_info(src_bs, &bdi)) {
2409 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2410 bdi.cluster_size / BDRV_SECTOR_SIZE);
2411 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002412 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002413 }
bellardea2384d2004-08-01 21:59:26 +00002414
Wenchao Xiaef806542013-12-04 17:10:57 +08002415 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002416 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002417 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2418 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2419 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002420 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002421 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002422 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002423 ret = -1;
2424 goto out;
2425 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002426
Peter Lieven9fd77f92017-04-21 11:11:55 +02002427 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2428 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002429 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002430 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002431 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002432 ret = -1;
2433 goto out;
edison51ef6722010-09-21 19:58:41 -07002434 }
2435
Max Reitz2e024cd2015-02-11 09:58:46 -05002436 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002437 /* Find driver and parse its options */
2438 drv = bdrv_find_format(out_fmt);
2439 if (!drv) {
2440 error_report("Unknown file format '%s'", out_fmt);
2441 ret = -1;
2442 goto out;
2443 }
2444
2445 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2446 if (!proto_drv) {
2447 error_report_err(local_err);
2448 ret = -1;
2449 goto out;
2450 }
2451
Max Reitz2e024cd2015-02-11 09:58:46 -05002452 if (!drv->create_opts) {
2453 error_report("Format driver '%s' does not support image creation",
2454 drv->format_name);
2455 ret = -1;
2456 goto out;
2457 }
Max Reitzf75613c2014-12-02 18:32:46 +01002458
Max Reitz2e024cd2015-02-11 09:58:46 -05002459 if (!proto_drv->create_opts) {
2460 error_report("Protocol driver '%s' does not support image creation",
2461 proto_drv->format_name);
2462 ret = -1;
2463 goto out;
2464 }
Max Reitzf75613c2014-12-02 18:32:46 +01002465
Max Reitz2e024cd2015-02-11 09:58:46 -05002466 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2467 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002468
Max Reitz2e024cd2015-02-11 09:58:46 -05002469 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002470 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002471 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002472 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002473 ret = -1;
2474 goto out;
2475 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002476 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002477
Yi Lic075c422020-08-19 09:36:07 +08002478 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2479 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002480 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2481 if (ret < 0) {
2482 goto out;
2483 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002484 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002485
Kevin Wolfa18953f2010-10-14 15:46:04 +02002486 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002487 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002488 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002489 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002490 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002491 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002492
David Edmondson168468f2020-02-05 11:02:48 +00002493 if (s.has_zero_init && s.target_has_backing) {
2494 error_report("Cannot use --target-is-zero when the destination "
2495 "image has a backing file");
2496 goto out;
2497 }
2498
Max Reitz48758a82017-04-26 15:46:48 +02002499 if (s.src_num > 1 && out_baseimg) {
2500 error_report("Having a backing file for the target makes no sense when "
2501 "concatenating multiple input images");
2502 ret = -1;
2503 goto out;
2504 }
2505
Eric Blaked9f059a2020-07-06 15:39:54 -05002506 if (out_baseimg_param) {
2507 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2508 warn_report("Deprecated use of backing file without explicit "
2509 "backing format");
2510 }
2511 }
2512
Kevin Wolfefa84d42009-05-18 16:42:12 +02002513 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002514 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002515 bool encryption =
2516 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002517 const char *encryptfmt =
2518 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002519 const char *preallocation =
2520 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002521
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002522 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002523 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002524 ret = -1;
2525 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002526 }
2527
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002528 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002529 error_report("Compression and encryption not supported at "
2530 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002531 ret = -1;
2532 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002533 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002534
Chunyan Liu83d05212014-06-05 17:20:51 +08002535 if (preallocation
2536 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002537 {
2538 error_report("Compression and preallocation not supported at "
2539 "the same time");
2540 ret = -1;
2541 goto out;
2542 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002543 }
2544
Eric Blake15e39ad2020-05-21 14:21:36 -05002545 /* Determine if bitmaps need copying */
2546 if (bitmaps) {
2547 if (s.src_num > 1) {
2548 error_report("Copying bitmaps only possible with single source");
2549 ret = -1;
2550 goto out;
2551 }
2552 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2553 error_report("Source lacks bitmap support");
2554 ret = -1;
2555 goto out;
2556 }
2557 }
2558
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002559 /*
2560 * The later open call will need any decryption secrets, and
2561 * bdrv_create() will purge "opts", so extract them now before
2562 * they are lost.
2563 */
2564 if (!skip_create) {
2565 open_opts = qdict_new();
2566 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002567
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002568 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002569 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002570 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002571 error_reportf_err(local_err, "%s: error while converting %s: ",
2572 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002573 goto out;
bellardea2384d2004-08-01 21:59:26 +00002574 }
2575 }
ths3b46e622007-09-17 08:09:54 +00002576
Max Reitz4d7c4872019-07-24 19:12:29 +02002577 s.target_is_new = !skip_create;
2578
Peter Lieven9fd77f92017-04-21 11:11:55 +02002579 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002580 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002581 if (ret < 0) {
2582 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002583 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002584 }
2585
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002586 if (skip_create) {
2587 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002588 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002589 } else {
2590 /* TODO ultimately we should allow --target-image-opts
2591 * to be used even when -n is not given.
2592 * That has to wait for bdrv_create to be improved
2593 * to allow filenames in option syntax
2594 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002595 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002596 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002597 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002598 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002599 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002600 ret = -1;
2601 goto out;
2602 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002603 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002604
Eric Blake15e39ad2020-05-21 14:21:36 -05002605 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2606 error_report("Format driver '%s' does not support bitmaps",
2607 out_bs->drv->format_name);
2608 ret = -1;
2609 goto out;
2610 }
2611
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002612 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002613 error_report("Compression not supported for this file format");
2614 ret = -1;
2615 goto out;
2616 }
2617
Eric Blake5def6b82016-06-23 16:37:19 -06002618 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002619 * or discard_alignment of the out_bs is greater. Limit to
2620 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2621 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002622 MAX(s.buf_sectors,
2623 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2624 out_bs->bl.pdiscard_alignment >>
2625 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002626
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002627 /* try to align the write requests to the destination to avoid unnecessary
2628 * RMW cycles. */
2629 s.alignment = MAX(pow2floor(s.min_sparse),
2630 DIV_ROUND_UP(out_bs->bl.request_alignment,
2631 BDRV_SECTOR_SIZE));
2632 assert(is_power_of_2(s.alignment));
2633
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002634 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002635 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002636 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002637 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002638 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002639 ret = -1;
2640 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002641 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002642 error_report("output file is smaller than input file");
2643 ret = -1;
2644 goto out;
2645 }
2646 }
2647
Max Reitzc69291e2020-01-21 16:59:14 +01002648 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002649 /* Errors are treated as "backing length unknown" (which means
2650 * s.target_backing_sectors has to be negative, which it will
2651 * be automatically). The backing file length is used only
2652 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002653 s.target_backing_sectors =
2654 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002655 } else {
2656 s.target_backing_sectors = -1;
2657 }
2658
Peter Lieven24f833c2013-11-27 11:07:07 +01002659 ret = bdrv_get_info(out_bs, &bdi);
2660 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002661 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002662 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002663 goto out;
2664 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002665 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002666 s.compressed = s.compressed || bdi.needs_compressed_writes;
2667 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002668 }
2669
Zhengui0c8c4892020-10-20 14:47:44 +00002670 if (rate_limit) {
2671 set_rate_limit(s.target, rate_limit);
2672 }
2673
Peter Lieven9fd77f92017-04-21 11:11:55 +02002674 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002675
2676 /* Now copy the bitmaps */
2677 if (bitmaps && ret == 0) {
2678 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2679 }
2680
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002681out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002682 if (!ret) {
2683 qemu_progress_print(100, 0);
2684 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002685 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002686 qemu_opts_del(opts);
2687 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002688 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002689 blk_unref(s.target);
2690 if (s.src) {
2691 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2692 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002693 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002694 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002695 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002696 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002697 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002698fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002699 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002700 g_free(options);
2701
Peter Lieven9fd77f92017-04-21 11:11:55 +02002702 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002703}
2704
bellard57d1a2b2004-08-03 21:15:11 +00002705
bellardfaea38e2006-08-05 21:31:00 +00002706static void dump_snapshots(BlockDriverState *bs)
2707{
2708 QEMUSnapshotInfo *sn_tab, *sn;
2709 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002710
2711 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2712 if (nb_sns <= 0)
2713 return;
2714 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002715 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002716 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002717 for(i = 0; i < nb_sns; i++) {
2718 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002719 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002720 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002721 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002722 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002723}
2724
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002725static void dump_json_image_info_list(ImageInfoList *list)
2726{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002727 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002728 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002729 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002730
2731 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2732 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002733 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002734 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002735 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002736 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002737 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002738 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002739}
2740
Benoît Canetc054b3f2012-09-05 13:09:02 +02002741static void dump_json_image_info(ImageInfo *info)
2742{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002743 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002744 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002745 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002746
2747 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2748 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002749 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002750 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002751 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002752 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002753 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002754 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002755}
2756
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002757static void dump_human_image_info_list(ImageInfoList *list)
2758{
2759 ImageInfoList *elem;
2760 bool delim = false;
2761
2762 for (elem = list; elem; elem = elem->next) {
2763 if (delim) {
2764 printf("\n");
2765 }
2766 delim = true;
2767
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002768 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002769 }
2770}
2771
2772static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2773{
2774 return strcmp(a, b) == 0;
2775}
2776
2777/**
2778 * Open an image file chain and return an ImageInfoList
2779 *
2780 * @filename: topmost image filename
2781 * @fmt: topmost image format (may be NULL to autodetect)
2782 * @chain: true - enumerate entire backing file chain
2783 * false - only topmost image file
2784 *
2785 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2786 * image file. If there was an error a message will have been printed to
2787 * stderr.
2788 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002789static ImageInfoList *collect_image_info_list(bool image_opts,
2790 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002791 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002792 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002793{
2794 ImageInfoList *head = NULL;
Eric Blakec3033fd2021-01-13 16:10:12 -06002795 ImageInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002796 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002797 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002798
2799 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2800
2801 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002802 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002803 BlockDriverState *bs;
2804 ImageInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002805
2806 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2807 error_report("Backing file '%s' creates an infinite loop.",
2808 filename);
2809 goto err;
2810 }
2811 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2812
Max Reitzefaa7c42016-03-16 19:54:38 +01002813 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002814 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2815 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002816 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002817 goto err;
2818 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002819 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002820
Wenchao Xia43526ec2013-06-06 12:27:58 +08002821 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002822 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002823 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002824 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002825 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002826 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002827
Eric Blakec3033fd2021-01-13 16:10:12 -06002828 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002829
Markus Armbruster26f54e92014-10-07 13:59:04 +02002830 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002831
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002832 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002833 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002834 image_opts = false;
2835
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002836 if (chain) {
2837 if (info->has_full_backing_filename) {
2838 filename = info->full_backing_filename;
2839 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002840 error_report("Could not determine absolute backing filename,"
2841 " but backing filename '%s' present",
2842 info->backing_filename);
2843 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002844 }
2845 if (info->has_backing_filename_format) {
2846 fmt = info->backing_filename_format;
2847 }
2848 }
2849 }
2850 g_hash_table_destroy(filenames);
2851 return head;
2852
2853err:
2854 qapi_free_ImageInfoList(head);
2855 g_hash_table_destroy(filenames);
2856 return NULL;
2857}
2858
Benoît Canetc054b3f2012-09-05 13:09:02 +02002859static int img_info(int argc, char **argv)
2860{
2861 int c;
2862 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002863 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002864 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002865 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002866 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002867 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002868
bellardea2384d2004-08-01 21:59:26 +00002869 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002870 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002871 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002872 int option_index = 0;
2873 static const struct option long_options[] = {
2874 {"help", no_argument, 0, 'h'},
2875 {"format", required_argument, 0, 'f'},
2876 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002877 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002878 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002879 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002880 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002881 {0, 0, 0, 0}
2882 };
Fam Zheng335e9932017-05-03 00:35:39 +08002883 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002884 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002885 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002886 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002887 }
bellardea2384d2004-08-01 21:59:26 +00002888 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002889 case ':':
2890 missing_argument(argv[optind - 1]);
2891 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002892 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002893 unrecognized_option(argv[optind - 1]);
2894 break;
bellardea2384d2004-08-01 21:59:26 +00002895 case 'h':
2896 help();
2897 break;
2898 case 'f':
2899 fmt = optarg;
2900 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002901 case 'U':
2902 force_share = true;
2903 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002904 case OPTION_OUTPUT:
2905 output = optarg;
2906 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002907 case OPTION_BACKING_CHAIN:
2908 chain = true;
2909 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002910 case OPTION_OBJECT:
2911 user_creatable_process_cmdline(optarg);
2912 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002913 case OPTION_IMAGE_OPTS:
2914 image_opts = true;
2915 break;
bellardea2384d2004-08-01 21:59:26 +00002916 }
2917 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002918 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002919 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002920 }
bellardea2384d2004-08-01 21:59:26 +00002921 filename = argv[optind++];
2922
Benoît Canetc054b3f2012-09-05 13:09:02 +02002923 if (output && !strcmp(output, "json")) {
2924 output_format = OFORMAT_JSON;
2925 } else if (output && !strcmp(output, "human")) {
2926 output_format = OFORMAT_HUMAN;
2927 } else if (output) {
2928 error_report("--output must be used with human or json as argument.");
2929 return 1;
2930 }
2931
Fam Zheng335e9932017-05-03 00:35:39 +08002932 list = collect_image_info_list(image_opts, filename, fmt, chain,
2933 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002934 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002935 return 1;
2936 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002937
Benoît Canetc054b3f2012-09-05 13:09:02 +02002938 switch (output_format) {
2939 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002940 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002941 break;
2942 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002943 if (chain) {
2944 dump_json_image_info_list(list);
2945 } else {
2946 dump_json_image_info(list->value);
2947 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002948 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002949 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002950
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002951 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002952 return 0;
2953}
2954
Eric Blake30065d12019-03-26 13:40:43 -05002955static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2956 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002957{
2958 switch (output_format) {
2959 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002960 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002961 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002962 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002963 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002964 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002965 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002966 e->start, e->length,
2967 e->has_offset ? e->offset : 0,
2968 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002969 }
2970 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2971 * Modify the flags here to allow more coalescing.
2972 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002973 if (next && (!next->data || next->zero)) {
2974 next->data = false;
2975 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002976 }
2977 break;
2978 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03002979 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08002980 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002981 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002982 e->zero ? "true" : "false",
2983 e->data ? "true" : "false");
2984 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002985 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002986 }
2987 putchar('}');
2988
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03002989 if (next) {
2990 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002991 }
2992 break;
2993 }
Eric Blake30065d12019-03-26 13:40:43 -05002994 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002995}
2996
Eric Blake5e344dd2017-10-11 22:47:02 -05002997static int get_block_status(BlockDriverState *bs, int64_t offset,
2998 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002999{
Eric Blake237d78f2017-10-11 22:47:03 -05003000 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003001 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003002 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003003 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003004 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003005 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003006
3007 /* As an optimization, we could cache the current range of unallocated
3008 * clusters in each file of the chain, and avoid querying the same
3009 * range repeatedly.
3010 */
3011
3012 depth = 0;
3013 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003014 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003015 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003016 if (ret < 0) {
3017 return ret;
3018 }
Eric Blake237d78f2017-10-11 22:47:03 -05003019 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003020 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3021 break;
3022 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003023 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003024 if (bs == NULL) {
3025 ret = 0;
3026 break;
3027 }
3028
3029 depth++;
3030 }
3031
John Snow28756452016-02-05 13:12:33 -05003032 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3033
Max Reitzf30c66b2019-02-01 20:29:05 +01003034 if (file && has_offset) {
3035 bdrv_refresh_filename(file);
3036 filename = file->filename;
3037 }
3038
John Snow28756452016-02-05 13:12:33 -05003039 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003040 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003041 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003042 .data = !!(ret & BDRV_BLOCK_DATA),
3043 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003044 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003045 .has_offset = has_offset,
3046 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01003047 .has_filename = filename,
3048 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003049 };
3050
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 return 0;
3052}
3053
Fam Zheng16b0d552016-01-26 11:59:02 +08003054static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3055{
3056 if (curr->length == 0) {
3057 return false;
3058 }
3059 if (curr->zero != next->zero ||
3060 curr->data != next->data ||
3061 curr->depth != next->depth ||
3062 curr->has_filename != next->has_filename ||
3063 curr->has_offset != next->has_offset) {
3064 return false;
3065 }
3066 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3067 return false;
3068 }
3069 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3070 return false;
3071 }
3072 return true;
3073}
3074
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003075static int img_map(int argc, char **argv)
3076{
3077 int c;
3078 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003079 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003080 BlockDriverState *bs;
3081 const char *filename, *fmt, *output;
3082 int64_t length;
3083 MapEntry curr = { .length = 0 }, next;
3084 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003085 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003086 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003087 int64_t start_offset = 0;
3088 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003089
3090 fmt = NULL;
3091 output = NULL;
3092 for (;;) {
3093 int option_index = 0;
3094 static const struct option long_options[] = {
3095 {"help", no_argument, 0, 'h'},
3096 {"format", required_argument, 0, 'f'},
3097 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003098 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003099 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003100 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003101 {"start-offset", required_argument, 0, 's'},
3102 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003103 {0, 0, 0, 0}
3104 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003105 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003106 long_options, &option_index);
3107 if (c == -1) {
3108 break;
3109 }
3110 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003111 case ':':
3112 missing_argument(argv[optind - 1]);
3113 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003114 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003115 unrecognized_option(argv[optind - 1]);
3116 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003117 case 'h':
3118 help();
3119 break;
3120 case 'f':
3121 fmt = optarg;
3122 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003123 case 'U':
3124 force_share = true;
3125 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003126 case OPTION_OUTPUT:
3127 output = optarg;
3128 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003129 case 's':
3130 start_offset = cvtnum("start offset", optarg);
3131 if (start_offset < 0) {
3132 return 1;
3133 }
3134 break;
3135 case 'l':
3136 max_length = cvtnum("max length", optarg);
3137 if (max_length < 0) {
3138 return 1;
3139 }
3140 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003141 case OPTION_OBJECT:
3142 user_creatable_process_cmdline(optarg);
3143 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003144 case OPTION_IMAGE_OPTS:
3145 image_opts = true;
3146 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003147 }
3148 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003149 if (optind != argc - 1) {
3150 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003151 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003152 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003153
3154 if (output && !strcmp(output, "json")) {
3155 output_format = OFORMAT_JSON;
3156 } else if (output && !strcmp(output, "human")) {
3157 output_format = OFORMAT_HUMAN;
3158 } else if (output) {
3159 error_report("--output must be used with human or json as argument.");
3160 return 1;
3161 }
3162
Fam Zheng335e9932017-05-03 00:35:39 +08003163 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003164 if (!blk) {
3165 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003166 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003167 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003168
3169 if (output_format == OFORMAT_HUMAN) {
3170 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003171 } else if (output_format == OFORMAT_JSON) {
3172 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003173 }
3174
Max Reitzf1d3cd72015-02-05 13:58:18 -05003175 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003176 if (length < 0) {
3177 error_report("Failed to get size for '%s'", filename);
3178 return 1;
3179 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003180 if (max_length != -1) {
3181 length = MIN(start_offset + max_length, length);
3182 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003183
Eyal Moscovicic0469492020-05-13 16:36:29 +03003184 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003185 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003186 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003187 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003188
Eric Blake5e344dd2017-10-11 22:47:02 -05003189 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003190 if (ret < 0) {
3191 error_report("Could not read file metadata: %s", strerror(-ret));
3192 goto out;
3193 }
3194
Fam Zheng16b0d552016-01-26 11:59:02 +08003195 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003196 curr.length += next.length;
3197 continue;
3198 }
3199
3200 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003201 ret = dump_map_entry(output_format, &curr, &next);
3202 if (ret < 0) {
3203 goto out;
3204 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003205 }
3206 curr = next;
3207 }
3208
Eric Blake30065d12019-03-26 13:40:43 -05003209 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003210 if (output_format == OFORMAT_JSON) {
3211 puts("]");
3212 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003213
3214out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003215 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003216 return ret < 0;
3217}
3218
aliguorif7b4a942009-01-07 17:40:15 +00003219#define SNAPSHOT_LIST 1
3220#define SNAPSHOT_CREATE 2
3221#define SNAPSHOT_APPLY 3
3222#define SNAPSHOT_DELETE 4
3223
Stuart Brady153859b2009-06-07 00:42:17 +01003224static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003225{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003226 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003227 BlockDriverState *bs;
3228 QEMUSnapshotInfo sn;
3229 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003230 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003231 int action = 0;
3232 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003233 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003234 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003235 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003236 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003237
Kevin Wolfce099542016-03-15 13:01:04 +01003238 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003239 /* Parse commandline parameters */
3240 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003241 static const struct option long_options[] = {
3242 {"help", no_argument, 0, 'h'},
3243 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003244 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003245 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003246 {0, 0, 0, 0}
3247 };
Fam Zheng335e9932017-05-03 00:35:39 +08003248 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003249 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003250 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003251 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003252 }
aliguorif7b4a942009-01-07 17:40:15 +00003253 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003254 case ':':
3255 missing_argument(argv[optind - 1]);
3256 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003257 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003258 unrecognized_option(argv[optind - 1]);
3259 break;
aliguorif7b4a942009-01-07 17:40:15 +00003260 case 'h':
3261 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003262 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003263 case 'l':
3264 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003265 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003266 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003267 }
3268 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003269 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003270 break;
3271 case 'a':
3272 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003273 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003274 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003275 }
3276 action = SNAPSHOT_APPLY;
3277 snapshot_name = optarg;
3278 break;
3279 case 'c':
3280 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003281 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003282 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003283 }
3284 action = SNAPSHOT_CREATE;
3285 snapshot_name = optarg;
3286 break;
3287 case 'd':
3288 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003289 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003290 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003291 }
3292 action = SNAPSHOT_DELETE;
3293 snapshot_name = optarg;
3294 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003295 case 'q':
3296 quiet = true;
3297 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003298 case 'U':
3299 force_share = true;
3300 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003301 case OPTION_OBJECT:
3302 user_creatable_process_cmdline(optarg);
3303 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003304 case OPTION_IMAGE_OPTS:
3305 image_opts = true;
3306 break;
aliguorif7b4a942009-01-07 17:40:15 +00003307 }
3308 }
3309
Kevin Wolffc11eb22013-08-05 10:53:04 +02003310 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003311 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003312 }
aliguorif7b4a942009-01-07 17:40:15 +00003313 filename = argv[optind++];
3314
3315 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003316 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3317 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003318 if (!blk) {
3319 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003320 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003321 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003322
3323 /* Perform the requested action */
3324 switch(action) {
3325 case SNAPSHOT_LIST:
3326 dump_snapshots(bs);
3327 break;
3328
3329 case SNAPSHOT_CREATE:
3330 memset(&sn, 0, sizeof(sn));
3331 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3332
3333 qemu_gettimeofday(&tv);
3334 sn.date_sec = tv.tv_sec;
3335 sn.date_nsec = tv.tv_usec * 1000;
3336
3337 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003338 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003339 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003340 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003341 }
aliguorif7b4a942009-01-07 17:40:15 +00003342 break;
3343
3344 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003345 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003346 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003347 error_reportf_err(err, "Could not apply snapshot '%s': ",
3348 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003349 }
aliguorif7b4a942009-01-07 17:40:15 +00003350 break;
3351
3352 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003353 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3354 if (ret < 0) {
3355 error_report("Could not delete snapshot '%s': snapshot not "
3356 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003357 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003358 } else {
3359 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3360 if (ret < 0) {
3361 error_reportf_err(err, "Could not delete snapshot '%s': ",
3362 snapshot_name);
3363 ret = 1;
3364 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003365 }
aliguorif7b4a942009-01-07 17:40:15 +00003366 break;
3367 }
3368
3369 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003370 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003371 if (ret) {
3372 return 1;
3373 }
Stuart Brady153859b2009-06-07 00:42:17 +01003374 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003375}
3376
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003377static int img_rebase(int argc, char **argv)
3378{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003379 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003380 uint8_t *buf_old = NULL;
3381 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003382 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003383 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003384 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003385 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3386 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003387 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003388 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003389 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003390 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003391 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003392 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003393 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003394
3395 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003396 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003397 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003398 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003399 out_baseimg = NULL;
3400 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003401 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003402 static const struct option long_options[] = {
3403 {"help", no_argument, 0, 'h'},
3404 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003405 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003406 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003407 {0, 0, 0, 0}
3408 };
Fam Zheng335e9932017-05-03 00:35:39 +08003409 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003410 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003411 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003412 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003413 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003414 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003415 case ':':
3416 missing_argument(argv[optind - 1]);
3417 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003418 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003419 unrecognized_option(argv[optind - 1]);
3420 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003421 case 'h':
3422 help();
3423 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003424 case 'f':
3425 fmt = optarg;
3426 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003427 case 'F':
3428 out_basefmt = optarg;
3429 break;
3430 case 'b':
3431 out_baseimg = optarg;
3432 break;
3433 case 'u':
3434 unsafe = 1;
3435 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003436 case 'p':
3437 progress = 1;
3438 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003439 case 't':
3440 cache = optarg;
3441 break;
Max Reitz40055952014-07-22 22:58:42 +02003442 case 'T':
3443 src_cache = optarg;
3444 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003445 case 'q':
3446 quiet = true;
3447 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003448 case OPTION_OBJECT:
3449 user_creatable_process_cmdline(optarg);
3450 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003451 case OPTION_IMAGE_OPTS:
3452 image_opts = true;
3453 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003454 case 'U':
3455 force_share = true;
3456 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003457 }
3458 }
3459
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003460 if (quiet) {
3461 progress = 0;
3462 }
3463
Fam Zhengac1307a2014-04-22 13:36:11 +08003464 if (optind != argc - 1) {
3465 error_exit("Expecting one image file name");
3466 }
3467 if (!unsafe && !out_baseimg) {
3468 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003469 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003470 filename = argv[optind++];
3471
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003472 qemu_progress_init(progress, 2.0);
3473 qemu_progress_print(0, 100);
3474
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003475 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003476 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003477 if (ret < 0) {
3478 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003479 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003480 }
3481
Kevin Wolfce099542016-03-15 13:01:04 +01003482 src_flags = 0;
3483 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003484 if (ret < 0) {
3485 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003486 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003487 }
3488
Kevin Wolfce099542016-03-15 13:01:04 +01003489 /* The source files are opened read-only, don't care about WCE */
3490 assert((src_flags & BDRV_O_RDWR) == 0);
3491 (void) src_writethrough;
3492
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003493 /*
3494 * Open the images.
3495 *
3496 * Ignore the old backing file for unsafe rebase in case we want to correct
3497 * the reference to a renamed or moved backing file.
3498 */
Fam Zheng335e9932017-05-03 00:35:39 +08003499 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3500 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003501 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003502 ret = -1;
3503 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003504 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003505 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003506
Max Reitz4a2061e2019-06-12 19:00:30 +02003507 unfiltered_bs = bdrv_skip_filters(bs);
3508
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003510 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003511 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003512 ret = -1;
3513 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003514 }
3515 }
3516
3517 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003518 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003519 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003520 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003521
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003522 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003523 blk_old_backing = blk_new(qemu_get_aio_context(),
3524 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003525 BLK_PERM_ALL);
3526 ret = blk_insert_bs(blk_old_backing, base_bs,
3527 &local_err);
3528 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003529 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003530 "Could not reuse old backing file '%s': ",
3531 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003532 goto out;
3533 }
3534 } else {
3535 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003536 }
Max Reitz644483d2015-02-05 13:58:17 -05003537
Alex Bligha6166732012-10-16 13:46:18 +01003538 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003539 const char *overlay_filename;
3540 char *out_real_path;
3541
Fam Zheng335e9932017-05-03 00:35:39 +08003542 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003543 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003544 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003545 }
3546 if (force_share) {
3547 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003548 }
3549
Max Reitzf30c66b2019-02-01 20:29:05 +01003550 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003551 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3552 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003553 out_real_path =
3554 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3555 out_baseimg,
3556 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003557 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003558 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003559 error_reportf_err(local_err,
3560 "Could not resolve backing filename: ");
3561 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003562 goto out;
3563 }
3564
Sam Eiderman863cc782019-05-23 19:33:36 +03003565 /*
3566 * Find out whether we rebase an image on top of a previous image
3567 * in its chain.
3568 */
3569 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003570 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003571 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003572 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003573
Kevin Wolfd861ab32019-04-25 14:25:10 +02003574 blk_new_backing = blk_new(qemu_get_aio_context(),
3575 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003576 BLK_PERM_ALL);
3577 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3578 &local_err);
3579 if (ret < 0) {
3580 error_reportf_err(local_err,
3581 "Could not reuse backing file '%s': ",
3582 out_baseimg);
3583 goto out;
3584 }
3585 } else {
3586 blk_new_backing = blk_new_open(out_real_path, NULL,
3587 options, src_flags, &local_err);
3588 g_free(out_real_path);
3589 if (!blk_new_backing) {
3590 error_reportf_err(local_err,
3591 "Could not open new backing file '%s': ",
3592 out_baseimg);
3593 ret = -1;
3594 goto out;
3595 }
Alex Bligha6166732012-10-16 13:46:18 +01003596 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003597 }
3598 }
3599
3600 /*
3601 * Check each unallocated cluster in the COW file. If it is unallocated,
3602 * accesses go to the backing file. We must therefore compare this cluster
3603 * in the old and new backing file, and if they differ we need to copy it
3604 * from the old backing file into the COW file.
3605 *
3606 * If qemu-img crashes during this step, no harm is done. The content of
3607 * the image is the same as the original one at any time.
3608 */
3609 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003610 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003611 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003612 int64_t new_backing_size = 0;
3613 uint64_t offset;
3614 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003615 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003616
Max Reitzf1d3cd72015-02-05 13:58:18 -05003617 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3618 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003619
Eric Blake41536282017-10-11 22:47:15 -05003620 size = blk_getlength(blk);
3621 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003622 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003623 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003624 ret = -1;
3625 goto out;
3626 }
Max Reitz35ddd932019-05-09 19:52:35 +02003627 if (blk_old_backing) {
3628 old_backing_size = blk_getlength(blk_old_backing);
3629 if (old_backing_size < 0) {
3630 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003631
Max Reitz35ddd932019-05-09 19:52:35 +02003632 bdrv_get_backing_filename(bs, backing_name,
3633 sizeof(backing_name));
3634 error_report("Could not get size of '%s': %s",
3635 backing_name, strerror(-old_backing_size));
3636 ret = -1;
3637 goto out;
3638 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003639 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003640 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003641 new_backing_size = blk_getlength(blk_new_backing);
3642 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003643 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003644 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003645 ret = -1;
3646 goto out;
3647 }
Alex Bligha6166732012-10-16 13:46:18 +01003648 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003649
Eric Blake41536282017-10-11 22:47:15 -05003650 if (size != 0) {
3651 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003652 }
3653
Eric Blake41536282017-10-11 22:47:15 -05003654 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003655 bool buf_old_is_zero = false;
3656
Eric Blake41536282017-10-11 22:47:15 -05003657 /* How many bytes can we handle with the next read? */
3658 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003659
3660 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003661 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003662 if (ret < 0) {
3663 error_report("error while reading image metadata: %s",
3664 strerror(-ret));
3665 goto out;
3666 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003667 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003668 continue;
3669 }
3670
Sam Eiderman863cc782019-05-23 19:33:36 +03003671 if (prefix_chain_bs) {
3672 /*
3673 * If cluster wasn't changed since prefix_chain, we don't need
3674 * to take action
3675 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003676 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3677 prefix_chain_bs, false,
3678 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003679 if (ret < 0) {
3680 error_report("error while reading image metadata: %s",
3681 strerror(-ret));
3682 goto out;
3683 }
3684 if (!ret) {
3685 continue;
3686 }
3687 }
3688
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003689 /*
3690 * Read old and new backing file and take into consideration that
3691 * backing files may be smaller than the COW image.
3692 */
Eric Blake41536282017-10-11 22:47:15 -05003693 if (offset >= old_backing_size) {
3694 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003695 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003696 } else {
Eric Blake41536282017-10-11 22:47:15 -05003697 if (offset + n > old_backing_size) {
3698 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003699 }
3700
Eric Blake41536282017-10-11 22:47:15 -05003701 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003702 if (ret < 0) {
3703 error_report("error while reading from old backing file");
3704 goto out;
3705 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003706 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003707
Eric Blake41536282017-10-11 22:47:15 -05003708 if (offset >= new_backing_size || !blk_new_backing) {
3709 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003710 } else {
Eric Blake41536282017-10-11 22:47:15 -05003711 if (offset + n > new_backing_size) {
3712 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003713 }
3714
Eric Blake41536282017-10-11 22:47:15 -05003715 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003716 if (ret < 0) {
3717 error_report("error while reading from new backing file");
3718 goto out;
3719 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003720 }
3721
3722 /* If they differ, we need to write to the COW file */
3723 uint64_t written = 0;
3724
Eric Blake41536282017-10-11 22:47:15 -05003725 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003726 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003727
Eric Blake41536282017-10-11 22:47:15 -05003728 if (compare_buffers(buf_old + written, buf_new + written,
3729 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003730 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003731 if (buf_old_is_zero) {
3732 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3733 } else {
3734 ret = blk_pwrite(blk, offset + written,
3735 buf_old + written, pnum, 0);
3736 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003737 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003738 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003739 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003740 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003741 }
3742 }
3743
3744 written += pnum;
3745 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003746 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003747 }
3748 }
3749
3750 /*
3751 * Change the backing file. All clusters that are different from the old
3752 * backing file are overwritten in the COW file now, so the visible content
3753 * doesn't change when we switch the backing file.
3754 */
Alex Bligha6166732012-10-16 13:46:18 +01003755 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003756 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3757 true);
Alex Bligha6166732012-10-16 13:46:18 +01003758 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003759 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003760 }
3761
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003762 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003763 error_report("Could not change the backing file to '%s': No "
3764 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003765 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003766 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003767 out_baseimg, strerror(-ret));
3768 }
3769
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003770 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003771 /*
3772 * TODO At this point it is possible to check if any clusters that are
3773 * allocated in the COW file are the same in the backing file. If so, they
3774 * could be dropped from the COW file. Don't do this before switching the
3775 * backing file, in case of a crash this would lead to corruption.
3776 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003777out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003778 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003779 /* Cleanup */
3780 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003781 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003782 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003783 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003784 qemu_vfree(buf_old);
3785 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003786
Markus Armbruster26f54e92014-10-07 13:59:04 +02003787 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003788 if (ret) {
3789 return 1;
3790 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003791 return 0;
3792}
3793
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003794static int img_resize(int argc, char **argv)
3795{
Markus Armbruster6750e792015-02-12 17:43:08 +01003796 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003797 int c, ret, relative;
3798 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003799 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003800 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003801 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003802 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003803 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003804
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003805 static QemuOptsList resize_options = {
3806 .name = "resize_options",
3807 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3808 .desc = {
3809 {
3810 .name = BLOCK_OPT_SIZE,
3811 .type = QEMU_OPT_SIZE,
3812 .help = "Virtual disk size"
3813 }, {
3814 /* end of list */
3815 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003816 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003817 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003818 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003819 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003820
Kevin Wolfe80fec72011-04-29 10:58:12 +02003821 /* Remove size from argv manually so that negative numbers are not treated
3822 * as options by getopt. */
3823 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003824 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003825 return 1;
3826 }
3827
3828 size = argv[--argc];
3829
3830 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003831 fmt = NULL;
3832 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003833 static const struct option long_options[] = {
3834 {"help", no_argument, 0, 'h'},
3835 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003836 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003837 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003838 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003839 {0, 0, 0, 0}
3840 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003841 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003842 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003843 if (c == -1) {
3844 break;
3845 }
3846 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003847 case ':':
3848 missing_argument(argv[optind - 1]);
3849 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003850 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003851 unrecognized_option(argv[optind - 1]);
3852 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003853 case 'h':
3854 help();
3855 break;
3856 case 'f':
3857 fmt = optarg;
3858 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003859 case 'q':
3860 quiet = true;
3861 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003862 case OPTION_OBJECT:
3863 user_creatable_process_cmdline(optarg);
3864 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003865 case OPTION_IMAGE_OPTS:
3866 image_opts = true;
3867 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003868 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003869 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003870 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003871 if (prealloc == PREALLOC_MODE__MAX) {
3872 error_report("Invalid preallocation mode '%s'", optarg);
3873 return 1;
3874 }
3875 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003876 case OPTION_SHRINK:
3877 shrink = true;
3878 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003879 }
3880 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003881 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003882 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003883 }
3884 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003885
3886 /* Choose grow, shrink, or absolute resize mode */
3887 switch (size[0]) {
3888 case '+':
3889 relative = 1;
3890 size++;
3891 break;
3892 case '-':
3893 relative = -1;
3894 size++;
3895 break;
3896 default:
3897 relative = 0;
3898 break;
3899 }
3900
3901 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003902 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02003903 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01003904 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003905 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003906 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003907 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003908 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003909 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3910 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003911
Max Reitzefaa7c42016-03-16 19:54:38 +01003912 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003913 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3914 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003915 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003916 ret = -1;
3917 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003918 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003919
Max Reitzdc5f6902017-06-13 22:20:55 +02003920 current_size = blk_getlength(blk);
3921 if (current_size < 0) {
3922 error_report("Failed to inquire current image length: %s",
3923 strerror(-current_size));
3924 ret = -1;
3925 goto out;
3926 }
3927
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003928 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003929 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003930 } else {
3931 total_size = n;
3932 }
3933 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003934 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003935 ret = -1;
3936 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003937 }
3938
Max Reitzdc5f6902017-06-13 22:20:55 +02003939 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3940 error_report("Preallocation can only be used for growing images");
3941 ret = -1;
3942 goto out;
3943 }
3944
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003945 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02003946 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003947 warn_report("Shrinking an image will delete all data beyond the "
3948 "shrunken image's end. Before performing such an "
3949 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02003950 ret = -1;
3951 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003952 }
3953
Max Reitze8d04f92019-09-18 11:51:43 +02003954 /*
3955 * The user expects the image to have the desired size after
3956 * resizing, so pass @exact=true. It is of no use to report
3957 * success when the image has not actually been resized.
3958 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02003959 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02003960 if (!ret) {
3961 qprintf(quiet, "Image resized.\n");
3962 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003963 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003964 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003965out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003966 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003967 if (ret) {
3968 return 1;
3969 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003970 return 0;
3971}
3972
Max Reitz76a3a342014-10-27 11:12:51 +01003973static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003974 int64_t offset, int64_t total_work_size,
3975 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003976{
3977 qemu_progress_print(100.f * offset / total_work_size, 0);
3978}
3979
Max Reitz51641352018-05-09 23:00:20 +02003980static int print_amend_option_help(const char *format)
3981{
3982 BlockDriver *drv;
3983
3984 /* Find driver and parse its options */
3985 drv = bdrv_find_format(format);
3986 if (!drv) {
3987 error_report("Unknown file format '%s'", format);
3988 return 1;
3989 }
3990
3991 if (!drv->bdrv_amend_options) {
3992 error_report("Format driver '%s' does not support option amendment",
3993 format);
3994 return 1;
3995 }
3996
Maxim Levitskydf373fb2020-06-25 14:55:39 +02003997 /* Every driver supporting amendment must have amend_opts */
3998 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02003999
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004000 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004001 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004002 return 0;
4003}
4004
Max Reitz6f176b42013-09-03 10:09:50 +02004005static int img_amend(int argc, char **argv)
4006{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004007 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004008 int c, ret = 0;
4009 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004010 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004011 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004012 const char *fmt = NULL, *filename, *cache;
4013 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004014 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004015 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004016 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004017 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004018 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004019 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004020
Max Reitzbd39e6e2014-07-22 22:58:43 +02004021 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004022 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004023 static const struct option long_options[] = {
4024 {"help", no_argument, 0, 'h'},
4025 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004026 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004027 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004028 {0, 0, 0, 0}
4029 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004030 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004031 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004032 if (c == -1) {
4033 break;
4034 }
4035
4036 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004037 case ':':
4038 missing_argument(argv[optind - 1]);
4039 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004040 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004041 unrecognized_option(argv[optind - 1]);
4042 break;
4043 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004044 help();
4045 break;
4046 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004047 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004048 ret = -1;
4049 goto out_no_progress;
4050 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004051 break;
4052 case 'f':
4053 fmt = optarg;
4054 break;
4055 case 't':
4056 cache = optarg;
4057 break;
4058 case 'p':
4059 progress = true;
4060 break;
4061 case 'q':
4062 quiet = true;
4063 break;
4064 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004065 user_creatable_process_cmdline(optarg);
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004066 break;
4067 case OPTION_IMAGE_OPTS:
4068 image_opts = true;
4069 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004070 case OPTION_FORCE:
4071 force = true;
4072 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004073 }
4074 }
4075
Max Reitz6f176b42013-09-03 10:09:50 +02004076 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004077 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004078 }
4079
Max Reitz76a3a342014-10-27 11:12:51 +01004080 if (quiet) {
4081 progress = false;
4082 }
4083 qemu_progress_init(progress, 1.0);
4084
Kevin Wolfa283cb62014-02-21 16:24:07 +01004085 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4086 if (fmt && has_help_option(options)) {
4087 /* If a format is explicitly specified (and possibly no filename is
4088 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004089 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004090 goto out;
4091 }
4092
4093 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004094 error_report("Expecting one image file name");
4095 ret = -1;
4096 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004097 }
Max Reitz6f176b42013-09-03 10:09:50 +02004098
Kevin Wolfce099542016-03-15 13:01:04 +01004099 flags = BDRV_O_RDWR;
4100 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004101 if (ret < 0) {
4102 error_report("Invalid cache option: %s", cache);
4103 goto out;
4104 }
4105
Fam Zheng335e9932017-05-03 00:35:39 +08004106 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4107 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004108 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004109 ret = -1;
4110 goto out;
4111 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004112 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004113
4114 fmt = bs->drv->format_name;
4115
Kevin Wolf626f84f2014-02-21 16:24:06 +01004116 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004117 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004118 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004119 goto out;
4120 }
4121
Max Reitz1f996682018-05-09 23:00:17 +02004122 if (!bs->drv->bdrv_amend_options) {
4123 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004124 fmt);
4125 ret = -1;
4126 goto out;
4127 }
4128
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004129 /* Every driver supporting amendment must have amend_opts */
4130 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004131
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004132 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4133 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004134 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004135 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004136 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4137 qemu_opts_del(opts);
4138 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004139 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004140 error_append_hint(&err,
4141 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004142 }
4143
Paolo Bonziniece90862017-01-04 15:56:24 +01004144 error_report_err(err);
4145 ret = -1;
4146 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004147 }
4148
Max Reitz76a3a342014-10-27 11:12:51 +01004149 /* In case the driver does not call amend_status_cb() */
4150 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004151 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004152 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004153 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004154 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004155 goto out;
4156 }
4157
4158out:
Max Reitz76a3a342014-10-27 11:12:51 +01004159 qemu_progress_end();
4160
Max Reitze814dff2015-08-20 16:00:38 -07004161out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004162 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004163 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004164 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004165 g_free(options);
4166
Max Reitz6f176b42013-09-03 10:09:50 +02004167 if (ret) {
4168 return 1;
4169 }
4170 return 0;
4171}
4172
Kevin Wolfb6133b82014-08-05 14:17:13 +02004173typedef struct BenchData {
4174 BlockBackend *blk;
4175 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004176 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004177 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004178 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004179 int nrreq;
4180 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004181 int flush_interval;
4182 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004183 uint8_t *buf;
4184 QEMUIOVector *qiov;
4185
4186 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004187 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004188 uint64_t offset;
4189} BenchData;
4190
Kevin Wolf55d539c2016-06-03 13:59:41 +02004191static void bench_undrained_flush_cb(void *opaque, int ret)
4192{
4193 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004194 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004195 exit(EXIT_FAILURE);
4196 }
4197}
4198
Kevin Wolfb6133b82014-08-05 14:17:13 +02004199static void bench_cb(void *opaque, int ret)
4200{
4201 BenchData *b = opaque;
4202 BlockAIOCB *acb;
4203
4204 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004205 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004206 exit(EXIT_FAILURE);
4207 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004208
4209 if (b->in_flush) {
4210 /* Just finished a flush with drained queue: Start next requests */
4211 assert(b->in_flight == 0);
4212 b->in_flush = false;
4213 } else if (b->in_flight > 0) {
4214 int remaining = b->n - b->in_flight;
4215
Kevin Wolfb6133b82014-08-05 14:17:13 +02004216 b->n--;
4217 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004218
4219 /* Time for flush? Drain queue if requested, then flush */
4220 if (b->flush_interval && remaining % b->flush_interval == 0) {
4221 if (!b->in_flight || !b->drain_on_flush) {
4222 BlockCompletionFunc *cb;
4223
4224 if (b->drain_on_flush) {
4225 b->in_flush = true;
4226 cb = bench_cb;
4227 } else {
4228 cb = bench_undrained_flush_cb;
4229 }
4230
4231 acb = blk_aio_flush(b->blk, cb, b);
4232 if (!acb) {
4233 error_report("Failed to issue flush request");
4234 exit(EXIT_FAILURE);
4235 }
4236 }
4237 if (b->drain_on_flush) {
4238 return;
4239 }
4240 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004241 }
4242
4243 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004244 int64_t offset = b->offset;
4245 /* blk_aio_* might look for completed I/Os and kick bench_cb
4246 * again, so make sure this operation is counted by in_flight
4247 * and b->offset is ready for the next submission.
4248 */
4249 b->in_flight++;
4250 b->offset += b->step;
4251 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004252 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004253 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004254 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004255 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004256 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004257 if (!acb) {
4258 error_report("Failed to issue request");
4259 exit(EXIT_FAILURE);
4260 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004261 }
4262}
4263
4264static int img_bench(int argc, char **argv)
4265{
4266 int c, ret = 0;
4267 const char *fmt = NULL, *filename;
4268 bool quiet = false;
4269 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004270 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004271 int count = 75000;
4272 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004273 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004274 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004275 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004276 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004277 int flush_interval = 0;
4278 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004279 int64_t image_size;
4280 BlockBackend *blk = NULL;
4281 BenchData data = {};
4282 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004283 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004284 struct timeval t1, t2;
4285 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004286 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004287 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004288
4289 for (;;) {
4290 static const struct option long_options[] = {
4291 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004292 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004293 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004294 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004295 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004296 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004297 {0, 0, 0, 0}
4298 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004299 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4300 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004301 if (c == -1) {
4302 break;
4303 }
4304
4305 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004306 case ':':
4307 missing_argument(argv[optind - 1]);
4308 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004309 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004310 unrecognized_option(argv[optind - 1]);
4311 break;
4312 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004313 help();
4314 break;
4315 case 'c':
4316 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004317 unsigned long res;
4318
4319 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004320 error_report("Invalid request count specified");
4321 return 1;
4322 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004323 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004324 break;
4325 }
4326 case 'd':
4327 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004328 unsigned long res;
4329
4330 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004331 error_report("Invalid queue depth specified");
4332 return 1;
4333 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004334 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004335 break;
4336 }
4337 case 'f':
4338 fmt = optarg;
4339 break;
4340 case 'n':
4341 flags |= BDRV_O_NATIVE_AIO;
4342 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004343 case 'i':
4344 ret = bdrv_parse_aio(optarg, &flags);
4345 if (ret < 0) {
4346 error_report("Invalid aio option: %s", optarg);
4347 ret = -1;
4348 goto out;
4349 }
4350 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004351 case 'o':
4352 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004353 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004354 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004355 return 1;
4356 }
4357 break;
4358 }
4359 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004360 case 'q':
4361 quiet = true;
4362 break;
4363 case 's':
4364 {
4365 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004366
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004367 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4368 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004369 return 1;
4370 }
4371
4372 bufsize = sval;
4373 break;
4374 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004375 case 'S':
4376 {
4377 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004378
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004379 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4380 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004381 return 1;
4382 }
4383
4384 step = sval;
4385 break;
4386 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004387 case 't':
4388 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4389 if (ret < 0) {
4390 error_report("Invalid cache mode");
4391 ret = -1;
4392 goto out;
4393 }
4394 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004395 case 'w':
4396 flags |= BDRV_O_RDWR;
4397 is_write = true;
4398 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004399 case 'U':
4400 force_share = true;
4401 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004402 case OPTION_PATTERN:
4403 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004404 unsigned long res;
4405
4406 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004407 error_report("Invalid pattern byte specified");
4408 return 1;
4409 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004410 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004411 break;
4412 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004413 case OPTION_FLUSH_INTERVAL:
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 Wolf55d539c2016-06-03 13:59:41 +02004418 error_report("Invalid flush interval specified");
4419 return 1;
4420 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004421 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004422 break;
4423 }
4424 case OPTION_NO_DRAIN:
4425 drain_on_flush = false;
4426 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004427 case OPTION_IMAGE_OPTS:
4428 image_opts = true;
4429 break;
4430 }
4431 }
4432
4433 if (optind != argc - 1) {
4434 error_exit("Expecting one image file name");
4435 }
4436 filename = argv[argc - 1];
4437
Kevin Wolf55d539c2016-06-03 13:59:41 +02004438 if (!is_write && flush_interval) {
4439 error_report("--flush-interval is only available in write tests");
4440 ret = -1;
4441 goto out;
4442 }
4443 if (flush_interval && flush_interval < depth) {
4444 error_report("Flush interval can't be smaller than depth");
4445 ret = -1;
4446 goto out;
4447 }
4448
Fam Zheng335e9932017-05-03 00:35:39 +08004449 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4450 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004451 if (!blk) {
4452 ret = -1;
4453 goto out;
4454 }
4455
4456 image_size = blk_getlength(blk);
4457 if (image_size < 0) {
4458 ret = image_size;
4459 goto out;
4460 }
4461
4462 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004463 .blk = blk,
4464 .image_size = image_size,
4465 .bufsize = bufsize,
4466 .step = step ?: bufsize,
4467 .nrreq = depth,
4468 .n = count,
4469 .offset = offset,
4470 .write = is_write,
4471 .flush_interval = flush_interval,
4472 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004473 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004474 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004475 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004476 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004477 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004478 if (flush_interval) {
4479 printf("Sending flush every %d requests\n", flush_interval);
4480 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004481
Fam Zheng79d46582018-01-16 14:08:58 +08004482 buf_size = data.nrreq * data.bufsize;
4483 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004484 memset(data.buf, pattern, data.nrreq * data.bufsize);
4485
Fam Zheng79d46582018-01-16 14:08:58 +08004486 blk_register_buf(blk, data.buf, buf_size);
4487
Kevin Wolfb6133b82014-08-05 14:17:13 +02004488 data.qiov = g_new(QEMUIOVector, data.nrreq);
4489 for (i = 0; i < data.nrreq; i++) {
4490 qemu_iovec_init(&data.qiov[i], 1);
4491 qemu_iovec_add(&data.qiov[i],
4492 data.buf + i * data.bufsize, data.bufsize);
4493 }
4494
4495 gettimeofday(&t1, NULL);
4496 bench_cb(&data, 0);
4497
4498 while (data.n > 0) {
4499 main_loop_wait(false);
4500 }
4501 gettimeofday(&t2, NULL);
4502
4503 printf("Run completed in %3.3f seconds.\n",
4504 (t2.tv_sec - t1.tv_sec)
4505 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4506
4507out:
Fam Zheng79d46582018-01-16 14:08:58 +08004508 if (data.buf) {
4509 blk_unregister_buf(blk, data.buf);
4510 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004511 qemu_vfree(data.buf);
4512 blk_unref(blk);
4513
4514 if (ret) {
4515 return 1;
4516 }
4517 return 0;
4518}
4519
Eric Blake3b51ab42020-05-12 20:16:45 -05004520enum ImgBitmapAct {
4521 BITMAP_ADD,
4522 BITMAP_REMOVE,
4523 BITMAP_CLEAR,
4524 BITMAP_ENABLE,
4525 BITMAP_DISABLE,
4526 BITMAP_MERGE,
4527};
4528typedef struct ImgBitmapAction {
4529 enum ImgBitmapAct act;
4530 const char *src; /* only used for merge */
4531 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4532} ImgBitmapAction;
4533
4534static int img_bitmap(int argc, char **argv)
4535{
4536 Error *err = NULL;
4537 int c, ret = 1;
4538 QemuOpts *opts = NULL;
4539 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4540 const char *filename, *bitmap;
4541 BlockBackend *blk = NULL, *src = NULL;
4542 BlockDriverState *bs = NULL, *src_bs = NULL;
4543 bool image_opts = false;
4544 int64_t granularity = 0;
4545 bool add = false, merge = false;
4546 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4547 ImgBitmapAction *act, *act_next;
4548 const char *op;
4549
4550 QSIMPLEQ_INIT(&actions);
4551
4552 for (;;) {
4553 static const struct option long_options[] = {
4554 {"help", no_argument, 0, 'h'},
4555 {"object", required_argument, 0, OPTION_OBJECT},
4556 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4557 {"add", no_argument, 0, OPTION_ADD},
4558 {"remove", no_argument, 0, OPTION_REMOVE},
4559 {"clear", no_argument, 0, OPTION_CLEAR},
4560 {"enable", no_argument, 0, OPTION_ENABLE},
4561 {"disable", no_argument, 0, OPTION_DISABLE},
4562 {"merge", required_argument, 0, OPTION_MERGE},
4563 {"granularity", required_argument, 0, 'g'},
4564 {"source-file", required_argument, 0, 'b'},
4565 {"source-format", required_argument, 0, 'F'},
4566 {0, 0, 0, 0}
4567 };
4568 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4569 if (c == -1) {
4570 break;
4571 }
4572
4573 switch (c) {
4574 case ':':
4575 missing_argument(argv[optind - 1]);
4576 break;
4577 case '?':
4578 unrecognized_option(argv[optind - 1]);
4579 break;
4580 case 'h':
4581 help();
4582 break;
4583 case 'b':
4584 src_filename = optarg;
4585 break;
4586 case 'f':
4587 fmt = optarg;
4588 break;
4589 case 'F':
4590 src_fmt = optarg;
4591 break;
4592 case 'g':
4593 granularity = cvtnum("granularity", optarg);
4594 if (granularity < 0) {
4595 return 1;
4596 }
4597 break;
4598 case OPTION_ADD:
4599 act = g_new0(ImgBitmapAction, 1);
4600 act->act = BITMAP_ADD;
4601 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4602 add = true;
4603 break;
4604 case OPTION_REMOVE:
4605 act = g_new0(ImgBitmapAction, 1);
4606 act->act = BITMAP_REMOVE;
4607 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4608 break;
4609 case OPTION_CLEAR:
4610 act = g_new0(ImgBitmapAction, 1);
4611 act->act = BITMAP_CLEAR;
4612 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4613 break;
4614 case OPTION_ENABLE:
4615 act = g_new0(ImgBitmapAction, 1);
4616 act->act = BITMAP_ENABLE;
4617 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4618 break;
4619 case OPTION_DISABLE:
4620 act = g_new0(ImgBitmapAction, 1);
4621 act->act = BITMAP_DISABLE;
4622 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4623 break;
4624 case OPTION_MERGE:
4625 act = g_new0(ImgBitmapAction, 1);
4626 act->act = BITMAP_MERGE;
4627 act->src = optarg;
4628 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4629 merge = true;
4630 break;
4631 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004632 user_creatable_process_cmdline(optarg);
Eric Blake3b51ab42020-05-12 20:16:45 -05004633 break;
4634 case OPTION_IMAGE_OPTS:
4635 image_opts = true;
4636 break;
4637 }
4638 }
4639
Eric Blake3b51ab42020-05-12 20:16:45 -05004640 if (QSIMPLEQ_EMPTY(&actions)) {
4641 error_report("Need at least one of --add, --remove, --clear, "
4642 "--enable, --disable, or --merge");
4643 goto out;
4644 }
4645
4646 if (granularity && !add) {
4647 error_report("granularity only supported with --add");
4648 goto out;
4649 }
4650 if (src_fmt && !src_filename) {
4651 error_report("-F only supported with -b");
4652 goto out;
4653 }
4654 if (src_filename && !merge) {
4655 error_report("Merge bitmap source file only supported with "
4656 "--merge");
4657 goto out;
4658 }
4659
4660 if (optind != argc - 2) {
4661 error_report("Expecting filename and bitmap name");
4662 goto out;
4663 }
4664
4665 filename = argv[optind];
4666 bitmap = argv[optind + 1];
4667
Eric Blake14f16bf2020-09-14 14:10:09 -05004668 /*
4669 * No need to open backing chains; we will be manipulating bitmaps
4670 * directly in this image without reference to image contents.
4671 */
4672 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4673 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004674 if (!blk) {
4675 goto out;
4676 }
4677 bs = blk_bs(blk);
4678 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004679 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4680 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004681 if (!src) {
4682 goto out;
4683 }
4684 src_bs = blk_bs(src);
4685 } else {
4686 src_bs = bs;
4687 }
4688
4689 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4690 switch (act->act) {
4691 case BITMAP_ADD:
4692 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4693 !!granularity, granularity, true, true,
4694 false, false, &err);
4695 op = "add";
4696 break;
4697 case BITMAP_REMOVE:
4698 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4699 op = "remove";
4700 break;
4701 case BITMAP_CLEAR:
4702 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4703 op = "clear";
4704 break;
4705 case BITMAP_ENABLE:
4706 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4707 op = "enable";
4708 break;
4709 case BITMAP_DISABLE:
4710 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4711 op = "disable";
4712 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004713 case BITMAP_MERGE:
4714 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4715 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004716 op = "merge";
4717 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004718 default:
4719 g_assert_not_reached();
4720 }
4721
4722 if (err) {
4723 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4724 op, bitmap);
4725 goto out;
4726 }
4727 g_free(act);
4728 }
4729
4730 ret = 0;
4731
4732 out:
4733 blk_unref(src);
4734 blk_unref(blk);
4735 qemu_opts_del(opts);
4736 return ret;
4737}
4738
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004739#define C_BS 01
4740#define C_COUNT 02
4741#define C_IF 04
4742#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004743#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004744
4745struct DdInfo {
4746 unsigned int flags;
4747 int64_t count;
4748};
4749
4750struct DdIo {
4751 int bsz; /* Block size */
4752 char *filename;
4753 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004754 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004755};
4756
4757struct DdOpts {
4758 const char *name;
4759 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4760 unsigned int flag;
4761};
4762
4763static int img_dd_bs(const char *arg,
4764 struct DdIo *in, struct DdIo *out,
4765 struct DdInfo *dd)
4766{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004767 int64_t res;
4768
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004769 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004770
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004771 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004772 return 1;
4773 }
4774 in->bsz = out->bsz = res;
4775
4776 return 0;
4777}
4778
4779static int img_dd_count(const char *arg,
4780 struct DdIo *in, struct DdIo *out,
4781 struct DdInfo *dd)
4782{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004783 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004784
Markus Armbruster606caa02017-02-21 21:14:04 +01004785 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004786 return 1;
4787 }
4788
4789 return 0;
4790}
4791
4792static int img_dd_if(const char *arg,
4793 struct DdIo *in, struct DdIo *out,
4794 struct DdInfo *dd)
4795{
4796 in->filename = g_strdup(arg);
4797
4798 return 0;
4799}
4800
4801static int img_dd_of(const char *arg,
4802 struct DdIo *in, struct DdIo *out,
4803 struct DdInfo *dd)
4804{
4805 out->filename = g_strdup(arg);
4806
4807 return 0;
4808}
4809
Reda Sallahif7c15532016-08-10 16:16:09 +02004810static int img_dd_skip(const char *arg,
4811 struct DdIo *in, struct DdIo *out,
4812 struct DdInfo *dd)
4813{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004814 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004815
Markus Armbruster606caa02017-02-21 21:14:04 +01004816 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004817 return 1;
4818 }
4819
4820 return 0;
4821}
4822
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004823static int img_dd(int argc, char **argv)
4824{
4825 int ret = 0;
4826 char *arg = NULL;
4827 char *tmp;
4828 BlockDriver *drv = NULL, *proto_drv = NULL;
4829 BlockBackend *blk1 = NULL, *blk2 = NULL;
4830 QemuOpts *opts = NULL;
4831 QemuOptsList *create_opts = NULL;
4832 Error *local_err = NULL;
4833 bool image_opts = false;
4834 int c, i;
4835 const char *out_fmt = "raw";
4836 const char *fmt = NULL;
4837 int64_t size = 0;
4838 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004839 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004840 struct DdInfo dd = {
4841 .flags = 0,
4842 .count = 0,
4843 };
4844 struct DdIo in = {
4845 .bsz = 512, /* Block size is by default 512 bytes */
4846 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004847 .buf = NULL,
4848 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004849 };
4850 struct DdIo out = {
4851 .bsz = 512,
4852 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004853 .buf = NULL,
4854 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004855 };
4856
4857 const struct DdOpts options[] = {
4858 { "bs", img_dd_bs, C_BS },
4859 { "count", img_dd_count, C_COUNT },
4860 { "if", img_dd_if, C_IF },
4861 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004862 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004863 { NULL, NULL, 0 }
4864 };
4865 const struct option long_options[] = {
4866 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004867 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004868 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004869 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004870 { 0, 0, 0, 0 }
4871 };
4872
Fam Zheng335e9932017-05-03 00:35:39 +08004873 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004874 if (c == EOF) {
4875 break;
4876 }
4877 switch (c) {
4878 case 'O':
4879 out_fmt = optarg;
4880 break;
4881 case 'f':
4882 fmt = optarg;
4883 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004884 case ':':
4885 missing_argument(argv[optind - 1]);
4886 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004887 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004888 unrecognized_option(argv[optind - 1]);
4889 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004890 case 'h':
4891 help();
4892 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004893 case 'U':
4894 force_share = true;
4895 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004896 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004897 user_creatable_process_cmdline(optarg);
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004898 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004899 case OPTION_IMAGE_OPTS:
4900 image_opts = true;
4901 break;
4902 }
4903 }
4904
4905 for (i = optind; i < argc; i++) {
4906 int j;
4907 arg = g_strdup(argv[i]);
4908
4909 tmp = strchr(arg, '=');
4910 if (tmp == NULL) {
4911 error_report("unrecognized operand %s", arg);
4912 ret = -1;
4913 goto out;
4914 }
4915
4916 *tmp++ = '\0';
4917
4918 for (j = 0; options[j].name != NULL; j++) {
4919 if (!strcmp(arg, options[j].name)) {
4920 break;
4921 }
4922 }
4923 if (options[j].name == NULL) {
4924 error_report("unrecognized operand %s", arg);
4925 ret = -1;
4926 goto out;
4927 }
4928
4929 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4930 ret = -1;
4931 goto out;
4932 }
4933 dd.flags |= options[j].flag;
4934 g_free(arg);
4935 arg = NULL;
4936 }
4937
4938 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4939 error_report("Must specify both input and output files");
4940 ret = -1;
4941 goto out;
4942 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004943
Fam Zheng335e9932017-05-03 00:35:39 +08004944 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4945 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004946
4947 if (!blk1) {
4948 ret = -1;
4949 goto out;
4950 }
4951
4952 drv = bdrv_find_format(out_fmt);
4953 if (!drv) {
4954 error_report("Unknown file format");
4955 ret = -1;
4956 goto out;
4957 }
4958 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4959
4960 if (!proto_drv) {
4961 error_report_err(local_err);
4962 ret = -1;
4963 goto out;
4964 }
4965 if (!drv->create_opts) {
4966 error_report("Format driver '%s' does not support image creation",
4967 drv->format_name);
4968 ret = -1;
4969 goto out;
4970 }
4971 if (!proto_drv->create_opts) {
4972 error_report("Protocol driver '%s' does not support image creation",
4973 proto_drv->format_name);
4974 ret = -1;
4975 goto out;
4976 }
4977 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4978 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4979
4980 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4981
4982 size = blk_getlength(blk1);
4983 if (size < 0) {
4984 error_report("Failed to get size for '%s'", in.filename);
4985 ret = -1;
4986 goto out;
4987 }
4988
4989 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
4990 dd.count * in.bsz < size) {
4991 size = dd.count * in.bsz;
4992 }
4993
Reda Sallahif7c15532016-08-10 16:16:09 +02004994 /* Overflow means the specified offset is beyond input image's size */
4995 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
4996 size < in.bsz * in.offset)) {
4997 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
4998 } else {
4999 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5000 size - in.bsz * in.offset, &error_abort);
5001 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005002
5003 ret = bdrv_create(drv, out.filename, opts, &local_err);
5004 if (ret < 0) {
5005 error_reportf_err(local_err,
5006 "%s: error while creating output image: ",
5007 out.filename);
5008 ret = -1;
5009 goto out;
5010 }
5011
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005012 /* TODO, we can't honour --image-opts for the target,
5013 * since it needs to be given in a format compatible
5014 * with the bdrv_create() call above which does not
5015 * support image-opts style.
5016 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005017 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005018 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005019
5020 if (!blk2) {
5021 ret = -1;
5022 goto out;
5023 }
5024
Reda Sallahif7c15532016-08-10 16:16:09 +02005025 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5026 size < in.offset * in.bsz)) {
5027 /* We give a warning if the skip option is bigger than the input
5028 * size and create an empty output disk image (i.e. like dd(1)).
5029 */
5030 error_report("%s: cannot skip to specified offset", in.filename);
5031 in_pos = size;
5032 } else {
5033 in_pos = in.offset * in.bsz;
5034 }
5035
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005036 in.buf = g_new(uint8_t, in.bsz);
5037
Reda Sallahif7c15532016-08-10 16:16:09 +02005038 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005039 int in_ret, out_ret;
5040
5041 if (in_pos + in.bsz > size) {
5042 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5043 } else {
5044 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5045 }
5046 if (in_ret < 0) {
5047 error_report("error while reading from input image file: %s",
5048 strerror(-in_ret));
5049 ret = -1;
5050 goto out;
5051 }
5052 in_pos += in_ret;
5053
5054 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5055
5056 if (out_ret < 0) {
5057 error_report("error while writing to output image file: %s",
5058 strerror(-out_ret));
5059 ret = -1;
5060 goto out;
5061 }
5062 out_pos += out_ret;
5063 }
5064
5065out:
5066 g_free(arg);
5067 qemu_opts_del(opts);
5068 qemu_opts_free(create_opts);
5069 blk_unref(blk1);
5070 blk_unref(blk2);
5071 g_free(in.filename);
5072 g_free(out.filename);
5073 g_free(in.buf);
5074 g_free(out.buf);
5075
5076 if (ret) {
5077 return 1;
5078 }
5079 return 0;
5080}
5081
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005082static void dump_json_block_measure_info(BlockMeasureInfo *info)
5083{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005084 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005085 QObject *obj;
5086 Visitor *v = qobject_output_visitor_new(&obj);
5087
5088 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5089 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005090 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005091 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005092 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005093 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005094 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005095 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005096}
5097
5098static int img_measure(int argc, char **argv)
5099{
5100 static const struct option long_options[] = {
5101 {"help", no_argument, 0, 'h'},
5102 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5103 {"object", required_argument, 0, OPTION_OBJECT},
5104 {"output", required_argument, 0, OPTION_OUTPUT},
5105 {"size", required_argument, 0, OPTION_SIZE},
5106 {"force-share", no_argument, 0, 'U'},
5107 {0, 0, 0, 0}
5108 };
5109 OutputFormat output_format = OFORMAT_HUMAN;
5110 BlockBackend *in_blk = NULL;
5111 BlockDriver *drv;
5112 const char *filename = NULL;
5113 const char *fmt = NULL;
5114 const char *out_fmt = "raw";
5115 char *options = NULL;
5116 char *snapshot_name = NULL;
5117 bool force_share = false;
5118 QemuOpts *opts = NULL;
5119 QemuOpts *object_opts = NULL;
5120 QemuOpts *sn_opts = NULL;
5121 QemuOptsList *create_opts = NULL;
5122 bool image_opts = false;
5123 uint64_t img_size = UINT64_MAX;
5124 BlockMeasureInfo *info = NULL;
5125 Error *local_err = NULL;
5126 int ret = 1;
5127 int c;
5128
5129 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5130 long_options, NULL)) != -1) {
5131 switch (c) {
5132 case '?':
5133 case 'h':
5134 help();
5135 break;
5136 case 'f':
5137 fmt = optarg;
5138 break;
5139 case 'O':
5140 out_fmt = optarg;
5141 break;
5142 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005143 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005144 goto out;
5145 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005146 break;
5147 case 'l':
5148 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5149 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5150 optarg, false);
5151 if (!sn_opts) {
5152 error_report("Failed in parsing snapshot param '%s'",
5153 optarg);
5154 goto out;
5155 }
5156 } else {
5157 snapshot_name = optarg;
5158 }
5159 break;
5160 case 'U':
5161 force_share = true;
5162 break;
5163 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005164 user_creatable_process_cmdline(optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005165 break;
5166 case OPTION_IMAGE_OPTS:
5167 image_opts = true;
5168 break;
5169 case OPTION_OUTPUT:
5170 if (!strcmp(optarg, "json")) {
5171 output_format = OFORMAT_JSON;
5172 } else if (!strcmp(optarg, "human")) {
5173 output_format = OFORMAT_HUMAN;
5174 } else {
5175 error_report("--output must be used with human or json "
5176 "as argument.");
5177 goto out;
5178 }
5179 break;
5180 case OPTION_SIZE:
5181 {
5182 int64_t sval;
5183
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005184 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005185 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005186 goto out;
5187 }
5188 img_size = (uint64_t)sval;
5189 }
5190 break;
5191 }
5192 }
5193
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005194 if (argc - optind > 1) {
5195 error_report("At most one filename argument is allowed.");
5196 goto out;
5197 } else if (argc - optind == 1) {
5198 filename = argv[optind];
5199 }
5200
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005201 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5202 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005203 goto out;
5204 }
5205 if (filename && img_size != UINT64_MAX) {
5206 error_report("--size N cannot be used together with a filename.");
5207 goto out;
5208 }
5209 if (!filename && img_size == UINT64_MAX) {
5210 error_report("Either --size N or one filename must be specified.");
5211 goto out;
5212 }
5213
5214 if (filename) {
5215 in_blk = img_open(image_opts, filename, fmt, 0,
5216 false, false, force_share);
5217 if (!in_blk) {
5218 goto out;
5219 }
5220
5221 if (sn_opts) {
5222 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5223 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5224 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5225 &local_err);
5226 } else if (snapshot_name != NULL) {
5227 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5228 snapshot_name, &local_err);
5229 }
5230 if (local_err) {
5231 error_reportf_err(local_err, "Failed to load snapshot: ");
5232 goto out;
5233 }
5234 }
5235
5236 drv = bdrv_find_format(out_fmt);
5237 if (!drv) {
5238 error_report("Unknown file format '%s'", out_fmt);
5239 goto out;
5240 }
5241 if (!drv->create_opts) {
5242 error_report("Format driver '%s' does not support image creation",
5243 drv->format_name);
5244 goto out;
5245 }
5246
5247 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5248 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5249 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5250 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005251 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005252 error_report_err(local_err);
5253 error_report("Invalid options for file format '%s'", out_fmt);
5254 goto out;
5255 }
5256 }
5257 if (img_size != UINT64_MAX) {
5258 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5259 }
5260
5261 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5262 if (local_err) {
5263 error_report_err(local_err);
5264 goto out;
5265 }
5266
5267 if (output_format == OFORMAT_HUMAN) {
5268 printf("required size: %" PRIu64 "\n", info->required);
5269 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005270 if (info->has_bitmaps) {
5271 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5272 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005273 } else {
5274 dump_json_block_measure_info(info);
5275 }
5276
5277 ret = 0;
5278
5279out:
5280 qapi_free_BlockMeasureInfo(info);
5281 qemu_opts_del(object_opts);
5282 qemu_opts_del(opts);
5283 qemu_opts_del(sn_opts);
5284 qemu_opts_free(create_opts);
5285 g_free(options);
5286 blk_unref(in_blk);
5287 return ret;
5288}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005289
Anthony Liguoric227f092009-10-01 16:12:16 -05005290static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005291#define DEF(option, callback, arg_string) \
5292 { option, callback },
5293#include "qemu-img-cmds.h"
5294#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005295 { NULL, NULL, },
5296};
5297
bellardea2384d2004-08-01 21:59:26 +00005298int main(int argc, char **argv)
5299{
Anthony Liguoric227f092009-10-01 16:12:16 -05005300 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005301 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005302 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005303 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005304 static const struct option long_options[] = {
5305 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005306 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005307 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005308 {0, 0, 0, 0}
5309 };
bellardea2384d2004-08-01 21:59:26 +00005310
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005311#ifdef CONFIG_POSIX
5312 signal(SIGPIPE, SIG_IGN);
5313#endif
5314
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005315 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005316 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005317 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005318 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005319
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005320 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005321 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005322 exit(EXIT_FAILURE);
5323 }
5324
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005325 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005326
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005327 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005328 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005329 if (argc < 2) {
5330 error_exit("Not enough arguments");
5331 }
Stuart Brady153859b2009-06-07 00:42:17 +01005332
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005333 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005334 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005335
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005336 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005337 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005338 case ':':
5339 missing_argument(argv[optind - 1]);
5340 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005341 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005342 unrecognized_option(argv[optind - 1]);
5343 return 0;
5344 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005345 help();
5346 return 0;
5347 case 'V':
5348 printf(QEMU_IMG_VERSION);
5349 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005350 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005351 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005352 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005353 }
bellardea2384d2004-08-01 21:59:26 +00005354 }
Stuart Brady153859b2009-06-07 00:42:17 +01005355
Denis V. Lunev10985132016-06-17 17:44:13 +03005356 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005357
Denis V. Lunev10985132016-06-17 17:44:13 +03005358 /* reset getopt_long scanning */
5359 argc -= optind;
5360 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005361 return 0;
5362 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005363 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005364 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005365
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005366 if (!trace_init_backends()) {
5367 exit(1);
5368 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005369 trace_init_file();
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005370 qemu_set_log(LOG_TRACE);
5371
Denis V. Lunev10985132016-06-17 17:44:13 +03005372 /* find the command */
5373 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5374 if (!strcmp(cmdname, cmd->name)) {
5375 return cmd->handler(argc, argv);
5376 }
5377 }
Jeff Cody7db16892014-04-25 17:02:32 -04005378
Stuart Brady153859b2009-06-07 00:42:17 +01005379 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005380 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005381}