blob: d7e846e60742db809142a70e2dbd4ca1c2ad0038 [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"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010036#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
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"
bellarde8445332006-06-14 15:32:10 +000052
Thomas Huth7e563bf2018-02-15 12:06:47 +010053#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020054 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040055
Anthony Liguoric227f092009-10-01 16:12:16 -050056typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010057 const char *name;
58 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050059} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010060
Federico Simoncelli8599ea42013-01-28 06:59:47 -050061enum {
62 OPTION_OUTPUT = 256,
63 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000064 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000065 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020066 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020067 OPTION_FLUSH_INTERVAL = 261,
68 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010069 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010070 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020071 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030072 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020073 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000074 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050075 OPTION_ADD = 269,
76 OPTION_REMOVE = 270,
77 OPTION_CLEAR = 271,
78 OPTION_ENABLE = 272,
79 OPTION_DISABLE = 273,
80 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050081 OPTION_BITMAPS = 275,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050082};
83
84typedef enum OutputFormat {
85 OFORMAT_JSON,
86 OFORMAT_HUMAN,
87} OutputFormat;
88
Kevin Wolfe6996142016-03-15 13:03:11 +010089/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040090#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000091
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010092static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000093{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010094 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000095}
96
Fam Zhengac1307a2014-04-22 13:36:11 +080097static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
98{
99 va_list ap;
100
Fam Zhengac1307a2014-04-22 13:36:11 +0800101 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200102 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800103 va_end(ap);
104
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200105 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800106 exit(EXIT_FAILURE);
107}
108
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800109static void QEMU_NORETURN missing_argument(const char *option)
110{
111 error_exit("missing argument for option '%s'", option);
112}
113
114static void QEMU_NORETURN unrecognized_option(const char *option)
115{
116 error_exit("unrecognized option '%s'", option);
117}
118
Eric Blake0562adf2020-05-12 20:16:41 -0500119/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800120static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000121{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100122 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400123 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300124 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300125 "QEMU disk image utility\n"
126 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300127 " '-h', '--help' display this help and exit\n"
128 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300129 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
130 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300131 "\n"
malc3f020d72010-02-08 12:04:56 +0300132 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100133#define DEF(option, callback, arg_string) \
134 " " arg_string "\n"
135#include "qemu-img-cmds.h"
136#undef DEF
malc3f020d72010-02-08 12:04:56 +0300137 "\n"
138 "Command parameters:\n"
139 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000140 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
141 " manual page for a description of the object properties. The most common\n"
142 " object type is a 'secret', which is used to supply passwords and/or\n"
143 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300144 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400145 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800146 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
147 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100148 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
149 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300150 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200151 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
152 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
153 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300154 " 'output_filename' is the destination disk image filename\n"
155 " 'output_fmt' is the destination format\n"
156 " 'options' is a comma separated list of format specific options in a\n"
157 " name=value format. Use -o ? for an overview of the options supported by the\n"
158 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800159 " 'snapshot_param' is param used for internal snapshot, format\n"
160 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
161 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300162 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400163 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
164 " new backing file match exactly. The image doesn't need a working\n"
165 " backing file before rebasing in this case (useful for renaming the\n"
166 " backing file). For image creation, allow creating without attempting\n"
167 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300168 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200169 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100170 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200171 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
172 " contain only zeros for qemu-img to create a sparse image during\n"
173 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
174 " unallocated or zero sectors, and the destination image will always be\n"
175 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200176 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100177 " '-n' skips the target volume creation (useful if the volume is created\n"
178 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300179 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500180 "Parameters to bitmap subcommand:\n"
181 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
182 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
183 " or '--merge source'\n"
184 " '-g granularity' sets the granularity for '--add' actions\n"
185 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
186 " bitmaps from an alternative file\n"
187 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200188 "Parameters to check subcommand:\n"
189 " '-r' tries to repair any inconsistencies that are found during the check.\n"
190 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
191 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200192 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200193 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100194 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500195 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100196 " '-m' specifies how many coroutines work in parallel during the convert\n"
197 " process (defaults to 8)\n"
198 " '-W' allow to write to the target out of order rather than sequential\n"
199 "\n"
malc3f020d72010-02-08 12:04:56 +0300200 "Parameters to snapshot subcommand:\n"
201 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
202 " '-a' applies a snapshot (revert disk to saved state)\n"
203 " '-c' creates a snapshot\n"
204 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100205 " '-l' lists all snapshots in the given image\n"
206 "\n"
207 "Parameters to compare subcommand:\n"
208 " '-f' first image format\n"
209 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200210 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
211 "\n"
212 "Parameters to dd subcommand:\n"
213 " 'bs=BYTES' read and write up to BYTES bytes at a time "
214 "(default: 512)\n"
215 " 'count=N' copy only N input blocks\n"
216 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200217 " 'of=FILE' write to FILE\n"
218 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100219
220 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300221 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500222 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800223 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000224}
225
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000226static QemuOptsList qemu_object_opts = {
227 .name = "object",
228 .implied_opt_name = "qom-type",
229 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
230 .desc = {
231 { }
232 },
233};
234
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200235static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
236{
237 if (user_creatable_print_help(type, opts)) {
238 exit(0);
239 }
240 return true;
241}
242
Markus Armbruster80c710c2020-04-15 09:49:26 +0200243/*
244 * Is @optarg safe for accumulate_options()?
245 * It is when multiple of them can be joined together separated by ','.
246 * To make that work, @optarg must not start with ',' (or else a
247 * separating ',' preceding it gets escaped), and it must not end with
248 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200249 * escaped), or be empty (or else a separating ',' preceding it can
250 * escape a separating ',' following it).
251 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200252 */
253static bool is_valid_option_list(const char *optarg)
254{
255 size_t len = strlen(optarg);
256 size_t i;
257
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200258 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200259 return false;
260 }
261
262 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
263 }
264 if ((len - i) % 2) {
265 return false;
266 }
267
268 return true;
269}
270
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200271static int accumulate_options(char **options, char *optarg)
272{
273 char *new_options;
274
275 if (!is_valid_option_list(optarg)) {
276 error_report("Invalid option list: %s", optarg);
277 return -1;
278 }
279
280 if (!*options) {
281 *options = g_strdup(optarg);
282 } else {
283 new_options = g_strdup_printf("%s,%s", *options, optarg);
284 g_free(*options);
285 *options = new_options;
286 }
287 return 0;
288}
289
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000290static QemuOptsList qemu_source_opts = {
291 .name = "source",
292 .implied_opt_name = "file",
293 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
294 .desc = {
295 { }
296 },
297};
298
Stefan Weil7c30f652013-06-16 17:01:05 +0200299static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100300{
301 int ret = 0;
302 if (!quiet) {
303 va_list args;
304 va_start(args, fmt);
305 ret = vprintf(fmt, args);
306 va_end(args);
307 }
308 return ret;
309}
310
bellardea2384d2004-08-01 21:59:26 +0000311
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100312static int print_block_option_help(const char *filename, const char *fmt)
313{
314 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800315 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500316 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100317
318 /* Find driver and parse its options */
319 drv = bdrv_find_format(fmt);
320 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100321 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100322 return 1;
323 }
324
Max Reitzd402b6a2018-05-09 23:00:21 +0200325 if (!drv->create_opts) {
326 error_report("Format driver '%s' does not support image creation", fmt);
327 return 1;
328 }
329
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800330 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100331 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500332 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100333 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100334 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800335 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100336 return 1;
337 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200338 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100339 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200340 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100341 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200342 return 1;
343 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800344 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100345 }
346
Max Reitzf4619af2019-04-13 17:20:37 +0200347 if (filename) {
348 printf("Supported options:\n");
349 } else {
350 printf("Supported %s options:\n", fmt);
351 }
Max Reitz63898712018-10-19 18:49:25 +0200352 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800353 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200354
355 if (!filename) {
356 printf("\n"
357 "The protocol level may support further options.\n"
358 "Specify the target filename to include those options.\n");
359 }
360
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100361 return 0;
362}
363
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000364
Max Reitzefaa7c42016-03-16 19:54:38 +0100365static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100366 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800367 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000368{
369 QDict *options;
370 Error *local_err = NULL;
371 BlockBackend *blk;
372 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800373 if (force_share) {
374 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200375 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800376 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200377 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800378 return NULL;
379 }
Max Reitz4615f872018-05-02 22:20:50 +0200380 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800381 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100382 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100384 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000385 return NULL;
386 }
Kevin Wolfce099542016-03-15 13:01:04 +0100387 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000388
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000389 return blk;
390}
391
Max Reitzefaa7c42016-03-16 19:54:38 +0100392static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100393 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000394 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800395 bool writethrough, bool quiet,
396 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000397{
398 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200399 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100400
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100401 if (!options) {
402 options = qdict_new();
403 }
bellard75c23802004-08-27 21:28:58 +0000404 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500405 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000406 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100407
Fam Zheng335e9932017-05-03 00:35:39 +0800408 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500409 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800410 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100411 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500412 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100413 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000414 return NULL;
bellard75c23802004-08-27 21:28:58 +0000415 }
Kevin Wolfce099542016-03-15 13:01:04 +0100416 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100417
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200418 return blk;
bellard75c23802004-08-27 21:28:58 +0000419}
420
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000421
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100422static int img_add_key_secrets(void *opaque,
423 const char *name, const char *value,
424 Error **errp)
425{
426 QDict *options = opaque;
427
428 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600429 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100430 }
431
432 return 0;
433}
434
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100435
Max Reitzefaa7c42016-03-16 19:54:38 +0100436static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000437 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100438 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800439 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000440{
441 BlockBackend *blk;
442 if (image_opts) {
443 QemuOpts *opts;
444 if (fmt) {
445 error_report("--image-opts and --format are mutually exclusive");
446 return NULL;
447 }
448 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
449 filename, true);
450 if (!opts) {
451 return NULL;
452 }
Fam Zheng335e9932017-05-03 00:35:39 +0800453 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
454 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000455 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100456 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800457 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000458 }
459 return blk;
460}
461
462
Chunyan Liu83d05212014-06-05 17:20:51 +0800463static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100464 const char *base_filename,
465 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200466{
Markus Armbruster6750e792015-02-12 17:43:08 +0100467 Error *err = NULL;
468
Kevin Wolfefa84d42009-05-18 16:42:12 +0200469 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100470 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100471 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100472 error_report("Backing file not supported for file format '%s'",
473 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100474 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900475 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200476 }
477 }
478 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100479 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100480 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100481 error_report("Backing file format not supported for file "
482 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100483 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900484 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200485 }
486 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900487 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200488}
489
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300490static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
491 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100492{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100493 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300494 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100495
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300496 err = qemu_strtosz(value, NULL, &res);
497 if (err < 0 && err != -ERANGE) {
498 error_report("Invalid %s specified. You may use "
499 "k, M, G, T, P or E suffixes for", name);
500 error_report("kilobytes, megabytes, gigabytes, terabytes, "
501 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100502 return err;
503 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300504 if (err == -ERANGE || res > max || res < min) {
505 error_report("Invalid %s specified. Must be between %" PRId64
506 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100507 return -ERANGE;
508 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300509 return res;
510}
511
512static int64_t cvtnum(const char *name, const char *value)
513{
514 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100515}
516
bellardea2384d2004-08-01 21:59:26 +0000517static int img_create(int argc, char **argv)
518{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200519 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100520 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000521 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000522 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000523 const char *filename;
524 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200525 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200526 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100527 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400528 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000529
bellardea2384d2004-08-01 21:59:26 +0000530 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000531 static const struct option long_options[] = {
532 {"help", no_argument, 0, 'h'},
533 {"object", required_argument, 0, OPTION_OBJECT},
534 {0, 0, 0, 0}
535 };
John Snow6e6e55f2017-07-17 20:34:22 -0400536 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000537 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100538 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000539 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100540 }
bellardea2384d2004-08-01 21:59:26 +0000541 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800542 case ':':
543 missing_argument(argv[optind - 1]);
544 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100545 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800546 unrecognized_option(argv[optind - 1]);
547 break;
bellardea2384d2004-08-01 21:59:26 +0000548 case 'h':
549 help();
550 break;
aliguori9230eaf2009-03-28 17:55:19 +0000551 case 'F':
552 base_fmt = optarg;
553 break;
bellardea2384d2004-08-01 21:59:26 +0000554 case 'b':
555 base_filename = optarg;
556 break;
557 case 'f':
558 fmt = optarg;
559 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200560 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200561 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100562 goto fail;
563 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200564 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100565 case 'q':
566 quiet = true;
567 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400568 case 'u':
569 flags |= BDRV_O_NO_BACKING;
570 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000571 case OPTION_OBJECT: {
572 QemuOpts *opts;
573 opts = qemu_opts_parse_noisily(&qemu_object_opts,
574 optarg, true);
575 if (!opts) {
576 goto fail;
577 }
578 } break;
bellardea2384d2004-08-01 21:59:26 +0000579 }
580 }
aliguori9230eaf2009-03-28 17:55:19 +0000581
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900582 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100583 filename = (optind < argc) ? argv[optind] : NULL;
584 if (options && has_help_option(options)) {
585 g_free(options);
586 return print_block_option_help(filename, fmt);
587 }
588
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100589 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800590 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100591 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100592 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900593
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000594 if (qemu_opts_foreach(&qemu_object_opts,
595 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200596 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000597 goto fail;
598 }
599
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100600 /* Get image size, if specified */
601 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100602 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100603
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300604 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100605 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100606 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100607 }
608 img_size = (uint64_t)sval;
609 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200610 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800611 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200612 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100613
Luiz Capitulino9b375252012-11-30 10:52:05 -0200614 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400615 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100616 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100617 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100618 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900619 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200620
Kevin Wolf77386bf2014-02-21 16:24:04 +0100621 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000622 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100623
624fail:
625 g_free(options);
626 return 1;
bellardea2384d2004-08-01 21:59:26 +0000627}
628
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100629static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500630{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500631 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100633 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600634
635 visit_type_ImageCheck(v, NULL, &check, &error_abort);
636 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500637 str = qobject_to_json_pretty(obj);
638 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100639 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200640 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600641 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200642 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500643}
644
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100645static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500646{
647 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100648 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500649 } else {
650 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100651 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
652 "Data may be corrupted, or further writes to the image "
653 "may corrupt it.\n",
654 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500655 }
656
657 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100658 qprintf(quiet,
659 "\n%" PRId64 " leaked clusters were found on the image.\n"
660 "This means waste of disk space, but no harm to data.\n",
661 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500662 }
663
664 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100665 qprintf(quiet,
666 "\n%" PRId64
667 " internal errors have occurred during the check.\n",
668 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500669 }
670 }
671
672 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100673 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
674 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
675 check->allocated_clusters, check->total_clusters,
676 check->allocated_clusters * 100.0 / check->total_clusters,
677 check->fragmented_clusters * 100.0 / check->allocated_clusters,
678 check->compressed_clusters * 100.0 /
679 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500680 }
681
682 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100683 qprintf(quiet,
684 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500685 }
686}
687
688static int collect_image_check(BlockDriverState *bs,
689 ImageCheck *check,
690 const char *filename,
691 const char *fmt,
692 int fix)
693{
694 int ret;
695 BdrvCheckResult result;
696
697 ret = bdrv_check(bs, &result, fix);
698 if (ret < 0) {
699 return ret;
700 }
701
702 check->filename = g_strdup(filename);
703 check->format = g_strdup(bdrv_get_format_name(bs));
704 check->check_errors = result.check_errors;
705 check->corruptions = result.corruptions;
706 check->has_corruptions = result.corruptions != 0;
707 check->leaks = result.leaks;
708 check->has_leaks = result.leaks != 0;
709 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100710 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500711 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100712 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500713 check->image_end_offset = result.image_end_offset;
714 check->has_image_end_offset = result.image_end_offset != 0;
715 check->total_clusters = result.bfi.total_clusters;
716 check->has_total_clusters = result.bfi.total_clusters != 0;
717 check->allocated_clusters = result.bfi.allocated_clusters;
718 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
719 check->fragmented_clusters = result.bfi.fragmented_clusters;
720 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100721 check->compressed_clusters = result.bfi.compressed_clusters;
722 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500723
724 return 0;
725}
726
Kevin Wolfe076f332010-06-29 11:43:13 +0200727/*
728 * Checks an image for consistency. Exit codes:
729 *
Max Reitzd6635c42014-06-02 22:15:21 +0200730 * 0 - Check completed, image is good
731 * 1 - Check not completed because of internal errors
732 * 2 - Check completed, image is corrupted
733 * 3 - Check completed, image has leaked clusters, but is good otherwise
734 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200735 */
aliguori15859692009-04-21 23:11:53 +0000736static int img_check(int argc, char **argv)
737{
738 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500739 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200740 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200741 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000742 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200743 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100744 int flags = BDRV_O_CHECK;
745 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200746 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100747 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000748 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800749 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000750
751 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500752 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200753 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100754
aliguori15859692009-04-21 23:11:53 +0000755 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500756 int option_index = 0;
757 static const struct option long_options[] = {
758 {"help", no_argument, 0, 'h'},
759 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530760 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500761 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000762 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000763 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800764 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500765 {0, 0, 0, 0}
766 };
Fam Zheng335e9932017-05-03 00:35:39 +0800767 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500768 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100769 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000770 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100771 }
aliguori15859692009-04-21 23:11:53 +0000772 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800773 case ':':
774 missing_argument(argv[optind - 1]);
775 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100776 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800777 unrecognized_option(argv[optind - 1]);
778 break;
aliguori15859692009-04-21 23:11:53 +0000779 case 'h':
780 help();
781 break;
782 case 'f':
783 fmt = optarg;
784 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200785 case 'r':
786 flags |= BDRV_O_RDWR;
787
788 if (!strcmp(optarg, "leaks")) {
789 fix = BDRV_FIX_LEAKS;
790 } else if (!strcmp(optarg, "all")) {
791 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
792 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800793 error_exit("Unknown option value for -r "
794 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200795 }
796 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500797 case OPTION_OUTPUT:
798 output = optarg;
799 break;
Max Reitz40055952014-07-22 22:58:42 +0200800 case 'T':
801 cache = optarg;
802 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100803 case 'q':
804 quiet = true;
805 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800806 case 'U':
807 force_share = true;
808 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000809 case OPTION_OBJECT: {
810 QemuOpts *opts;
811 opts = qemu_opts_parse_noisily(&qemu_object_opts,
812 optarg, true);
813 if (!opts) {
814 return 1;
815 }
816 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000817 case OPTION_IMAGE_OPTS:
818 image_opts = true;
819 break;
aliguori15859692009-04-21 23:11:53 +0000820 }
821 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200822 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800823 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100824 }
aliguori15859692009-04-21 23:11:53 +0000825 filename = argv[optind++];
826
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500827 if (output && !strcmp(output, "json")) {
828 output_format = OFORMAT_JSON;
829 } else if (output && !strcmp(output, "human")) {
830 output_format = OFORMAT_HUMAN;
831 } else if (output) {
832 error_report("--output must be used with human or json as argument.");
833 return 1;
834 }
835
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000836 if (qemu_opts_foreach(&qemu_object_opts,
837 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200838 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000839 return 1;
840 }
841
Kevin Wolfce099542016-03-15 13:01:04 +0100842 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200843 if (ret < 0) {
844 error_report("Invalid source cache option: %s", cache);
845 return 1;
846 }
847
Fam Zheng335e9932017-05-03 00:35:39 +0800848 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
849 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200850 if (!blk) {
851 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900852 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200853 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500854
855 check = g_new0(ImageCheck, 1);
856 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200857
858 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200859 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200860 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500861 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200862 }
863
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500864 if (check->corruptions_fixed || check->leaks_fixed) {
865 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100866 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500867
868 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100869 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500870 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100871 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500872
873 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100874 qprintf(quiet,
875 "The following inconsistencies were found and repaired:\n\n"
876 " %" PRId64 " leaked clusters\n"
877 " %" PRId64 " corruptions\n\n"
878 "Double checking the fixed image now...\n",
879 check->leaks_fixed,
880 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500881 }
882
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800883 qapi_free_ImageCheck(check);
884 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500885 ret = collect_image_check(bs, check, filename, fmt, 0);
886
887 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100888 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500889 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100890 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200891 }
892
Max Reitz832390a2014-10-23 15:29:12 +0200893 if (!ret) {
894 switch (output_format) {
895 case OFORMAT_HUMAN:
896 dump_human_image_check(check, quiet);
897 break;
898 case OFORMAT_JSON:
899 dump_json_image_check(check, quiet);
900 break;
901 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500902 }
903
904 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200905 if (ret) {
906 error_report("Check failed: %s", strerror(-ret));
907 } else {
908 error_report("Check failed");
909 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500910 ret = 1;
911 goto fail;
912 }
913
914 if (check->corruptions) {
915 ret = 2;
916 } else if (check->leaks) {
917 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200918 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500919 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000920 }
921
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500922fail:
923 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200924 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500925 return ret;
aliguori15859692009-04-21 23:11:53 +0000926}
927
Max Reitzd4a32382014-10-24 15:57:37 +0200928typedef struct CommonBlockJobCBInfo {
929 BlockDriverState *bs;
930 Error **errp;
931} CommonBlockJobCBInfo;
932
933static void common_block_job_cb(void *opaque, int ret)
934{
935 CommonBlockJobCBInfo *cbi = opaque;
936
937 if (ret < 0) {
938 error_setg_errno(cbi->errp, -ret, "Block job failed");
939 }
Max Reitzd4a32382014-10-24 15:57:37 +0200940}
941
942static void run_block_job(BlockJob *job, Error **errp)
943{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200944 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800945 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200946
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200947 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200948 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200949 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200950 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200951 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300952 if (job->job.progress.total) {
953 progress = (float)job->job.progress.current /
954 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200955 }
956 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200957 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200958
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200959 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200960 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800961 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200962 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800963 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200964 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200965 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200966
sochin.jiang4172a002017-06-15 14:47:33 +0800967 /* publish completion progress only when success */
968 if (!ret) {
969 qemu_progress_print(100.f, 0);
970 }
Max Reitzd4a32382014-10-24 15:57:37 +0200971}
972
bellardea2384d2004-08-01 21:59:26 +0000973static int img_commit(int argc, char **argv)
974{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400975 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200976 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200977 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200978 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100979 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200980 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100981 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200982 Error *local_err = NULL;
983 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000984 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200985 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000986
987 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400988 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200989 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000990 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000991 static const struct option long_options[] = {
992 {"help", no_argument, 0, 'h'},
993 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000994 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000995 {0, 0, 0, 0}
996 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800997 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000998 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100999 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001000 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001001 }
bellardea2384d2004-08-01 21:59:26 +00001002 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001003 case ':':
1004 missing_argument(argv[optind - 1]);
1005 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001006 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001007 unrecognized_option(argv[optind - 1]);
1008 break;
bellardea2384d2004-08-01 21:59:26 +00001009 case 'h':
1010 help();
1011 break;
1012 case 'f':
1013 fmt = optarg;
1014 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001015 case 't':
1016 cache = optarg;
1017 break;
Max Reitz1b22bff2014-10-24 15:57:40 +02001018 case 'b':
1019 base = optarg;
1020 /* -b implies -d */
1021 drop = true;
1022 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001023 case 'd':
1024 drop = true;
1025 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001026 case 'p':
1027 progress = true;
1028 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001029 case 'q':
1030 quiet = true;
1031 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001032 case OPTION_OBJECT: {
1033 QemuOpts *opts;
1034 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1035 optarg, true);
1036 if (!opts) {
1037 return 1;
1038 }
1039 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001040 case OPTION_IMAGE_OPTS:
1041 image_opts = true;
1042 break;
bellardea2384d2004-08-01 21:59:26 +00001043 }
1044 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001045
1046 /* Progress is not shown in Quiet mode */
1047 if (quiet) {
1048 progress = false;
1049 }
1050
Kevin Wolffc11eb22013-08-05 10:53:04 +02001051 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001052 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001053 }
bellardea2384d2004-08-01 21:59:26 +00001054 filename = argv[optind++];
1055
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001056 if (qemu_opts_foreach(&qemu_object_opts,
1057 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001058 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001059 return 1;
1060 }
1061
Max Reitz9a86fe42014-10-24 15:57:38 +02001062 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001063 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001064 if (ret < 0) {
1065 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001066 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001067 }
1068
Fam Zheng335e9932017-05-03 00:35:39 +08001069 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1070 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001071 if (!blk) {
1072 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001073 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001074 bs = blk_bs(blk);
1075
Max Reitz687fa1d2014-10-24 15:57:39 +02001076 qemu_progress_init(progress, 1.f);
1077 qemu_progress_print(0.f, 100);
1078
Max Reitz1b22bff2014-10-24 15:57:40 +02001079 if (base) {
1080 base_bs = bdrv_find_backing_image(bs, base);
1081 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001082 error_setg(&local_err,
1083 "Did not find '%s' in the backing chain of '%s'",
1084 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001085 goto done;
1086 }
1087 } else {
1088 /* This is different from QMP, which by default uses the deepest file in
1089 * the backing chain (i.e., the very base); however, the traditional
1090 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001091 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001092 if (!base_bs) {
1093 error_setg(&local_err, "Image does not have a backing file");
1094 goto done;
1095 }
bellardea2384d2004-08-01 21:59:26 +00001096 }
1097
Max Reitzd4a32382014-10-24 15:57:37 +02001098 cbi = (CommonBlockJobCBInfo){
1099 .errp = &local_err,
1100 .bs = bs,
1101 };
1102
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001103 aio_context = bdrv_get_aio_context(bs);
1104 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001105 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001106 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001107 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001108 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001109 if (local_err) {
1110 goto done;
1111 }
1112
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001113 /* When the block job completes, the BlockBackend reference will point to
1114 * the old backing file. In order to avoid that the top image is already
1115 * deleted, so we can still empty it afterwards, increment the reference
1116 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001117 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001118 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001119 }
1120
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001121 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001122 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001123 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001124 if (local_err) {
1125 goto unref_backing;
1126 }
1127
Max Reitz2d97fde2020-04-29 16:11:26 +02001128 if (!drop) {
1129 BlockBackend *old_backing_blk;
1130
1131 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1132 &local_err);
1133 if (!old_backing_blk) {
1134 goto unref_backing;
1135 }
1136 ret = blk_make_empty(old_backing_blk, &local_err);
1137 blk_unref(old_backing_blk);
1138 if (ret == -ENOTSUP) {
1139 error_free(local_err);
1140 local_err = NULL;
1141 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001142 goto unref_backing;
1143 }
1144 }
1145
1146unref_backing:
1147 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001148 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001149 }
Max Reitzd4a32382014-10-24 15:57:37 +02001150
1151done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001152 qemu_progress_end();
1153
Markus Armbruster26f54e92014-10-07 13:59:04 +02001154 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001155
1156 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001157 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001158 return 1;
1159 }
Max Reitzd4a32382014-10-24 15:57:37 +02001160
1161 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001162 return 0;
1163}
1164
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001165/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001166 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1167 * of the first sector boundary within buf where the sector contains a
1168 * non-zero byte. This function is robust to a buffer that is not
1169 * sector-aligned.
1170 */
1171static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1172{
1173 int64_t i;
1174 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1175
1176 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1177 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1178 return i;
1179 }
1180 }
1181 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1182 return i;
1183 }
1184 return -1;
1185}
1186
1187/*
thsf58c7b32008-06-05 21:53:49 +00001188 * Returns true iff the first sector pointed to by 'buf' contains at least
1189 * a non-NUL byte.
1190 *
1191 * 'pnum' is set to the number of sectors (including and immediately following
1192 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001193 * The function will try to align the end offset to alignment boundaries so
1194 * that the request will at least end aligned and consequtive requests will
1195 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001196 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001197static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1198 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001199{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001200 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001201 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001202
1203 if (n <= 0) {
1204 *pnum = 0;
1205 return 0;
1206 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001207 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001208 for(i = 1; i < n; i++) {
1209 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001210 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001211 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001212 }
bellardea2384d2004-08-01 21:59:26 +00001213 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001214
1215 tail = (sector_num + i) & (alignment - 1);
1216 if (tail) {
1217 if (is_zero && i <= tail) {
1218 /* treat unallocated areas which only consist
1219 * of a small tail as allocated. */
1220 is_zero = false;
1221 }
1222 if (!is_zero) {
1223 /* align up end offset of allocated areas. */
1224 i += alignment - tail;
1225 i = MIN(i, n);
1226 } else {
1227 /* align down end offset of zero areas. */
1228 i -= tail;
1229 }
1230 }
bellardea2384d2004-08-01 21:59:26 +00001231 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001232 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001233}
1234
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001235/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001236 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1237 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1238 * breaking up write requests for only small sparse areas.
1239 */
1240static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001241 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001242{
1243 int ret;
1244 int num_checked, num_used;
1245
1246 if (n < min) {
1247 min = n;
1248 }
1249
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001250 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001251 if (!ret) {
1252 return ret;
1253 }
1254
1255 num_used = *pnum;
1256 buf += BDRV_SECTOR_SIZE * *pnum;
1257 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001258 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001259 num_checked = num_used;
1260
1261 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001262 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001263
1264 buf += BDRV_SECTOR_SIZE * *pnum;
1265 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001266 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001267 num_checked += *pnum;
1268 if (ret) {
1269 num_used = num_checked;
1270 } else if (*pnum >= min) {
1271 break;
1272 }
1273 }
1274
1275 *pnum = num_used;
1276 return 1;
1277}
1278
1279/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001280 * Compares two buffers sector by sector. Returns 0 if the first
1281 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001282 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001283 * pnum is set to the sector-aligned size of the buffer prefix that
1284 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001285 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001286static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1287 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001288{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001289 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001290 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001291
Eric Blakedc61cd32017-10-11 22:47:14 -05001292 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001293
Eric Blakedc61cd32017-10-11 22:47:14 -05001294 res = !!memcmp(buf1, buf2, i);
1295 while (i < bytes) {
1296 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001297
Eric Blakedc61cd32017-10-11 22:47:14 -05001298 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001299 break;
1300 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001301 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001302 }
1303
1304 *pnum = i;
1305 return res;
1306}
1307
Stefano Garzarella97ede572019-05-08 12:43:24 +02001308#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001309
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001310/*
1311 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1312 *
Eric Blake0608e402017-10-11 22:47:12 -05001313 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1314 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1315 * failure), and 4 on error (the exit status for read errors), after emitting
1316 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001317 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001318 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001319 * @param offset: Starting offset to check
1320 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001321 * @param filename: Name of disk file we are checking (logging purpose)
1322 * @param buffer: Allocated buffer for storing read data
1323 * @param quiet: Flag for quiet mode
1324 */
Eric Blakec41508e2017-10-11 22:47:13 -05001325static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1326 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001327 uint8_t *buffer, bool quiet)
1328{
Eric Blakedebb38a2017-10-11 22:47:11 -05001329 int ret = 0;
1330 int64_t idx;
1331
Eric Blakec41508e2017-10-11 22:47:13 -05001332 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 if (ret < 0) {
1334 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001335 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001336 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001337 }
Eric Blakec41508e2017-10-11 22:47:13 -05001338 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001339 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001340 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001341 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001342 return 1;
1343 }
1344
1345 return 0;
1346}
1347
1348/*
1349 * Compares two images. Exit codes:
1350 *
1351 * 0 - Images are identical
1352 * 1 - Images differ
1353 * >1 - Error occurred
1354 */
1355static int img_compare(int argc, char **argv)
1356{
Max Reitz40055952014-07-22 22:58:42 +02001357 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001358 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001360 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001361 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001362 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001363 int allocated1, allocated2;
1364 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1365 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001366 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001367 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001368 int64_t total_size;
1369 int64_t offset = 0;
1370 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001371 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001372 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001373 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001374 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001375
Max Reitz40055952014-07-22 22:58:42 +02001376 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001377 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001378 static const struct option long_options[] = {
1379 {"help", no_argument, 0, 'h'},
1380 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001381 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001382 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001383 {0, 0, 0, 0}
1384 };
Fam Zheng335e9932017-05-03 00:35:39 +08001385 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001386 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001387 if (c == -1) {
1388 break;
1389 }
1390 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001391 case ':':
1392 missing_argument(argv[optind - 1]);
1393 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001395 unrecognized_option(argv[optind - 1]);
1396 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001397 case 'h':
1398 help();
1399 break;
1400 case 'f':
1401 fmt1 = optarg;
1402 break;
1403 case 'F':
1404 fmt2 = optarg;
1405 break;
Max Reitz40055952014-07-22 22:58:42 +02001406 case 'T':
1407 cache = optarg;
1408 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001409 case 'p':
1410 progress = true;
1411 break;
1412 case 'q':
1413 quiet = true;
1414 break;
1415 case 's':
1416 strict = true;
1417 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001418 case 'U':
1419 force_share = true;
1420 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001421 case OPTION_OBJECT: {
1422 QemuOpts *opts;
1423 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1424 optarg, true);
1425 if (!opts) {
1426 ret = 2;
1427 goto out4;
1428 }
1429 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001430 case OPTION_IMAGE_OPTS:
1431 image_opts = true;
1432 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001433 }
1434 }
1435
1436 /* Progress is not shown in Quiet mode */
1437 if (quiet) {
1438 progress = false;
1439 }
1440
1441
Kevin Wolffc11eb22013-08-05 10:53:04 +02001442 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001443 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001444 }
1445 filename1 = argv[optind++];
1446 filename2 = argv[optind++];
1447
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001448 if (qemu_opts_foreach(&qemu_object_opts,
1449 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001450 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001451 ret = 2;
1452 goto out4;
1453 }
1454
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001455 /* Initialize before goto out */
1456 qemu_progress_init(progress, 2.0);
1457
Kevin Wolfce099542016-03-15 13:01:04 +01001458 flags = 0;
1459 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001460 if (ret < 0) {
1461 error_report("Invalid source cache option: %s", cache);
1462 ret = 2;
1463 goto out3;
1464 }
1465
Fam Zheng335e9932017-05-03 00:35:39 +08001466 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1467 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001468 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001469 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001470 goto out3;
1471 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001472
Fam Zheng335e9932017-05-03 00:35:39 +08001473 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1474 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001475 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001476 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001477 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001478 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001479 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001480 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001481
Max Reitzf1d3cd72015-02-05 13:58:18 -05001482 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1483 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001484 total_size1 = blk_getlength(blk1);
1485 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001486 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001488 ret = 4;
1489 goto out;
1490 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001491 total_size2 = blk_getlength(blk2);
1492 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001493 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001494 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001495 ret = 4;
1496 goto out;
1497 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001498 total_size = MIN(total_size1, total_size2);
1499 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500
1501 qemu_progress_print(0, 100);
1502
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001504 ret = 1;
1505 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1506 goto out;
1507 }
1508
Eric Blake033d9fc2017-10-11 22:47:16 -05001509 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001510 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001511
Eric Blake033d9fc2017-10-11 22:47:16 -05001512 status1 = bdrv_block_status_above(bs1, NULL, offset,
1513 total_size1 - offset, &pnum1, NULL,
1514 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001515 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001516 ret = 3;
1517 error_report("Sector allocation test failed for %s", filename1);
1518 goto out;
1519 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001520 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521
Eric Blake033d9fc2017-10-11 22:47:16 -05001522 status2 = bdrv_block_status_above(bs2, NULL, offset,
1523 total_size2 - offset, &pnum2, NULL,
1524 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001525 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001526 ret = 3;
1527 error_report("Sector allocation test failed for %s", filename2);
1528 goto out;
1529 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001530 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001531
1532 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001533 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001534
Fam Zheng25ad8e62016-01-13 16:37:41 +08001535 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001536 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001537 ret = 1;
1538 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001539 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001540 goto out;
1541 }
1542 }
1543 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001544 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001545 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001547 int64_t pnum;
1548
Eric Blake033d9fc2017-10-11 22:47:16 -05001549 chunk = MIN(chunk, IO_BUF_SIZE);
1550 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 if (ret < 0) {
1552 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001553 " of %s: %s",
1554 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001555 ret = 4;
1556 goto out;
1557 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001558 ret = blk_pread(blk2, offset, buf2, chunk);
1559 if (ret < 0) {
1560 error_report("Error while reading offset %" PRId64
1561 " of %s: %s",
1562 offset, filename2, strerror(-ret));
1563 ret = 4;
1564 goto out;
1565 }
1566 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1567 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001568 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001569 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001570 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001571 goto out;
1572 }
1573 }
1574 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001575 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001576 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001577 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001578 filename1, buf1, quiet);
1579 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001580 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001581 filename2, buf1, quiet);
1582 }
1583 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001584 goto out;
1585 }
1586 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001587 offset += chunk;
1588 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001589 }
1590
Eric Blake033d9fc2017-10-11 22:47:16 -05001591 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001592 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001593 const char *filename_over;
1594
1595 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001596 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001597 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001598 filename_over = filename1;
1599 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001600 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001601 filename_over = filename2;
1602 }
1603
Eric Blake033d9fc2017-10-11 22:47:16 -05001604 while (offset < progress_base) {
1605 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1606 progress_base - offset, &chunk,
1607 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001608 if (ret < 0) {
1609 ret = 3;
1610 error_report("Sector allocation test failed for %s",
1611 filename_over);
1612 goto out;
1613
1614 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001615 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001616 chunk = MIN(chunk, IO_BUF_SIZE);
1617 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001618 filename_over, buf1, quiet);
1619 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001620 goto out;
1621 }
1622 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001623 offset += chunk;
1624 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001625 }
1626 }
1627
1628 qprintf(quiet, "Images are identical.\n");
1629 ret = 0;
1630
1631out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001632 qemu_vfree(buf1);
1633 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001634 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001635out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001636 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001637out3:
1638 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001639out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001640 return ret;
1641}
1642
Eric Blake6c729dd2020-05-21 14:21:35 -05001643/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1644static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1645 const char *src_node, const char *src_name,
1646 Error **errp)
1647{
1648 BlockDirtyBitmapMergeSource *merge_src;
1649 BlockDirtyBitmapMergeSourceList *list;
1650
1651 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1652 merge_src->type = QTYPE_QDICT;
1653 merge_src->u.external.node = g_strdup(src_node);
1654 merge_src->u.external.name = g_strdup(src_name);
1655 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1656 list->value = merge_src;
1657 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1658 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1659}
1660
Kevin Wolf690c7302015-03-19 13:33:32 +01001661enum ImgConvertBlockStatus {
1662 BLK_DATA,
1663 BLK_ZERO,
1664 BLK_BACKING_FILE,
1665};
1666
Peter Lieven2d9187b2017-02-28 13:40:07 +01001667#define MAX_COROUTINES 16
1668
Kevin Wolf690c7302015-03-19 13:33:32 +01001669typedef struct ImgConvertState {
1670 BlockBackend **src;
1671 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001672 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001673 int64_t total_sectors;
1674 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001675 int64_t allocated_done;
1676 int64_t sector_num;
1677 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001678 enum ImgConvertBlockStatus status;
1679 int64_t sector_next_status;
1680 BlockBackend *target;
1681 bool has_zero_init;
1682 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001683 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001684 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001686 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001687 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001688 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001689 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001690 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001691 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001692 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001693 size_t cluster_sectors;
1694 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001695 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001696 int running_coroutines;
1697 Coroutine *co[MAX_COROUTINES];
1698 int64_t wait_sector_num[MAX_COROUTINES];
1699 CoMutex lock;
1700 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001701} ImgConvertState;
1702
Peter Lieven2d9187b2017-02-28 13:40:07 +01001703static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1704 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001705{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001706 *src_cur = 0;
1707 *src_cur_offset = 0;
1708 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1709 *src_cur_offset += s->src_sectors[*src_cur];
1710 (*src_cur)++;
1711 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001712 }
1713}
1714
1715static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1716{
Eric Blake31826642017-10-11 22:47:08 -05001717 int64_t src_cur_offset;
1718 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001719 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001720
Peter Lieven2d9187b2017-02-28 13:40:07 +01001721 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001722
1723 assert(s->total_sectors > sector_num);
1724 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1725
Max Reitz351c8ef2018-05-01 18:57:49 +02001726 if (s->target_backing_sectors >= 0) {
1727 if (sector_num >= s->target_backing_sectors) {
1728 post_backing_zero = s->unallocated_blocks_are_zero;
1729 } else if (sector_num + n > s->target_backing_sectors) {
1730 /* Split requests around target_backing_sectors (because
1731 * starting from there, zeros are handled differently) */
1732 n = s->target_backing_sectors - sector_num;
1733 }
1734 }
1735
Kevin Wolf690c7302015-03-19 13:33:32 +01001736 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001737 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1738 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001739
Max Reitz8eaac022019-05-07 22:35:03 +02001740 do {
1741 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001742
Max Reitz8eaac022019-05-07 22:35:03 +02001743 if (s->target_has_backing) {
1744 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1745 count, &count, NULL, NULL);
1746 } else {
1747 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1748 offset, count, &count, NULL,
1749 NULL);
1750 }
1751
1752 if (ret < 0) {
1753 if (s->salvage) {
1754 if (n == 1) {
1755 if (!s->quiet) {
1756 warn_report("error while reading block status at "
1757 "offset %" PRIu64 ": %s", offset,
1758 strerror(-ret));
1759 }
1760 /* Just try to read the data, then */
1761 ret = BDRV_BLOCK_DATA;
1762 count = BDRV_SECTOR_SIZE;
1763 } else {
1764 /* Retry on a shorter range */
1765 n = DIV_ROUND_UP(n, 4);
1766 }
1767 } else {
1768 error_report("error while reading block status at offset "
1769 "%" PRIu64 ": %s", offset, strerror(-ret));
1770 return ret;
1771 }
1772 }
1773 } while (ret < 0);
1774
Eric Blake31826642017-10-11 22:47:08 -05001775 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001776
1777 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001778 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001779 } else if (ret & BDRV_BLOCK_DATA) {
1780 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001781 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001782 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001783 }
1784
1785 s->sector_next_status = sector_num + n;
1786 }
1787
1788 n = MIN(n, s->sector_next_status - sector_num);
1789 if (s->status == BLK_DATA) {
1790 n = MIN(n, s->buf_sectors);
1791 }
1792
1793 /* We need to write complete clusters for compressed images, so if an
1794 * unallocated area is shorter than that, we must consider the whole
1795 * cluster allocated. */
1796 if (s->compressed) {
1797 if (n < s->cluster_sectors) {
1798 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1799 s->status = BLK_DATA;
1800 } else {
1801 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1802 }
1803 }
1804
1805 return n;
1806}
1807
Peter Lieven2d9187b2017-02-28 13:40:07 +01001808static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1809 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001810{
Max Reitz8eaac022019-05-07 22:35:03 +02001811 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001812 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001813
Kevin Wolf690c7302015-03-19 13:33:32 +01001814 assert(nb_sectors <= s->buf_sectors);
1815 while (nb_sectors > 0) {
1816 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001817 int src_cur;
1818 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001819 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001820
1821 /* In the case of compression with multiple source files, we can get a
1822 * nb_sectors that spreads into the next part. So we must be able to
1823 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001824 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1825 blk = s->src[src_cur];
1826 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001827
Max Reitz8eaac022019-05-07 22:35:03 +02001828 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001829
Max Reitz8eaac022019-05-07 22:35:03 +02001830 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1831 if (single_read_until > offset) {
1832 n = 1;
1833 }
1834
1835 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001836 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001837 if (s->salvage) {
1838 if (n > 1) {
1839 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1840 continue;
1841 } else {
1842 if (!s->quiet) {
1843 warn_report("error while reading offset %" PRIu64
1844 ": %s", offset, strerror(-ret));
1845 }
1846 memset(buf, 0, BDRV_SECTOR_SIZE);
1847 }
1848 } else {
1849 return ret;
1850 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001851 }
1852
1853 sector_num += n;
1854 nb_sectors -= n;
1855 buf += n * BDRV_SECTOR_SIZE;
1856 }
1857
1858 return 0;
1859}
1860
Peter Lieven2d9187b2017-02-28 13:40:07 +01001861
1862static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1863 int nb_sectors, uint8_t *buf,
1864 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001865{
1866 int ret;
1867
1868 while (nb_sectors > 0) {
1869 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001870 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1871
Peter Lieven2d9187b2017-02-28 13:40:07 +01001872 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001873 case BLK_BACKING_FILE:
1874 /* If we have a backing file, leave clusters unallocated that are
1875 * unallocated in the source image, so that the backing file is
1876 * visible at the respective offset. */
1877 assert(s->target_has_backing);
1878 break;
1879
1880 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001881 /* If we're told to keep the target fully allocated (-S 0) or there
1882 * is real non-zero data, we must write it. Otherwise we can treat
1883 * it as zero sectors.
1884 * Compressed clusters need to be written as a whole, so in that
1885 * case we can only save the write if the buffer is completely
1886 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001887 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001888 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001889 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1890 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001891 (s->compressed &&
1892 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001893 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001894 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1895 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001896 if (ret < 0) {
1897 return ret;
1898 }
1899 break;
1900 }
1901 /* fall-through */
1902
1903 case BLK_ZERO:
1904 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001905 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001906 break;
1907 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001908 ret = blk_co_pwrite_zeroes(s->target,
1909 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001910 n << BDRV_SECTOR_BITS,
1911 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001912 if (ret < 0) {
1913 return ret;
1914 }
1915 break;
1916 }
1917
1918 sector_num += n;
1919 nb_sectors -= n;
1920 buf += n * BDRV_SECTOR_SIZE;
1921 }
1922
1923 return 0;
1924}
1925
Fam Zhengee5306d2018-06-01 17:26:48 +08001926static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1927 int nb_sectors)
1928{
1929 int n, ret;
1930
1931 while (nb_sectors > 0) {
1932 BlockBackend *blk;
1933 int src_cur;
1934 int64_t bs_sectors, src_cur_offset;
1935 int64_t offset;
1936
1937 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1938 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1939 blk = s->src[src_cur];
1940 bs_sectors = s->src_sectors[src_cur];
1941
1942 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1943
1944 ret = blk_co_copy_range(blk, offset, s->target,
1945 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001946 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001947 if (ret < 0) {
1948 return ret;
1949 }
1950
1951 sector_num += n;
1952 nb_sectors -= n;
1953 }
1954 return 0;
1955}
1956
Peter Lieven2d9187b2017-02-28 13:40:07 +01001957static void coroutine_fn convert_co_do_copy(void *opaque)
1958{
1959 ImgConvertState *s = opaque;
1960 uint8_t *buf = NULL;
1961 int ret, i;
1962 int index = -1;
1963
1964 for (i = 0; i < s->num_coroutines; i++) {
1965 if (s->co[i] == qemu_coroutine_self()) {
1966 index = i;
1967 break;
1968 }
1969 }
1970 assert(index >= 0);
1971
1972 s->running_coroutines++;
1973 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1974
1975 while (1) {
1976 int n;
1977 int64_t sector_num;
1978 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001979 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001980
1981 qemu_co_mutex_lock(&s->lock);
1982 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1983 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001984 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001985 }
1986 n = convert_iteration_sectors(s, s->sector_num);
1987 if (n < 0) {
1988 qemu_co_mutex_unlock(&s->lock);
1989 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001990 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001991 }
1992 /* save current sector and allocation status to local variables */
1993 sector_num = s->sector_num;
1994 status = s->status;
1995 if (!s->min_sparse && s->status == BLK_ZERO) {
1996 n = MIN(n, s->buf_sectors);
1997 }
1998 /* increment global sector counter so that other coroutines can
1999 * already continue reading beyond this request */
2000 s->sector_num += n;
2001 qemu_co_mutex_unlock(&s->lock);
2002
2003 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2004 s->allocated_done += n;
2005 qemu_progress_print(100.0 * s->allocated_done /
2006 s->allocated_sectors, 0);
2007 }
2008
Fam Zhengee5306d2018-06-01 17:26:48 +08002009retry:
2010 copy_range = s->copy_range && s->status == BLK_DATA;
2011 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002012 ret = convert_co_read(s, sector_num, n, buf);
2013 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002014 error_report("error while reading at byte %lld: %s",
2015 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002016 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002017 }
2018 } else if (!s->min_sparse && status == BLK_ZERO) {
2019 status = BLK_DATA;
2020 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2021 }
2022
2023 if (s->wr_in_order) {
2024 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002025 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002026 s->wait_sector_num[index] = sector_num;
2027 qemu_coroutine_yield();
2028 }
2029 s->wait_sector_num[index] = -1;
2030 }
2031
Anton Nefedovb91127e2017-04-26 11:33:15 +03002032 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002033 if (copy_range) {
2034 ret = convert_co_copy_range(s, sector_num, n);
2035 if (ret) {
2036 s->copy_range = false;
2037 goto retry;
2038 }
2039 } else {
2040 ret = convert_co_write(s, sector_num, n, buf, status);
2041 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002042 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002043 error_report("error while writing at byte %lld: %s",
2044 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002045 s->ret = ret;
2046 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002047 }
2048
2049 if (s->wr_in_order) {
2050 /* reenter the coroutine that might have waited
2051 * for this write to complete */
2052 s->wr_offs = sector_num + n;
2053 for (i = 0; i < s->num_coroutines; i++) {
2054 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2055 /*
2056 * A -> B -> A cannot occur because A has
2057 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2058 * B will never enter A during this time window.
2059 */
2060 qemu_coroutine_enter(s->co[i]);
2061 break;
2062 }
2063 }
2064 }
2065 }
2066
Peter Lieven2d9187b2017-02-28 13:40:07 +01002067 qemu_vfree(buf);
2068 s->co[index] = NULL;
2069 s->running_coroutines--;
2070 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2071 /* the convert job finished successfully */
2072 s->ret = 0;
2073 }
2074}
2075
Kevin Wolf690c7302015-03-19 13:33:32 +01002076static int convert_do_copy(ImgConvertState *s)
2077{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002078 int ret, i, n;
2079 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002080
2081 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002082 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2083 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002084 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002085 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002086
2087 if (!s->has_zero_init && !s->target_has_backing &&
2088 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
2089 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01002090 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01002091 if (ret == 0) {
2092 s->has_zero_init = true;
2093 }
2094 }
2095
2096 /* Allocate buffer for copied data. For compressed images, only one cluster
2097 * can be copied at a time. */
2098 if (s->compressed) {
2099 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2100 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002101 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002102 }
2103 s->buf_sectors = s->cluster_sectors;
2104 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002105
Kevin Wolf690c7302015-03-19 13:33:32 +01002106 while (sector_num < s->total_sectors) {
2107 n = convert_iteration_sectors(s, sector_num);
2108 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002109 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002110 }
Max Reitzaad15de2016-03-24 23:33:57 +01002111 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2112 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002113 s->allocated_sectors += n;
2114 }
2115 sector_num += n;
2116 }
2117
2118 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002119 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002120 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002121
Peter Lieven2d9187b2017-02-28 13:40:07 +01002122 qemu_co_mutex_init(&s->lock);
2123 for (i = 0; i < s->num_coroutines; i++) {
2124 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2125 s->wait_sector_num[i] = -1;
2126 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002127 }
2128
Anton Nefedovb91127e2017-04-26 11:33:15 +03002129 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002130 main_loop_wait(false);
2131 }
2132
2133 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002134 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002135 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002136 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002137 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002138 }
2139 }
2140
Peter Lieven2d9187b2017-02-28 13:40:07 +01002141 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002142}
2143
Eric Blake15e39ad2020-05-21 14:21:36 -05002144static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2145{
2146 BdrvDirtyBitmap *bm;
2147 Error *err = NULL;
2148
2149 FOR_EACH_DIRTY_BITMAP(src, bm) {
2150 const char *name;
2151
2152 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2153 continue;
2154 }
2155 name = bdrv_dirty_bitmap_name(bm);
2156 qmp_block_dirty_bitmap_add(dst->node_name, name,
2157 true, bdrv_dirty_bitmap_granularity(bm),
2158 true, true,
2159 true, !bdrv_dirty_bitmap_enabled(bm),
2160 &err);
2161 if (err) {
2162 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2163 return -1;
2164 }
2165
2166 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2167 &err);
2168 if (err) {
2169 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2170 return -1;
2171 }
2172 }
2173
2174 return 0;
2175}
2176
Peter Lieven6360ab22018-07-13 09:15:39 +02002177#define MAX_BUF_SECTORS 32768
2178
bellardea2384d2004-08-01 21:59:26 +00002179static int img_convert(int argc, char **argv)
2180{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002181 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002182 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002183 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2184 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002185 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002186 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002187 BlockDriverState *out_bs;
2188 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002189 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002190 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002191 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002192 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002193 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002194 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002195 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002196 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002197 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002198 bool bitmaps = false;
bellardea2384d2004-08-01 21:59:26 +00002199
Peter Lieven9fd77f92017-04-21 11:11:55 +02002200 ImgConvertState s = (ImgConvertState) {
2201 /* Need at least 4k of zeros for sparse detection */
2202 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002203 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002204 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2205 .wr_in_order = true,
2206 .num_coroutines = 8,
2207 };
2208
bellardea2384d2004-08-01 21:59:26 +00002209 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002210 static const struct option long_options[] = {
2211 {"help", no_argument, 0, 'h'},
2212 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002213 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002214 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002215 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002216 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002217 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002218 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002219 {0, 0, 0, 0}
2220 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002221 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002222 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002223 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002224 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002225 }
bellardea2384d2004-08-01 21:59:26 +00002226 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002227 case ':':
2228 missing_argument(argv[optind - 1]);
2229 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002230 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002231 unrecognized_option(argv[optind - 1]);
2232 break;
bellardea2384d2004-08-01 21:59:26 +00002233 case 'h':
2234 help();
2235 break;
2236 case 'f':
2237 fmt = optarg;
2238 break;
2239 case 'O':
2240 out_fmt = optarg;
2241 break;
thsf58c7b32008-06-05 21:53:49 +00002242 case 'B':
2243 out_baseimg = optarg;
2244 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002245 case 'C':
2246 s.copy_range = true;
2247 break;
bellardea2384d2004-08-01 21:59:26 +00002248 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002249 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002250 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002251 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002252 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002253 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002254 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002255 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002256 case 'l':
2257 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002258 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2259 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002260 if (!sn_opts) {
2261 error_report("Failed in parsing snapshot param '%s'",
2262 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002263 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002264 }
2265 } else {
2266 snapshot_name = optarg;
2267 }
2268 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002269 case 'S':
2270 {
2271 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002272
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002273 sval = cvtnum("buffer size for sparse output", optarg);
2274 if (sval < 0) {
2275 goto fail_getopt;
2276 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002277 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2278 error_report("Invalid buffer size for sparse output specified. "
2279 "Valid sizes are multiples of %llu up to %llu. Select "
2280 "0 to disable sparse detection (fully allocates output).",
2281 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002282 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002283 }
2284
Peter Lieven9fd77f92017-04-21 11:11:55 +02002285 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002286 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002287 break;
2288 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002289 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002290 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002291 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002292 case 't':
2293 cache = optarg;
2294 break;
Max Reitz40055952014-07-22 22:58:42 +02002295 case 'T':
2296 src_cache = optarg;
2297 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002298 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002299 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002300 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002301 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002302 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002303 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002304 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002305 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2306 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002307 error_report("Invalid number of coroutines. Allowed number of"
2308 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002309 goto fail_getopt;
2310 }
2311 break;
2312 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002313 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002314 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002315 case 'U':
2316 force_share = true;
2317 break;
Max Reitz3258b912017-04-26 15:46:47 +02002318 case OPTION_OBJECT: {
2319 QemuOpts *object_opts;
2320 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2321 optarg, true);
2322 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002323 goto fail_getopt;
2324 }
2325 break;
Max Reitz3258b912017-04-26 15:46:47 +02002326 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002327 case OPTION_IMAGE_OPTS:
2328 image_opts = true;
2329 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002330 case OPTION_SALVAGE:
2331 s.salvage = true;
2332 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002333 case OPTION_TARGET_IMAGE_OPTS:
2334 tgt_image_opts = true;
2335 break;
David Edmondson168468f2020-02-05 11:02:48 +00002336 case OPTION_TARGET_IS_ZERO:
2337 /*
2338 * The user asserting that the target is blank has the
2339 * same effect as the target driver supporting zero
2340 * initialisation.
2341 */
2342 s.has_zero_init = true;
2343 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002344 case OPTION_BITMAPS:
2345 bitmaps = true;
2346 break;
bellardea2384d2004-08-01 21:59:26 +00002347 }
2348 }
ths3b46e622007-09-17 08:09:54 +00002349
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002350 if (!out_fmt && !tgt_image_opts) {
2351 out_fmt = "raw";
2352 }
2353
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002354 if (qemu_opts_foreach(&qemu_object_opts,
2355 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002356 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002357 goto fail_getopt;
2358 }
2359
Fam Zhenge11ce122018-07-27 11:34:01 +08002360 if (s.compressed && s.copy_range) {
2361 error_report("Cannot enable copy offloading when -c is used");
2362 goto fail_getopt;
2363 }
2364
2365 if (explict_min_sparse && s.copy_range) {
2366 error_report("Cannot enable copy offloading when -S is used");
2367 goto fail_getopt;
2368 }
2369
Max Reitz8eaac022019-05-07 22:35:03 +02002370 if (s.copy_range && s.salvage) {
2371 error_report("Cannot use copy offloading in salvaging mode");
2372 goto fail_getopt;
2373 }
2374
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002375 if (tgt_image_opts && !skip_create) {
2376 error_report("--target-image-opts requires use of -n flag");
2377 goto fail_getopt;
2378 }
2379
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002380 if (skip_create && options) {
2381 warn_report("-o has no effect when skipping image creation");
2382 warn_report("This will become an error in future QEMU versions.");
2383 }
2384
David Edmondson168468f2020-02-05 11:02:48 +00002385 if (s.has_zero_init && !skip_create) {
2386 error_report("--target-is-zero requires use of -n flag");
2387 goto fail_getopt;
2388 }
2389
Peter Lieven9fd77f92017-04-21 11:11:55 +02002390 s.src_num = argc - optind - 1;
2391 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2392
2393 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002394 if (out_fmt) {
2395 ret = print_block_option_help(out_filename, out_fmt);
2396 goto fail_getopt;
2397 } else {
2398 error_report("Option help requires a format be specified");
2399 goto fail_getopt;
2400 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002401 }
2402
2403 if (s.src_num < 1) {
2404 error_report("Must specify image file name");
2405 goto fail_getopt;
2406 }
2407
Peter Lieven9fd77f92017-04-21 11:11:55 +02002408 /* ret is still -EINVAL until here */
2409 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2410 if (ret < 0) {
2411 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002412 goto fail_getopt;
2413 }
2414
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002415 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002416 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002417 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002418 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002419 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002420 qemu_progress_print(0, 100);
2421
Peter Lieven9fd77f92017-04-21 11:11:55 +02002422 s.src = g_new0(BlockBackend *, s.src_num);
2423 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002424
Peter Lieven9fd77f92017-04-21 11:11:55 +02002425 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2426 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002427 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002428 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002429 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002430 ret = -1;
2431 goto out;
2432 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002433 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2434 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002435 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002436 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002437 ret = -1;
2438 goto out;
2439 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002440 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002441 }
bellardea2384d2004-08-01 21:59:26 +00002442
Wenchao Xiaef806542013-12-04 17:10:57 +08002443 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002444 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002445 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2446 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2447 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002448 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002449 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002450 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002451 ret = -1;
2452 goto out;
2453 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002454
Peter Lieven9fd77f92017-04-21 11:11:55 +02002455 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2456 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002457 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002458 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002459 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002460 ret = -1;
2461 goto out;
edison51ef6722010-09-21 19:58:41 -07002462 }
2463
Max Reitz2e024cd2015-02-11 09:58:46 -05002464 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002465 /* Find driver and parse its options */
2466 drv = bdrv_find_format(out_fmt);
2467 if (!drv) {
2468 error_report("Unknown file format '%s'", out_fmt);
2469 ret = -1;
2470 goto out;
2471 }
2472
2473 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2474 if (!proto_drv) {
2475 error_report_err(local_err);
2476 ret = -1;
2477 goto out;
2478 }
2479
Max Reitz2e024cd2015-02-11 09:58:46 -05002480 if (!drv->create_opts) {
2481 error_report("Format driver '%s' does not support image creation",
2482 drv->format_name);
2483 ret = -1;
2484 goto out;
2485 }
Max Reitzf75613c2014-12-02 18:32:46 +01002486
Max Reitz2e024cd2015-02-11 09:58:46 -05002487 if (!proto_drv->create_opts) {
2488 error_report("Protocol driver '%s' does not support image creation",
2489 proto_drv->format_name);
2490 ret = -1;
2491 goto out;
2492 }
Max Reitzf75613c2014-12-02 18:32:46 +01002493
Max Reitz2e024cd2015-02-11 09:58:46 -05002494 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2495 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002496
Max Reitz2e024cd2015-02-11 09:58:46 -05002497 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002498 if (options) {
2499 qemu_opts_do_parse(opts, options, NULL, &local_err);
2500 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002501 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002502 ret = -1;
2503 goto out;
2504 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002505 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002506
Peter Lieven9fd77f92017-04-21 11:11:55 +02002507 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002508 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002509 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2510 if (ret < 0) {
2511 goto out;
2512 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002513 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002514
Kevin Wolfa18953f2010-10-14 15:46:04 +02002515 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002516 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002517 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002518 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002519 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002520 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002521
David Edmondson168468f2020-02-05 11:02:48 +00002522 if (s.has_zero_init && s.target_has_backing) {
2523 error_report("Cannot use --target-is-zero when the destination "
2524 "image has a backing file");
2525 goto out;
2526 }
2527
Max Reitz48758a82017-04-26 15:46:48 +02002528 if (s.src_num > 1 && out_baseimg) {
2529 error_report("Having a backing file for the target makes no sense when "
2530 "concatenating multiple input images");
2531 ret = -1;
2532 goto out;
2533 }
2534
Kevin Wolfefa84d42009-05-18 16:42:12 +02002535 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002536 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002537 bool encryption =
2538 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002539 const char *encryptfmt =
2540 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002541 const char *preallocation =
2542 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002543
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002544 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002545 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002546 ret = -1;
2547 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002548 }
2549
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002550 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002551 error_report("Compression and encryption not supported at "
2552 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002553 ret = -1;
2554 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002555 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002556
Chunyan Liu83d05212014-06-05 17:20:51 +08002557 if (preallocation
2558 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002559 {
2560 error_report("Compression and preallocation not supported at "
2561 "the same time");
2562 ret = -1;
2563 goto out;
2564 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002565 }
2566
Eric Blake15e39ad2020-05-21 14:21:36 -05002567 /* Determine if bitmaps need copying */
2568 if (bitmaps) {
2569 if (s.src_num > 1) {
2570 error_report("Copying bitmaps only possible with single source");
2571 ret = -1;
2572 goto out;
2573 }
2574 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2575 error_report("Source lacks bitmap support");
2576 ret = -1;
2577 goto out;
2578 }
2579 }
2580
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002581 /*
2582 * The later open call will need any decryption secrets, and
2583 * bdrv_create() will purge "opts", so extract them now before
2584 * they are lost.
2585 */
2586 if (!skip_create) {
2587 open_opts = qdict_new();
2588 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002589
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002590 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002591 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002592 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002593 error_reportf_err(local_err, "%s: error while converting %s: ",
2594 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002595 goto out;
bellardea2384d2004-08-01 21:59:26 +00002596 }
2597 }
ths3b46e622007-09-17 08:09:54 +00002598
Max Reitz4d7c4872019-07-24 19:12:29 +02002599 s.target_is_new = !skip_create;
2600
Peter Lieven9fd77f92017-04-21 11:11:55 +02002601 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002602 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002603 if (ret < 0) {
2604 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002605 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002606 }
2607
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002608 if (skip_create) {
2609 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002610 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002611 } else {
2612 /* TODO ultimately we should allow --target-image-opts
2613 * to be used even when -n is not given.
2614 * That has to wait for bdrv_create to be improved
2615 * to allow filenames in option syntax
2616 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002617 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002618 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002619 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002620 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002621 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002622 ret = -1;
2623 goto out;
2624 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002625 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002626
Eric Blake15e39ad2020-05-21 14:21:36 -05002627 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2628 error_report("Format driver '%s' does not support bitmaps",
2629 out_bs->drv->format_name);
2630 ret = -1;
2631 goto out;
2632 }
2633
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002634 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002635 error_report("Compression not supported for this file format");
2636 ret = -1;
2637 goto out;
2638 }
2639
Eric Blake5def6b82016-06-23 16:37:19 -06002640 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002641 * or discard_alignment of the out_bs is greater. Limit to
2642 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2643 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002644 MAX(s.buf_sectors,
2645 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2646 out_bs->bl.pdiscard_alignment >>
2647 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002648
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002649 /* try to align the write requests to the destination to avoid unnecessary
2650 * RMW cycles. */
2651 s.alignment = MAX(pow2floor(s.min_sparse),
2652 DIV_ROUND_UP(out_bs->bl.request_alignment,
2653 BDRV_SECTOR_SIZE));
2654 assert(is_power_of_2(s.alignment));
2655
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002656 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002657 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002658 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002659 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002660 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002661 ret = -1;
2662 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002663 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002664 error_report("output file is smaller than input file");
2665 ret = -1;
2666 goto out;
2667 }
2668 }
2669
Max Reitzc69291e2020-01-21 16:59:14 +01002670 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002671 /* Errors are treated as "backing length unknown" (which means
2672 * s.target_backing_sectors has to be negative, which it will
2673 * be automatically). The backing file length is used only
2674 * for optimizations, so such a case is not fatal. */
2675 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2676 } else {
2677 s.target_backing_sectors = -1;
2678 }
2679
Peter Lieven24f833c2013-11-27 11:07:07 +01002680 ret = bdrv_get_info(out_bs, &bdi);
2681 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002682 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002683 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002684 goto out;
2685 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002686 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002687 s.compressed = s.compressed || bdi.needs_compressed_writes;
2688 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002689 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002690 }
2691
Peter Lieven9fd77f92017-04-21 11:11:55 +02002692 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002693
2694 /* Now copy the bitmaps */
2695 if (bitmaps && ret == 0) {
2696 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2697 }
2698
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002699out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002700 if (!ret) {
2701 qemu_progress_print(100, 0);
2702 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002703 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002704 qemu_opts_del(opts);
2705 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002706 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002707 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002708 blk_unref(s.target);
2709 if (s.src) {
2710 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2711 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002712 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002713 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002714 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002715 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002716fail_getopt:
2717 g_free(options);
2718
Peter Lieven9fd77f92017-04-21 11:11:55 +02002719 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002720}
2721
bellard57d1a2b2004-08-03 21:15:11 +00002722
bellardfaea38e2006-08-05 21:31:00 +00002723static void dump_snapshots(BlockDriverState *bs)
2724{
2725 QEMUSnapshotInfo *sn_tab, *sn;
2726 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002727
2728 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2729 if (nb_sns <= 0)
2730 return;
2731 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002732 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002733 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002734 for(i = 0; i < nb_sns; i++) {
2735 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002736 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002737 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002738 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002739 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002740}
2741
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002742static void dump_json_image_info_list(ImageInfoList *list)
2743{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002744 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002745 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002746 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002747
2748 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2749 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002750 str = qobject_to_json_pretty(obj);
2751 assert(str != NULL);
2752 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002753 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002754 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002755 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002756}
2757
Benoît Canetc054b3f2012-09-05 13:09:02 +02002758static void dump_json_image_info(ImageInfo *info)
2759{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002760 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002761 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002762 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002763
2764 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2765 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002766 str = qobject_to_json_pretty(obj);
2767 assert(str != NULL);
2768 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002769 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002770 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002771 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002772}
2773
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002774static void dump_human_image_info_list(ImageInfoList *list)
2775{
2776 ImageInfoList *elem;
2777 bool delim = false;
2778
2779 for (elem = list; elem; elem = elem->next) {
2780 if (delim) {
2781 printf("\n");
2782 }
2783 delim = true;
2784
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002785 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002786 }
2787}
2788
2789static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2790{
2791 return strcmp(a, b) == 0;
2792}
2793
2794/**
2795 * Open an image file chain and return an ImageInfoList
2796 *
2797 * @filename: topmost image filename
2798 * @fmt: topmost image format (may be NULL to autodetect)
2799 * @chain: true - enumerate entire backing file chain
2800 * false - only topmost image file
2801 *
2802 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2803 * image file. If there was an error a message will have been printed to
2804 * stderr.
2805 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002806static ImageInfoList *collect_image_info_list(bool image_opts,
2807 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002808 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002809 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002810{
2811 ImageInfoList *head = NULL;
2812 ImageInfoList **last = &head;
2813 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002814 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002815
2816 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2817
2818 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002819 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002820 BlockDriverState *bs;
2821 ImageInfo *info;
2822 ImageInfoList *elem;
2823
2824 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2825 error_report("Backing file '%s' creates an infinite loop.",
2826 filename);
2827 goto err;
2828 }
2829 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2830
Max Reitzefaa7c42016-03-16 19:54:38 +01002831 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002832 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2833 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002834 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002835 goto err;
2836 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002837 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002838
Wenchao Xia43526ec2013-06-06 12:27:58 +08002839 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002840 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002841 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002842 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002843 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002844 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002845
2846 elem = g_new0(ImageInfoList, 1);
2847 elem->value = info;
2848 *last = elem;
2849 last = &elem->next;
2850
Markus Armbruster26f54e92014-10-07 13:59:04 +02002851 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002852
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002853 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002854 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002855 image_opts = false;
2856
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002857 if (chain) {
2858 if (info->has_full_backing_filename) {
2859 filename = info->full_backing_filename;
2860 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002861 error_report("Could not determine absolute backing filename,"
2862 " but backing filename '%s' present",
2863 info->backing_filename);
2864 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002865 }
2866 if (info->has_backing_filename_format) {
2867 fmt = info->backing_filename_format;
2868 }
2869 }
2870 }
2871 g_hash_table_destroy(filenames);
2872 return head;
2873
2874err:
2875 qapi_free_ImageInfoList(head);
2876 g_hash_table_destroy(filenames);
2877 return NULL;
2878}
2879
Benoît Canetc054b3f2012-09-05 13:09:02 +02002880static int img_info(int argc, char **argv)
2881{
2882 int c;
2883 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002884 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002885 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002886 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002887 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002888 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002889
bellardea2384d2004-08-01 21:59:26 +00002890 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002891 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002892 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002893 int option_index = 0;
2894 static const struct option long_options[] = {
2895 {"help", no_argument, 0, 'h'},
2896 {"format", required_argument, 0, 'f'},
2897 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002898 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002899 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002900 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002901 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002902 {0, 0, 0, 0}
2903 };
Fam Zheng335e9932017-05-03 00:35:39 +08002904 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002905 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002906 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002907 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002908 }
bellardea2384d2004-08-01 21:59:26 +00002909 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002910 case ':':
2911 missing_argument(argv[optind - 1]);
2912 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002913 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002914 unrecognized_option(argv[optind - 1]);
2915 break;
bellardea2384d2004-08-01 21:59:26 +00002916 case 'h':
2917 help();
2918 break;
2919 case 'f':
2920 fmt = optarg;
2921 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002922 case 'U':
2923 force_share = true;
2924 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002925 case OPTION_OUTPUT:
2926 output = optarg;
2927 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002928 case OPTION_BACKING_CHAIN:
2929 chain = true;
2930 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002931 case OPTION_OBJECT: {
2932 QemuOpts *opts;
2933 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2934 optarg, true);
2935 if (!opts) {
2936 return 1;
2937 }
2938 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002939 case OPTION_IMAGE_OPTS:
2940 image_opts = true;
2941 break;
bellardea2384d2004-08-01 21:59:26 +00002942 }
2943 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002944 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002945 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002946 }
bellardea2384d2004-08-01 21:59:26 +00002947 filename = argv[optind++];
2948
Benoît Canetc054b3f2012-09-05 13:09:02 +02002949 if (output && !strcmp(output, "json")) {
2950 output_format = OFORMAT_JSON;
2951 } else if (output && !strcmp(output, "human")) {
2952 output_format = OFORMAT_HUMAN;
2953 } else if (output) {
2954 error_report("--output must be used with human or json as argument.");
2955 return 1;
2956 }
2957
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002958 if (qemu_opts_foreach(&qemu_object_opts,
2959 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002960 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002961 return 1;
2962 }
2963
Fam Zheng335e9932017-05-03 00:35:39 +08002964 list = collect_image_info_list(image_opts, filename, fmt, chain,
2965 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002966 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002967 return 1;
2968 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002969
Benoît Canetc054b3f2012-09-05 13:09:02 +02002970 switch (output_format) {
2971 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002972 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002973 break;
2974 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002975 if (chain) {
2976 dump_json_image_info_list(list);
2977 } else {
2978 dump_json_image_info(list->value);
2979 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002980 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002981 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002982
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002983 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002984 return 0;
2985}
2986
Eric Blake30065d12019-03-26 13:40:43 -05002987static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2988 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002989{
2990 switch (output_format) {
2991 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002992 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002993 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002994 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002995 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002996 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002997 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002998 e->start, e->length,
2999 e->has_offset ? e->offset : 0,
3000 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003001 }
3002 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3003 * Modify the flags here to allow more coalescing.
3004 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003005 if (next && (!next->data || next->zero)) {
3006 next->data = false;
3007 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003008 }
3009 break;
3010 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003011 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08003012 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003013 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08003014 e->zero ? "true" : "false",
3015 e->data ? "true" : "false");
3016 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003017 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003018 }
3019 putchar('}');
3020
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003021 if (next) {
3022 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003023 }
3024 break;
3025 }
Eric Blake30065d12019-03-26 13:40:43 -05003026 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003027}
3028
Eric Blake5e344dd2017-10-11 22:47:02 -05003029static int get_block_status(BlockDriverState *bs, int64_t offset,
3030 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003031{
Eric Blake237d78f2017-10-11 22:47:03 -05003032 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003033 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003034 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003035 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003036 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003037 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003038
3039 /* As an optimization, we could cache the current range of unallocated
3040 * clusters in each file of the chain, and avoid querying the same
3041 * range repeatedly.
3042 */
3043
3044 depth = 0;
3045 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05003046 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003047 if (ret < 0) {
3048 return ret;
3049 }
Eric Blake237d78f2017-10-11 22:47:03 -05003050 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3052 break;
3053 }
Kevin Wolf760e0062015-06-17 14:55:21 +02003054 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003055 if (bs == NULL) {
3056 ret = 0;
3057 break;
3058 }
3059
3060 depth++;
3061 }
3062
John Snow28756452016-02-05 13:12:33 -05003063 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3064
Max Reitzf30c66b2019-02-01 20:29:05 +01003065 if (file && has_offset) {
3066 bdrv_refresh_filename(file);
3067 filename = file->filename;
3068 }
3069
John Snow28756452016-02-05 13:12:33 -05003070 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003071 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003072 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003073 .data = !!(ret & BDRV_BLOCK_DATA),
3074 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003075 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003076 .has_offset = has_offset,
3077 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01003078 .has_filename = filename,
3079 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003080 };
3081
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003082 return 0;
3083}
3084
Fam Zheng16b0d552016-01-26 11:59:02 +08003085static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3086{
3087 if (curr->length == 0) {
3088 return false;
3089 }
3090 if (curr->zero != next->zero ||
3091 curr->data != next->data ||
3092 curr->depth != next->depth ||
3093 curr->has_filename != next->has_filename ||
3094 curr->has_offset != next->has_offset) {
3095 return false;
3096 }
3097 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3098 return false;
3099 }
3100 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3101 return false;
3102 }
3103 return true;
3104}
3105
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003106static int img_map(int argc, char **argv)
3107{
3108 int c;
3109 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003110 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003111 BlockDriverState *bs;
3112 const char *filename, *fmt, *output;
3113 int64_t length;
3114 MapEntry curr = { .length = 0 }, next;
3115 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003116 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003117 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003118 int64_t start_offset = 0;
3119 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003120
3121 fmt = NULL;
3122 output = NULL;
3123 for (;;) {
3124 int option_index = 0;
3125 static const struct option long_options[] = {
3126 {"help", no_argument, 0, 'h'},
3127 {"format", required_argument, 0, 'f'},
3128 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003129 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003130 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003131 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003132 {"start-offset", required_argument, 0, 's'},
3133 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003134 {0, 0, 0, 0}
3135 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003136 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003137 long_options, &option_index);
3138 if (c == -1) {
3139 break;
3140 }
3141 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003142 case ':':
3143 missing_argument(argv[optind - 1]);
3144 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003145 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003146 unrecognized_option(argv[optind - 1]);
3147 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003148 case 'h':
3149 help();
3150 break;
3151 case 'f':
3152 fmt = optarg;
3153 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003154 case 'U':
3155 force_share = true;
3156 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003157 case OPTION_OUTPUT:
3158 output = optarg;
3159 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003160 case 's':
3161 start_offset = cvtnum("start offset", optarg);
3162 if (start_offset < 0) {
3163 return 1;
3164 }
3165 break;
3166 case 'l':
3167 max_length = cvtnum("max length", optarg);
3168 if (max_length < 0) {
3169 return 1;
3170 }
3171 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003172 case OPTION_OBJECT: {
3173 QemuOpts *opts;
3174 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3175 optarg, true);
3176 if (!opts) {
3177 return 1;
3178 }
3179 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003180 case OPTION_IMAGE_OPTS:
3181 image_opts = true;
3182 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003183 }
3184 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003185 if (optind != argc - 1) {
3186 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003187 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003188 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003189
3190 if (output && !strcmp(output, "json")) {
3191 output_format = OFORMAT_JSON;
3192 } else if (output && !strcmp(output, "human")) {
3193 output_format = OFORMAT_HUMAN;
3194 } else if (output) {
3195 error_report("--output must be used with human or json as argument.");
3196 return 1;
3197 }
3198
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003199 if (qemu_opts_foreach(&qemu_object_opts,
3200 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003201 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003202 return 1;
3203 }
3204
Fam Zheng335e9932017-05-03 00:35:39 +08003205 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003206 if (!blk) {
3207 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003208 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003209 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003210
3211 if (output_format == OFORMAT_HUMAN) {
3212 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003213 } else if (output_format == OFORMAT_JSON) {
3214 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003215 }
3216
Max Reitzf1d3cd72015-02-05 13:58:18 -05003217 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003218 if (length < 0) {
3219 error_report("Failed to get size for '%s'", filename);
3220 return 1;
3221 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003222 if (max_length != -1) {
3223 length = MIN(start_offset + max_length, length);
3224 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003225
Eyal Moscovicic0469492020-05-13 16:36:29 +03003226 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003227 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003228 int64_t offset = curr.start + curr.length;
3229 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003230
3231 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003232 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003233 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003234
3235 if (ret < 0) {
3236 error_report("Could not read file metadata: %s", strerror(-ret));
3237 goto out;
3238 }
3239
Fam Zheng16b0d552016-01-26 11:59:02 +08003240 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003241 curr.length += next.length;
3242 continue;
3243 }
3244
3245 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003246 ret = dump_map_entry(output_format, &curr, &next);
3247 if (ret < 0) {
3248 goto out;
3249 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003250 }
3251 curr = next;
3252 }
3253
Eric Blake30065d12019-03-26 13:40:43 -05003254 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003255 if (output_format == OFORMAT_JSON) {
3256 puts("]");
3257 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003258
3259out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003260 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003261 return ret < 0;
3262}
3263
aliguorif7b4a942009-01-07 17:40:15 +00003264#define SNAPSHOT_LIST 1
3265#define SNAPSHOT_CREATE 2
3266#define SNAPSHOT_APPLY 3
3267#define SNAPSHOT_DELETE 4
3268
Stuart Brady153859b2009-06-07 00:42:17 +01003269static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003270{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003271 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003272 BlockDriverState *bs;
3273 QEMUSnapshotInfo sn;
3274 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003275 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003276 int action = 0;
3277 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003278 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003279 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003280 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003281 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003282
Kevin Wolfce099542016-03-15 13:01:04 +01003283 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003284 /* Parse commandline parameters */
3285 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003286 static const struct option long_options[] = {
3287 {"help", no_argument, 0, 'h'},
3288 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003289 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003290 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003291 {0, 0, 0, 0}
3292 };
Fam Zheng335e9932017-05-03 00:35:39 +08003293 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003294 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003295 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003296 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003297 }
aliguorif7b4a942009-01-07 17:40:15 +00003298 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003299 case ':':
3300 missing_argument(argv[optind - 1]);
3301 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003302 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003303 unrecognized_option(argv[optind - 1]);
3304 break;
aliguorif7b4a942009-01-07 17:40:15 +00003305 case 'h':
3306 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003307 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003308 case 'l':
3309 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003310 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003311 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003312 }
3313 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003314 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003315 break;
3316 case 'a':
3317 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003318 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003319 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003320 }
3321 action = SNAPSHOT_APPLY;
3322 snapshot_name = optarg;
3323 break;
3324 case 'c':
3325 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003326 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003327 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003328 }
3329 action = SNAPSHOT_CREATE;
3330 snapshot_name = optarg;
3331 break;
3332 case 'd':
3333 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003334 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003335 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003336 }
3337 action = SNAPSHOT_DELETE;
3338 snapshot_name = optarg;
3339 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003340 case 'q':
3341 quiet = true;
3342 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003343 case 'U':
3344 force_share = true;
3345 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003346 case OPTION_OBJECT: {
3347 QemuOpts *opts;
3348 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3349 optarg, true);
3350 if (!opts) {
3351 return 1;
3352 }
3353 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003354 case OPTION_IMAGE_OPTS:
3355 image_opts = true;
3356 break;
aliguorif7b4a942009-01-07 17:40:15 +00003357 }
3358 }
3359
Kevin Wolffc11eb22013-08-05 10:53:04 +02003360 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003361 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003362 }
aliguorif7b4a942009-01-07 17:40:15 +00003363 filename = argv[optind++];
3364
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003365 if (qemu_opts_foreach(&qemu_object_opts,
3366 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003367 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003368 return 1;
3369 }
3370
aliguorif7b4a942009-01-07 17:40:15 +00003371 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003372 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3373 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003374 if (!blk) {
3375 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003376 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003377 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003378
3379 /* Perform the requested action */
3380 switch(action) {
3381 case SNAPSHOT_LIST:
3382 dump_snapshots(bs);
3383 break;
3384
3385 case SNAPSHOT_CREATE:
3386 memset(&sn, 0, sizeof(sn));
3387 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3388
3389 qemu_gettimeofday(&tv);
3390 sn.date_sec = tv.tv_sec;
3391 sn.date_nsec = tv.tv_usec * 1000;
3392
3393 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003394 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003395 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003396 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003397 }
aliguorif7b4a942009-01-07 17:40:15 +00003398 break;
3399
3400 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003401 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003402 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003403 error_reportf_err(err, "Could not apply snapshot '%s': ",
3404 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003405 }
aliguorif7b4a942009-01-07 17:40:15 +00003406 break;
3407
3408 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003409 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3410 if (ret < 0) {
3411 error_report("Could not delete snapshot '%s': snapshot not "
3412 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003413 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003414 } else {
3415 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3416 if (ret < 0) {
3417 error_reportf_err(err, "Could not delete snapshot '%s': ",
3418 snapshot_name);
3419 ret = 1;
3420 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003421 }
aliguorif7b4a942009-01-07 17:40:15 +00003422 break;
3423 }
3424
3425 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003426 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003427 if (ret) {
3428 return 1;
3429 }
Stuart Brady153859b2009-06-07 00:42:17 +01003430 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003431}
3432
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003433static int img_rebase(int argc, char **argv)
3434{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003435 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003436 uint8_t *buf_old = NULL;
3437 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003438 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003439 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003440 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3441 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003442 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003443 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003444 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003445 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003446 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003447 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003448 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003449
3450 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003451 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003452 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003453 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003454 out_baseimg = NULL;
3455 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003456 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003457 static const struct option long_options[] = {
3458 {"help", no_argument, 0, 'h'},
3459 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003460 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003461 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003462 {0, 0, 0, 0}
3463 };
Fam Zheng335e9932017-05-03 00:35:39 +08003464 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003465 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003466 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003467 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003468 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003469 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003470 case ':':
3471 missing_argument(argv[optind - 1]);
3472 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003473 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003474 unrecognized_option(argv[optind - 1]);
3475 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003476 case 'h':
3477 help();
3478 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003479 case 'f':
3480 fmt = optarg;
3481 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003482 case 'F':
3483 out_basefmt = optarg;
3484 break;
3485 case 'b':
3486 out_baseimg = optarg;
3487 break;
3488 case 'u':
3489 unsafe = 1;
3490 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003491 case 'p':
3492 progress = 1;
3493 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003494 case 't':
3495 cache = optarg;
3496 break;
Max Reitz40055952014-07-22 22:58:42 +02003497 case 'T':
3498 src_cache = optarg;
3499 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003500 case 'q':
3501 quiet = true;
3502 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003503 case OPTION_OBJECT: {
3504 QemuOpts *opts;
3505 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3506 optarg, true);
3507 if (!opts) {
3508 return 1;
3509 }
3510 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003511 case OPTION_IMAGE_OPTS:
3512 image_opts = true;
3513 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003514 case 'U':
3515 force_share = true;
3516 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003517 }
3518 }
3519
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003520 if (quiet) {
3521 progress = 0;
3522 }
3523
Fam Zhengac1307a2014-04-22 13:36:11 +08003524 if (optind != argc - 1) {
3525 error_exit("Expecting one image file name");
3526 }
3527 if (!unsafe && !out_baseimg) {
3528 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003529 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003530 filename = argv[optind++];
3531
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003532 if (qemu_opts_foreach(&qemu_object_opts,
3533 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003534 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003535 return 1;
3536 }
3537
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003538 qemu_progress_init(progress, 2.0);
3539 qemu_progress_print(0, 100);
3540
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003541 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003542 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003543 if (ret < 0) {
3544 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003545 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003546 }
3547
Kevin Wolfce099542016-03-15 13:01:04 +01003548 src_flags = 0;
3549 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003550 if (ret < 0) {
3551 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003552 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003553 }
3554
Kevin Wolfce099542016-03-15 13:01:04 +01003555 /* The source files are opened read-only, don't care about WCE */
3556 assert((src_flags & BDRV_O_RDWR) == 0);
3557 (void) src_writethrough;
3558
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003559 /*
3560 * Open the images.
3561 *
3562 * Ignore the old backing file for unsafe rebase in case we want to correct
3563 * the reference to a renamed or moved backing file.
3564 */
Fam Zheng335e9932017-05-03 00:35:39 +08003565 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3566 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003567 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003568 ret = -1;
3569 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003570 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003571 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003572
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003573 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003574 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003575 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003576 ret = -1;
3577 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003578 }
3579 }
3580
3581 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003582 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003583 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003584 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003585
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003586 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003587 blk_old_backing = blk_new(qemu_get_aio_context(),
3588 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003589 BLK_PERM_ALL);
3590 ret = blk_insert_bs(blk_old_backing, base_bs,
3591 &local_err);
3592 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003593 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003594 "Could not reuse old backing file '%s': ",
3595 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003596 goto out;
3597 }
3598 } else {
3599 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003600 }
Max Reitz644483d2015-02-05 13:58:17 -05003601
Alex Bligha6166732012-10-16 13:46:18 +01003602 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003603 const char *overlay_filename;
3604 char *out_real_path;
3605
Fam Zheng335e9932017-05-03 00:35:39 +08003606 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003607 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003608 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003609 }
3610 if (force_share) {
3611 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003612 }
3613
Max Reitzf30c66b2019-02-01 20:29:05 +01003614 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003615 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3616 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003617 out_real_path =
3618 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3619 out_baseimg,
3620 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003621 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003622 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003623 error_reportf_err(local_err,
3624 "Could not resolve backing filename: ");
3625 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003626 goto out;
3627 }
3628
Sam Eiderman863cc782019-05-23 19:33:36 +03003629 /*
3630 * Find out whether we rebase an image on top of a previous image
3631 * in its chain.
3632 */
3633 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003634 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003635 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003636 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003637
Kevin Wolfd861ab32019-04-25 14:25:10 +02003638 blk_new_backing = blk_new(qemu_get_aio_context(),
3639 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003640 BLK_PERM_ALL);
3641 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3642 &local_err);
3643 if (ret < 0) {
3644 error_reportf_err(local_err,
3645 "Could not reuse backing file '%s': ",
3646 out_baseimg);
3647 goto out;
3648 }
3649 } else {
3650 blk_new_backing = blk_new_open(out_real_path, NULL,
3651 options, src_flags, &local_err);
3652 g_free(out_real_path);
3653 if (!blk_new_backing) {
3654 error_reportf_err(local_err,
3655 "Could not open new backing file '%s': ",
3656 out_baseimg);
3657 ret = -1;
3658 goto out;
3659 }
Alex Bligha6166732012-10-16 13:46:18 +01003660 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003661 }
3662 }
3663
3664 /*
3665 * Check each unallocated cluster in the COW file. If it is unallocated,
3666 * accesses go to the backing file. We must therefore compare this cluster
3667 * in the old and new backing file, and if they differ we need to copy it
3668 * from the old backing file into the COW file.
3669 *
3670 * If qemu-img crashes during this step, no harm is done. The content of
3671 * the image is the same as the original one at any time.
3672 */
3673 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003674 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003675 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003676 int64_t new_backing_size = 0;
3677 uint64_t offset;
3678 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003679 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003680
Max Reitzf1d3cd72015-02-05 13:58:18 -05003681 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3682 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003683
Eric Blake41536282017-10-11 22:47:15 -05003684 size = blk_getlength(blk);
3685 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003686 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003687 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003688 ret = -1;
3689 goto out;
3690 }
Max Reitz35ddd932019-05-09 19:52:35 +02003691 if (blk_old_backing) {
3692 old_backing_size = blk_getlength(blk_old_backing);
3693 if (old_backing_size < 0) {
3694 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003695
Max Reitz35ddd932019-05-09 19:52:35 +02003696 bdrv_get_backing_filename(bs, backing_name,
3697 sizeof(backing_name));
3698 error_report("Could not get size of '%s': %s",
3699 backing_name, strerror(-old_backing_size));
3700 ret = -1;
3701 goto out;
3702 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003703 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003704 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003705 new_backing_size = blk_getlength(blk_new_backing);
3706 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003707 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003708 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003709 ret = -1;
3710 goto out;
3711 }
Alex Bligha6166732012-10-16 13:46:18 +01003712 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003713
Eric Blake41536282017-10-11 22:47:15 -05003714 if (size != 0) {
3715 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003716 }
3717
Eric Blake41536282017-10-11 22:47:15 -05003718 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003719 bool buf_old_is_zero = false;
3720
Eric Blake41536282017-10-11 22:47:15 -05003721 /* How many bytes can we handle with the next read? */
3722 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003723
3724 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003725 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003726 if (ret < 0) {
3727 error_report("error while reading image metadata: %s",
3728 strerror(-ret));
3729 goto out;
3730 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003731 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003732 continue;
3733 }
3734
Sam Eiderman863cc782019-05-23 19:33:36 +03003735 if (prefix_chain_bs) {
3736 /*
3737 * If cluster wasn't changed since prefix_chain, we don't need
3738 * to take action
3739 */
3740 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003741 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003742 if (ret < 0) {
3743 error_report("error while reading image metadata: %s",
3744 strerror(-ret));
3745 goto out;
3746 }
3747 if (!ret) {
3748 continue;
3749 }
3750 }
3751
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003752 /*
3753 * Read old and new backing file and take into consideration that
3754 * backing files may be smaller than the COW image.
3755 */
Eric Blake41536282017-10-11 22:47:15 -05003756 if (offset >= old_backing_size) {
3757 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003758 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003759 } else {
Eric Blake41536282017-10-11 22:47:15 -05003760 if (offset + n > old_backing_size) {
3761 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003762 }
3763
Eric Blake41536282017-10-11 22:47:15 -05003764 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003765 if (ret < 0) {
3766 error_report("error while reading from old backing file");
3767 goto out;
3768 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003769 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003770
Eric Blake41536282017-10-11 22:47:15 -05003771 if (offset >= new_backing_size || !blk_new_backing) {
3772 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003773 } else {
Eric Blake41536282017-10-11 22:47:15 -05003774 if (offset + n > new_backing_size) {
3775 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003776 }
3777
Eric Blake41536282017-10-11 22:47:15 -05003778 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003779 if (ret < 0) {
3780 error_report("error while reading from new backing file");
3781 goto out;
3782 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003783 }
3784
3785 /* If they differ, we need to write to the COW file */
3786 uint64_t written = 0;
3787
Eric Blake41536282017-10-11 22:47:15 -05003788 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003789 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003790
Eric Blake41536282017-10-11 22:47:15 -05003791 if (compare_buffers(buf_old + written, buf_new + written,
3792 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003793 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003794 if (buf_old_is_zero) {
3795 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3796 } else {
3797 ret = blk_pwrite(blk, offset + written,
3798 buf_old + written, pnum, 0);
3799 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003800 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003801 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003802 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003803 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003804 }
3805 }
3806
3807 written += pnum;
3808 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003809 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003810 }
3811 }
3812
3813 /*
3814 * Change the backing file. All clusters that are different from the old
3815 * backing file are overwritten in the COW file now, so the visible content
3816 * doesn't change when we switch the backing file.
3817 */
Alex Bligha6166732012-10-16 13:46:18 +01003818 if (out_baseimg && *out_baseimg) {
3819 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3820 } else {
3821 ret = bdrv_change_backing_file(bs, NULL, NULL);
3822 }
3823
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003824 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003825 error_report("Could not change the backing file to '%s': No "
3826 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003827 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003828 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003829 out_baseimg, strerror(-ret));
3830 }
3831
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003832 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003833 /*
3834 * TODO At this point it is possible to check if any clusters that are
3835 * allocated in the COW file are the same in the backing file. If so, they
3836 * could be dropped from the COW file. Don't do this before switching the
3837 * backing file, in case of a crash this would lead to corruption.
3838 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003839out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003840 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003841 /* Cleanup */
3842 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003843 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003844 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003845 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003846 qemu_vfree(buf_old);
3847 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003848
Markus Armbruster26f54e92014-10-07 13:59:04 +02003849 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003850 if (ret) {
3851 return 1;
3852 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003853 return 0;
3854}
3855
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003856static int img_resize(int argc, char **argv)
3857{
Markus Armbruster6750e792015-02-12 17:43:08 +01003858 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003859 int c, ret, relative;
3860 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003861 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003862 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003863 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003864 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003865 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003866
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003867 static QemuOptsList resize_options = {
3868 .name = "resize_options",
3869 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3870 .desc = {
3871 {
3872 .name = BLOCK_OPT_SIZE,
3873 .type = QEMU_OPT_SIZE,
3874 .help = "Virtual disk size"
3875 }, {
3876 /* end of list */
3877 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003878 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003879 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003880 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003881 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003882
Kevin Wolfe80fec72011-04-29 10:58:12 +02003883 /* Remove size from argv manually so that negative numbers are not treated
3884 * as options by getopt. */
3885 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003886 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003887 return 1;
3888 }
3889
3890 size = argv[--argc];
3891
3892 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003893 fmt = NULL;
3894 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003895 static const struct option long_options[] = {
3896 {"help", no_argument, 0, 'h'},
3897 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003898 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003899 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003900 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003901 {0, 0, 0, 0}
3902 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003903 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003904 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003905 if (c == -1) {
3906 break;
3907 }
3908 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003909 case ':':
3910 missing_argument(argv[optind - 1]);
3911 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003912 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003913 unrecognized_option(argv[optind - 1]);
3914 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003915 case 'h':
3916 help();
3917 break;
3918 case 'f':
3919 fmt = optarg;
3920 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003921 case 'q':
3922 quiet = true;
3923 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003924 case OPTION_OBJECT: {
3925 QemuOpts *opts;
3926 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3927 optarg, true);
3928 if (!opts) {
3929 return 1;
3930 }
3931 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003932 case OPTION_IMAGE_OPTS:
3933 image_opts = true;
3934 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003935 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003936 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003937 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003938 if (prealloc == PREALLOC_MODE__MAX) {
3939 error_report("Invalid preallocation mode '%s'", optarg);
3940 return 1;
3941 }
3942 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003943 case OPTION_SHRINK:
3944 shrink = true;
3945 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003946 }
3947 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003948 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003949 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003950 }
3951 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003952
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003953 if (qemu_opts_foreach(&qemu_object_opts,
3954 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003955 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003956 return 1;
3957 }
3958
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003959 /* Choose grow, shrink, or absolute resize mode */
3960 switch (size[0]) {
3961 case '+':
3962 relative = 1;
3963 size++;
3964 break;
3965 case '-':
3966 relative = -1;
3967 size++;
3968 break;
3969 default:
3970 relative = 0;
3971 break;
3972 }
3973
3974 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003975 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003976 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003977 if (err) {
3978 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003979 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003980 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003981 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003982 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003983 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3984 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003985
Max Reitzefaa7c42016-03-16 19:54:38 +01003986 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003987 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3988 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003989 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003990 ret = -1;
3991 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003992 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003993
Max Reitzdc5f6902017-06-13 22:20:55 +02003994 current_size = blk_getlength(blk);
3995 if (current_size < 0) {
3996 error_report("Failed to inquire current image length: %s",
3997 strerror(-current_size));
3998 ret = -1;
3999 goto out;
4000 }
4001
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004002 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004003 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004004 } else {
4005 total_size = n;
4006 }
4007 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004008 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004009 ret = -1;
4010 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004011 }
4012
Max Reitzdc5f6902017-06-13 22:20:55 +02004013 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4014 error_report("Preallocation can only be used for growing images");
4015 ret = -1;
4016 goto out;
4017 }
4018
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004019 if (total_size < current_size && !shrink) {
4020 warn_report("Shrinking an image will delete all data beyond the "
4021 "shrunken image's end. Before performing such an "
4022 "operation, make sure there is no important data there.");
4023
4024 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4025 error_report(
4026 "Use the --shrink option to perform a shrink operation.");
4027 ret = -1;
4028 goto out;
4029 } else {
4030 warn_report("Using the --shrink option will suppress this message. "
4031 "Note that future versions of qemu-img may refuse to "
4032 "shrink images without this option.");
4033 }
4034 }
4035
Max Reitze8d04f92019-09-18 11:51:43 +02004036 /*
4037 * The user expects the image to have the desired size after
4038 * resizing, so pass @exact=true. It is of no use to report
4039 * success when the image has not actually been resized.
4040 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004041 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004042 if (!ret) {
4043 qprintf(quiet, "Image resized.\n");
4044 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004045 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004046 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004047out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004048 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004049 if (ret) {
4050 return 1;
4051 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004052 return 0;
4053}
4054
Max Reitz76a3a342014-10-27 11:12:51 +01004055static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004056 int64_t offset, int64_t total_work_size,
4057 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004058{
4059 qemu_progress_print(100.f * offset / total_work_size, 0);
4060}
4061
Max Reitz51641352018-05-09 23:00:20 +02004062static int print_amend_option_help(const char *format)
4063{
4064 BlockDriver *drv;
4065
4066 /* Find driver and parse its options */
4067 drv = bdrv_find_format(format);
4068 if (!drv) {
4069 error_report("Unknown file format '%s'", format);
4070 return 1;
4071 }
4072
4073 if (!drv->bdrv_amend_options) {
4074 error_report("Format driver '%s' does not support option amendment",
4075 format);
4076 return 1;
4077 }
4078
4079 /* Every driver supporting amendment must have create_opts */
4080 assert(drv->create_opts);
4081
4082 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02004083 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004084 printf("\nNote that not all of these options may be amendable.\n");
4085 return 0;
4086}
4087
Max Reitz6f176b42013-09-03 10:09:50 +02004088static int img_amend(int argc, char **argv)
4089{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004090 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004091 int c, ret = 0;
4092 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004093 QemuOptsList *create_opts = NULL;
4094 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004095 const char *fmt = NULL, *filename, *cache;
4096 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004097 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004098 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004099 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004100 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004101 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004102
Max Reitzbd39e6e2014-07-22 22:58:43 +02004103 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004104 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004105 static const struct option long_options[] = {
4106 {"help", no_argument, 0, 'h'},
4107 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004108 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004109 {0, 0, 0, 0}
4110 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004111 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004112 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004113 if (c == -1) {
4114 break;
4115 }
4116
4117 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004118 case ':':
4119 missing_argument(argv[optind - 1]);
4120 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004121 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004122 unrecognized_option(argv[optind - 1]);
4123 break;
4124 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004125 help();
4126 break;
4127 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004128 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004129 ret = -1;
4130 goto out_no_progress;
4131 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004132 break;
4133 case 'f':
4134 fmt = optarg;
4135 break;
4136 case 't':
4137 cache = optarg;
4138 break;
4139 case 'p':
4140 progress = true;
4141 break;
4142 case 'q':
4143 quiet = true;
4144 break;
4145 case OPTION_OBJECT:
4146 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4147 optarg, true);
4148 if (!opts) {
4149 ret = -1;
4150 goto out_no_progress;
4151 }
4152 break;
4153 case OPTION_IMAGE_OPTS:
4154 image_opts = true;
4155 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004156 }
4157 }
4158
Max Reitz6f176b42013-09-03 10:09:50 +02004159 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004160 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004161 }
4162
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004163 if (qemu_opts_foreach(&qemu_object_opts,
4164 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004165 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004166 ret = -1;
4167 goto out_no_progress;
4168 }
4169
Max Reitz76a3a342014-10-27 11:12:51 +01004170 if (quiet) {
4171 progress = false;
4172 }
4173 qemu_progress_init(progress, 1.0);
4174
Kevin Wolfa283cb62014-02-21 16:24:07 +01004175 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4176 if (fmt && has_help_option(options)) {
4177 /* If a format is explicitly specified (and possibly no filename is
4178 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004179 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004180 goto out;
4181 }
4182
4183 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004184 error_report("Expecting one image file name");
4185 ret = -1;
4186 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004187 }
Max Reitz6f176b42013-09-03 10:09:50 +02004188
Kevin Wolfce099542016-03-15 13:01:04 +01004189 flags = BDRV_O_RDWR;
4190 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004191 if (ret < 0) {
4192 error_report("Invalid cache option: %s", cache);
4193 goto out;
4194 }
4195
Fam Zheng335e9932017-05-03 00:35:39 +08004196 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4197 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004198 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004199 ret = -1;
4200 goto out;
4201 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004202 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004203
4204 fmt = bs->drv->format_name;
4205
Kevin Wolf626f84f2014-02-21 16:24:06 +01004206 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004207 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004208 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004209 goto out;
4210 }
4211
Max Reitz1f996682018-05-09 23:00:17 +02004212 if (!bs->drv->bdrv_amend_options) {
4213 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004214 fmt);
4215 ret = -1;
4216 goto out;
4217 }
4218
Max Reitz1f996682018-05-09 23:00:17 +02004219 /* Every driver supporting amendment must have create_opts */
4220 assert(bs->drv->create_opts);
4221
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004222 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004223 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004224 qemu_opts_do_parse(opts, options, NULL, &err);
4225 if (err) {
4226 error_report_err(err);
4227 ret = -1;
4228 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004229 }
4230
Max Reitz76a3a342014-10-27 11:12:51 +01004231 /* In case the driver does not call amend_status_cb() */
4232 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004233 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004234 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004235 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004236 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004237 goto out;
4238 }
4239
4240out:
Max Reitz76a3a342014-10-27 11:12:51 +01004241 qemu_progress_end();
4242
Max Reitze814dff2015-08-20 16:00:38 -07004243out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004244 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004245 qemu_opts_del(opts);
4246 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004247 g_free(options);
4248
Max Reitz6f176b42013-09-03 10:09:50 +02004249 if (ret) {
4250 return 1;
4251 }
4252 return 0;
4253}
4254
Kevin Wolfb6133b82014-08-05 14:17:13 +02004255typedef struct BenchData {
4256 BlockBackend *blk;
4257 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004258 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004259 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004260 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004261 int nrreq;
4262 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004263 int flush_interval;
4264 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004265 uint8_t *buf;
4266 QEMUIOVector *qiov;
4267
4268 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004269 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004270 uint64_t offset;
4271} BenchData;
4272
Kevin Wolf55d539c2016-06-03 13:59:41 +02004273static void bench_undrained_flush_cb(void *opaque, int ret)
4274{
4275 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004276 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004277 exit(EXIT_FAILURE);
4278 }
4279}
4280
Kevin Wolfb6133b82014-08-05 14:17:13 +02004281static void bench_cb(void *opaque, int ret)
4282{
4283 BenchData *b = opaque;
4284 BlockAIOCB *acb;
4285
4286 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004287 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004288 exit(EXIT_FAILURE);
4289 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004290
4291 if (b->in_flush) {
4292 /* Just finished a flush with drained queue: Start next requests */
4293 assert(b->in_flight == 0);
4294 b->in_flush = false;
4295 } else if (b->in_flight > 0) {
4296 int remaining = b->n - b->in_flight;
4297
Kevin Wolfb6133b82014-08-05 14:17:13 +02004298 b->n--;
4299 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004300
4301 /* Time for flush? Drain queue if requested, then flush */
4302 if (b->flush_interval && remaining % b->flush_interval == 0) {
4303 if (!b->in_flight || !b->drain_on_flush) {
4304 BlockCompletionFunc *cb;
4305
4306 if (b->drain_on_flush) {
4307 b->in_flush = true;
4308 cb = bench_cb;
4309 } else {
4310 cb = bench_undrained_flush_cb;
4311 }
4312
4313 acb = blk_aio_flush(b->blk, cb, b);
4314 if (!acb) {
4315 error_report("Failed to issue flush request");
4316 exit(EXIT_FAILURE);
4317 }
4318 }
4319 if (b->drain_on_flush) {
4320 return;
4321 }
4322 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004323 }
4324
4325 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004326 int64_t offset = b->offset;
4327 /* blk_aio_* might look for completed I/Os and kick bench_cb
4328 * again, so make sure this operation is counted by in_flight
4329 * and b->offset is ready for the next submission.
4330 */
4331 b->in_flight++;
4332 b->offset += b->step;
4333 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004334 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004335 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004336 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004337 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004338 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004339 if (!acb) {
4340 error_report("Failed to issue request");
4341 exit(EXIT_FAILURE);
4342 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004343 }
4344}
4345
4346static int img_bench(int argc, char **argv)
4347{
4348 int c, ret = 0;
4349 const char *fmt = NULL, *filename;
4350 bool quiet = false;
4351 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004352 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004353 int count = 75000;
4354 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004355 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004356 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004357 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004358 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004359 int flush_interval = 0;
4360 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004361 int64_t image_size;
4362 BlockBackend *blk = NULL;
4363 BenchData data = {};
4364 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004365 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004366 struct timeval t1, t2;
4367 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004368 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004369 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004370
4371 for (;;) {
4372 static const struct option long_options[] = {
4373 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004374 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004375 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004376 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004377 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004378 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004379 {0, 0, 0, 0}
4380 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004381 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4382 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004383 if (c == -1) {
4384 break;
4385 }
4386
4387 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004388 case ':':
4389 missing_argument(argv[optind - 1]);
4390 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004391 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004392 unrecognized_option(argv[optind - 1]);
4393 break;
4394 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004395 help();
4396 break;
4397 case 'c':
4398 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004399 unsigned long res;
4400
4401 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004402 error_report("Invalid request count specified");
4403 return 1;
4404 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004405 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004406 break;
4407 }
4408 case 'd':
4409 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004410 unsigned long res;
4411
4412 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004413 error_report("Invalid queue depth specified");
4414 return 1;
4415 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004416 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004417 break;
4418 }
4419 case 'f':
4420 fmt = optarg;
4421 break;
4422 case 'n':
4423 flags |= BDRV_O_NATIVE_AIO;
4424 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004425 case 'i':
4426 ret = bdrv_parse_aio(optarg, &flags);
4427 if (ret < 0) {
4428 error_report("Invalid aio option: %s", optarg);
4429 ret = -1;
4430 goto out;
4431 }
4432 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004433 case 'o':
4434 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004435 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004436 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004437 return 1;
4438 }
4439 break;
4440 }
4441 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004442 case 'q':
4443 quiet = true;
4444 break;
4445 case 's':
4446 {
4447 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004448
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004449 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4450 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004451 return 1;
4452 }
4453
4454 bufsize = sval;
4455 break;
4456 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004457 case 'S':
4458 {
4459 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004460
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004461 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4462 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004463 return 1;
4464 }
4465
4466 step = sval;
4467 break;
4468 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004469 case 't':
4470 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4471 if (ret < 0) {
4472 error_report("Invalid cache mode");
4473 ret = -1;
4474 goto out;
4475 }
4476 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004477 case 'w':
4478 flags |= BDRV_O_RDWR;
4479 is_write = true;
4480 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004481 case 'U':
4482 force_share = true;
4483 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004484 case OPTION_PATTERN:
4485 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004486 unsigned long res;
4487
4488 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004489 error_report("Invalid pattern byte specified");
4490 return 1;
4491 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004492 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004493 break;
4494 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004495 case OPTION_FLUSH_INTERVAL:
4496 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004497 unsigned long res;
4498
4499 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004500 error_report("Invalid flush interval specified");
4501 return 1;
4502 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004503 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004504 break;
4505 }
4506 case OPTION_NO_DRAIN:
4507 drain_on_flush = false;
4508 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004509 case OPTION_IMAGE_OPTS:
4510 image_opts = true;
4511 break;
4512 }
4513 }
4514
4515 if (optind != argc - 1) {
4516 error_exit("Expecting one image file name");
4517 }
4518 filename = argv[argc - 1];
4519
Kevin Wolf55d539c2016-06-03 13:59:41 +02004520 if (!is_write && flush_interval) {
4521 error_report("--flush-interval is only available in write tests");
4522 ret = -1;
4523 goto out;
4524 }
4525 if (flush_interval && flush_interval < depth) {
4526 error_report("Flush interval can't be smaller than depth");
4527 ret = -1;
4528 goto out;
4529 }
4530
Fam Zheng335e9932017-05-03 00:35:39 +08004531 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4532 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004533 if (!blk) {
4534 ret = -1;
4535 goto out;
4536 }
4537
4538 image_size = blk_getlength(blk);
4539 if (image_size < 0) {
4540 ret = image_size;
4541 goto out;
4542 }
4543
4544 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004545 .blk = blk,
4546 .image_size = image_size,
4547 .bufsize = bufsize,
4548 .step = step ?: bufsize,
4549 .nrreq = depth,
4550 .n = count,
4551 .offset = offset,
4552 .write = is_write,
4553 .flush_interval = flush_interval,
4554 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004555 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004556 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004557 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004558 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004559 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004560 if (flush_interval) {
4561 printf("Sending flush every %d requests\n", flush_interval);
4562 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004563
Fam Zheng79d46582018-01-16 14:08:58 +08004564 buf_size = data.nrreq * data.bufsize;
4565 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004566 memset(data.buf, pattern, data.nrreq * data.bufsize);
4567
Fam Zheng79d46582018-01-16 14:08:58 +08004568 blk_register_buf(blk, data.buf, buf_size);
4569
Kevin Wolfb6133b82014-08-05 14:17:13 +02004570 data.qiov = g_new(QEMUIOVector, data.nrreq);
4571 for (i = 0; i < data.nrreq; i++) {
4572 qemu_iovec_init(&data.qiov[i], 1);
4573 qemu_iovec_add(&data.qiov[i],
4574 data.buf + i * data.bufsize, data.bufsize);
4575 }
4576
4577 gettimeofday(&t1, NULL);
4578 bench_cb(&data, 0);
4579
4580 while (data.n > 0) {
4581 main_loop_wait(false);
4582 }
4583 gettimeofday(&t2, NULL);
4584
4585 printf("Run completed in %3.3f seconds.\n",
4586 (t2.tv_sec - t1.tv_sec)
4587 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4588
4589out:
Fam Zheng79d46582018-01-16 14:08:58 +08004590 if (data.buf) {
4591 blk_unregister_buf(blk, data.buf);
4592 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004593 qemu_vfree(data.buf);
4594 blk_unref(blk);
4595
4596 if (ret) {
4597 return 1;
4598 }
4599 return 0;
4600}
4601
Eric Blake3b51ab42020-05-12 20:16:45 -05004602enum ImgBitmapAct {
4603 BITMAP_ADD,
4604 BITMAP_REMOVE,
4605 BITMAP_CLEAR,
4606 BITMAP_ENABLE,
4607 BITMAP_DISABLE,
4608 BITMAP_MERGE,
4609};
4610typedef struct ImgBitmapAction {
4611 enum ImgBitmapAct act;
4612 const char *src; /* only used for merge */
4613 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4614} ImgBitmapAction;
4615
4616static int img_bitmap(int argc, char **argv)
4617{
4618 Error *err = NULL;
4619 int c, ret = 1;
4620 QemuOpts *opts = NULL;
4621 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4622 const char *filename, *bitmap;
4623 BlockBackend *blk = NULL, *src = NULL;
4624 BlockDriverState *bs = NULL, *src_bs = NULL;
4625 bool image_opts = false;
4626 int64_t granularity = 0;
4627 bool add = false, merge = false;
4628 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4629 ImgBitmapAction *act, *act_next;
4630 const char *op;
4631
4632 QSIMPLEQ_INIT(&actions);
4633
4634 for (;;) {
4635 static const struct option long_options[] = {
4636 {"help", no_argument, 0, 'h'},
4637 {"object", required_argument, 0, OPTION_OBJECT},
4638 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4639 {"add", no_argument, 0, OPTION_ADD},
4640 {"remove", no_argument, 0, OPTION_REMOVE},
4641 {"clear", no_argument, 0, OPTION_CLEAR},
4642 {"enable", no_argument, 0, OPTION_ENABLE},
4643 {"disable", no_argument, 0, OPTION_DISABLE},
4644 {"merge", required_argument, 0, OPTION_MERGE},
4645 {"granularity", required_argument, 0, 'g'},
4646 {"source-file", required_argument, 0, 'b'},
4647 {"source-format", required_argument, 0, 'F'},
4648 {0, 0, 0, 0}
4649 };
4650 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4651 if (c == -1) {
4652 break;
4653 }
4654
4655 switch (c) {
4656 case ':':
4657 missing_argument(argv[optind - 1]);
4658 break;
4659 case '?':
4660 unrecognized_option(argv[optind - 1]);
4661 break;
4662 case 'h':
4663 help();
4664 break;
4665 case 'b':
4666 src_filename = optarg;
4667 break;
4668 case 'f':
4669 fmt = optarg;
4670 break;
4671 case 'F':
4672 src_fmt = optarg;
4673 break;
4674 case 'g':
4675 granularity = cvtnum("granularity", optarg);
4676 if (granularity < 0) {
4677 return 1;
4678 }
4679 break;
4680 case OPTION_ADD:
4681 act = g_new0(ImgBitmapAction, 1);
4682 act->act = BITMAP_ADD;
4683 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4684 add = true;
4685 break;
4686 case OPTION_REMOVE:
4687 act = g_new0(ImgBitmapAction, 1);
4688 act->act = BITMAP_REMOVE;
4689 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4690 break;
4691 case OPTION_CLEAR:
4692 act = g_new0(ImgBitmapAction, 1);
4693 act->act = BITMAP_CLEAR;
4694 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4695 break;
4696 case OPTION_ENABLE:
4697 act = g_new0(ImgBitmapAction, 1);
4698 act->act = BITMAP_ENABLE;
4699 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4700 break;
4701 case OPTION_DISABLE:
4702 act = g_new0(ImgBitmapAction, 1);
4703 act->act = BITMAP_DISABLE;
4704 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4705 break;
4706 case OPTION_MERGE:
4707 act = g_new0(ImgBitmapAction, 1);
4708 act->act = BITMAP_MERGE;
4709 act->src = optarg;
4710 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4711 merge = true;
4712 break;
4713 case OPTION_OBJECT:
4714 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4715 if (!opts) {
4716 goto out;
4717 }
4718 break;
4719 case OPTION_IMAGE_OPTS:
4720 image_opts = true;
4721 break;
4722 }
4723 }
4724
4725 if (qemu_opts_foreach(&qemu_object_opts,
4726 user_creatable_add_opts_foreach,
4727 qemu_img_object_print_help, &error_fatal)) {
4728 goto out;
4729 }
4730
4731 if (QSIMPLEQ_EMPTY(&actions)) {
4732 error_report("Need at least one of --add, --remove, --clear, "
4733 "--enable, --disable, or --merge");
4734 goto out;
4735 }
4736
4737 if (granularity && !add) {
4738 error_report("granularity only supported with --add");
4739 goto out;
4740 }
4741 if (src_fmt && !src_filename) {
4742 error_report("-F only supported with -b");
4743 goto out;
4744 }
4745 if (src_filename && !merge) {
4746 error_report("Merge bitmap source file only supported with "
4747 "--merge");
4748 goto out;
4749 }
4750
4751 if (optind != argc - 2) {
4752 error_report("Expecting filename and bitmap name");
4753 goto out;
4754 }
4755
4756 filename = argv[optind];
4757 bitmap = argv[optind + 1];
4758
4759 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4760 false);
4761 if (!blk) {
4762 goto out;
4763 }
4764 bs = blk_bs(blk);
4765 if (src_filename) {
4766 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4767 if (!src) {
4768 goto out;
4769 }
4770 src_bs = blk_bs(src);
4771 } else {
4772 src_bs = bs;
4773 }
4774
4775 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4776 switch (act->act) {
4777 case BITMAP_ADD:
4778 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4779 !!granularity, granularity, true, true,
4780 false, false, &err);
4781 op = "add";
4782 break;
4783 case BITMAP_REMOVE:
4784 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4785 op = "remove";
4786 break;
4787 case BITMAP_CLEAR:
4788 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4789 op = "clear";
4790 break;
4791 case BITMAP_ENABLE:
4792 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4793 op = "enable";
4794 break;
4795 case BITMAP_DISABLE:
4796 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4797 op = "disable";
4798 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004799 case BITMAP_MERGE:
4800 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4801 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004802 op = "merge";
4803 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004804 default:
4805 g_assert_not_reached();
4806 }
4807
4808 if (err) {
4809 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4810 op, bitmap);
4811 goto out;
4812 }
4813 g_free(act);
4814 }
4815
4816 ret = 0;
4817
4818 out:
4819 blk_unref(src);
4820 blk_unref(blk);
4821 qemu_opts_del(opts);
4822 return ret;
4823}
4824
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004825#define C_BS 01
4826#define C_COUNT 02
4827#define C_IF 04
4828#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004829#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004830
4831struct DdInfo {
4832 unsigned int flags;
4833 int64_t count;
4834};
4835
4836struct DdIo {
4837 int bsz; /* Block size */
4838 char *filename;
4839 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004840 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004841};
4842
4843struct DdOpts {
4844 const char *name;
4845 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4846 unsigned int flag;
4847};
4848
4849static int img_dd_bs(const char *arg,
4850 struct DdIo *in, struct DdIo *out,
4851 struct DdInfo *dd)
4852{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004853 int64_t res;
4854
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004855 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004856
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004857 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004858 return 1;
4859 }
4860 in->bsz = out->bsz = res;
4861
4862 return 0;
4863}
4864
4865static int img_dd_count(const char *arg,
4866 struct DdIo *in, struct DdIo *out,
4867 struct DdInfo *dd)
4868{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004869 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004870
Markus Armbruster606caa02017-02-21 21:14:04 +01004871 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004872 return 1;
4873 }
4874
4875 return 0;
4876}
4877
4878static int img_dd_if(const char *arg,
4879 struct DdIo *in, struct DdIo *out,
4880 struct DdInfo *dd)
4881{
4882 in->filename = g_strdup(arg);
4883
4884 return 0;
4885}
4886
4887static int img_dd_of(const char *arg,
4888 struct DdIo *in, struct DdIo *out,
4889 struct DdInfo *dd)
4890{
4891 out->filename = g_strdup(arg);
4892
4893 return 0;
4894}
4895
Reda Sallahif7c15532016-08-10 16:16:09 +02004896static int img_dd_skip(const char *arg,
4897 struct DdIo *in, struct DdIo *out,
4898 struct DdInfo *dd)
4899{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004900 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004901
Markus Armbruster606caa02017-02-21 21:14:04 +01004902 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004903 return 1;
4904 }
4905
4906 return 0;
4907}
4908
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004909static int img_dd(int argc, char **argv)
4910{
4911 int ret = 0;
4912 char *arg = NULL;
4913 char *tmp;
4914 BlockDriver *drv = NULL, *proto_drv = NULL;
4915 BlockBackend *blk1 = NULL, *blk2 = NULL;
4916 QemuOpts *opts = NULL;
4917 QemuOptsList *create_opts = NULL;
4918 Error *local_err = NULL;
4919 bool image_opts = false;
4920 int c, i;
4921 const char *out_fmt = "raw";
4922 const char *fmt = NULL;
4923 int64_t size = 0;
4924 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004925 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004926 struct DdInfo dd = {
4927 .flags = 0,
4928 .count = 0,
4929 };
4930 struct DdIo in = {
4931 .bsz = 512, /* Block size is by default 512 bytes */
4932 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004933 .buf = NULL,
4934 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004935 };
4936 struct DdIo out = {
4937 .bsz = 512,
4938 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004939 .buf = NULL,
4940 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004941 };
4942
4943 const struct DdOpts options[] = {
4944 { "bs", img_dd_bs, C_BS },
4945 { "count", img_dd_count, C_COUNT },
4946 { "if", img_dd_if, C_IF },
4947 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004948 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004949 { NULL, NULL, 0 }
4950 };
4951 const struct option long_options[] = {
4952 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004953 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004954 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004955 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004956 { 0, 0, 0, 0 }
4957 };
4958
Fam Zheng335e9932017-05-03 00:35:39 +08004959 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004960 if (c == EOF) {
4961 break;
4962 }
4963 switch (c) {
4964 case 'O':
4965 out_fmt = optarg;
4966 break;
4967 case 'f':
4968 fmt = optarg;
4969 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004970 case ':':
4971 missing_argument(argv[optind - 1]);
4972 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004973 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004974 unrecognized_option(argv[optind - 1]);
4975 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004976 case 'h':
4977 help();
4978 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004979 case 'U':
4980 force_share = true;
4981 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004982 case OPTION_OBJECT:
4983 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004984 ret = -1;
4985 goto out;
4986 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004987 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004988 case OPTION_IMAGE_OPTS:
4989 image_opts = true;
4990 break;
4991 }
4992 }
4993
4994 for (i = optind; i < argc; i++) {
4995 int j;
4996 arg = g_strdup(argv[i]);
4997
4998 tmp = strchr(arg, '=');
4999 if (tmp == NULL) {
5000 error_report("unrecognized operand %s", arg);
5001 ret = -1;
5002 goto out;
5003 }
5004
5005 *tmp++ = '\0';
5006
5007 for (j = 0; options[j].name != NULL; j++) {
5008 if (!strcmp(arg, options[j].name)) {
5009 break;
5010 }
5011 }
5012 if (options[j].name == NULL) {
5013 error_report("unrecognized operand %s", arg);
5014 ret = -1;
5015 goto out;
5016 }
5017
5018 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5019 ret = -1;
5020 goto out;
5021 }
5022 dd.flags |= options[j].flag;
5023 g_free(arg);
5024 arg = NULL;
5025 }
5026
5027 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5028 error_report("Must specify both input and output files");
5029 ret = -1;
5030 goto out;
5031 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005032
5033 if (qemu_opts_foreach(&qemu_object_opts,
5034 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005035 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005036 ret = -1;
5037 goto out;
5038 }
5039
Fam Zheng335e9932017-05-03 00:35:39 +08005040 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5041 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005042
5043 if (!blk1) {
5044 ret = -1;
5045 goto out;
5046 }
5047
5048 drv = bdrv_find_format(out_fmt);
5049 if (!drv) {
5050 error_report("Unknown file format");
5051 ret = -1;
5052 goto out;
5053 }
5054 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5055
5056 if (!proto_drv) {
5057 error_report_err(local_err);
5058 ret = -1;
5059 goto out;
5060 }
5061 if (!drv->create_opts) {
5062 error_report("Format driver '%s' does not support image creation",
5063 drv->format_name);
5064 ret = -1;
5065 goto out;
5066 }
5067 if (!proto_drv->create_opts) {
5068 error_report("Protocol driver '%s' does not support image creation",
5069 proto_drv->format_name);
5070 ret = -1;
5071 goto out;
5072 }
5073 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5074 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5075
5076 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5077
5078 size = blk_getlength(blk1);
5079 if (size < 0) {
5080 error_report("Failed to get size for '%s'", in.filename);
5081 ret = -1;
5082 goto out;
5083 }
5084
5085 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5086 dd.count * in.bsz < size) {
5087 size = dd.count * in.bsz;
5088 }
5089
Reda Sallahif7c15532016-08-10 16:16:09 +02005090 /* Overflow means the specified offset is beyond input image's size */
5091 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5092 size < in.bsz * in.offset)) {
5093 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5094 } else {
5095 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5096 size - in.bsz * in.offset, &error_abort);
5097 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005098
5099 ret = bdrv_create(drv, out.filename, opts, &local_err);
5100 if (ret < 0) {
5101 error_reportf_err(local_err,
5102 "%s: error while creating output image: ",
5103 out.filename);
5104 ret = -1;
5105 goto out;
5106 }
5107
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005108 /* TODO, we can't honour --image-opts for the target,
5109 * since it needs to be given in a format compatible
5110 * with the bdrv_create() call above which does not
5111 * support image-opts style.
5112 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005113 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005114 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005115
5116 if (!blk2) {
5117 ret = -1;
5118 goto out;
5119 }
5120
Reda Sallahif7c15532016-08-10 16:16:09 +02005121 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5122 size < in.offset * in.bsz)) {
5123 /* We give a warning if the skip option is bigger than the input
5124 * size and create an empty output disk image (i.e. like dd(1)).
5125 */
5126 error_report("%s: cannot skip to specified offset", in.filename);
5127 in_pos = size;
5128 } else {
5129 in_pos = in.offset * in.bsz;
5130 }
5131
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005132 in.buf = g_new(uint8_t, in.bsz);
5133
Reda Sallahif7c15532016-08-10 16:16:09 +02005134 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005135 int in_ret, out_ret;
5136
5137 if (in_pos + in.bsz > size) {
5138 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5139 } else {
5140 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5141 }
5142 if (in_ret < 0) {
5143 error_report("error while reading from input image file: %s",
5144 strerror(-in_ret));
5145 ret = -1;
5146 goto out;
5147 }
5148 in_pos += in_ret;
5149
5150 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5151
5152 if (out_ret < 0) {
5153 error_report("error while writing to output image file: %s",
5154 strerror(-out_ret));
5155 ret = -1;
5156 goto out;
5157 }
5158 out_pos += out_ret;
5159 }
5160
5161out:
5162 g_free(arg);
5163 qemu_opts_del(opts);
5164 qemu_opts_free(create_opts);
5165 blk_unref(blk1);
5166 blk_unref(blk2);
5167 g_free(in.filename);
5168 g_free(out.filename);
5169 g_free(in.buf);
5170 g_free(out.buf);
5171
5172 if (ret) {
5173 return 1;
5174 }
5175 return 0;
5176}
5177
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005178static void dump_json_block_measure_info(BlockMeasureInfo *info)
5179{
5180 QString *str;
5181 QObject *obj;
5182 Visitor *v = qobject_output_visitor_new(&obj);
5183
5184 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5185 visit_complete(v, &obj);
5186 str = qobject_to_json_pretty(obj);
5187 assert(str != NULL);
5188 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005189 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005190 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005191 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005192}
5193
5194static int img_measure(int argc, char **argv)
5195{
5196 static const struct option long_options[] = {
5197 {"help", no_argument, 0, 'h'},
5198 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5199 {"object", required_argument, 0, OPTION_OBJECT},
5200 {"output", required_argument, 0, OPTION_OUTPUT},
5201 {"size", required_argument, 0, OPTION_SIZE},
5202 {"force-share", no_argument, 0, 'U'},
5203 {0, 0, 0, 0}
5204 };
5205 OutputFormat output_format = OFORMAT_HUMAN;
5206 BlockBackend *in_blk = NULL;
5207 BlockDriver *drv;
5208 const char *filename = NULL;
5209 const char *fmt = NULL;
5210 const char *out_fmt = "raw";
5211 char *options = NULL;
5212 char *snapshot_name = NULL;
5213 bool force_share = false;
5214 QemuOpts *opts = NULL;
5215 QemuOpts *object_opts = NULL;
5216 QemuOpts *sn_opts = NULL;
5217 QemuOptsList *create_opts = NULL;
5218 bool image_opts = false;
5219 uint64_t img_size = UINT64_MAX;
5220 BlockMeasureInfo *info = NULL;
5221 Error *local_err = NULL;
5222 int ret = 1;
5223 int c;
5224
5225 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5226 long_options, NULL)) != -1) {
5227 switch (c) {
5228 case '?':
5229 case 'h':
5230 help();
5231 break;
5232 case 'f':
5233 fmt = optarg;
5234 break;
5235 case 'O':
5236 out_fmt = optarg;
5237 break;
5238 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005239 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005240 goto out;
5241 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005242 break;
5243 case 'l':
5244 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5245 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5246 optarg, false);
5247 if (!sn_opts) {
5248 error_report("Failed in parsing snapshot param '%s'",
5249 optarg);
5250 goto out;
5251 }
5252 } else {
5253 snapshot_name = optarg;
5254 }
5255 break;
5256 case 'U':
5257 force_share = true;
5258 break;
5259 case OPTION_OBJECT:
5260 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5261 optarg, true);
5262 if (!object_opts) {
5263 goto out;
5264 }
5265 break;
5266 case OPTION_IMAGE_OPTS:
5267 image_opts = true;
5268 break;
5269 case OPTION_OUTPUT:
5270 if (!strcmp(optarg, "json")) {
5271 output_format = OFORMAT_JSON;
5272 } else if (!strcmp(optarg, "human")) {
5273 output_format = OFORMAT_HUMAN;
5274 } else {
5275 error_report("--output must be used with human or json "
5276 "as argument.");
5277 goto out;
5278 }
5279 break;
5280 case OPTION_SIZE:
5281 {
5282 int64_t sval;
5283
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005284 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005285 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005286 goto out;
5287 }
5288 img_size = (uint64_t)sval;
5289 }
5290 break;
5291 }
5292 }
5293
5294 if (qemu_opts_foreach(&qemu_object_opts,
5295 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005296 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005297 goto out;
5298 }
5299
5300 if (argc - optind > 1) {
5301 error_report("At most one filename argument is allowed.");
5302 goto out;
5303 } else if (argc - optind == 1) {
5304 filename = argv[optind];
5305 }
5306
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005307 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5308 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005309 goto out;
5310 }
5311 if (filename && img_size != UINT64_MAX) {
5312 error_report("--size N cannot be used together with a filename.");
5313 goto out;
5314 }
5315 if (!filename && img_size == UINT64_MAX) {
5316 error_report("Either --size N or one filename must be specified.");
5317 goto out;
5318 }
5319
5320 if (filename) {
5321 in_blk = img_open(image_opts, filename, fmt, 0,
5322 false, false, force_share);
5323 if (!in_blk) {
5324 goto out;
5325 }
5326
5327 if (sn_opts) {
5328 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5329 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5330 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5331 &local_err);
5332 } else if (snapshot_name != NULL) {
5333 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5334 snapshot_name, &local_err);
5335 }
5336 if (local_err) {
5337 error_reportf_err(local_err, "Failed to load snapshot: ");
5338 goto out;
5339 }
5340 }
5341
5342 drv = bdrv_find_format(out_fmt);
5343 if (!drv) {
5344 error_report("Unknown file format '%s'", out_fmt);
5345 goto out;
5346 }
5347 if (!drv->create_opts) {
5348 error_report("Format driver '%s' does not support image creation",
5349 drv->format_name);
5350 goto out;
5351 }
5352
5353 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5354 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5355 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5356 if (options) {
5357 qemu_opts_do_parse(opts, options, NULL, &local_err);
5358 if (local_err) {
5359 error_report_err(local_err);
5360 error_report("Invalid options for file format '%s'", out_fmt);
5361 goto out;
5362 }
5363 }
5364 if (img_size != UINT64_MAX) {
5365 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5366 }
5367
5368 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5369 if (local_err) {
5370 error_report_err(local_err);
5371 goto out;
5372 }
5373
5374 if (output_format == OFORMAT_HUMAN) {
5375 printf("required size: %" PRIu64 "\n", info->required);
5376 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005377 if (info->has_bitmaps) {
5378 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5379 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005380 } else {
5381 dump_json_block_measure_info(info);
5382 }
5383
5384 ret = 0;
5385
5386out:
5387 qapi_free_BlockMeasureInfo(info);
5388 qemu_opts_del(object_opts);
5389 qemu_opts_del(opts);
5390 qemu_opts_del(sn_opts);
5391 qemu_opts_free(create_opts);
5392 g_free(options);
5393 blk_unref(in_blk);
5394 return ret;
5395}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005396
Anthony Liguoric227f092009-10-01 16:12:16 -05005397static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005398#define DEF(option, callback, arg_string) \
5399 { option, callback },
5400#include "qemu-img-cmds.h"
5401#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005402 { NULL, NULL, },
5403};
5404
bellardea2384d2004-08-01 21:59:26 +00005405int main(int argc, char **argv)
5406{
Anthony Liguoric227f092009-10-01 16:12:16 -05005407 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005408 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005409 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005410 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005411 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005412 static const struct option long_options[] = {
5413 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005414 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005415 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005416 {0, 0, 0, 0}
5417 };
bellardea2384d2004-08-01 21:59:26 +00005418
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005419#ifdef CONFIG_POSIX
5420 signal(SIGPIPE, SIG_IGN);
5421#endif
5422
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005423 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005424 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005425 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005426
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005427 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005428 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005429 exit(EXIT_FAILURE);
5430 }
5431
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005432 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005433
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005434 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005435 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005436 if (argc < 2) {
5437 error_exit("Not enough arguments");
5438 }
Stuart Brady153859b2009-06-07 00:42:17 +01005439
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005440 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005441 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005442 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005443
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005444 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005445 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005446 case ':':
5447 missing_argument(argv[optind - 1]);
5448 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005449 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005450 unrecognized_option(argv[optind - 1]);
5451 return 0;
5452 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005453 help();
5454 return 0;
5455 case 'V':
5456 printf(QEMU_IMG_VERSION);
5457 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005458 case 'T':
5459 g_free(trace_file);
5460 trace_file = trace_opt_parse(optarg);
5461 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005462 }
bellardea2384d2004-08-01 21:59:26 +00005463 }
Stuart Brady153859b2009-06-07 00:42:17 +01005464
Denis V. Lunev10985132016-06-17 17:44:13 +03005465 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005466
Denis V. Lunev10985132016-06-17 17:44:13 +03005467 /* reset getopt_long scanning */
5468 argc -= optind;
5469 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005470 return 0;
5471 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005472 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005473 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005474
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005475 if (!trace_init_backends()) {
5476 exit(1);
5477 }
5478 trace_init_file(trace_file);
5479 qemu_set_log(LOG_TRACE);
5480
Denis V. Lunev10985132016-06-17 17:44:13 +03005481 /* find the command */
5482 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5483 if (!strcmp(cmdname, cmd->name)) {
5484 return cmd->handler(argc, argv);
5485 }
5486 }
Jeff Cody7db16892014-04-25 17:02:32 -04005487
Stuart Brady153859b2009-06-07 00:42:17 +01005488 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005489 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005490}