blob: 53bd32bf8fd196bd0e352b0b033cf377e4036460 [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,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020082 OPTION_FORCE = 276,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050083};
84
85typedef enum OutputFormat {
86 OFORMAT_JSON,
87 OFORMAT_HUMAN,
88} OutputFormat;
89
Kevin Wolfe6996142016-03-15 13:03:11 +010090/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040091#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000092
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010093static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000094{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010095 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000096}
97
Fam Zhengac1307a2014-04-22 13:36:11 +080098static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
99{
100 va_list ap;
101
Fam Zhengac1307a2014-04-22 13:36:11 +0800102 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200103 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800104 va_end(ap);
105
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200106 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800107 exit(EXIT_FAILURE);
108}
109
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800110static void QEMU_NORETURN missing_argument(const char *option)
111{
112 error_exit("missing argument for option '%s'", option);
113}
114
115static void QEMU_NORETURN unrecognized_option(const char *option)
116{
117 error_exit("unrecognized option '%s'", option);
118}
119
Eric Blake0562adf2020-05-12 20:16:41 -0500120/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800121static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000122{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100123 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400124 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300125 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300126 "QEMU disk image utility\n"
127 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300128 " '-h', '--help' display this help and exit\n"
129 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300130 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
131 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300132 "\n"
malc3f020d72010-02-08 12:04:56 +0300133 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100134#define DEF(option, callback, arg_string) \
135 " " arg_string "\n"
136#include "qemu-img-cmds.h"
137#undef DEF
malc3f020d72010-02-08 12:04:56 +0300138 "\n"
139 "Command parameters:\n"
140 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000141 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
142 " manual page for a description of the object properties. The most common\n"
143 " object type is a 'secret', which is used to supply passwords and/or\n"
144 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300145 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400146 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800147 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
148 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100149 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
150 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300151 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200152 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
153 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
154 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300155 " 'output_filename' is the destination disk image filename\n"
156 " 'output_fmt' is the destination format\n"
157 " 'options' is a comma separated list of format specific options in a\n"
158 " name=value format. Use -o ? for an overview of the options supported by the\n"
159 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800160 " 'snapshot_param' is param used for internal snapshot, format\n"
161 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
162 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300163 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400164 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
165 " new backing file match exactly. The image doesn't need a working\n"
166 " backing file before rebasing in this case (useful for renaming the\n"
167 " backing file). For image creation, allow creating without attempting\n"
168 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300169 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200170 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100171 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200172 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
173 " contain only zeros for qemu-img to create a sparse image during\n"
174 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
175 " unallocated or zero sectors, and the destination image will always be\n"
176 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200177 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100178 " '-n' skips the target volume creation (useful if the volume is created\n"
179 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300180 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500181 "Parameters to bitmap subcommand:\n"
182 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
183 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
184 " or '--merge source'\n"
185 " '-g granularity' sets the granularity for '--add' actions\n"
186 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
187 " bitmaps from an alternative file\n"
188 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200189 "Parameters to check subcommand:\n"
190 " '-r' tries to repair any inconsistencies that are found during the check.\n"
191 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
192 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200193 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200194 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100195 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500196 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100197 " '-m' specifies how many coroutines work in parallel during the convert\n"
198 " process (defaults to 8)\n"
199 " '-W' allow to write to the target out of order rather than sequential\n"
200 "\n"
malc3f020d72010-02-08 12:04:56 +0300201 "Parameters to snapshot subcommand:\n"
202 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
203 " '-a' applies a snapshot (revert disk to saved state)\n"
204 " '-c' creates a snapshot\n"
205 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100206 " '-l' lists all snapshots in the given image\n"
207 "\n"
208 "Parameters to compare subcommand:\n"
209 " '-f' first image format\n"
210 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200211 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
212 "\n"
213 "Parameters to dd subcommand:\n"
214 " 'bs=BYTES' read and write up to BYTES bytes at a time "
215 "(default: 512)\n"
216 " 'count=N' copy only N input blocks\n"
217 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200218 " 'of=FILE' write to FILE\n"
219 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100220
221 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300222 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500223 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800224 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000225}
226
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000227static QemuOptsList qemu_object_opts = {
228 .name = "object",
229 .implied_opt_name = "qom-type",
230 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
231 .desc = {
232 { }
233 },
234};
235
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200236static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
237{
238 if (user_creatable_print_help(type, opts)) {
239 exit(0);
240 }
241 return true;
242}
243
Markus Armbruster80c710c2020-04-15 09:49:26 +0200244/*
245 * Is @optarg safe for accumulate_options()?
246 * It is when multiple of them can be joined together separated by ','.
247 * To make that work, @optarg must not start with ',' (or else a
248 * separating ',' preceding it gets escaped), and it must not end with
249 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200250 * escaped), or be empty (or else a separating ',' preceding it can
251 * escape a separating ',' following it).
252 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200253 */
254static bool is_valid_option_list(const char *optarg)
255{
256 size_t len = strlen(optarg);
257 size_t i;
258
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200259 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200260 return false;
261 }
262
263 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
264 }
265 if ((len - i) % 2) {
266 return false;
267 }
268
269 return true;
270}
271
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200272static int accumulate_options(char **options, char *optarg)
273{
274 char *new_options;
275
276 if (!is_valid_option_list(optarg)) {
277 error_report("Invalid option list: %s", optarg);
278 return -1;
279 }
280
281 if (!*options) {
282 *options = g_strdup(optarg);
283 } else {
284 new_options = g_strdup_printf("%s,%s", *options, optarg);
285 g_free(*options);
286 *options = new_options;
287 }
288 return 0;
289}
290
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000291static QemuOptsList qemu_source_opts = {
292 .name = "source",
293 .implied_opt_name = "file",
294 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
295 .desc = {
296 { }
297 },
298};
299
Stefan Weil7c30f652013-06-16 17:01:05 +0200300static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100301{
302 int ret = 0;
303 if (!quiet) {
304 va_list args;
305 va_start(args, fmt);
306 ret = vprintf(fmt, args);
307 va_end(args);
308 }
309 return ret;
310}
311
bellardea2384d2004-08-01 21:59:26 +0000312
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100313static int print_block_option_help(const char *filename, const char *fmt)
314{
315 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800316 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500317 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100318
319 /* Find driver and parse its options */
320 drv = bdrv_find_format(fmt);
321 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100322 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100323 return 1;
324 }
325
Max Reitzd402b6a2018-05-09 23:00:21 +0200326 if (!drv->create_opts) {
327 error_report("Format driver '%s' does not support image creation", fmt);
328 return 1;
329 }
330
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800331 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100332 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500333 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100334 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100335 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800336 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100337 return 1;
338 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200339 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100340 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200341 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100342 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200343 return 1;
344 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800345 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100346 }
347
Max Reitzf4619af2019-04-13 17:20:37 +0200348 if (filename) {
349 printf("Supported options:\n");
350 } else {
351 printf("Supported %s options:\n", fmt);
352 }
Max Reitz63898712018-10-19 18:49:25 +0200353 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800354 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200355
356 if (!filename) {
357 printf("\n"
358 "The protocol level may support further options.\n"
359 "Specify the target filename to include those options.\n");
360 }
361
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100362 return 0;
363}
364
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000365
Max Reitzefaa7c42016-03-16 19:54:38 +0100366static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100367 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800368 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000369{
370 QDict *options;
371 Error *local_err = NULL;
372 BlockBackend *blk;
373 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800374 if (force_share) {
375 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200376 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800377 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200378 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800379 return NULL;
380 }
Max Reitz4615f872018-05-02 22:20:50 +0200381 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800382 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100383 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000384 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100385 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000386 return NULL;
387 }
Kevin Wolfce099542016-03-15 13:01:04 +0100388 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000389
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000390 return blk;
391}
392
Max Reitzefaa7c42016-03-16 19:54:38 +0100393static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100394 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000395 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800396 bool writethrough, bool quiet,
397 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000398{
399 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200400 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100401
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100402 if (!options) {
403 options = qdict_new();
404 }
bellard75c23802004-08-27 21:28:58 +0000405 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500406 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000407 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100408
Fam Zheng335e9932017-05-03 00:35:39 +0800409 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500410 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800411 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100412 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500413 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100414 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000415 return NULL;
bellard75c23802004-08-27 21:28:58 +0000416 }
Kevin Wolfce099542016-03-15 13:01:04 +0100417 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100418
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200419 return blk;
bellard75c23802004-08-27 21:28:58 +0000420}
421
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000422
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100423static int img_add_key_secrets(void *opaque,
424 const char *name, const char *value,
425 Error **errp)
426{
427 QDict *options = opaque;
428
429 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600430 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100431 }
432
433 return 0;
434}
435
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100436
Max Reitzefaa7c42016-03-16 19:54:38 +0100437static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000438 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100439 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800440 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000441{
442 BlockBackend *blk;
443 if (image_opts) {
444 QemuOpts *opts;
445 if (fmt) {
446 error_report("--image-opts and --format are mutually exclusive");
447 return NULL;
448 }
449 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
450 filename, true);
451 if (!opts) {
452 return NULL;
453 }
Fam Zheng335e9932017-05-03 00:35:39 +0800454 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
455 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000456 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100457 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800458 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000459 }
460 return blk;
461}
462
463
Chunyan Liu83d05212014-06-05 17:20:51 +0800464static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100465 const char *base_filename,
466 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200467{
Markus Armbruster6750e792015-02-12 17:43:08 +0100468 Error *err = NULL;
469
Kevin Wolfefa84d42009-05-18 16:42:12 +0200470 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100471 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100472 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100473 error_report("Backing file not supported for file format '%s'",
474 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100475 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900476 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200477 }
478 }
479 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100480 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100481 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100482 error_report("Backing file format not supported for file "
483 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100484 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900485 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200486 }
487 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900488 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200489}
490
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300491static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
492 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100493{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100494 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300495 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100496
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300497 err = qemu_strtosz(value, NULL, &res);
498 if (err < 0 && err != -ERANGE) {
499 error_report("Invalid %s specified. You may use "
500 "k, M, G, T, P or E suffixes for", name);
501 error_report("kilobytes, megabytes, gigabytes, terabytes, "
502 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100503 return err;
504 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300505 if (err == -ERANGE || res > max || res < min) {
506 error_report("Invalid %s specified. Must be between %" PRId64
507 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100508 return -ERANGE;
509 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300510 return res;
511}
512
513static int64_t cvtnum(const char *name, const char *value)
514{
515 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100516}
517
bellardea2384d2004-08-01 21:59:26 +0000518static int img_create(int argc, char **argv)
519{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200520 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100521 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000522 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000523 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000524 const char *filename;
525 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200526 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200527 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100528 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400529 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000530
bellardea2384d2004-08-01 21:59:26 +0000531 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000532 static const struct option long_options[] = {
533 {"help", no_argument, 0, 'h'},
534 {"object", required_argument, 0, OPTION_OBJECT},
535 {0, 0, 0, 0}
536 };
John Snow6e6e55f2017-07-17 20:34:22 -0400537 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000538 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100539 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000540 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100541 }
bellardea2384d2004-08-01 21:59:26 +0000542 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800543 case ':':
544 missing_argument(argv[optind - 1]);
545 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100546 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800547 unrecognized_option(argv[optind - 1]);
548 break;
bellardea2384d2004-08-01 21:59:26 +0000549 case 'h':
550 help();
551 break;
aliguori9230eaf2009-03-28 17:55:19 +0000552 case 'F':
553 base_fmt = optarg;
554 break;
bellardea2384d2004-08-01 21:59:26 +0000555 case 'b':
556 base_filename = optarg;
557 break;
558 case 'f':
559 fmt = optarg;
560 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200561 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200562 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100563 goto fail;
564 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200565 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100566 case 'q':
567 quiet = true;
568 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400569 case 'u':
570 flags |= BDRV_O_NO_BACKING;
571 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000572 case OPTION_OBJECT: {
573 QemuOpts *opts;
574 opts = qemu_opts_parse_noisily(&qemu_object_opts,
575 optarg, true);
576 if (!opts) {
577 goto fail;
578 }
579 } break;
bellardea2384d2004-08-01 21:59:26 +0000580 }
581 }
aliguori9230eaf2009-03-28 17:55:19 +0000582
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900583 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100584 filename = (optind < argc) ? argv[optind] : NULL;
585 if (options && has_help_option(options)) {
586 g_free(options);
587 return print_block_option_help(filename, fmt);
588 }
589
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100590 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800591 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100592 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100593 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900594
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000595 if (qemu_opts_foreach(&qemu_object_opts,
596 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200597 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000598 goto fail;
599 }
600
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100601 /* Get image size, if specified */
602 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100603 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100604
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300605 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100606 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100607 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100608 }
609 img_size = (uint64_t)sval;
610 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200611 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800612 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200613 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100614
Luiz Capitulino9b375252012-11-30 10:52:05 -0200615 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400616 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100617 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100618 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100619 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900620 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200621
Kevin Wolf77386bf2014-02-21 16:24:04 +0100622 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000623 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100624
625fail:
626 g_free(options);
627 return 1;
bellardea2384d2004-08-01 21:59:26 +0000628}
629
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100630static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500631{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500633 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100634 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600635
636 visit_type_ImageCheck(v, NULL, &check, &error_abort);
637 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500638 str = qobject_to_json_pretty(obj);
639 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100640 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200641 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600642 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200643 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500644}
645
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100646static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647{
648 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100649 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500650 } else {
651 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100652 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
653 "Data may be corrupted, or further writes to the image "
654 "may corrupt it.\n",
655 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500656 }
657
658 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100659 qprintf(quiet,
660 "\n%" PRId64 " leaked clusters were found on the image.\n"
661 "This means waste of disk space, but no harm to data.\n",
662 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500663 }
664
665 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100666 qprintf(quiet,
667 "\n%" PRId64
668 " internal errors have occurred during the check.\n",
669 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500670 }
671 }
672
673 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100674 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
675 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
676 check->allocated_clusters, check->total_clusters,
677 check->allocated_clusters * 100.0 / check->total_clusters,
678 check->fragmented_clusters * 100.0 / check->allocated_clusters,
679 check->compressed_clusters * 100.0 /
680 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500681 }
682
683 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100684 qprintf(quiet,
685 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 }
687}
688
689static int collect_image_check(BlockDriverState *bs,
690 ImageCheck *check,
691 const char *filename,
692 const char *fmt,
693 int fix)
694{
695 int ret;
696 BdrvCheckResult result;
697
698 ret = bdrv_check(bs, &result, fix);
699 if (ret < 0) {
700 return ret;
701 }
702
703 check->filename = g_strdup(filename);
704 check->format = g_strdup(bdrv_get_format_name(bs));
705 check->check_errors = result.check_errors;
706 check->corruptions = result.corruptions;
707 check->has_corruptions = result.corruptions != 0;
708 check->leaks = result.leaks;
709 check->has_leaks = result.leaks != 0;
710 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100711 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100713 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500714 check->image_end_offset = result.image_end_offset;
715 check->has_image_end_offset = result.image_end_offset != 0;
716 check->total_clusters = result.bfi.total_clusters;
717 check->has_total_clusters = result.bfi.total_clusters != 0;
718 check->allocated_clusters = result.bfi.allocated_clusters;
719 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
720 check->fragmented_clusters = result.bfi.fragmented_clusters;
721 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100722 check->compressed_clusters = result.bfi.compressed_clusters;
723 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500724
725 return 0;
726}
727
Kevin Wolfe076f332010-06-29 11:43:13 +0200728/*
729 * Checks an image for consistency. Exit codes:
730 *
Max Reitzd6635c42014-06-02 22:15:21 +0200731 * 0 - Check completed, image is good
732 * 1 - Check not completed because of internal errors
733 * 2 - Check completed, image is corrupted
734 * 3 - Check completed, image has leaked clusters, but is good otherwise
735 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200736 */
aliguori15859692009-04-21 23:11:53 +0000737static int img_check(int argc, char **argv)
738{
739 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500740 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200741 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200742 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000743 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200744 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100745 int flags = BDRV_O_CHECK;
746 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200747 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100748 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000749 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800750 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000751
752 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500753 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200754 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100755
aliguori15859692009-04-21 23:11:53 +0000756 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500757 int option_index = 0;
758 static const struct option long_options[] = {
759 {"help", no_argument, 0, 'h'},
760 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530761 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500762 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000763 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000764 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800765 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500766 {0, 0, 0, 0}
767 };
Fam Zheng335e9932017-05-03 00:35:39 +0800768 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500769 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100770 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000771 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100772 }
aliguori15859692009-04-21 23:11:53 +0000773 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800774 case ':':
775 missing_argument(argv[optind - 1]);
776 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100777 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800778 unrecognized_option(argv[optind - 1]);
779 break;
aliguori15859692009-04-21 23:11:53 +0000780 case 'h':
781 help();
782 break;
783 case 'f':
784 fmt = optarg;
785 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200786 case 'r':
787 flags |= BDRV_O_RDWR;
788
789 if (!strcmp(optarg, "leaks")) {
790 fix = BDRV_FIX_LEAKS;
791 } else if (!strcmp(optarg, "all")) {
792 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
793 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800794 error_exit("Unknown option value for -r "
795 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200796 }
797 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500798 case OPTION_OUTPUT:
799 output = optarg;
800 break;
Max Reitz40055952014-07-22 22:58:42 +0200801 case 'T':
802 cache = optarg;
803 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100804 case 'q':
805 quiet = true;
806 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800807 case 'U':
808 force_share = true;
809 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000810 case OPTION_OBJECT: {
811 QemuOpts *opts;
812 opts = qemu_opts_parse_noisily(&qemu_object_opts,
813 optarg, true);
814 if (!opts) {
815 return 1;
816 }
817 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000818 case OPTION_IMAGE_OPTS:
819 image_opts = true;
820 break;
aliguori15859692009-04-21 23:11:53 +0000821 }
822 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200823 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800824 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100825 }
aliguori15859692009-04-21 23:11:53 +0000826 filename = argv[optind++];
827
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500828 if (output && !strcmp(output, "json")) {
829 output_format = OFORMAT_JSON;
830 } else if (output && !strcmp(output, "human")) {
831 output_format = OFORMAT_HUMAN;
832 } else if (output) {
833 error_report("--output must be used with human or json as argument.");
834 return 1;
835 }
836
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000837 if (qemu_opts_foreach(&qemu_object_opts,
838 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200839 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000840 return 1;
841 }
842
Kevin Wolfce099542016-03-15 13:01:04 +0100843 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200844 if (ret < 0) {
845 error_report("Invalid source cache option: %s", cache);
846 return 1;
847 }
848
Fam Zheng335e9932017-05-03 00:35:39 +0800849 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
850 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200851 if (!blk) {
852 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900853 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200854 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500855
856 check = g_new0(ImageCheck, 1);
857 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200858
859 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200860 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200861 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500862 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200863 }
864
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500865 if (check->corruptions_fixed || check->leaks_fixed) {
866 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100867 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500868
869 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100870 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500871 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100872 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500873
874 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100875 qprintf(quiet,
876 "The following inconsistencies were found and repaired:\n\n"
877 " %" PRId64 " leaked clusters\n"
878 " %" PRId64 " corruptions\n\n"
879 "Double checking the fixed image now...\n",
880 check->leaks_fixed,
881 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500882 }
883
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800884 qapi_free_ImageCheck(check);
885 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500886 ret = collect_image_check(bs, check, filename, fmt, 0);
887
888 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100889 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500890 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100891 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200892 }
893
Max Reitz832390a2014-10-23 15:29:12 +0200894 if (!ret) {
895 switch (output_format) {
896 case OFORMAT_HUMAN:
897 dump_human_image_check(check, quiet);
898 break;
899 case OFORMAT_JSON:
900 dump_json_image_check(check, quiet);
901 break;
902 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500903 }
904
905 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200906 if (ret) {
907 error_report("Check failed: %s", strerror(-ret));
908 } else {
909 error_report("Check failed");
910 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500911 ret = 1;
912 goto fail;
913 }
914
915 if (check->corruptions) {
916 ret = 2;
917 } else if (check->leaks) {
918 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200919 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500920 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000921 }
922
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500923fail:
924 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200925 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500926 return ret;
aliguori15859692009-04-21 23:11:53 +0000927}
928
Max Reitzd4a32382014-10-24 15:57:37 +0200929typedef struct CommonBlockJobCBInfo {
930 BlockDriverState *bs;
931 Error **errp;
932} CommonBlockJobCBInfo;
933
934static void common_block_job_cb(void *opaque, int ret)
935{
936 CommonBlockJobCBInfo *cbi = opaque;
937
938 if (ret < 0) {
939 error_setg_errno(cbi->errp, -ret, "Block job failed");
940 }
Max Reitzd4a32382014-10-24 15:57:37 +0200941}
942
943static void run_block_job(BlockJob *job, Error **errp)
944{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200945 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800946 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200947
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200948 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200949 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200950 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200951 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200952 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300953 if (job->job.progress.total) {
954 progress = (float)job->job.progress.current /
955 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200956 }
957 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200958 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200959
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200960 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200961 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800962 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200963 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800964 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200965 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200966 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200967
sochin.jiang4172a002017-06-15 14:47:33 +0800968 /* publish completion progress only when success */
969 if (!ret) {
970 qemu_progress_print(100.f, 0);
971 }
Max Reitzd4a32382014-10-24 15:57:37 +0200972}
973
bellardea2384d2004-08-01 21:59:26 +0000974static int img_commit(int argc, char **argv)
975{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400976 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200977 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200978 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200979 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100980 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200981 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100982 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200983 Error *local_err = NULL;
984 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000985 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200986 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000987
988 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400989 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200990 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000991 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000992 static const struct option long_options[] = {
993 {"help", no_argument, 0, 'h'},
994 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000995 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000996 {0, 0, 0, 0}
997 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800998 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000999 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001000 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001001 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001002 }
bellardea2384d2004-08-01 21:59:26 +00001003 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001004 case ':':
1005 missing_argument(argv[optind - 1]);
1006 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001007 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001008 unrecognized_option(argv[optind - 1]);
1009 break;
bellardea2384d2004-08-01 21:59:26 +00001010 case 'h':
1011 help();
1012 break;
1013 case 'f':
1014 fmt = optarg;
1015 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001016 case 't':
1017 cache = optarg;
1018 break;
Max Reitz1b22bff2014-10-24 15:57:40 +02001019 case 'b':
1020 base = optarg;
1021 /* -b implies -d */
1022 drop = true;
1023 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001024 case 'd':
1025 drop = true;
1026 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001027 case 'p':
1028 progress = true;
1029 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001030 case 'q':
1031 quiet = true;
1032 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001033 case OPTION_OBJECT: {
1034 QemuOpts *opts;
1035 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1036 optarg, true);
1037 if (!opts) {
1038 return 1;
1039 }
1040 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001041 case OPTION_IMAGE_OPTS:
1042 image_opts = true;
1043 break;
bellardea2384d2004-08-01 21:59:26 +00001044 }
1045 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001046
1047 /* Progress is not shown in Quiet mode */
1048 if (quiet) {
1049 progress = false;
1050 }
1051
Kevin Wolffc11eb22013-08-05 10:53:04 +02001052 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001053 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001054 }
bellardea2384d2004-08-01 21:59:26 +00001055 filename = argv[optind++];
1056
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001057 if (qemu_opts_foreach(&qemu_object_opts,
1058 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001059 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001060 return 1;
1061 }
1062
Max Reitz9a86fe42014-10-24 15:57:38 +02001063 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001064 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001065 if (ret < 0) {
1066 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001067 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001068 }
1069
Fam Zheng335e9932017-05-03 00:35:39 +08001070 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1071 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001072 if (!blk) {
1073 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001074 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001075 bs = blk_bs(blk);
1076
Max Reitz687fa1d2014-10-24 15:57:39 +02001077 qemu_progress_init(progress, 1.f);
1078 qemu_progress_print(0.f, 100);
1079
Max Reitz1b22bff2014-10-24 15:57:40 +02001080 if (base) {
1081 base_bs = bdrv_find_backing_image(bs, base);
1082 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001083 error_setg(&local_err,
1084 "Did not find '%s' in the backing chain of '%s'",
1085 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001086 goto done;
1087 }
1088 } else {
1089 /* This is different from QMP, which by default uses the deepest file in
1090 * the backing chain (i.e., the very base); however, the traditional
1091 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001092 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001093 if (!base_bs) {
1094 error_setg(&local_err, "Image does not have a backing file");
1095 goto done;
1096 }
bellardea2384d2004-08-01 21:59:26 +00001097 }
1098
Max Reitzd4a32382014-10-24 15:57:37 +02001099 cbi = (CommonBlockJobCBInfo){
1100 .errp = &local_err,
1101 .bs = bs,
1102 };
1103
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001104 aio_context = bdrv_get_aio_context(bs);
1105 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001106 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001107 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001108 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001109 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001110 if (local_err) {
1111 goto done;
1112 }
1113
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001114 /* When the block job completes, the BlockBackend reference will point to
1115 * the old backing file. In order to avoid that the top image is already
1116 * deleted, so we can still empty it afterwards, increment the reference
1117 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001118 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001119 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001120 }
1121
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001122 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001123 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001124 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001125 if (local_err) {
1126 goto unref_backing;
1127 }
1128
Max Reitz2d97fde2020-04-29 16:11:26 +02001129 if (!drop) {
1130 BlockBackend *old_backing_blk;
1131
1132 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1133 &local_err);
1134 if (!old_backing_blk) {
1135 goto unref_backing;
1136 }
1137 ret = blk_make_empty(old_backing_blk, &local_err);
1138 blk_unref(old_backing_blk);
1139 if (ret == -ENOTSUP) {
1140 error_free(local_err);
1141 local_err = NULL;
1142 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001143 goto unref_backing;
1144 }
1145 }
1146
1147unref_backing:
1148 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001149 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001150 }
Max Reitzd4a32382014-10-24 15:57:37 +02001151
1152done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001153 qemu_progress_end();
1154
Markus Armbruster26f54e92014-10-07 13:59:04 +02001155 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001156
1157 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001158 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001159 return 1;
1160 }
Max Reitzd4a32382014-10-24 15:57:37 +02001161
1162 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001163 return 0;
1164}
1165
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001166/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001167 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1168 * of the first sector boundary within buf where the sector contains a
1169 * non-zero byte. This function is robust to a buffer that is not
1170 * sector-aligned.
1171 */
1172static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1173{
1174 int64_t i;
1175 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1176
1177 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1178 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1179 return i;
1180 }
1181 }
1182 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1183 return i;
1184 }
1185 return -1;
1186}
1187
1188/*
thsf58c7b32008-06-05 21:53:49 +00001189 * Returns true iff the first sector pointed to by 'buf' contains at least
1190 * a non-NUL byte.
1191 *
1192 * 'pnum' is set to the number of sectors (including and immediately following
1193 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001194 * The function will try to align the end offset to alignment boundaries so
1195 * that the request will at least end aligned and consequtive requests will
1196 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001197 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001198static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1199 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001200{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001201 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001202 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001203
1204 if (n <= 0) {
1205 *pnum = 0;
1206 return 0;
1207 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001208 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001209 for(i = 1; i < n; i++) {
1210 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001211 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001212 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001213 }
bellardea2384d2004-08-01 21:59:26 +00001214 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001215
1216 tail = (sector_num + i) & (alignment - 1);
1217 if (tail) {
1218 if (is_zero && i <= tail) {
1219 /* treat unallocated areas which only consist
1220 * of a small tail as allocated. */
1221 is_zero = false;
1222 }
1223 if (!is_zero) {
1224 /* align up end offset of allocated areas. */
1225 i += alignment - tail;
1226 i = MIN(i, n);
1227 } else {
1228 /* align down end offset of zero areas. */
1229 i -= tail;
1230 }
1231 }
bellardea2384d2004-08-01 21:59:26 +00001232 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001233 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001234}
1235
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001236/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001237 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1238 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1239 * breaking up write requests for only small sparse areas.
1240 */
1241static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001242 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001243{
1244 int ret;
1245 int num_checked, num_used;
1246
1247 if (n < min) {
1248 min = n;
1249 }
1250
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001251 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001252 if (!ret) {
1253 return ret;
1254 }
1255
1256 num_used = *pnum;
1257 buf += BDRV_SECTOR_SIZE * *pnum;
1258 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001259 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001260 num_checked = num_used;
1261
1262 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001263 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001264
1265 buf += BDRV_SECTOR_SIZE * *pnum;
1266 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001267 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001268 num_checked += *pnum;
1269 if (ret) {
1270 num_used = num_checked;
1271 } else if (*pnum >= min) {
1272 break;
1273 }
1274 }
1275
1276 *pnum = num_used;
1277 return 1;
1278}
1279
1280/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001281 * Compares two buffers sector by sector. Returns 0 if the first
1282 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001283 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001284 * pnum is set to the sector-aligned size of the buffer prefix that
1285 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001286 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001287static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1288 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001289{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001290 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001291 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001292
Eric Blakedc61cd32017-10-11 22:47:14 -05001293 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001294
Eric Blakedc61cd32017-10-11 22:47:14 -05001295 res = !!memcmp(buf1, buf2, i);
1296 while (i < bytes) {
1297 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001298
Eric Blakedc61cd32017-10-11 22:47:14 -05001299 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001300 break;
1301 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001302 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001303 }
1304
1305 *pnum = i;
1306 return res;
1307}
1308
Stefano Garzarella97ede572019-05-08 12:43:24 +02001309#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001310
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001311/*
1312 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1313 *
Eric Blake0608e402017-10-11 22:47:12 -05001314 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1315 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1316 * failure), and 4 on error (the exit status for read errors), after emitting
1317 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001319 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001320 * @param offset: Starting offset to check
1321 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001322 * @param filename: Name of disk file we are checking (logging purpose)
1323 * @param buffer: Allocated buffer for storing read data
1324 * @param quiet: Flag for quiet mode
1325 */
Eric Blakec41508e2017-10-11 22:47:13 -05001326static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1327 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001328 uint8_t *buffer, bool quiet)
1329{
Eric Blakedebb38a2017-10-11 22:47:11 -05001330 int ret = 0;
1331 int64_t idx;
1332
Eric Blakec41508e2017-10-11 22:47:13 -05001333 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001334 if (ret < 0) {
1335 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001336 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001337 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001338 }
Eric Blakec41508e2017-10-11 22:47:13 -05001339 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001340 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001341 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001342 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001343 return 1;
1344 }
1345
1346 return 0;
1347}
1348
1349/*
1350 * Compares two images. Exit codes:
1351 *
1352 * 0 - Images are identical
1353 * 1 - Images differ
1354 * >1 - Error occurred
1355 */
1356static int img_compare(int argc, char **argv)
1357{
Max Reitz40055952014-07-22 22:58:42 +02001358 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001359 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001360 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001361 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001362 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001363 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 int allocated1, allocated2;
1365 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1366 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001367 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001368 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001369 int64_t total_size;
1370 int64_t offset = 0;
1371 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001372 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001373 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001374 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001375 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001376
Max Reitz40055952014-07-22 22:58:42 +02001377 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001379 static const struct option long_options[] = {
1380 {"help", no_argument, 0, 'h'},
1381 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001382 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001383 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001384 {0, 0, 0, 0}
1385 };
Fam Zheng335e9932017-05-03 00:35:39 +08001386 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001387 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001388 if (c == -1) {
1389 break;
1390 }
1391 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001392 case ':':
1393 missing_argument(argv[optind - 1]);
1394 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001396 unrecognized_option(argv[optind - 1]);
1397 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001398 case 'h':
1399 help();
1400 break;
1401 case 'f':
1402 fmt1 = optarg;
1403 break;
1404 case 'F':
1405 fmt2 = optarg;
1406 break;
Max Reitz40055952014-07-22 22:58:42 +02001407 case 'T':
1408 cache = optarg;
1409 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001410 case 'p':
1411 progress = true;
1412 break;
1413 case 'q':
1414 quiet = true;
1415 break;
1416 case 's':
1417 strict = true;
1418 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001419 case 'U':
1420 force_share = true;
1421 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001422 case OPTION_OBJECT: {
1423 QemuOpts *opts;
1424 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1425 optarg, true);
1426 if (!opts) {
1427 ret = 2;
1428 goto out4;
1429 }
1430 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001431 case OPTION_IMAGE_OPTS:
1432 image_opts = true;
1433 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001434 }
1435 }
1436
1437 /* Progress is not shown in Quiet mode */
1438 if (quiet) {
1439 progress = false;
1440 }
1441
1442
Kevin Wolffc11eb22013-08-05 10:53:04 +02001443 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001444 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001445 }
1446 filename1 = argv[optind++];
1447 filename2 = argv[optind++];
1448
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001449 if (qemu_opts_foreach(&qemu_object_opts,
1450 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001451 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001452 ret = 2;
1453 goto out4;
1454 }
1455
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001456 /* Initialize before goto out */
1457 qemu_progress_init(progress, 2.0);
1458
Kevin Wolfce099542016-03-15 13:01:04 +01001459 flags = 0;
1460 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001461 if (ret < 0) {
1462 error_report("Invalid source cache option: %s", cache);
1463 ret = 2;
1464 goto out3;
1465 }
1466
Fam Zheng335e9932017-05-03 00:35:39 +08001467 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1468 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001469 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001470 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001471 goto out3;
1472 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001473
Fam Zheng335e9932017-05-03 00:35:39 +08001474 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1475 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001476 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001477 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001478 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001480 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001481 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001482
Max Reitzf1d3cd72015-02-05 13:58:18 -05001483 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1484 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001485 total_size1 = blk_getlength(blk1);
1486 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001487 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001488 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001489 ret = 4;
1490 goto out;
1491 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 total_size2 = blk_getlength(blk2);
1493 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001494 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001495 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001496 ret = 4;
1497 goto out;
1498 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 total_size = MIN(total_size1, total_size2);
1500 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501
1502 qemu_progress_print(0, 100);
1503
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505 ret = 1;
1506 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1507 goto out;
1508 }
1509
Eric Blake033d9fc2017-10-11 22:47:16 -05001510 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001511 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001512
Eric Blake033d9fc2017-10-11 22:47:16 -05001513 status1 = bdrv_block_status_above(bs1, NULL, offset,
1514 total_size1 - offset, &pnum1, NULL,
1515 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001516 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001517 ret = 3;
1518 error_report("Sector allocation test failed for %s", filename1);
1519 goto out;
1520 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001521 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522
Eric Blake033d9fc2017-10-11 22:47:16 -05001523 status2 = bdrv_block_status_above(bs2, NULL, offset,
1524 total_size2 - offset, &pnum2, NULL,
1525 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001526 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001527 ret = 3;
1528 error_report("Sector allocation test failed for %s", filename2);
1529 goto out;
1530 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001531 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001532
1533 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001534 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001535
Fam Zheng25ad8e62016-01-13 16:37:41 +08001536 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001537 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001538 ret = 1;
1539 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001540 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001541 goto out;
1542 }
1543 }
1544 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001545 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001546 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001548 int64_t pnum;
1549
Eric Blake033d9fc2017-10-11 22:47:16 -05001550 chunk = MIN(chunk, IO_BUF_SIZE);
1551 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552 if (ret < 0) {
1553 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001554 " of %s: %s",
1555 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001556 ret = 4;
1557 goto out;
1558 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001559 ret = blk_pread(blk2, offset, buf2, chunk);
1560 if (ret < 0) {
1561 error_report("Error while reading offset %" PRId64
1562 " of %s: %s",
1563 offset, filename2, strerror(-ret));
1564 ret = 4;
1565 goto out;
1566 }
1567 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1568 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001569 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001570 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001571 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001572 goto out;
1573 }
1574 }
1575 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001576 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001577 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001578 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001579 filename1, buf1, quiet);
1580 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001581 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001582 filename2, buf1, quiet);
1583 }
1584 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001585 goto out;
1586 }
1587 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001588 offset += chunk;
1589 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001590 }
1591
Eric Blake033d9fc2017-10-11 22:47:16 -05001592 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001593 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001594 const char *filename_over;
1595
1596 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001597 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001598 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001599 filename_over = filename1;
1600 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001601 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001602 filename_over = filename2;
1603 }
1604
Eric Blake033d9fc2017-10-11 22:47:16 -05001605 while (offset < progress_base) {
1606 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1607 progress_base - offset, &chunk,
1608 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001609 if (ret < 0) {
1610 ret = 3;
1611 error_report("Sector allocation test failed for %s",
1612 filename_over);
1613 goto out;
1614
1615 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001616 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001617 chunk = MIN(chunk, IO_BUF_SIZE);
1618 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001619 filename_over, buf1, quiet);
1620 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001621 goto out;
1622 }
1623 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001624 offset += chunk;
1625 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001626 }
1627 }
1628
1629 qprintf(quiet, "Images are identical.\n");
1630 ret = 0;
1631
1632out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001633 qemu_vfree(buf1);
1634 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001635 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001636out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001637 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001638out3:
1639 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001640out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001641 return ret;
1642}
1643
Eric Blake6c729dd2020-05-21 14:21:35 -05001644/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1645static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1646 const char *src_node, const char *src_name,
1647 Error **errp)
1648{
1649 BlockDirtyBitmapMergeSource *merge_src;
1650 BlockDirtyBitmapMergeSourceList *list;
1651
1652 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1653 merge_src->type = QTYPE_QDICT;
1654 merge_src->u.external.node = g_strdup(src_node);
1655 merge_src->u.external.name = g_strdup(src_name);
1656 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1657 list->value = merge_src;
1658 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1659 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1660}
1661
Kevin Wolf690c7302015-03-19 13:33:32 +01001662enum ImgConvertBlockStatus {
1663 BLK_DATA,
1664 BLK_ZERO,
1665 BLK_BACKING_FILE,
1666};
1667
Peter Lieven2d9187b2017-02-28 13:40:07 +01001668#define MAX_COROUTINES 16
1669
Kevin Wolf690c7302015-03-19 13:33:32 +01001670typedef struct ImgConvertState {
1671 BlockBackend **src;
1672 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001673 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001674 int64_t total_sectors;
1675 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001676 int64_t allocated_done;
1677 int64_t sector_num;
1678 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001679 enum ImgConvertBlockStatus status;
1680 int64_t sector_next_status;
1681 BlockBackend *target;
1682 bool has_zero_init;
1683 bool compressed;
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) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001728 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001729 } 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
Kevin Wolf690c7302015-03-19 13:33:32 +01002087 /* Allocate buffer for copied data. For compressed images, only one cluster
2088 * can be copied at a time. */
2089 if (s->compressed) {
2090 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2091 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002092 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002093 }
2094 s->buf_sectors = s->cluster_sectors;
2095 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002096
Kevin Wolf690c7302015-03-19 13:33:32 +01002097 while (sector_num < s->total_sectors) {
2098 n = convert_iteration_sectors(s, sector_num);
2099 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002100 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002101 }
Max Reitzaad15de2016-03-24 23:33:57 +01002102 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2103 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002104 s->allocated_sectors += n;
2105 }
2106 sector_num += n;
2107 }
2108
2109 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002110 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002111 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002112
Peter Lieven2d9187b2017-02-28 13:40:07 +01002113 qemu_co_mutex_init(&s->lock);
2114 for (i = 0; i < s->num_coroutines; i++) {
2115 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2116 s->wait_sector_num[i] = -1;
2117 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002118 }
2119
Anton Nefedovb91127e2017-04-26 11:33:15 +03002120 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002121 main_loop_wait(false);
2122 }
2123
2124 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002125 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002126 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002127 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002129 }
2130 }
2131
Peter Lieven2d9187b2017-02-28 13:40:07 +01002132 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002133}
2134
Eric Blake15e39ad2020-05-21 14:21:36 -05002135static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2136{
2137 BdrvDirtyBitmap *bm;
2138 Error *err = NULL;
2139
2140 FOR_EACH_DIRTY_BITMAP(src, bm) {
2141 const char *name;
2142
2143 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2144 continue;
2145 }
2146 name = bdrv_dirty_bitmap_name(bm);
2147 qmp_block_dirty_bitmap_add(dst->node_name, name,
2148 true, bdrv_dirty_bitmap_granularity(bm),
2149 true, true,
2150 true, !bdrv_dirty_bitmap_enabled(bm),
2151 &err);
2152 if (err) {
2153 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2154 return -1;
2155 }
2156
2157 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2158 &err);
2159 if (err) {
2160 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2161 return -1;
2162 }
2163 }
2164
2165 return 0;
2166}
2167
Peter Lieven6360ab22018-07-13 09:15:39 +02002168#define MAX_BUF_SECTORS 32768
2169
bellardea2384d2004-08-01 21:59:26 +00002170static int img_convert(int argc, char **argv)
2171{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002172 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002173 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002174 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2175 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002176 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002177 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002178 BlockDriverState *out_bs;
2179 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002180 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002181 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002182 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002183 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002184 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002185 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002186 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002187 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002188 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002189 bool bitmaps = false;
bellardea2384d2004-08-01 21:59:26 +00002190
Peter Lieven9fd77f92017-04-21 11:11:55 +02002191 ImgConvertState s = (ImgConvertState) {
2192 /* Need at least 4k of zeros for sparse detection */
2193 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002194 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002195 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2196 .wr_in_order = true,
2197 .num_coroutines = 8,
2198 };
2199
bellardea2384d2004-08-01 21:59:26 +00002200 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002201 static const struct option long_options[] = {
2202 {"help", no_argument, 0, 'h'},
2203 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002204 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002205 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002206 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002207 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002208 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002209 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002210 {0, 0, 0, 0}
2211 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002212 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002213 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002214 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002215 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002216 }
bellardea2384d2004-08-01 21:59:26 +00002217 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002218 case ':':
2219 missing_argument(argv[optind - 1]);
2220 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002221 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002222 unrecognized_option(argv[optind - 1]);
2223 break;
bellardea2384d2004-08-01 21:59:26 +00002224 case 'h':
2225 help();
2226 break;
2227 case 'f':
2228 fmt = optarg;
2229 break;
2230 case 'O':
2231 out_fmt = optarg;
2232 break;
thsf58c7b32008-06-05 21:53:49 +00002233 case 'B':
2234 out_baseimg = optarg;
2235 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002236 case 'C':
2237 s.copy_range = true;
2238 break;
bellardea2384d2004-08-01 21:59:26 +00002239 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002240 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002241 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002242 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002243 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002244 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002245 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002246 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002247 case 'l':
2248 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002249 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2250 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002251 if (!sn_opts) {
2252 error_report("Failed in parsing snapshot param '%s'",
2253 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002254 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002255 }
2256 } else {
2257 snapshot_name = optarg;
2258 }
2259 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002260 case 'S':
2261 {
2262 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002263
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002264 sval = cvtnum("buffer size for sparse output", optarg);
2265 if (sval < 0) {
2266 goto fail_getopt;
2267 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002268 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2269 error_report("Invalid buffer size for sparse output specified. "
2270 "Valid sizes are multiples of %llu up to %llu. Select "
2271 "0 to disable sparse detection (fully allocates output).",
2272 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002273 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002274 }
2275
Peter Lieven9fd77f92017-04-21 11:11:55 +02002276 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002277 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002278 break;
2279 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002280 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002281 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002282 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002283 case 't':
2284 cache = optarg;
2285 break;
Max Reitz40055952014-07-22 22:58:42 +02002286 case 'T':
2287 src_cache = optarg;
2288 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002289 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002290 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002291 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002292 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002293 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002294 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002295 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002296 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2297 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002298 error_report("Invalid number of coroutines. Allowed number of"
2299 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002300 goto fail_getopt;
2301 }
2302 break;
2303 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002304 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002305 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002306 case 'U':
2307 force_share = true;
2308 break;
Max Reitz3258b912017-04-26 15:46:47 +02002309 case OPTION_OBJECT: {
2310 QemuOpts *object_opts;
2311 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2312 optarg, true);
2313 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002314 goto fail_getopt;
2315 }
2316 break;
Max Reitz3258b912017-04-26 15:46:47 +02002317 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002318 case OPTION_IMAGE_OPTS:
2319 image_opts = true;
2320 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002321 case OPTION_SALVAGE:
2322 s.salvage = true;
2323 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002324 case OPTION_TARGET_IMAGE_OPTS:
2325 tgt_image_opts = true;
2326 break;
David Edmondson168468f2020-02-05 11:02:48 +00002327 case OPTION_TARGET_IS_ZERO:
2328 /*
2329 * The user asserting that the target is blank has the
2330 * same effect as the target driver supporting zero
2331 * initialisation.
2332 */
2333 s.has_zero_init = true;
2334 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002335 case OPTION_BITMAPS:
2336 bitmaps = true;
2337 break;
bellardea2384d2004-08-01 21:59:26 +00002338 }
2339 }
ths3b46e622007-09-17 08:09:54 +00002340
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002341 if (!out_fmt && !tgt_image_opts) {
2342 out_fmt = "raw";
2343 }
2344
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002345 if (qemu_opts_foreach(&qemu_object_opts,
2346 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002347 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002348 goto fail_getopt;
2349 }
2350
Fam Zhenge11ce122018-07-27 11:34:01 +08002351 if (s.compressed && s.copy_range) {
2352 error_report("Cannot enable copy offloading when -c is used");
2353 goto fail_getopt;
2354 }
2355
2356 if (explict_min_sparse && s.copy_range) {
2357 error_report("Cannot enable copy offloading when -S is used");
2358 goto fail_getopt;
2359 }
2360
Max Reitz8eaac022019-05-07 22:35:03 +02002361 if (s.copy_range && s.salvage) {
2362 error_report("Cannot use copy offloading in salvaging mode");
2363 goto fail_getopt;
2364 }
2365
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002366 if (tgt_image_opts && !skip_create) {
2367 error_report("--target-image-opts requires use of -n flag");
2368 goto fail_getopt;
2369 }
2370
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002371 if (skip_create && options) {
2372 warn_report("-o has no effect when skipping image creation");
2373 warn_report("This will become an error in future QEMU versions.");
2374 }
2375
David Edmondson168468f2020-02-05 11:02:48 +00002376 if (s.has_zero_init && !skip_create) {
2377 error_report("--target-is-zero requires use of -n flag");
2378 goto fail_getopt;
2379 }
2380
Peter Lieven9fd77f92017-04-21 11:11:55 +02002381 s.src_num = argc - optind - 1;
2382 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2383
2384 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002385 if (out_fmt) {
2386 ret = print_block_option_help(out_filename, out_fmt);
2387 goto fail_getopt;
2388 } else {
2389 error_report("Option help requires a format be specified");
2390 goto fail_getopt;
2391 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002392 }
2393
2394 if (s.src_num < 1) {
2395 error_report("Must specify image file name");
2396 goto fail_getopt;
2397 }
2398
Peter Lieven9fd77f92017-04-21 11:11:55 +02002399 /* ret is still -EINVAL until here */
2400 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2401 if (ret < 0) {
2402 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002403 goto fail_getopt;
2404 }
2405
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002406 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002407 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002408 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002409 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002410 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002411 qemu_progress_print(0, 100);
2412
Peter Lieven9fd77f92017-04-21 11:11:55 +02002413 s.src = g_new0(BlockBackend *, s.src_num);
2414 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002415
Peter Lieven9fd77f92017-04-21 11:11:55 +02002416 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2417 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002418 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002419 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002420 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002421 ret = -1;
2422 goto out;
2423 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002424 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2425 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002426 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002427 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002428 ret = -1;
2429 goto out;
2430 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002431 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002432 }
bellardea2384d2004-08-01 21:59:26 +00002433
Wenchao Xiaef806542013-12-04 17:10:57 +08002434 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002435 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002436 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2437 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2438 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002439 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002440 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002441 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002442 ret = -1;
2443 goto out;
2444 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002445
Peter Lieven9fd77f92017-04-21 11:11:55 +02002446 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2447 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002448 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002449 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002450 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002451 ret = -1;
2452 goto out;
edison51ef6722010-09-21 19:58:41 -07002453 }
2454
Max Reitz2e024cd2015-02-11 09:58:46 -05002455 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002456 /* Find driver and parse its options */
2457 drv = bdrv_find_format(out_fmt);
2458 if (!drv) {
2459 error_report("Unknown file format '%s'", out_fmt);
2460 ret = -1;
2461 goto out;
2462 }
2463
2464 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2465 if (!proto_drv) {
2466 error_report_err(local_err);
2467 ret = -1;
2468 goto out;
2469 }
2470
Max Reitz2e024cd2015-02-11 09:58:46 -05002471 if (!drv->create_opts) {
2472 error_report("Format driver '%s' does not support image creation",
2473 drv->format_name);
2474 ret = -1;
2475 goto out;
2476 }
Max Reitzf75613c2014-12-02 18:32:46 +01002477
Max Reitz2e024cd2015-02-11 09:58:46 -05002478 if (!proto_drv->create_opts) {
2479 error_report("Protocol driver '%s' does not support image creation",
2480 proto_drv->format_name);
2481 ret = -1;
2482 goto out;
2483 }
Max Reitzf75613c2014-12-02 18:32:46 +01002484
Max Reitz2e024cd2015-02-11 09:58:46 -05002485 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2486 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002487
Max Reitz2e024cd2015-02-11 09:58:46 -05002488 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002489 if (options) {
2490 qemu_opts_do_parse(opts, options, NULL, &local_err);
2491 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002492 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002493 ret = -1;
2494 goto out;
2495 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002496 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002497
Peter Lieven9fd77f92017-04-21 11:11:55 +02002498 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002499 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002500 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2501 if (ret < 0) {
2502 goto out;
2503 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002504 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002505
Kevin Wolfa18953f2010-10-14 15:46:04 +02002506 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002507 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002508 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002509 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002510 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002511 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002512
David Edmondson168468f2020-02-05 11:02:48 +00002513 if (s.has_zero_init && s.target_has_backing) {
2514 error_report("Cannot use --target-is-zero when the destination "
2515 "image has a backing file");
2516 goto out;
2517 }
2518
Max Reitz48758a82017-04-26 15:46:48 +02002519 if (s.src_num > 1 && out_baseimg) {
2520 error_report("Having a backing file for the target makes no sense when "
2521 "concatenating multiple input images");
2522 ret = -1;
2523 goto out;
2524 }
2525
Kevin Wolfefa84d42009-05-18 16:42:12 +02002526 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002527 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002528 bool encryption =
2529 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002530 const char *encryptfmt =
2531 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002532 const char *preallocation =
2533 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002534
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002535 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002536 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002537 ret = -1;
2538 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002539 }
2540
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002541 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002542 error_report("Compression and encryption not supported at "
2543 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002544 ret = -1;
2545 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002546 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002547
Chunyan Liu83d05212014-06-05 17:20:51 +08002548 if (preallocation
2549 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002550 {
2551 error_report("Compression and preallocation not supported at "
2552 "the same time");
2553 ret = -1;
2554 goto out;
2555 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002556 }
2557
Eric Blake15e39ad2020-05-21 14:21:36 -05002558 /* Determine if bitmaps need copying */
2559 if (bitmaps) {
2560 if (s.src_num > 1) {
2561 error_report("Copying bitmaps only possible with single source");
2562 ret = -1;
2563 goto out;
2564 }
2565 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2566 error_report("Source lacks bitmap support");
2567 ret = -1;
2568 goto out;
2569 }
2570 }
2571
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002572 /*
2573 * The later open call will need any decryption secrets, and
2574 * bdrv_create() will purge "opts", so extract them now before
2575 * they are lost.
2576 */
2577 if (!skip_create) {
2578 open_opts = qdict_new();
2579 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002580
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002581 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002582 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002583 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002584 error_reportf_err(local_err, "%s: error while converting %s: ",
2585 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002586 goto out;
bellardea2384d2004-08-01 21:59:26 +00002587 }
2588 }
ths3b46e622007-09-17 08:09:54 +00002589
Max Reitz4d7c4872019-07-24 19:12:29 +02002590 s.target_is_new = !skip_create;
2591
Peter Lieven9fd77f92017-04-21 11:11:55 +02002592 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002593 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002594 if (ret < 0) {
2595 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002596 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002597 }
2598
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002599 if (skip_create) {
2600 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002601 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002602 } else {
2603 /* TODO ultimately we should allow --target-image-opts
2604 * to be used even when -n is not given.
2605 * That has to wait for bdrv_create to be improved
2606 * to allow filenames in option syntax
2607 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002608 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002609 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002610 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002611 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002612 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002613 ret = -1;
2614 goto out;
2615 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002616 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002617
Eric Blake15e39ad2020-05-21 14:21:36 -05002618 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2619 error_report("Format driver '%s' does not support bitmaps",
2620 out_bs->drv->format_name);
2621 ret = -1;
2622 goto out;
2623 }
2624
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002625 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002626 error_report("Compression not supported for this file format");
2627 ret = -1;
2628 goto out;
2629 }
2630
Eric Blake5def6b82016-06-23 16:37:19 -06002631 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002632 * or discard_alignment of the out_bs is greater. Limit to
2633 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2634 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002635 MAX(s.buf_sectors,
2636 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2637 out_bs->bl.pdiscard_alignment >>
2638 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002639
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002640 /* try to align the write requests to the destination to avoid unnecessary
2641 * RMW cycles. */
2642 s.alignment = MAX(pow2floor(s.min_sparse),
2643 DIV_ROUND_UP(out_bs->bl.request_alignment,
2644 BDRV_SECTOR_SIZE));
2645 assert(is_power_of_2(s.alignment));
2646
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002647 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002648 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002649 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002650 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002651 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002652 ret = -1;
2653 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002654 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002655 error_report("output file is smaller than input file");
2656 ret = -1;
2657 goto out;
2658 }
2659 }
2660
Max Reitzc69291e2020-01-21 16:59:14 +01002661 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002662 /* Errors are treated as "backing length unknown" (which means
2663 * s.target_backing_sectors has to be negative, which it will
2664 * be automatically). The backing file length is used only
2665 * for optimizations, so such a case is not fatal. */
2666 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2667 } else {
2668 s.target_backing_sectors = -1;
2669 }
2670
Peter Lieven24f833c2013-11-27 11:07:07 +01002671 ret = bdrv_get_info(out_bs, &bdi);
2672 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002673 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002674 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002675 goto out;
2676 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002677 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002678 s.compressed = s.compressed || bdi.needs_compressed_writes;
2679 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002680 }
2681
Peter Lieven9fd77f92017-04-21 11:11:55 +02002682 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002683
2684 /* Now copy the bitmaps */
2685 if (bitmaps && ret == 0) {
2686 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2687 }
2688
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002689out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002690 if (!ret) {
2691 qemu_progress_print(100, 0);
2692 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002693 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002694 qemu_opts_del(opts);
2695 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002696 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002697 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002698 blk_unref(s.target);
2699 if (s.src) {
2700 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2701 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002702 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002703 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002704 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002705 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002706fail_getopt:
2707 g_free(options);
2708
Peter Lieven9fd77f92017-04-21 11:11:55 +02002709 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002710}
2711
bellard57d1a2b2004-08-03 21:15:11 +00002712
bellardfaea38e2006-08-05 21:31:00 +00002713static void dump_snapshots(BlockDriverState *bs)
2714{
2715 QEMUSnapshotInfo *sn_tab, *sn;
2716 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002717
2718 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2719 if (nb_sns <= 0)
2720 return;
2721 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002722 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002723 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002724 for(i = 0; i < nb_sns; i++) {
2725 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002726 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002727 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002728 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002729 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002730}
2731
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002732static void dump_json_image_info_list(ImageInfoList *list)
2733{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002734 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002735 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002736 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002737
2738 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2739 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002740 str = qobject_to_json_pretty(obj);
2741 assert(str != NULL);
2742 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002743 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002744 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002745 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002746}
2747
Benoît Canetc054b3f2012-09-05 13:09:02 +02002748static void dump_json_image_info(ImageInfo *info)
2749{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002750 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002751 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002752 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002753
2754 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2755 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002756 str = qobject_to_json_pretty(obj);
2757 assert(str != NULL);
2758 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002759 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002760 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002761 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002762}
2763
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002764static void dump_human_image_info_list(ImageInfoList *list)
2765{
2766 ImageInfoList *elem;
2767 bool delim = false;
2768
2769 for (elem = list; elem; elem = elem->next) {
2770 if (delim) {
2771 printf("\n");
2772 }
2773 delim = true;
2774
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002775 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002776 }
2777}
2778
2779static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2780{
2781 return strcmp(a, b) == 0;
2782}
2783
2784/**
2785 * Open an image file chain and return an ImageInfoList
2786 *
2787 * @filename: topmost image filename
2788 * @fmt: topmost image format (may be NULL to autodetect)
2789 * @chain: true - enumerate entire backing file chain
2790 * false - only topmost image file
2791 *
2792 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2793 * image file. If there was an error a message will have been printed to
2794 * stderr.
2795 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002796static ImageInfoList *collect_image_info_list(bool image_opts,
2797 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002798 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002799 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002800{
2801 ImageInfoList *head = NULL;
2802 ImageInfoList **last = &head;
2803 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002804 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002805
2806 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2807
2808 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002809 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002810 BlockDriverState *bs;
2811 ImageInfo *info;
2812 ImageInfoList *elem;
2813
2814 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2815 error_report("Backing file '%s' creates an infinite loop.",
2816 filename);
2817 goto err;
2818 }
2819 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2820
Max Reitzefaa7c42016-03-16 19:54:38 +01002821 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002822 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2823 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002824 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002825 goto err;
2826 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002827 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002828
Wenchao Xia43526ec2013-06-06 12:27:58 +08002829 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002830 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002831 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002832 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002833 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002834 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002835
2836 elem = g_new0(ImageInfoList, 1);
2837 elem->value = info;
2838 *last = elem;
2839 last = &elem->next;
2840
Markus Armbruster26f54e92014-10-07 13:59:04 +02002841 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002842
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002843 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002844 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002845 image_opts = false;
2846
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002847 if (chain) {
2848 if (info->has_full_backing_filename) {
2849 filename = info->full_backing_filename;
2850 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002851 error_report("Could not determine absolute backing filename,"
2852 " but backing filename '%s' present",
2853 info->backing_filename);
2854 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002855 }
2856 if (info->has_backing_filename_format) {
2857 fmt = info->backing_filename_format;
2858 }
2859 }
2860 }
2861 g_hash_table_destroy(filenames);
2862 return head;
2863
2864err:
2865 qapi_free_ImageInfoList(head);
2866 g_hash_table_destroy(filenames);
2867 return NULL;
2868}
2869
Benoît Canetc054b3f2012-09-05 13:09:02 +02002870static int img_info(int argc, char **argv)
2871{
2872 int c;
2873 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002874 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002875 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002876 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002877 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002878 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002879
bellardea2384d2004-08-01 21:59:26 +00002880 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002881 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002882 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002883 int option_index = 0;
2884 static const struct option long_options[] = {
2885 {"help", no_argument, 0, 'h'},
2886 {"format", required_argument, 0, 'f'},
2887 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002888 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002889 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002890 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002891 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002892 {0, 0, 0, 0}
2893 };
Fam Zheng335e9932017-05-03 00:35:39 +08002894 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002895 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002896 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002897 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002898 }
bellardea2384d2004-08-01 21:59:26 +00002899 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002900 case ':':
2901 missing_argument(argv[optind - 1]);
2902 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002903 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002904 unrecognized_option(argv[optind - 1]);
2905 break;
bellardea2384d2004-08-01 21:59:26 +00002906 case 'h':
2907 help();
2908 break;
2909 case 'f':
2910 fmt = optarg;
2911 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002912 case 'U':
2913 force_share = true;
2914 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002915 case OPTION_OUTPUT:
2916 output = optarg;
2917 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002918 case OPTION_BACKING_CHAIN:
2919 chain = true;
2920 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002921 case OPTION_OBJECT: {
2922 QemuOpts *opts;
2923 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2924 optarg, true);
2925 if (!opts) {
2926 return 1;
2927 }
2928 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002929 case OPTION_IMAGE_OPTS:
2930 image_opts = true;
2931 break;
bellardea2384d2004-08-01 21:59:26 +00002932 }
2933 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002934 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002935 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002936 }
bellardea2384d2004-08-01 21:59:26 +00002937 filename = argv[optind++];
2938
Benoît Canetc054b3f2012-09-05 13:09:02 +02002939 if (output && !strcmp(output, "json")) {
2940 output_format = OFORMAT_JSON;
2941 } else if (output && !strcmp(output, "human")) {
2942 output_format = OFORMAT_HUMAN;
2943 } else if (output) {
2944 error_report("--output must be used with human or json as argument.");
2945 return 1;
2946 }
2947
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002948 if (qemu_opts_foreach(&qemu_object_opts,
2949 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002950 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002951 return 1;
2952 }
2953
Fam Zheng335e9932017-05-03 00:35:39 +08002954 list = collect_image_info_list(image_opts, filename, fmt, chain,
2955 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002956 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002957 return 1;
2958 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002959
Benoît Canetc054b3f2012-09-05 13:09:02 +02002960 switch (output_format) {
2961 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002962 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002963 break;
2964 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002965 if (chain) {
2966 dump_json_image_info_list(list);
2967 } else {
2968 dump_json_image_info(list->value);
2969 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002970 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002971 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002972
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002973 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002974 return 0;
2975}
2976
Eric Blake30065d12019-03-26 13:40:43 -05002977static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2978 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002979{
2980 switch (output_format) {
2981 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002982 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002983 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002984 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002985 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002986 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002987 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002988 e->start, e->length,
2989 e->has_offset ? e->offset : 0,
2990 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002991 }
2992 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2993 * Modify the flags here to allow more coalescing.
2994 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002995 if (next && (!next->data || next->zero)) {
2996 next->data = false;
2997 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002998 }
2999 break;
3000 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003001 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08003002 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003003 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08003004 e->zero ? "true" : "false",
3005 e->data ? "true" : "false");
3006 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003007 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003008 }
3009 putchar('}');
3010
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003011 if (next) {
3012 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003013 }
3014 break;
3015 }
Eric Blake30065d12019-03-26 13:40:43 -05003016 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003017}
3018
Eric Blake5e344dd2017-10-11 22:47:02 -05003019static int get_block_status(BlockDriverState *bs, int64_t offset,
3020 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003021{
Eric Blake237d78f2017-10-11 22:47:03 -05003022 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003023 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003024 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003025 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003026 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003027 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003028
3029 /* As an optimization, we could cache the current range of unallocated
3030 * clusters in each file of the chain, and avoid querying the same
3031 * range repeatedly.
3032 */
3033
3034 depth = 0;
3035 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05003036 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003037 if (ret < 0) {
3038 return ret;
3039 }
Eric Blake237d78f2017-10-11 22:47:03 -05003040 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003041 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3042 break;
3043 }
Kevin Wolf760e0062015-06-17 14:55:21 +02003044 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045 if (bs == NULL) {
3046 ret = 0;
3047 break;
3048 }
3049
3050 depth++;
3051 }
3052
John Snow28756452016-02-05 13:12:33 -05003053 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3054
Max Reitzf30c66b2019-02-01 20:29:05 +01003055 if (file && has_offset) {
3056 bdrv_refresh_filename(file);
3057 filename = file->filename;
3058 }
3059
John Snow28756452016-02-05 13:12:33 -05003060 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003061 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003062 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003063 .data = !!(ret & BDRV_BLOCK_DATA),
3064 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003065 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003066 .has_offset = has_offset,
3067 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01003068 .has_filename = filename,
3069 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003070 };
3071
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003072 return 0;
3073}
3074
Fam Zheng16b0d552016-01-26 11:59:02 +08003075static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3076{
3077 if (curr->length == 0) {
3078 return false;
3079 }
3080 if (curr->zero != next->zero ||
3081 curr->data != next->data ||
3082 curr->depth != next->depth ||
3083 curr->has_filename != next->has_filename ||
3084 curr->has_offset != next->has_offset) {
3085 return false;
3086 }
3087 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3088 return false;
3089 }
3090 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3091 return false;
3092 }
3093 return true;
3094}
3095
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003096static int img_map(int argc, char **argv)
3097{
3098 int c;
3099 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003100 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003101 BlockDriverState *bs;
3102 const char *filename, *fmt, *output;
3103 int64_t length;
3104 MapEntry curr = { .length = 0 }, next;
3105 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003106 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003107 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003108 int64_t start_offset = 0;
3109 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003110
3111 fmt = NULL;
3112 output = NULL;
3113 for (;;) {
3114 int option_index = 0;
3115 static const struct option long_options[] = {
3116 {"help", no_argument, 0, 'h'},
3117 {"format", required_argument, 0, 'f'},
3118 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003119 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003120 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003121 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003122 {"start-offset", required_argument, 0, 's'},
3123 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003124 {0, 0, 0, 0}
3125 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003126 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003127 long_options, &option_index);
3128 if (c == -1) {
3129 break;
3130 }
3131 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003132 case ':':
3133 missing_argument(argv[optind - 1]);
3134 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003135 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003136 unrecognized_option(argv[optind - 1]);
3137 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003138 case 'h':
3139 help();
3140 break;
3141 case 'f':
3142 fmt = optarg;
3143 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003144 case 'U':
3145 force_share = true;
3146 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003147 case OPTION_OUTPUT:
3148 output = optarg;
3149 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003150 case 's':
3151 start_offset = cvtnum("start offset", optarg);
3152 if (start_offset < 0) {
3153 return 1;
3154 }
3155 break;
3156 case 'l':
3157 max_length = cvtnum("max length", optarg);
3158 if (max_length < 0) {
3159 return 1;
3160 }
3161 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003162 case OPTION_OBJECT: {
3163 QemuOpts *opts;
3164 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3165 optarg, true);
3166 if (!opts) {
3167 return 1;
3168 }
3169 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003170 case OPTION_IMAGE_OPTS:
3171 image_opts = true;
3172 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003173 }
3174 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003175 if (optind != argc - 1) {
3176 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003177 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003178 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003179
3180 if (output && !strcmp(output, "json")) {
3181 output_format = OFORMAT_JSON;
3182 } else if (output && !strcmp(output, "human")) {
3183 output_format = OFORMAT_HUMAN;
3184 } else if (output) {
3185 error_report("--output must be used with human or json as argument.");
3186 return 1;
3187 }
3188
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003189 if (qemu_opts_foreach(&qemu_object_opts,
3190 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003191 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003192 return 1;
3193 }
3194
Fam Zheng335e9932017-05-03 00:35:39 +08003195 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003196 if (!blk) {
3197 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003198 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003199 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003200
3201 if (output_format == OFORMAT_HUMAN) {
3202 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003203 } else if (output_format == OFORMAT_JSON) {
3204 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003205 }
3206
Max Reitzf1d3cd72015-02-05 13:58:18 -05003207 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003208 if (length < 0) {
3209 error_report("Failed to get size for '%s'", filename);
3210 return 1;
3211 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003212 if (max_length != -1) {
3213 length = MIN(start_offset + max_length, length);
3214 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003215
Eyal Moscovicic0469492020-05-13 16:36:29 +03003216 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003217 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003218 int64_t offset = curr.start + curr.length;
3219 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003220
3221 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003222 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003223 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003224
3225 if (ret < 0) {
3226 error_report("Could not read file metadata: %s", strerror(-ret));
3227 goto out;
3228 }
3229
Fam Zheng16b0d552016-01-26 11:59:02 +08003230 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003231 curr.length += next.length;
3232 continue;
3233 }
3234
3235 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003236 ret = dump_map_entry(output_format, &curr, &next);
3237 if (ret < 0) {
3238 goto out;
3239 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003240 }
3241 curr = next;
3242 }
3243
Eric Blake30065d12019-03-26 13:40:43 -05003244 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003245 if (output_format == OFORMAT_JSON) {
3246 puts("]");
3247 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003248
3249out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003250 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003251 return ret < 0;
3252}
3253
aliguorif7b4a942009-01-07 17:40:15 +00003254#define SNAPSHOT_LIST 1
3255#define SNAPSHOT_CREATE 2
3256#define SNAPSHOT_APPLY 3
3257#define SNAPSHOT_DELETE 4
3258
Stuart Brady153859b2009-06-07 00:42:17 +01003259static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003260{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003261 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003262 BlockDriverState *bs;
3263 QEMUSnapshotInfo sn;
3264 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003265 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003266 int action = 0;
3267 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003268 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003269 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003270 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003271 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003272
Kevin Wolfce099542016-03-15 13:01:04 +01003273 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003274 /* Parse commandline parameters */
3275 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003276 static const struct option long_options[] = {
3277 {"help", no_argument, 0, 'h'},
3278 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003279 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003280 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003281 {0, 0, 0, 0}
3282 };
Fam Zheng335e9932017-05-03 00:35:39 +08003283 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003284 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003285 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003286 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003287 }
aliguorif7b4a942009-01-07 17:40:15 +00003288 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003289 case ':':
3290 missing_argument(argv[optind - 1]);
3291 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003292 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003293 unrecognized_option(argv[optind - 1]);
3294 break;
aliguorif7b4a942009-01-07 17:40:15 +00003295 case 'h':
3296 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003297 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003298 case 'l':
3299 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003300 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003301 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003302 }
3303 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003304 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003305 break;
3306 case 'a':
3307 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003308 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003309 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003310 }
3311 action = SNAPSHOT_APPLY;
3312 snapshot_name = optarg;
3313 break;
3314 case 'c':
3315 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003316 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003317 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003318 }
3319 action = SNAPSHOT_CREATE;
3320 snapshot_name = optarg;
3321 break;
3322 case 'd':
3323 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003324 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003325 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003326 }
3327 action = SNAPSHOT_DELETE;
3328 snapshot_name = optarg;
3329 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003330 case 'q':
3331 quiet = true;
3332 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003333 case 'U':
3334 force_share = true;
3335 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003336 case OPTION_OBJECT: {
3337 QemuOpts *opts;
3338 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3339 optarg, true);
3340 if (!opts) {
3341 return 1;
3342 }
3343 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003344 case OPTION_IMAGE_OPTS:
3345 image_opts = true;
3346 break;
aliguorif7b4a942009-01-07 17:40:15 +00003347 }
3348 }
3349
Kevin Wolffc11eb22013-08-05 10:53:04 +02003350 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003351 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003352 }
aliguorif7b4a942009-01-07 17:40:15 +00003353 filename = argv[optind++];
3354
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003355 if (qemu_opts_foreach(&qemu_object_opts,
3356 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003357 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003358 return 1;
3359 }
3360
aliguorif7b4a942009-01-07 17:40:15 +00003361 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003362 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3363 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003364 if (!blk) {
3365 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003366 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003367 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003368
3369 /* Perform the requested action */
3370 switch(action) {
3371 case SNAPSHOT_LIST:
3372 dump_snapshots(bs);
3373 break;
3374
3375 case SNAPSHOT_CREATE:
3376 memset(&sn, 0, sizeof(sn));
3377 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3378
3379 qemu_gettimeofday(&tv);
3380 sn.date_sec = tv.tv_sec;
3381 sn.date_nsec = tv.tv_usec * 1000;
3382
3383 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003384 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003385 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003386 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003387 }
aliguorif7b4a942009-01-07 17:40:15 +00003388 break;
3389
3390 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003391 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003392 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003393 error_reportf_err(err, "Could not apply snapshot '%s': ",
3394 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003395 }
aliguorif7b4a942009-01-07 17:40:15 +00003396 break;
3397
3398 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003399 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3400 if (ret < 0) {
3401 error_report("Could not delete snapshot '%s': snapshot not "
3402 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003403 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003404 } else {
3405 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3406 if (ret < 0) {
3407 error_reportf_err(err, "Could not delete snapshot '%s': ",
3408 snapshot_name);
3409 ret = 1;
3410 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003411 }
aliguorif7b4a942009-01-07 17:40:15 +00003412 break;
3413 }
3414
3415 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003416 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003417 if (ret) {
3418 return 1;
3419 }
Stuart Brady153859b2009-06-07 00:42:17 +01003420 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003421}
3422
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003423static int img_rebase(int argc, char **argv)
3424{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003425 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003426 uint8_t *buf_old = NULL;
3427 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003428 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003429 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003430 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3431 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003432 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003433 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003434 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003435 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003436 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003437 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003438 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003439
3440 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003441 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003442 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003443 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003444 out_baseimg = NULL;
3445 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003446 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003447 static const struct option long_options[] = {
3448 {"help", no_argument, 0, 'h'},
3449 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003450 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003451 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003452 {0, 0, 0, 0}
3453 };
Fam Zheng335e9932017-05-03 00:35:39 +08003454 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003455 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003456 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003457 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003458 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003459 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003460 case ':':
3461 missing_argument(argv[optind - 1]);
3462 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003463 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003464 unrecognized_option(argv[optind - 1]);
3465 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003466 case 'h':
3467 help();
3468 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003469 case 'f':
3470 fmt = optarg;
3471 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003472 case 'F':
3473 out_basefmt = optarg;
3474 break;
3475 case 'b':
3476 out_baseimg = optarg;
3477 break;
3478 case 'u':
3479 unsafe = 1;
3480 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003481 case 'p':
3482 progress = 1;
3483 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003484 case 't':
3485 cache = optarg;
3486 break;
Max Reitz40055952014-07-22 22:58:42 +02003487 case 'T':
3488 src_cache = optarg;
3489 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003490 case 'q':
3491 quiet = true;
3492 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003493 case OPTION_OBJECT: {
3494 QemuOpts *opts;
3495 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3496 optarg, true);
3497 if (!opts) {
3498 return 1;
3499 }
3500 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003501 case OPTION_IMAGE_OPTS:
3502 image_opts = true;
3503 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003504 case 'U':
3505 force_share = true;
3506 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003507 }
3508 }
3509
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003510 if (quiet) {
3511 progress = 0;
3512 }
3513
Fam Zhengac1307a2014-04-22 13:36:11 +08003514 if (optind != argc - 1) {
3515 error_exit("Expecting one image file name");
3516 }
3517 if (!unsafe && !out_baseimg) {
3518 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003519 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003520 filename = argv[optind++];
3521
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003522 if (qemu_opts_foreach(&qemu_object_opts,
3523 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003524 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003525 return 1;
3526 }
3527
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003528 qemu_progress_init(progress, 2.0);
3529 qemu_progress_print(0, 100);
3530
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003531 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003532 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003533 if (ret < 0) {
3534 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003535 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003536 }
3537
Kevin Wolfce099542016-03-15 13:01:04 +01003538 src_flags = 0;
3539 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003540 if (ret < 0) {
3541 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003542 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003543 }
3544
Kevin Wolfce099542016-03-15 13:01:04 +01003545 /* The source files are opened read-only, don't care about WCE */
3546 assert((src_flags & BDRV_O_RDWR) == 0);
3547 (void) src_writethrough;
3548
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003549 /*
3550 * Open the images.
3551 *
3552 * Ignore the old backing file for unsafe rebase in case we want to correct
3553 * the reference to a renamed or moved backing file.
3554 */
Fam Zheng335e9932017-05-03 00:35:39 +08003555 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3556 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003557 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003558 ret = -1;
3559 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003560 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003561 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003562
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003563 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003564 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003565 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003566 ret = -1;
3567 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003568 }
3569 }
3570
3571 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003572 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003573 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003574 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003575
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003576 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003577 blk_old_backing = blk_new(qemu_get_aio_context(),
3578 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003579 BLK_PERM_ALL);
3580 ret = blk_insert_bs(blk_old_backing, base_bs,
3581 &local_err);
3582 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003583 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003584 "Could not reuse old backing file '%s': ",
3585 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003586 goto out;
3587 }
3588 } else {
3589 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003590 }
Max Reitz644483d2015-02-05 13:58:17 -05003591
Alex Bligha6166732012-10-16 13:46:18 +01003592 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003593 const char *overlay_filename;
3594 char *out_real_path;
3595
Fam Zheng335e9932017-05-03 00:35:39 +08003596 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003597 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003598 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003599 }
3600 if (force_share) {
3601 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003602 }
3603
Max Reitzf30c66b2019-02-01 20:29:05 +01003604 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003605 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3606 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003607 out_real_path =
3608 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3609 out_baseimg,
3610 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003611 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003612 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003613 error_reportf_err(local_err,
3614 "Could not resolve backing filename: ");
3615 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003616 goto out;
3617 }
3618
Sam Eiderman863cc782019-05-23 19:33:36 +03003619 /*
3620 * Find out whether we rebase an image on top of a previous image
3621 * in its chain.
3622 */
3623 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003624 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003625 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003626 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003627
Kevin Wolfd861ab32019-04-25 14:25:10 +02003628 blk_new_backing = blk_new(qemu_get_aio_context(),
3629 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003630 BLK_PERM_ALL);
3631 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3632 &local_err);
3633 if (ret < 0) {
3634 error_reportf_err(local_err,
3635 "Could not reuse backing file '%s': ",
3636 out_baseimg);
3637 goto out;
3638 }
3639 } else {
3640 blk_new_backing = blk_new_open(out_real_path, NULL,
3641 options, src_flags, &local_err);
3642 g_free(out_real_path);
3643 if (!blk_new_backing) {
3644 error_reportf_err(local_err,
3645 "Could not open new backing file '%s': ",
3646 out_baseimg);
3647 ret = -1;
3648 goto out;
3649 }
Alex Bligha6166732012-10-16 13:46:18 +01003650 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003651 }
3652 }
3653
3654 /*
3655 * Check each unallocated cluster in the COW file. If it is unallocated,
3656 * accesses go to the backing file. We must therefore compare this cluster
3657 * in the old and new backing file, and if they differ we need to copy it
3658 * from the old backing file into the COW file.
3659 *
3660 * If qemu-img crashes during this step, no harm is done. The content of
3661 * the image is the same as the original one at any time.
3662 */
3663 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003664 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003665 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003666 int64_t new_backing_size = 0;
3667 uint64_t offset;
3668 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003669 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003670
Max Reitzf1d3cd72015-02-05 13:58:18 -05003671 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3672 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003673
Eric Blake41536282017-10-11 22:47:15 -05003674 size = blk_getlength(blk);
3675 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003676 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003677 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003678 ret = -1;
3679 goto out;
3680 }
Max Reitz35ddd932019-05-09 19:52:35 +02003681 if (blk_old_backing) {
3682 old_backing_size = blk_getlength(blk_old_backing);
3683 if (old_backing_size < 0) {
3684 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003685
Max Reitz35ddd932019-05-09 19:52:35 +02003686 bdrv_get_backing_filename(bs, backing_name,
3687 sizeof(backing_name));
3688 error_report("Could not get size of '%s': %s",
3689 backing_name, strerror(-old_backing_size));
3690 ret = -1;
3691 goto out;
3692 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003693 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003694 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003695 new_backing_size = blk_getlength(blk_new_backing);
3696 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003697 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003698 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003699 ret = -1;
3700 goto out;
3701 }
Alex Bligha6166732012-10-16 13:46:18 +01003702 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003703
Eric Blake41536282017-10-11 22:47:15 -05003704 if (size != 0) {
3705 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003706 }
3707
Eric Blake41536282017-10-11 22:47:15 -05003708 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003709 bool buf_old_is_zero = false;
3710
Eric Blake41536282017-10-11 22:47:15 -05003711 /* How many bytes can we handle with the next read? */
3712 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003713
3714 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003715 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003716 if (ret < 0) {
3717 error_report("error while reading image metadata: %s",
3718 strerror(-ret));
3719 goto out;
3720 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003721 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003722 continue;
3723 }
3724
Sam Eiderman863cc782019-05-23 19:33:36 +03003725 if (prefix_chain_bs) {
3726 /*
3727 * If cluster wasn't changed since prefix_chain, we don't need
3728 * to take action
3729 */
3730 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003731 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003732 if (ret < 0) {
3733 error_report("error while reading image metadata: %s",
3734 strerror(-ret));
3735 goto out;
3736 }
3737 if (!ret) {
3738 continue;
3739 }
3740 }
3741
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003742 /*
3743 * Read old and new backing file and take into consideration that
3744 * backing files may be smaller than the COW image.
3745 */
Eric Blake41536282017-10-11 22:47:15 -05003746 if (offset >= old_backing_size) {
3747 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003748 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003749 } else {
Eric Blake41536282017-10-11 22:47:15 -05003750 if (offset + n > old_backing_size) {
3751 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003752 }
3753
Eric Blake41536282017-10-11 22:47:15 -05003754 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003755 if (ret < 0) {
3756 error_report("error while reading from old backing file");
3757 goto out;
3758 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003759 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003760
Eric Blake41536282017-10-11 22:47:15 -05003761 if (offset >= new_backing_size || !blk_new_backing) {
3762 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003763 } else {
Eric Blake41536282017-10-11 22:47:15 -05003764 if (offset + n > new_backing_size) {
3765 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003766 }
3767
Eric Blake41536282017-10-11 22:47:15 -05003768 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003769 if (ret < 0) {
3770 error_report("error while reading from new backing file");
3771 goto out;
3772 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003773 }
3774
3775 /* If they differ, we need to write to the COW file */
3776 uint64_t written = 0;
3777
Eric Blake41536282017-10-11 22:47:15 -05003778 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003779 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003780
Eric Blake41536282017-10-11 22:47:15 -05003781 if (compare_buffers(buf_old + written, buf_new + written,
3782 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003783 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003784 if (buf_old_is_zero) {
3785 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3786 } else {
3787 ret = blk_pwrite(blk, offset + written,
3788 buf_old + written, pnum, 0);
3789 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003790 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003791 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003792 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003793 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003794 }
3795 }
3796
3797 written += pnum;
3798 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003799 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003800 }
3801 }
3802
3803 /*
3804 * Change the backing file. All clusters that are different from the old
3805 * backing file are overwritten in the COW file now, so the visible content
3806 * doesn't change when we switch the backing file.
3807 */
Alex Bligha6166732012-10-16 13:46:18 +01003808 if (out_baseimg && *out_baseimg) {
3809 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3810 } else {
3811 ret = bdrv_change_backing_file(bs, NULL, NULL);
3812 }
3813
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003814 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003815 error_report("Could not change the backing file to '%s': No "
3816 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003817 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003818 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003819 out_baseimg, strerror(-ret));
3820 }
3821
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003822 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003823 /*
3824 * TODO At this point it is possible to check if any clusters that are
3825 * allocated in the COW file are the same in the backing file. If so, they
3826 * could be dropped from the COW file. Don't do this before switching the
3827 * backing file, in case of a crash this would lead to corruption.
3828 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003829out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003830 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003831 /* Cleanup */
3832 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003833 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003834 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003835 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003836 qemu_vfree(buf_old);
3837 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003838
Markus Armbruster26f54e92014-10-07 13:59:04 +02003839 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003840 if (ret) {
3841 return 1;
3842 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003843 return 0;
3844}
3845
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003846static int img_resize(int argc, char **argv)
3847{
Markus Armbruster6750e792015-02-12 17:43:08 +01003848 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003849 int c, ret, relative;
3850 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003851 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003852 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003853 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003854 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003855 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003856
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003857 static QemuOptsList resize_options = {
3858 .name = "resize_options",
3859 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3860 .desc = {
3861 {
3862 .name = BLOCK_OPT_SIZE,
3863 .type = QEMU_OPT_SIZE,
3864 .help = "Virtual disk size"
3865 }, {
3866 /* end of list */
3867 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003868 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003869 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003870 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003871 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003872
Kevin Wolfe80fec72011-04-29 10:58:12 +02003873 /* Remove size from argv manually so that negative numbers are not treated
3874 * as options by getopt. */
3875 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003876 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003877 return 1;
3878 }
3879
3880 size = argv[--argc];
3881
3882 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003883 fmt = NULL;
3884 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003885 static const struct option long_options[] = {
3886 {"help", no_argument, 0, 'h'},
3887 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003888 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003889 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003890 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003891 {0, 0, 0, 0}
3892 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003893 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003894 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003895 if (c == -1) {
3896 break;
3897 }
3898 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003899 case ':':
3900 missing_argument(argv[optind - 1]);
3901 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003902 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003903 unrecognized_option(argv[optind - 1]);
3904 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003905 case 'h':
3906 help();
3907 break;
3908 case 'f':
3909 fmt = optarg;
3910 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003911 case 'q':
3912 quiet = true;
3913 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003914 case OPTION_OBJECT: {
3915 QemuOpts *opts;
3916 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3917 optarg, true);
3918 if (!opts) {
3919 return 1;
3920 }
3921 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003922 case OPTION_IMAGE_OPTS:
3923 image_opts = true;
3924 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003925 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003926 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003927 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003928 if (prealloc == PREALLOC_MODE__MAX) {
3929 error_report("Invalid preallocation mode '%s'", optarg);
3930 return 1;
3931 }
3932 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003933 case OPTION_SHRINK:
3934 shrink = true;
3935 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003936 }
3937 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003938 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003939 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003940 }
3941 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003942
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003943 if (qemu_opts_foreach(&qemu_object_opts,
3944 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003945 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003946 return 1;
3947 }
3948
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003949 /* Choose grow, shrink, or absolute resize mode */
3950 switch (size[0]) {
3951 case '+':
3952 relative = 1;
3953 size++;
3954 break;
3955 case '-':
3956 relative = -1;
3957 size++;
3958 break;
3959 default:
3960 relative = 0;
3961 break;
3962 }
3963
3964 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003965 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003966 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003967 if (err) {
3968 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003969 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003970 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003971 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003972 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003973 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3974 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003975
Max Reitzefaa7c42016-03-16 19:54:38 +01003976 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003977 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3978 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003979 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003980 ret = -1;
3981 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003982 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003983
Max Reitzdc5f6902017-06-13 22:20:55 +02003984 current_size = blk_getlength(blk);
3985 if (current_size < 0) {
3986 error_report("Failed to inquire current image length: %s",
3987 strerror(-current_size));
3988 ret = -1;
3989 goto out;
3990 }
3991
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003992 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003993 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003994 } else {
3995 total_size = n;
3996 }
3997 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003998 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003999 ret = -1;
4000 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004001 }
4002
Max Reitzdc5f6902017-06-13 22:20:55 +02004003 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4004 error_report("Preallocation can only be used for growing images");
4005 ret = -1;
4006 goto out;
4007 }
4008
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004009 if (total_size < current_size && !shrink) {
4010 warn_report("Shrinking an image will delete all data beyond the "
4011 "shrunken image's end. Before performing such an "
4012 "operation, make sure there is no important data there.");
4013
4014 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
4015 error_report(
4016 "Use the --shrink option to perform a shrink operation.");
4017 ret = -1;
4018 goto out;
4019 } else {
4020 warn_report("Using the --shrink option will suppress this message. "
4021 "Note that future versions of qemu-img may refuse to "
4022 "shrink images without this option.");
4023 }
4024 }
4025
Max Reitze8d04f92019-09-18 11:51:43 +02004026 /*
4027 * The user expects the image to have the desired size after
4028 * resizing, so pass @exact=true. It is of no use to report
4029 * success when the image has not actually been resized.
4030 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004031 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004032 if (!ret) {
4033 qprintf(quiet, "Image resized.\n");
4034 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004035 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004036 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004037out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004038 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004039 if (ret) {
4040 return 1;
4041 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004042 return 0;
4043}
4044
Max Reitz76a3a342014-10-27 11:12:51 +01004045static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004046 int64_t offset, int64_t total_work_size,
4047 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004048{
4049 qemu_progress_print(100.f * offset / total_work_size, 0);
4050}
4051
Max Reitz51641352018-05-09 23:00:20 +02004052static int print_amend_option_help(const char *format)
4053{
4054 BlockDriver *drv;
4055
4056 /* Find driver and parse its options */
4057 drv = bdrv_find_format(format);
4058 if (!drv) {
4059 error_report("Unknown file format '%s'", format);
4060 return 1;
4061 }
4062
4063 if (!drv->bdrv_amend_options) {
4064 error_report("Format driver '%s' does not support option amendment",
4065 format);
4066 return 1;
4067 }
4068
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004069 /* Every driver supporting amendment must have amend_opts */
4070 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004071
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004072 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004073 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004074 return 0;
4075}
4076
Max Reitz6f176b42013-09-03 10:09:50 +02004077static int img_amend(int argc, char **argv)
4078{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004079 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004080 int c, ret = 0;
4081 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004082 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004083 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004084 const char *fmt = NULL, *filename, *cache;
4085 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004086 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004087 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004088 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004089 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004090 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004091 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004092
Max Reitzbd39e6e2014-07-22 22:58:43 +02004093 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004094 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004095 static const struct option long_options[] = {
4096 {"help", no_argument, 0, 'h'},
4097 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004098 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004099 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004100 {0, 0, 0, 0}
4101 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004102 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004103 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004104 if (c == -1) {
4105 break;
4106 }
4107
4108 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004109 case ':':
4110 missing_argument(argv[optind - 1]);
4111 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004112 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004113 unrecognized_option(argv[optind - 1]);
4114 break;
4115 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004116 help();
4117 break;
4118 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004119 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004120 ret = -1;
4121 goto out_no_progress;
4122 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004123 break;
4124 case 'f':
4125 fmt = optarg;
4126 break;
4127 case 't':
4128 cache = optarg;
4129 break;
4130 case 'p':
4131 progress = true;
4132 break;
4133 case 'q':
4134 quiet = true;
4135 break;
4136 case OPTION_OBJECT:
4137 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4138 optarg, true);
4139 if (!opts) {
4140 ret = -1;
4141 goto out_no_progress;
4142 }
4143 break;
4144 case OPTION_IMAGE_OPTS:
4145 image_opts = true;
4146 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004147 case OPTION_FORCE:
4148 force = true;
4149 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004150 }
4151 }
4152
Max Reitz6f176b42013-09-03 10:09:50 +02004153 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004154 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004155 }
4156
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004157 if (qemu_opts_foreach(&qemu_object_opts,
4158 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004159 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004160 ret = -1;
4161 goto out_no_progress;
4162 }
4163
Max Reitz76a3a342014-10-27 11:12:51 +01004164 if (quiet) {
4165 progress = false;
4166 }
4167 qemu_progress_init(progress, 1.0);
4168
Kevin Wolfa283cb62014-02-21 16:24:07 +01004169 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4170 if (fmt && has_help_option(options)) {
4171 /* If a format is explicitly specified (and possibly no filename is
4172 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004173 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004174 goto out;
4175 }
4176
4177 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004178 error_report("Expecting one image file name");
4179 ret = -1;
4180 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004181 }
Max Reitz6f176b42013-09-03 10:09:50 +02004182
Kevin Wolfce099542016-03-15 13:01:04 +01004183 flags = BDRV_O_RDWR;
4184 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004185 if (ret < 0) {
4186 error_report("Invalid cache option: %s", cache);
4187 goto out;
4188 }
4189
Fam Zheng335e9932017-05-03 00:35:39 +08004190 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4191 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004192 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004193 ret = -1;
4194 goto out;
4195 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004196 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004197
4198 fmt = bs->drv->format_name;
4199
Kevin Wolf626f84f2014-02-21 16:24:06 +01004200 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004201 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004202 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004203 goto out;
4204 }
4205
Max Reitz1f996682018-05-09 23:00:17 +02004206 if (!bs->drv->bdrv_amend_options) {
4207 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004208 fmt);
4209 ret = -1;
4210 goto out;
4211 }
4212
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004213 /* Every driver supporting amendment must have amend_opts */
4214 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004215
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004216 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4217 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004218 qemu_opts_do_parse(opts, options, NULL, &err);
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004219
Paolo Bonziniece90862017-01-04 15:56:24 +01004220 if (err) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004221 /* Try to parse options using the create options */
4222 Error *err1 = NULL;
4223 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4224 qemu_opts_del(opts);
4225 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
4226 qemu_opts_do_parse(opts, options, NULL, &err1);
4227
4228 if (!err1) {
4229 error_append_hint(&err,
4230 "This option is only supported for image creation\n");
4231 } else {
4232 error_free(err1);
4233 }
4234
Paolo Bonziniece90862017-01-04 15:56:24 +01004235 error_report_err(err);
4236 ret = -1;
4237 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004238 }
4239
Max Reitz76a3a342014-10-27 11:12:51 +01004240 /* In case the driver does not call amend_status_cb() */
4241 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004242 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004243 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004244 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004245 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004246 goto out;
4247 }
4248
4249out:
Max Reitz76a3a342014-10-27 11:12:51 +01004250 qemu_progress_end();
4251
Max Reitze814dff2015-08-20 16:00:38 -07004252out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004253 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004254 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004255 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004256 g_free(options);
4257
Max Reitz6f176b42013-09-03 10:09:50 +02004258 if (ret) {
4259 return 1;
4260 }
4261 return 0;
4262}
4263
Kevin Wolfb6133b82014-08-05 14:17:13 +02004264typedef struct BenchData {
4265 BlockBackend *blk;
4266 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004267 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004268 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004269 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004270 int nrreq;
4271 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004272 int flush_interval;
4273 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004274 uint8_t *buf;
4275 QEMUIOVector *qiov;
4276
4277 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004278 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004279 uint64_t offset;
4280} BenchData;
4281
Kevin Wolf55d539c2016-06-03 13:59:41 +02004282static void bench_undrained_flush_cb(void *opaque, int ret)
4283{
4284 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004285 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004286 exit(EXIT_FAILURE);
4287 }
4288}
4289
Kevin Wolfb6133b82014-08-05 14:17:13 +02004290static void bench_cb(void *opaque, int ret)
4291{
4292 BenchData *b = opaque;
4293 BlockAIOCB *acb;
4294
4295 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004296 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004297 exit(EXIT_FAILURE);
4298 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004299
4300 if (b->in_flush) {
4301 /* Just finished a flush with drained queue: Start next requests */
4302 assert(b->in_flight == 0);
4303 b->in_flush = false;
4304 } else if (b->in_flight > 0) {
4305 int remaining = b->n - b->in_flight;
4306
Kevin Wolfb6133b82014-08-05 14:17:13 +02004307 b->n--;
4308 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004309
4310 /* Time for flush? Drain queue if requested, then flush */
4311 if (b->flush_interval && remaining % b->flush_interval == 0) {
4312 if (!b->in_flight || !b->drain_on_flush) {
4313 BlockCompletionFunc *cb;
4314
4315 if (b->drain_on_flush) {
4316 b->in_flush = true;
4317 cb = bench_cb;
4318 } else {
4319 cb = bench_undrained_flush_cb;
4320 }
4321
4322 acb = blk_aio_flush(b->blk, cb, b);
4323 if (!acb) {
4324 error_report("Failed to issue flush request");
4325 exit(EXIT_FAILURE);
4326 }
4327 }
4328 if (b->drain_on_flush) {
4329 return;
4330 }
4331 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004332 }
4333
4334 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004335 int64_t offset = b->offset;
4336 /* blk_aio_* might look for completed I/Os and kick bench_cb
4337 * again, so make sure this operation is counted by in_flight
4338 * and b->offset is ready for the next submission.
4339 */
4340 b->in_flight++;
4341 b->offset += b->step;
4342 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004343 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004344 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004345 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004346 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004347 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004348 if (!acb) {
4349 error_report("Failed to issue request");
4350 exit(EXIT_FAILURE);
4351 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004352 }
4353}
4354
4355static int img_bench(int argc, char **argv)
4356{
4357 int c, ret = 0;
4358 const char *fmt = NULL, *filename;
4359 bool quiet = false;
4360 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004361 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004362 int count = 75000;
4363 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004364 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004365 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004366 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004367 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004368 int flush_interval = 0;
4369 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004370 int64_t image_size;
4371 BlockBackend *blk = NULL;
4372 BenchData data = {};
4373 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004374 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004375 struct timeval t1, t2;
4376 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004377 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004378 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004379
4380 for (;;) {
4381 static const struct option long_options[] = {
4382 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004383 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004384 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004385 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004386 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004387 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004388 {0, 0, 0, 0}
4389 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004390 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4391 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004392 if (c == -1) {
4393 break;
4394 }
4395
4396 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004397 case ':':
4398 missing_argument(argv[optind - 1]);
4399 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004400 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004401 unrecognized_option(argv[optind - 1]);
4402 break;
4403 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004404 help();
4405 break;
4406 case 'c':
4407 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004408 unsigned long res;
4409
4410 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004411 error_report("Invalid request count specified");
4412 return 1;
4413 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004414 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004415 break;
4416 }
4417 case 'd':
4418 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004419 unsigned long res;
4420
4421 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004422 error_report("Invalid queue depth specified");
4423 return 1;
4424 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004425 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004426 break;
4427 }
4428 case 'f':
4429 fmt = optarg;
4430 break;
4431 case 'n':
4432 flags |= BDRV_O_NATIVE_AIO;
4433 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004434 case 'i':
4435 ret = bdrv_parse_aio(optarg, &flags);
4436 if (ret < 0) {
4437 error_report("Invalid aio option: %s", optarg);
4438 ret = -1;
4439 goto out;
4440 }
4441 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004442 case 'o':
4443 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004444 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004445 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004446 return 1;
4447 }
4448 break;
4449 }
4450 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004451 case 'q':
4452 quiet = true;
4453 break;
4454 case 's':
4455 {
4456 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004457
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004458 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4459 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004460 return 1;
4461 }
4462
4463 bufsize = sval;
4464 break;
4465 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004466 case 'S':
4467 {
4468 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004469
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004470 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4471 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004472 return 1;
4473 }
4474
4475 step = sval;
4476 break;
4477 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004478 case 't':
4479 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4480 if (ret < 0) {
4481 error_report("Invalid cache mode");
4482 ret = -1;
4483 goto out;
4484 }
4485 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004486 case 'w':
4487 flags |= BDRV_O_RDWR;
4488 is_write = true;
4489 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004490 case 'U':
4491 force_share = true;
4492 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004493 case OPTION_PATTERN:
4494 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004495 unsigned long res;
4496
4497 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004498 error_report("Invalid pattern byte specified");
4499 return 1;
4500 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004501 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004502 break;
4503 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004504 case OPTION_FLUSH_INTERVAL:
4505 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004506 unsigned long res;
4507
4508 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004509 error_report("Invalid flush interval specified");
4510 return 1;
4511 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004512 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004513 break;
4514 }
4515 case OPTION_NO_DRAIN:
4516 drain_on_flush = false;
4517 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004518 case OPTION_IMAGE_OPTS:
4519 image_opts = true;
4520 break;
4521 }
4522 }
4523
4524 if (optind != argc - 1) {
4525 error_exit("Expecting one image file name");
4526 }
4527 filename = argv[argc - 1];
4528
Kevin Wolf55d539c2016-06-03 13:59:41 +02004529 if (!is_write && flush_interval) {
4530 error_report("--flush-interval is only available in write tests");
4531 ret = -1;
4532 goto out;
4533 }
4534 if (flush_interval && flush_interval < depth) {
4535 error_report("Flush interval can't be smaller than depth");
4536 ret = -1;
4537 goto out;
4538 }
4539
Fam Zheng335e9932017-05-03 00:35:39 +08004540 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4541 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004542 if (!blk) {
4543 ret = -1;
4544 goto out;
4545 }
4546
4547 image_size = blk_getlength(blk);
4548 if (image_size < 0) {
4549 ret = image_size;
4550 goto out;
4551 }
4552
4553 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004554 .blk = blk,
4555 .image_size = image_size,
4556 .bufsize = bufsize,
4557 .step = step ?: bufsize,
4558 .nrreq = depth,
4559 .n = count,
4560 .offset = offset,
4561 .write = is_write,
4562 .flush_interval = flush_interval,
4563 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004564 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004565 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004566 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004567 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004568 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004569 if (flush_interval) {
4570 printf("Sending flush every %d requests\n", flush_interval);
4571 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004572
Fam Zheng79d46582018-01-16 14:08:58 +08004573 buf_size = data.nrreq * data.bufsize;
4574 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004575 memset(data.buf, pattern, data.nrreq * data.bufsize);
4576
Fam Zheng79d46582018-01-16 14:08:58 +08004577 blk_register_buf(blk, data.buf, buf_size);
4578
Kevin Wolfb6133b82014-08-05 14:17:13 +02004579 data.qiov = g_new(QEMUIOVector, data.nrreq);
4580 for (i = 0; i < data.nrreq; i++) {
4581 qemu_iovec_init(&data.qiov[i], 1);
4582 qemu_iovec_add(&data.qiov[i],
4583 data.buf + i * data.bufsize, data.bufsize);
4584 }
4585
4586 gettimeofday(&t1, NULL);
4587 bench_cb(&data, 0);
4588
4589 while (data.n > 0) {
4590 main_loop_wait(false);
4591 }
4592 gettimeofday(&t2, NULL);
4593
4594 printf("Run completed in %3.3f seconds.\n",
4595 (t2.tv_sec - t1.tv_sec)
4596 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4597
4598out:
Fam Zheng79d46582018-01-16 14:08:58 +08004599 if (data.buf) {
4600 blk_unregister_buf(blk, data.buf);
4601 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004602 qemu_vfree(data.buf);
4603 blk_unref(blk);
4604
4605 if (ret) {
4606 return 1;
4607 }
4608 return 0;
4609}
4610
Eric Blake3b51ab42020-05-12 20:16:45 -05004611enum ImgBitmapAct {
4612 BITMAP_ADD,
4613 BITMAP_REMOVE,
4614 BITMAP_CLEAR,
4615 BITMAP_ENABLE,
4616 BITMAP_DISABLE,
4617 BITMAP_MERGE,
4618};
4619typedef struct ImgBitmapAction {
4620 enum ImgBitmapAct act;
4621 const char *src; /* only used for merge */
4622 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4623} ImgBitmapAction;
4624
4625static int img_bitmap(int argc, char **argv)
4626{
4627 Error *err = NULL;
4628 int c, ret = 1;
4629 QemuOpts *opts = NULL;
4630 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4631 const char *filename, *bitmap;
4632 BlockBackend *blk = NULL, *src = NULL;
4633 BlockDriverState *bs = NULL, *src_bs = NULL;
4634 bool image_opts = false;
4635 int64_t granularity = 0;
4636 bool add = false, merge = false;
4637 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4638 ImgBitmapAction *act, *act_next;
4639 const char *op;
4640
4641 QSIMPLEQ_INIT(&actions);
4642
4643 for (;;) {
4644 static const struct option long_options[] = {
4645 {"help", no_argument, 0, 'h'},
4646 {"object", required_argument, 0, OPTION_OBJECT},
4647 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4648 {"add", no_argument, 0, OPTION_ADD},
4649 {"remove", no_argument, 0, OPTION_REMOVE},
4650 {"clear", no_argument, 0, OPTION_CLEAR},
4651 {"enable", no_argument, 0, OPTION_ENABLE},
4652 {"disable", no_argument, 0, OPTION_DISABLE},
4653 {"merge", required_argument, 0, OPTION_MERGE},
4654 {"granularity", required_argument, 0, 'g'},
4655 {"source-file", required_argument, 0, 'b'},
4656 {"source-format", required_argument, 0, 'F'},
4657 {0, 0, 0, 0}
4658 };
4659 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4660 if (c == -1) {
4661 break;
4662 }
4663
4664 switch (c) {
4665 case ':':
4666 missing_argument(argv[optind - 1]);
4667 break;
4668 case '?':
4669 unrecognized_option(argv[optind - 1]);
4670 break;
4671 case 'h':
4672 help();
4673 break;
4674 case 'b':
4675 src_filename = optarg;
4676 break;
4677 case 'f':
4678 fmt = optarg;
4679 break;
4680 case 'F':
4681 src_fmt = optarg;
4682 break;
4683 case 'g':
4684 granularity = cvtnum("granularity", optarg);
4685 if (granularity < 0) {
4686 return 1;
4687 }
4688 break;
4689 case OPTION_ADD:
4690 act = g_new0(ImgBitmapAction, 1);
4691 act->act = BITMAP_ADD;
4692 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4693 add = true;
4694 break;
4695 case OPTION_REMOVE:
4696 act = g_new0(ImgBitmapAction, 1);
4697 act->act = BITMAP_REMOVE;
4698 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4699 break;
4700 case OPTION_CLEAR:
4701 act = g_new0(ImgBitmapAction, 1);
4702 act->act = BITMAP_CLEAR;
4703 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4704 break;
4705 case OPTION_ENABLE:
4706 act = g_new0(ImgBitmapAction, 1);
4707 act->act = BITMAP_ENABLE;
4708 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4709 break;
4710 case OPTION_DISABLE:
4711 act = g_new0(ImgBitmapAction, 1);
4712 act->act = BITMAP_DISABLE;
4713 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4714 break;
4715 case OPTION_MERGE:
4716 act = g_new0(ImgBitmapAction, 1);
4717 act->act = BITMAP_MERGE;
4718 act->src = optarg;
4719 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4720 merge = true;
4721 break;
4722 case OPTION_OBJECT:
4723 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4724 if (!opts) {
4725 goto out;
4726 }
4727 break;
4728 case OPTION_IMAGE_OPTS:
4729 image_opts = true;
4730 break;
4731 }
4732 }
4733
4734 if (qemu_opts_foreach(&qemu_object_opts,
4735 user_creatable_add_opts_foreach,
4736 qemu_img_object_print_help, &error_fatal)) {
4737 goto out;
4738 }
4739
4740 if (QSIMPLEQ_EMPTY(&actions)) {
4741 error_report("Need at least one of --add, --remove, --clear, "
4742 "--enable, --disable, or --merge");
4743 goto out;
4744 }
4745
4746 if (granularity && !add) {
4747 error_report("granularity only supported with --add");
4748 goto out;
4749 }
4750 if (src_fmt && !src_filename) {
4751 error_report("-F only supported with -b");
4752 goto out;
4753 }
4754 if (src_filename && !merge) {
4755 error_report("Merge bitmap source file only supported with "
4756 "--merge");
4757 goto out;
4758 }
4759
4760 if (optind != argc - 2) {
4761 error_report("Expecting filename and bitmap name");
4762 goto out;
4763 }
4764
4765 filename = argv[optind];
4766 bitmap = argv[optind + 1];
4767
4768 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4769 false);
4770 if (!blk) {
4771 goto out;
4772 }
4773 bs = blk_bs(blk);
4774 if (src_filename) {
4775 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4776 if (!src) {
4777 goto out;
4778 }
4779 src_bs = blk_bs(src);
4780 } else {
4781 src_bs = bs;
4782 }
4783
4784 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4785 switch (act->act) {
4786 case BITMAP_ADD:
4787 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4788 !!granularity, granularity, true, true,
4789 false, false, &err);
4790 op = "add";
4791 break;
4792 case BITMAP_REMOVE:
4793 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4794 op = "remove";
4795 break;
4796 case BITMAP_CLEAR:
4797 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4798 op = "clear";
4799 break;
4800 case BITMAP_ENABLE:
4801 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4802 op = "enable";
4803 break;
4804 case BITMAP_DISABLE:
4805 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4806 op = "disable";
4807 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004808 case BITMAP_MERGE:
4809 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4810 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004811 op = "merge";
4812 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004813 default:
4814 g_assert_not_reached();
4815 }
4816
4817 if (err) {
4818 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4819 op, bitmap);
4820 goto out;
4821 }
4822 g_free(act);
4823 }
4824
4825 ret = 0;
4826
4827 out:
4828 blk_unref(src);
4829 blk_unref(blk);
4830 qemu_opts_del(opts);
4831 return ret;
4832}
4833
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004834#define C_BS 01
4835#define C_COUNT 02
4836#define C_IF 04
4837#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004838#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004839
4840struct DdInfo {
4841 unsigned int flags;
4842 int64_t count;
4843};
4844
4845struct DdIo {
4846 int bsz; /* Block size */
4847 char *filename;
4848 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004849 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004850};
4851
4852struct DdOpts {
4853 const char *name;
4854 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4855 unsigned int flag;
4856};
4857
4858static int img_dd_bs(const char *arg,
4859 struct DdIo *in, struct DdIo *out,
4860 struct DdInfo *dd)
4861{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004862 int64_t res;
4863
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004864 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004865
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004866 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004867 return 1;
4868 }
4869 in->bsz = out->bsz = res;
4870
4871 return 0;
4872}
4873
4874static int img_dd_count(const char *arg,
4875 struct DdIo *in, struct DdIo *out,
4876 struct DdInfo *dd)
4877{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004878 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004879
Markus Armbruster606caa02017-02-21 21:14:04 +01004880 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004881 return 1;
4882 }
4883
4884 return 0;
4885}
4886
4887static int img_dd_if(const char *arg,
4888 struct DdIo *in, struct DdIo *out,
4889 struct DdInfo *dd)
4890{
4891 in->filename = g_strdup(arg);
4892
4893 return 0;
4894}
4895
4896static int img_dd_of(const char *arg,
4897 struct DdIo *in, struct DdIo *out,
4898 struct DdInfo *dd)
4899{
4900 out->filename = g_strdup(arg);
4901
4902 return 0;
4903}
4904
Reda Sallahif7c15532016-08-10 16:16:09 +02004905static int img_dd_skip(const char *arg,
4906 struct DdIo *in, struct DdIo *out,
4907 struct DdInfo *dd)
4908{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004909 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004910
Markus Armbruster606caa02017-02-21 21:14:04 +01004911 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004912 return 1;
4913 }
4914
4915 return 0;
4916}
4917
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004918static int img_dd(int argc, char **argv)
4919{
4920 int ret = 0;
4921 char *arg = NULL;
4922 char *tmp;
4923 BlockDriver *drv = NULL, *proto_drv = NULL;
4924 BlockBackend *blk1 = NULL, *blk2 = NULL;
4925 QemuOpts *opts = NULL;
4926 QemuOptsList *create_opts = NULL;
4927 Error *local_err = NULL;
4928 bool image_opts = false;
4929 int c, i;
4930 const char *out_fmt = "raw";
4931 const char *fmt = NULL;
4932 int64_t size = 0;
4933 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004934 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004935 struct DdInfo dd = {
4936 .flags = 0,
4937 .count = 0,
4938 };
4939 struct DdIo in = {
4940 .bsz = 512, /* Block size is by default 512 bytes */
4941 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004942 .buf = NULL,
4943 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004944 };
4945 struct DdIo out = {
4946 .bsz = 512,
4947 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004948 .buf = NULL,
4949 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004950 };
4951
4952 const struct DdOpts options[] = {
4953 { "bs", img_dd_bs, C_BS },
4954 { "count", img_dd_count, C_COUNT },
4955 { "if", img_dd_if, C_IF },
4956 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004957 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004958 { NULL, NULL, 0 }
4959 };
4960 const struct option long_options[] = {
4961 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004962 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004963 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004964 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004965 { 0, 0, 0, 0 }
4966 };
4967
Fam Zheng335e9932017-05-03 00:35:39 +08004968 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004969 if (c == EOF) {
4970 break;
4971 }
4972 switch (c) {
4973 case 'O':
4974 out_fmt = optarg;
4975 break;
4976 case 'f':
4977 fmt = optarg;
4978 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004979 case ':':
4980 missing_argument(argv[optind - 1]);
4981 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004982 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004983 unrecognized_option(argv[optind - 1]);
4984 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004985 case 'h':
4986 help();
4987 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004988 case 'U':
4989 force_share = true;
4990 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004991 case OPTION_OBJECT:
4992 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004993 ret = -1;
4994 goto out;
4995 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004996 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004997 case OPTION_IMAGE_OPTS:
4998 image_opts = true;
4999 break;
5000 }
5001 }
5002
5003 for (i = optind; i < argc; i++) {
5004 int j;
5005 arg = g_strdup(argv[i]);
5006
5007 tmp = strchr(arg, '=');
5008 if (tmp == NULL) {
5009 error_report("unrecognized operand %s", arg);
5010 ret = -1;
5011 goto out;
5012 }
5013
5014 *tmp++ = '\0';
5015
5016 for (j = 0; options[j].name != NULL; j++) {
5017 if (!strcmp(arg, options[j].name)) {
5018 break;
5019 }
5020 }
5021 if (options[j].name == NULL) {
5022 error_report("unrecognized operand %s", arg);
5023 ret = -1;
5024 goto out;
5025 }
5026
5027 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5028 ret = -1;
5029 goto out;
5030 }
5031 dd.flags |= options[j].flag;
5032 g_free(arg);
5033 arg = NULL;
5034 }
5035
5036 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5037 error_report("Must specify both input and output files");
5038 ret = -1;
5039 goto out;
5040 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005041
5042 if (qemu_opts_foreach(&qemu_object_opts,
5043 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005044 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005045 ret = -1;
5046 goto out;
5047 }
5048
Fam Zheng335e9932017-05-03 00:35:39 +08005049 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5050 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005051
5052 if (!blk1) {
5053 ret = -1;
5054 goto out;
5055 }
5056
5057 drv = bdrv_find_format(out_fmt);
5058 if (!drv) {
5059 error_report("Unknown file format");
5060 ret = -1;
5061 goto out;
5062 }
5063 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5064
5065 if (!proto_drv) {
5066 error_report_err(local_err);
5067 ret = -1;
5068 goto out;
5069 }
5070 if (!drv->create_opts) {
5071 error_report("Format driver '%s' does not support image creation",
5072 drv->format_name);
5073 ret = -1;
5074 goto out;
5075 }
5076 if (!proto_drv->create_opts) {
5077 error_report("Protocol driver '%s' does not support image creation",
5078 proto_drv->format_name);
5079 ret = -1;
5080 goto out;
5081 }
5082 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5083 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5084
5085 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5086
5087 size = blk_getlength(blk1);
5088 if (size < 0) {
5089 error_report("Failed to get size for '%s'", in.filename);
5090 ret = -1;
5091 goto out;
5092 }
5093
5094 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5095 dd.count * in.bsz < size) {
5096 size = dd.count * in.bsz;
5097 }
5098
Reda Sallahif7c15532016-08-10 16:16:09 +02005099 /* Overflow means the specified offset is beyond input image's size */
5100 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5101 size < in.bsz * in.offset)) {
5102 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5103 } else {
5104 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5105 size - in.bsz * in.offset, &error_abort);
5106 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005107
5108 ret = bdrv_create(drv, out.filename, opts, &local_err);
5109 if (ret < 0) {
5110 error_reportf_err(local_err,
5111 "%s: error while creating output image: ",
5112 out.filename);
5113 ret = -1;
5114 goto out;
5115 }
5116
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005117 /* TODO, we can't honour --image-opts for the target,
5118 * since it needs to be given in a format compatible
5119 * with the bdrv_create() call above which does not
5120 * support image-opts style.
5121 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005122 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005123 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005124
5125 if (!blk2) {
5126 ret = -1;
5127 goto out;
5128 }
5129
Reda Sallahif7c15532016-08-10 16:16:09 +02005130 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5131 size < in.offset * in.bsz)) {
5132 /* We give a warning if the skip option is bigger than the input
5133 * size and create an empty output disk image (i.e. like dd(1)).
5134 */
5135 error_report("%s: cannot skip to specified offset", in.filename);
5136 in_pos = size;
5137 } else {
5138 in_pos = in.offset * in.bsz;
5139 }
5140
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005141 in.buf = g_new(uint8_t, in.bsz);
5142
Reda Sallahif7c15532016-08-10 16:16:09 +02005143 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005144 int in_ret, out_ret;
5145
5146 if (in_pos + in.bsz > size) {
5147 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5148 } else {
5149 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5150 }
5151 if (in_ret < 0) {
5152 error_report("error while reading from input image file: %s",
5153 strerror(-in_ret));
5154 ret = -1;
5155 goto out;
5156 }
5157 in_pos += in_ret;
5158
5159 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5160
5161 if (out_ret < 0) {
5162 error_report("error while writing to output image file: %s",
5163 strerror(-out_ret));
5164 ret = -1;
5165 goto out;
5166 }
5167 out_pos += out_ret;
5168 }
5169
5170out:
5171 g_free(arg);
5172 qemu_opts_del(opts);
5173 qemu_opts_free(create_opts);
5174 blk_unref(blk1);
5175 blk_unref(blk2);
5176 g_free(in.filename);
5177 g_free(out.filename);
5178 g_free(in.buf);
5179 g_free(out.buf);
5180
5181 if (ret) {
5182 return 1;
5183 }
5184 return 0;
5185}
5186
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005187static void dump_json_block_measure_info(BlockMeasureInfo *info)
5188{
5189 QString *str;
5190 QObject *obj;
5191 Visitor *v = qobject_output_visitor_new(&obj);
5192
5193 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5194 visit_complete(v, &obj);
5195 str = qobject_to_json_pretty(obj);
5196 assert(str != NULL);
5197 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005198 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005199 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005200 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005201}
5202
5203static int img_measure(int argc, char **argv)
5204{
5205 static const struct option long_options[] = {
5206 {"help", no_argument, 0, 'h'},
5207 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5208 {"object", required_argument, 0, OPTION_OBJECT},
5209 {"output", required_argument, 0, OPTION_OUTPUT},
5210 {"size", required_argument, 0, OPTION_SIZE},
5211 {"force-share", no_argument, 0, 'U'},
5212 {0, 0, 0, 0}
5213 };
5214 OutputFormat output_format = OFORMAT_HUMAN;
5215 BlockBackend *in_blk = NULL;
5216 BlockDriver *drv;
5217 const char *filename = NULL;
5218 const char *fmt = NULL;
5219 const char *out_fmt = "raw";
5220 char *options = NULL;
5221 char *snapshot_name = NULL;
5222 bool force_share = false;
5223 QemuOpts *opts = NULL;
5224 QemuOpts *object_opts = NULL;
5225 QemuOpts *sn_opts = NULL;
5226 QemuOptsList *create_opts = NULL;
5227 bool image_opts = false;
5228 uint64_t img_size = UINT64_MAX;
5229 BlockMeasureInfo *info = NULL;
5230 Error *local_err = NULL;
5231 int ret = 1;
5232 int c;
5233
5234 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5235 long_options, NULL)) != -1) {
5236 switch (c) {
5237 case '?':
5238 case 'h':
5239 help();
5240 break;
5241 case 'f':
5242 fmt = optarg;
5243 break;
5244 case 'O':
5245 out_fmt = optarg;
5246 break;
5247 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005248 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005249 goto out;
5250 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005251 break;
5252 case 'l':
5253 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5254 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5255 optarg, false);
5256 if (!sn_opts) {
5257 error_report("Failed in parsing snapshot param '%s'",
5258 optarg);
5259 goto out;
5260 }
5261 } else {
5262 snapshot_name = optarg;
5263 }
5264 break;
5265 case 'U':
5266 force_share = true;
5267 break;
5268 case OPTION_OBJECT:
5269 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5270 optarg, true);
5271 if (!object_opts) {
5272 goto out;
5273 }
5274 break;
5275 case OPTION_IMAGE_OPTS:
5276 image_opts = true;
5277 break;
5278 case OPTION_OUTPUT:
5279 if (!strcmp(optarg, "json")) {
5280 output_format = OFORMAT_JSON;
5281 } else if (!strcmp(optarg, "human")) {
5282 output_format = OFORMAT_HUMAN;
5283 } else {
5284 error_report("--output must be used with human or json "
5285 "as argument.");
5286 goto out;
5287 }
5288 break;
5289 case OPTION_SIZE:
5290 {
5291 int64_t sval;
5292
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005293 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005294 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005295 goto out;
5296 }
5297 img_size = (uint64_t)sval;
5298 }
5299 break;
5300 }
5301 }
5302
5303 if (qemu_opts_foreach(&qemu_object_opts,
5304 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005305 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005306 goto out;
5307 }
5308
5309 if (argc - optind > 1) {
5310 error_report("At most one filename argument is allowed.");
5311 goto out;
5312 } else if (argc - optind == 1) {
5313 filename = argv[optind];
5314 }
5315
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005316 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5317 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005318 goto out;
5319 }
5320 if (filename && img_size != UINT64_MAX) {
5321 error_report("--size N cannot be used together with a filename.");
5322 goto out;
5323 }
5324 if (!filename && img_size == UINT64_MAX) {
5325 error_report("Either --size N or one filename must be specified.");
5326 goto out;
5327 }
5328
5329 if (filename) {
5330 in_blk = img_open(image_opts, filename, fmt, 0,
5331 false, false, force_share);
5332 if (!in_blk) {
5333 goto out;
5334 }
5335
5336 if (sn_opts) {
5337 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5338 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5339 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5340 &local_err);
5341 } else if (snapshot_name != NULL) {
5342 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5343 snapshot_name, &local_err);
5344 }
5345 if (local_err) {
5346 error_reportf_err(local_err, "Failed to load snapshot: ");
5347 goto out;
5348 }
5349 }
5350
5351 drv = bdrv_find_format(out_fmt);
5352 if (!drv) {
5353 error_report("Unknown file format '%s'", out_fmt);
5354 goto out;
5355 }
5356 if (!drv->create_opts) {
5357 error_report("Format driver '%s' does not support image creation",
5358 drv->format_name);
5359 goto out;
5360 }
5361
5362 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5363 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5364 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5365 if (options) {
5366 qemu_opts_do_parse(opts, options, NULL, &local_err);
5367 if (local_err) {
5368 error_report_err(local_err);
5369 error_report("Invalid options for file format '%s'", out_fmt);
5370 goto out;
5371 }
5372 }
5373 if (img_size != UINT64_MAX) {
5374 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5375 }
5376
5377 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5378 if (local_err) {
5379 error_report_err(local_err);
5380 goto out;
5381 }
5382
5383 if (output_format == OFORMAT_HUMAN) {
5384 printf("required size: %" PRIu64 "\n", info->required);
5385 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005386 if (info->has_bitmaps) {
5387 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5388 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005389 } else {
5390 dump_json_block_measure_info(info);
5391 }
5392
5393 ret = 0;
5394
5395out:
5396 qapi_free_BlockMeasureInfo(info);
5397 qemu_opts_del(object_opts);
5398 qemu_opts_del(opts);
5399 qemu_opts_del(sn_opts);
5400 qemu_opts_free(create_opts);
5401 g_free(options);
5402 blk_unref(in_blk);
5403 return ret;
5404}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005405
Anthony Liguoric227f092009-10-01 16:12:16 -05005406static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005407#define DEF(option, callback, arg_string) \
5408 { option, callback },
5409#include "qemu-img-cmds.h"
5410#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005411 { NULL, NULL, },
5412};
5413
bellardea2384d2004-08-01 21:59:26 +00005414int main(int argc, char **argv)
5415{
Anthony Liguoric227f092009-10-01 16:12:16 -05005416 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005417 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005418 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005419 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005420 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005421 static const struct option long_options[] = {
5422 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005423 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005424 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005425 {0, 0, 0, 0}
5426 };
bellardea2384d2004-08-01 21:59:26 +00005427
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005428#ifdef CONFIG_POSIX
5429 signal(SIGPIPE, SIG_IGN);
5430#endif
5431
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005432 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005433 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005434 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005435
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005436 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005437 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005438 exit(EXIT_FAILURE);
5439 }
5440
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005441 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005442
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005443 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005444 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005445 if (argc < 2) {
5446 error_exit("Not enough arguments");
5447 }
Stuart Brady153859b2009-06-07 00:42:17 +01005448
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005449 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005450 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005451 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005452
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005453 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005454 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005455 case ':':
5456 missing_argument(argv[optind - 1]);
5457 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005458 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005459 unrecognized_option(argv[optind - 1]);
5460 return 0;
5461 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005462 help();
5463 return 0;
5464 case 'V':
5465 printf(QEMU_IMG_VERSION);
5466 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005467 case 'T':
5468 g_free(trace_file);
5469 trace_file = trace_opt_parse(optarg);
5470 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005471 }
bellardea2384d2004-08-01 21:59:26 +00005472 }
Stuart Brady153859b2009-06-07 00:42:17 +01005473
Denis V. Lunev10985132016-06-17 17:44:13 +03005474 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005475
Denis V. Lunev10985132016-06-17 17:44:13 +03005476 /* reset getopt_long scanning */
5477 argc -= optind;
5478 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005479 return 0;
5480 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005481 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005482 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005483
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005484 if (!trace_init_backends()) {
5485 exit(1);
5486 }
5487 trace_init_file(trace_file);
5488 qemu_set_log(LOG_TRACE);
5489
Denis V. Lunev10985132016-06-17 17:44:13 +03005490 /* find the command */
5491 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5492 if (!strcmp(cmdname, cmd->name)) {
5493 return cmd->handler(argc, argv);
5494 }
5495 }
Jeff Cody7db16892014-04-25 17:02:32 -04005496
Stuart Brady153859b2009-06-07 00:42:17 +01005497 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005498 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005499}