blob: 116e05867558ea825cd899f88774348b4d376fee [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"
Marc-André Lureau16a18f22022-03-23 19:57:35 +040029#include "qemu/qemu-progress.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080030#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010031#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050032#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010033#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010034#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010035#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010036#include "qapi/qmp/qdict.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010044#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020045#include "qemu/units.h"
Peter Maydell5df022c2022-02-26 18:07:23 +000046#include "qemu/memalign.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000047#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020048#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010049#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020050#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080051#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010052#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030053#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000054#include "qemu/throttle.h"
55#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000056
Thomas Huth7e563bf2018-02-15 12:06:47 +010057#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020058 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040059
Anthony Liguoric227f092009-10-01 16:12:16 -050060typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010061 const char *name;
62 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050063} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010064
Federico Simoncelli8599ea42013-01-28 06:59:47 -050065enum {
66 OPTION_OUTPUT = 256,
67 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000068 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000069 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020070 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020071 OPTION_FLUSH_INTERVAL = 261,
72 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010073 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010074 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020075 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030076 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020077 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000078 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050079 OPTION_ADD = 269,
80 OPTION_REMOVE = 270,
81 OPTION_CLEAR = 271,
82 OPTION_ENABLE = 272,
83 OPTION_DISABLE = 273,
84 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050085 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020086 OPTION_FORCE = 276,
Eric Blake955171e2021-07-21 10:53:48 -050087 OPTION_SKIP_BROKEN = 277,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050088};
89
90typedef enum OutputFormat {
91 OFORMAT_JSON,
92 OFORMAT_HUMAN,
93} OutputFormat;
94
Kevin Wolfe6996142016-03-15 13:03:11 +010095/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040096#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000097
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010098static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000099{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100100 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +0000101}
102
Marc-André Lureau9edc6312022-02-20 20:39:25 +0400103static void QEMU_NORETURN G_GNUC_PRINTF(1, 2) error_exit(const char *fmt, ...)
Fam Zhengac1307a2014-04-22 13:36:11 +0800104{
105 va_list ap;
106
Fam Zhengac1307a2014-04-22 13:36:11 +0800107 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200108 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800109 va_end(ap);
110
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200111 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800112 exit(EXIT_FAILURE);
113}
114
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800115static void QEMU_NORETURN missing_argument(const char *option)
116{
117 error_exit("missing argument for option '%s'", option);
118}
119
120static void QEMU_NORETURN unrecognized_option(const char *option)
121{
122 error_exit("unrecognized option '%s'", option);
123}
124
Eric Blake0562adf2020-05-12 20:16:41 -0500125/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800126static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000127{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100128 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400129 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300130 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300131 "QEMU disk image utility\n"
132 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300133 " '-h', '--help' display this help and exit\n"
134 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300135 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
136 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300137 "\n"
malc3f020d72010-02-08 12:04:56 +0300138 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100139#define DEF(option, callback, arg_string) \
140 " " arg_string "\n"
141#include "qemu-img-cmds.h"
142#undef DEF
malc3f020d72010-02-08 12:04:56 +0300143 "\n"
144 "Command parameters:\n"
145 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000146 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
147 " manual page for a description of the object properties. The most common\n"
148 " object type is a 'secret', which is used to supply passwords and/or\n"
149 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300150 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400151 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800152 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
153 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100154 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
155 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300156 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200157 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
158 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
159 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300160 " 'output_filename' is the destination disk image filename\n"
161 " 'output_fmt' is the destination format\n"
162 " 'options' is a comma separated list of format specific options in a\n"
163 " name=value format. Use -o ? for an overview of the options supported by the\n"
164 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800165 " 'snapshot_param' is param used for internal snapshot, format\n"
166 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
167 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300168 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400169 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
170 " new backing file match exactly. The image doesn't need a working\n"
171 " backing file before rebasing in this case (useful for renaming the\n"
172 " backing file). For image creation, allow creating without attempting\n"
173 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300174 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200175 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100176 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200177 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
178 " contain only zeros for qemu-img to create a sparse image during\n"
179 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
180 " unallocated or zero sectors, and the destination image will always be\n"
181 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200182 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100183 " '-n' skips the target volume creation (useful if the volume is created\n"
184 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300185 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500186 "Parameters to bitmap subcommand:\n"
187 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
188 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
189 " or '--merge source'\n"
190 " '-g granularity' sets the granularity for '--add' actions\n"
191 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
192 " bitmaps from an alternative file\n"
193 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200194 "Parameters to check subcommand:\n"
195 " '-r' tries to repair any inconsistencies that are found during the check.\n"
196 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
197 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200198 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200199 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100200 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500201 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100202 " '-m' specifies how many coroutines work in parallel during the convert\n"
203 " process (defaults to 8)\n"
204 " '-W' allow to write to the target out of order rather than sequential\n"
205 "\n"
malc3f020d72010-02-08 12:04:56 +0300206 "Parameters to snapshot subcommand:\n"
207 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
208 " '-a' applies a snapshot (revert disk to saved state)\n"
209 " '-c' creates a snapshot\n"
210 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100211 " '-l' lists all snapshots in the given image\n"
212 "\n"
213 "Parameters to compare subcommand:\n"
214 " '-f' first image format\n"
215 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200216 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
217 "\n"
218 "Parameters to dd subcommand:\n"
219 " 'bs=BYTES' read and write up to BYTES bytes at a time "
220 "(default: 512)\n"
221 " 'count=N' copy only N input blocks\n"
222 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200223 " 'of=FILE' write to FILE\n"
224 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100225
226 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300227 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500228 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800229 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000230}
231
Markus Armbruster80c710c2020-04-15 09:49:26 +0200232/*
233 * Is @optarg safe for accumulate_options()?
234 * It is when multiple of them can be joined together separated by ','.
235 * To make that work, @optarg must not start with ',' (or else a
236 * separating ',' preceding it gets escaped), and it must not end with
237 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200238 * escaped), or be empty (or else a separating ',' preceding it can
239 * escape a separating ',' following it).
240 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200241 */
242static bool is_valid_option_list(const char *optarg)
243{
244 size_t len = strlen(optarg);
245 size_t i;
246
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200247 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200248 return false;
249 }
250
251 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
252 }
253 if ((len - i) % 2) {
254 return false;
255 }
256
257 return true;
258}
259
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200260static int accumulate_options(char **options, char *optarg)
261{
262 char *new_options;
263
264 if (!is_valid_option_list(optarg)) {
265 error_report("Invalid option list: %s", optarg);
266 return -1;
267 }
268
269 if (!*options) {
270 *options = g_strdup(optarg);
271 } else {
272 new_options = g_strdup_printf("%s,%s", *options, optarg);
273 g_free(*options);
274 *options = new_options;
275 }
276 return 0;
277}
278
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000279static QemuOptsList qemu_source_opts = {
280 .name = "source",
281 .implied_opt_name = "file",
282 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
283 .desc = {
284 { }
285 },
286};
287
Marc-André Lureau9edc6312022-02-20 20:39:25 +0400288static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100289{
290 int ret = 0;
291 if (!quiet) {
292 va_list args;
293 va_start(args, fmt);
294 ret = vprintf(fmt, args);
295 va_end(args);
296 }
297 return ret;
298}
299
bellardea2384d2004-08-01 21:59:26 +0000300
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100301static int print_block_option_help(const char *filename, const char *fmt)
302{
303 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800304 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500305 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100306
307 /* Find driver and parse its options */
308 drv = bdrv_find_format(fmt);
309 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100310 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100311 return 1;
312 }
313
Max Reitzd402b6a2018-05-09 23:00:21 +0200314 if (!drv->create_opts) {
315 error_report("Format driver '%s' does not support image creation", fmt);
316 return 1;
317 }
318
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800319 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100320 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500321 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100322 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100323 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800324 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100325 return 1;
326 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200327 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100328 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200329 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100330 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200331 return 1;
332 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800333 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100334 }
335
Max Reitzf4619af2019-04-13 17:20:37 +0200336 if (filename) {
337 printf("Supported options:\n");
338 } else {
339 printf("Supported %s options:\n", fmt);
340 }
Max Reitz63898712018-10-19 18:49:25 +0200341 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800342 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200343
344 if (!filename) {
345 printf("\n"
346 "The protocol level may support further options.\n"
347 "Specify the target filename to include those options.\n");
348 }
349
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100350 return 0;
351}
352
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000353
Max Reitzefaa7c42016-03-16 19:54:38 +0100354static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100355 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800356 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000357{
358 QDict *options;
359 Error *local_err = NULL;
360 BlockBackend *blk;
361 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800362 if (force_share) {
363 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200364 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800365 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200366 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800367 return NULL;
368 }
Max Reitz4615f872018-05-02 22:20:50 +0200369 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800370 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100371 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000372 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100373 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000374 return NULL;
375 }
Kevin Wolfce099542016-03-15 13:01:04 +0100376 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000377
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000378 return blk;
379}
380
Max Reitzefaa7c42016-03-16 19:54:38 +0100381static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100382 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800384 bool writethrough, bool quiet,
385 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000386{
387 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200388 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100389
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100390 if (!options) {
391 options = qdict_new();
392 }
bellard75c23802004-08-27 21:28:58 +0000393 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500394 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000395 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100396
Fam Zheng335e9932017-05-03 00:35:39 +0800397 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500398 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800399 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100400 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500401 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100402 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000403 return NULL;
bellard75c23802004-08-27 21:28:58 +0000404 }
Kevin Wolfce099542016-03-15 13:01:04 +0100405 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100406
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200407 return blk;
bellard75c23802004-08-27 21:28:58 +0000408}
409
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000410
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100411static int img_add_key_secrets(void *opaque,
412 const char *name, const char *value,
413 Error **errp)
414{
415 QDict *options = opaque;
416
417 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600418 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100419 }
420
421 return 0;
422}
423
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100424
Max Reitzefaa7c42016-03-16 19:54:38 +0100425static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000426 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100427 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800428 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000429{
430 BlockBackend *blk;
431 if (image_opts) {
432 QemuOpts *opts;
433 if (fmt) {
434 error_report("--image-opts and --format are mutually exclusive");
435 return NULL;
436 }
437 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
438 filename, true);
439 if (!opts) {
440 return NULL;
441 }
Fam Zheng335e9932017-05-03 00:35:39 +0800442 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
443 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000444 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100445 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800446 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000447 }
448 return blk;
449}
450
451
Chunyan Liu83d05212014-06-05 17:20:51 +0800452static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100453 const char *base_filename,
454 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200455{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200456 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200457 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200458 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100459 error_report("Backing file not supported for file format '%s'",
460 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900461 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200462 }
463 }
464 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200465 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100466 error_report("Backing file format not supported for file "
467 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900468 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200469 }
470 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900471 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200472}
473
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300474static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
475 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100476{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100477 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300478 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100479
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300480 err = qemu_strtosz(value, NULL, &res);
481 if (err < 0 && err != -ERANGE) {
482 error_report("Invalid %s specified. You may use "
483 "k, M, G, T, P or E suffixes for", name);
484 error_report("kilobytes, megabytes, gigabytes, terabytes, "
485 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100486 return err;
487 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300488 if (err == -ERANGE || res > max || res < min) {
489 error_report("Invalid %s specified. Must be between %" PRId64
490 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100491 return -ERANGE;
492 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300493 return res;
494}
495
496static int64_t cvtnum(const char *name, const char *value)
497{
498 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100499}
500
bellardea2384d2004-08-01 21:59:26 +0000501static int img_create(int argc, char **argv)
502{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200503 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100504 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000505 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000506 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000507 const char *filename;
508 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200509 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200510 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100511 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400512 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000513
bellardea2384d2004-08-01 21:59:26 +0000514 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000515 static const struct option long_options[] = {
516 {"help", no_argument, 0, 'h'},
517 {"object", required_argument, 0, OPTION_OBJECT},
518 {0, 0, 0, 0}
519 };
John Snow6e6e55f2017-07-17 20:34:22 -0400520 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000521 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100522 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000523 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100524 }
bellardea2384d2004-08-01 21:59:26 +0000525 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800526 case ':':
527 missing_argument(argv[optind - 1]);
528 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100529 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800530 unrecognized_option(argv[optind - 1]);
531 break;
bellardea2384d2004-08-01 21:59:26 +0000532 case 'h':
533 help();
534 break;
aliguori9230eaf2009-03-28 17:55:19 +0000535 case 'F':
536 base_fmt = optarg;
537 break;
bellardea2384d2004-08-01 21:59:26 +0000538 case 'b':
539 base_filename = optarg;
540 break;
541 case 'f':
542 fmt = optarg;
543 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200544 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200545 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100546 goto fail;
547 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200548 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100549 case 'q':
550 quiet = true;
551 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400552 case 'u':
553 flags |= BDRV_O_NO_BACKING;
554 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100555 case OPTION_OBJECT:
556 user_creatable_process_cmdline(optarg);
557 break;
bellardea2384d2004-08-01 21:59:26 +0000558 }
559 }
aliguori9230eaf2009-03-28 17:55:19 +0000560
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900561 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100562 filename = (optind < argc) ? argv[optind] : NULL;
563 if (options && has_help_option(options)) {
564 g_free(options);
565 return print_block_option_help(filename, fmt);
566 }
567
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100568 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800569 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100570 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100571 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900572
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100573 /* Get image size, if specified */
574 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100575 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100576
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300577 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100578 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100579 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100580 }
581 img_size = (uint64_t)sval;
582 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200583 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800584 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200585 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100586
Luiz Capitulino9b375252012-11-30 10:52:05 -0200587 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400588 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100589 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100590 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100591 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900592 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200593
Kevin Wolf77386bf2014-02-21 16:24:04 +0100594 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000595 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100596
597fail:
598 g_free(options);
599 return 1;
bellardea2384d2004-08-01 21:59:26 +0000600}
601
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100602static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500603{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100604 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500605 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100606 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600607
608 visit_type_ImageCheck(v, NULL, &check, &error_abort);
609 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100610 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500611 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100612 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200613 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600614 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100615 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500616}
617
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100618static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500619{
620 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100621 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500622 } else {
623 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100624 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
625 "Data may be corrupted, or further writes to the image "
626 "may corrupt it.\n",
627 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500628 }
629
630 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100631 qprintf(quiet,
632 "\n%" PRId64 " leaked clusters were found on the image.\n"
633 "This means waste of disk space, but no harm to data.\n",
634 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500635 }
636
637 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100638 qprintf(quiet,
639 "\n%" PRId64
640 " internal errors have occurred during the check.\n",
641 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500642 }
643 }
644
645 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100646 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
647 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
648 check->allocated_clusters, check->total_clusters,
649 check->allocated_clusters * 100.0 / check->total_clusters,
650 check->fragmented_clusters * 100.0 / check->allocated_clusters,
651 check->compressed_clusters * 100.0 /
652 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500653 }
654
655 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100656 qprintf(quiet,
657 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500658 }
659}
660
661static int collect_image_check(BlockDriverState *bs,
662 ImageCheck *check,
663 const char *filename,
664 const char *fmt,
665 int fix)
666{
667 int ret;
668 BdrvCheckResult result;
669
670 ret = bdrv_check(bs, &result, fix);
671 if (ret < 0) {
672 return ret;
673 }
674
675 check->filename = g_strdup(filename);
676 check->format = g_strdup(bdrv_get_format_name(bs));
677 check->check_errors = result.check_errors;
678 check->corruptions = result.corruptions;
679 check->has_corruptions = result.corruptions != 0;
680 check->leaks = result.leaks;
681 check->has_leaks = result.leaks != 0;
682 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100683 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100685 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500686 check->image_end_offset = result.image_end_offset;
687 check->has_image_end_offset = result.image_end_offset != 0;
688 check->total_clusters = result.bfi.total_clusters;
689 check->has_total_clusters = result.bfi.total_clusters != 0;
690 check->allocated_clusters = result.bfi.allocated_clusters;
691 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
692 check->fragmented_clusters = result.bfi.fragmented_clusters;
693 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100694 check->compressed_clusters = result.bfi.compressed_clusters;
695 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696
697 return 0;
698}
699
Kevin Wolfe076f332010-06-29 11:43:13 +0200700/*
701 * Checks an image for consistency. Exit codes:
702 *
Max Reitzd6635c42014-06-02 22:15:21 +0200703 * 0 - Check completed, image is good
704 * 1 - Check not completed because of internal errors
705 * 2 - Check completed, image is corrupted
706 * 3 - Check completed, image has leaked clusters, but is good otherwise
707 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200708 */
aliguori15859692009-04-21 23:11:53 +0000709static int img_check(int argc, char **argv)
710{
711 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200713 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200714 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000715 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200716 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100717 int flags = BDRV_O_CHECK;
718 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200719 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100720 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000721 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800722 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000723
724 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500725 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200726 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100727
aliguori15859692009-04-21 23:11:53 +0000728 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500729 int option_index = 0;
730 static const struct option long_options[] = {
731 {"help", no_argument, 0, 'h'},
732 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530733 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500734 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000735 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000736 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800737 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500738 {0, 0, 0, 0}
739 };
Fam Zheng335e9932017-05-03 00:35:39 +0800740 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500741 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100742 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000743 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100744 }
aliguori15859692009-04-21 23:11:53 +0000745 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800746 case ':':
747 missing_argument(argv[optind - 1]);
748 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100749 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800750 unrecognized_option(argv[optind - 1]);
751 break;
aliguori15859692009-04-21 23:11:53 +0000752 case 'h':
753 help();
754 break;
755 case 'f':
756 fmt = optarg;
757 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200758 case 'r':
759 flags |= BDRV_O_RDWR;
760
761 if (!strcmp(optarg, "leaks")) {
762 fix = BDRV_FIX_LEAKS;
763 } else if (!strcmp(optarg, "all")) {
764 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
765 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800766 error_exit("Unknown option value for -r "
767 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200768 }
769 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500770 case OPTION_OUTPUT:
771 output = optarg;
772 break;
Max Reitz40055952014-07-22 22:58:42 +0200773 case 'T':
774 cache = optarg;
775 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100776 case 'q':
777 quiet = true;
778 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800779 case 'U':
780 force_share = true;
781 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100782 case OPTION_OBJECT:
783 user_creatable_process_cmdline(optarg);
784 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000785 case OPTION_IMAGE_OPTS:
786 image_opts = true;
787 break;
aliguori15859692009-04-21 23:11:53 +0000788 }
789 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200790 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800791 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100792 }
aliguori15859692009-04-21 23:11:53 +0000793 filename = argv[optind++];
794
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 if (output && !strcmp(output, "json")) {
796 output_format = OFORMAT_JSON;
797 } else if (output && !strcmp(output, "human")) {
798 output_format = OFORMAT_HUMAN;
799 } else if (output) {
800 error_report("--output must be used with human or json as argument.");
801 return 1;
802 }
803
Kevin Wolfce099542016-03-15 13:01:04 +0100804 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200805 if (ret < 0) {
806 error_report("Invalid source cache option: %s", cache);
807 return 1;
808 }
809
Fam Zheng335e9932017-05-03 00:35:39 +0800810 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
811 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200812 if (!blk) {
813 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900814 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200815 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500816
817 check = g_new0(ImageCheck, 1);
818 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200819
820 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200821 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200822 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500823 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200824 }
825
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826 if (check->corruptions_fixed || check->leaks_fixed) {
827 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100828 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500829
830 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100831 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500832 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100833 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500834
835 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100836 qprintf(quiet,
837 "The following inconsistencies were found and repaired:\n\n"
838 " %" PRId64 " leaked clusters\n"
839 " %" PRId64 " corruptions\n\n"
840 "Double checking the fixed image now...\n",
841 check->leaks_fixed,
842 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500843 }
844
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800845 qapi_free_ImageCheck(check);
846 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500847 ret = collect_image_check(bs, check, filename, fmt, 0);
848
849 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100850 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500851 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100852 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200853 }
854
Max Reitz832390a2014-10-23 15:29:12 +0200855 if (!ret) {
856 switch (output_format) {
857 case OFORMAT_HUMAN:
858 dump_human_image_check(check, quiet);
859 break;
860 case OFORMAT_JSON:
861 dump_json_image_check(check, quiet);
862 break;
863 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500864 }
865
866 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200867 if (ret) {
868 error_report("Check failed: %s", strerror(-ret));
869 } else {
870 error_report("Check failed");
871 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500872 ret = 1;
873 goto fail;
874 }
875
876 if (check->corruptions) {
877 ret = 2;
878 } else if (check->leaks) {
879 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200880 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500881 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000882 }
883
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500884fail:
885 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200886 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500887 return ret;
aliguori15859692009-04-21 23:11:53 +0000888}
889
Max Reitzd4a32382014-10-24 15:57:37 +0200890typedef struct CommonBlockJobCBInfo {
891 BlockDriverState *bs;
892 Error **errp;
893} CommonBlockJobCBInfo;
894
895static void common_block_job_cb(void *opaque, int ret)
896{
897 CommonBlockJobCBInfo *cbi = opaque;
898
899 if (ret < 0) {
900 error_setg_errno(cbi->errp, -ret, "Block job failed");
901 }
Max Reitzd4a32382014-10-24 15:57:37 +0200902}
903
904static void run_block_job(BlockJob *job, Error **errp)
905{
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200906 uint64_t progress_current, progress_total;
Vladimir Sementsov-Ogievskiydf9a3162021-05-06 17:13:53 +0300907 AioContext *aio_context = block_job_get_aio_context(job);
sochin.jiang4172a002017-06-15 14:47:33 +0800908 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200909
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200910 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200911 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200912 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200913 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200914 aio_poll(aio_context, true);
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200915
916 progress_get_snapshot(&job->job.progress, &progress_current,
917 &progress_total);
918 if (progress_total) {
919 progress = (float)progress_current / progress_total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200920 }
921 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200922 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200923
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200924 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200925 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800926 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200927 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800928 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200929 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200930 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200931
sochin.jiang4172a002017-06-15 14:47:33 +0800932 /* publish completion progress only when success */
933 if (!ret) {
934 qemu_progress_print(100.f, 0);
935 }
Max Reitzd4a32382014-10-24 15:57:37 +0200936}
937
bellardea2384d2004-08-01 21:59:26 +0000938static int img_commit(int argc, char **argv)
939{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400940 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200941 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200942 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200943 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100944 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200945 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100946 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200947 Error *local_err = NULL;
948 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000949 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200950 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000951 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000952
953 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400954 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200955 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000956 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000957 static const struct option long_options[] = {
958 {"help", no_argument, 0, 'h'},
959 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000960 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000961 {0, 0, 0, 0}
962 };
Zhenguia0441b62020-10-20 14:47:43 +0000963 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000964 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100965 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000966 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100967 }
bellardea2384d2004-08-01 21:59:26 +0000968 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800969 case ':':
970 missing_argument(argv[optind - 1]);
971 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100972 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800973 unrecognized_option(argv[optind - 1]);
974 break;
bellardea2384d2004-08-01 21:59:26 +0000975 case 'h':
976 help();
977 break;
978 case 'f':
979 fmt = optarg;
980 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400981 case 't':
982 cache = optarg;
983 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200984 case 'b':
985 base = optarg;
986 /* -b implies -d */
987 drop = true;
988 break;
Max Reitz9a86fe42014-10-24 15:57:38 +0200989 case 'd':
990 drop = true;
991 break;
Max Reitz687fa1d2014-10-24 15:57:39 +0200992 case 'p':
993 progress = true;
994 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100995 case 'q':
996 quiet = true;
997 break;
Zhenguia0441b62020-10-20 14:47:43 +0000998 case 'r':
999 rate_limit = cvtnum("rate limit", optarg);
1000 if (rate_limit < 0) {
1001 return 1;
1002 }
1003 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001004 case OPTION_OBJECT:
1005 user_creatable_process_cmdline(optarg);
1006 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001007 case OPTION_IMAGE_OPTS:
1008 image_opts = true;
1009 break;
bellardea2384d2004-08-01 21:59:26 +00001010 }
1011 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001012
1013 /* Progress is not shown in Quiet mode */
1014 if (quiet) {
1015 progress = false;
1016 }
1017
Kevin Wolffc11eb22013-08-05 10:53:04 +02001018 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001019 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001020 }
bellardea2384d2004-08-01 21:59:26 +00001021 filename = argv[optind++];
1022
Max Reitz9a86fe42014-10-24 15:57:38 +02001023 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001024 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001025 if (ret < 0) {
1026 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001027 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001028 }
1029
Fam Zheng335e9932017-05-03 00:35:39 +08001030 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1031 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001032 if (!blk) {
1033 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001034 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001035 bs = blk_bs(blk);
1036
Max Reitz687fa1d2014-10-24 15:57:39 +02001037 qemu_progress_init(progress, 1.f);
1038 qemu_progress_print(0.f, 100);
1039
Max Reitz1b22bff2014-10-24 15:57:40 +02001040 if (base) {
1041 base_bs = bdrv_find_backing_image(bs, base);
1042 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001043 error_setg(&local_err,
1044 "Did not find '%s' in the backing chain of '%s'",
1045 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001046 goto done;
1047 }
1048 } else {
1049 /* This is different from QMP, which by default uses the deepest file in
1050 * the backing chain (i.e., the very base); however, the traditional
1051 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001052 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001053 if (!base_bs) {
1054 error_setg(&local_err, "Image does not have a backing file");
1055 goto done;
1056 }
bellardea2384d2004-08-01 21:59:26 +00001057 }
1058
Max Reitzd4a32382014-10-24 15:57:37 +02001059 cbi = (CommonBlockJobCBInfo){
1060 .errp = &local_err,
1061 .bs = bs,
1062 };
1063
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001064 aio_context = bdrv_get_aio_context(bs);
1065 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001066 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001067 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001068 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001069 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001070 if (local_err) {
1071 goto done;
1072 }
1073
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001074 /* When the block job completes, the BlockBackend reference will point to
1075 * the old backing file. In order to avoid that the top image is already
1076 * deleted, so we can still empty it afterwards, increment the reference
1077 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001078 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001079 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001080 }
1081
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001082 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001083 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001084 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001085 if (local_err) {
1086 goto unref_backing;
1087 }
1088
Max Reitz2d97fde2020-04-29 16:11:26 +02001089 if (!drop) {
1090 BlockBackend *old_backing_blk;
1091
1092 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1093 &local_err);
1094 if (!old_backing_blk) {
1095 goto unref_backing;
1096 }
1097 ret = blk_make_empty(old_backing_blk, &local_err);
1098 blk_unref(old_backing_blk);
1099 if (ret == -ENOTSUP) {
1100 error_free(local_err);
1101 local_err = NULL;
1102 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001103 goto unref_backing;
1104 }
1105 }
1106
1107unref_backing:
1108 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001109 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001110 }
Max Reitzd4a32382014-10-24 15:57:37 +02001111
1112done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001113 qemu_progress_end();
1114
Markus Armbruster26f54e92014-10-07 13:59:04 +02001115 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001116
1117 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001118 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001119 return 1;
1120 }
Max Reitzd4a32382014-10-24 15:57:37 +02001121
1122 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001123 return 0;
1124}
1125
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001126/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001127 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1128 * of the first sector boundary within buf where the sector contains a
1129 * non-zero byte. This function is robust to a buffer that is not
1130 * sector-aligned.
1131 */
1132static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1133{
1134 int64_t i;
1135 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1136
1137 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1138 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1139 return i;
1140 }
1141 }
1142 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1143 return i;
1144 }
1145 return -1;
1146}
1147
1148/*
thsf58c7b32008-06-05 21:53:49 +00001149 * Returns true iff the first sector pointed to by 'buf' contains at least
1150 * a non-NUL byte.
1151 *
1152 * 'pnum' is set to the number of sectors (including and immediately following
1153 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001154 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001155 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001156 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001157 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001158static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1159 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001160{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001161 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001162 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001163
1164 if (n <= 0) {
1165 *pnum = 0;
1166 return 0;
1167 }
Yi Lic075c422020-08-19 09:36:07 +08001168 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001169 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001170 buf += BDRV_SECTOR_SIZE;
1171 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001172 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001173 }
bellardea2384d2004-08-01 21:59:26 +00001174 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001175
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001176 if (i == n) {
1177 /*
1178 * The whole buf is the same.
1179 * No reason to split it into chunks, so return now.
1180 */
1181 *pnum = i;
1182 return !is_zero;
1183 }
1184
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001185 tail = (sector_num + i) & (alignment - 1);
1186 if (tail) {
1187 if (is_zero && i <= tail) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001188 /*
1189 * For sure next sector after i is data, and it will rewrite this
1190 * tail anyway due to RMW. So, let's just write data now.
1191 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001192 is_zero = false;
1193 }
1194 if (!is_zero) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001195 /* If possible, align up end offset of allocated areas. */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001196 i += alignment - tail;
1197 i = MIN(i, n);
1198 } else {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001199 /*
1200 * For sure next sector after i is data, and it will rewrite this
1201 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1202 * to aligned bound.
1203 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001204 i -= tail;
1205 }
1206 }
bellardea2384d2004-08-01 21:59:26 +00001207 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001208 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001209}
1210
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001211/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001212 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1213 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1214 * breaking up write requests for only small sparse areas.
1215 */
1216static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001217 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001218{
1219 int ret;
1220 int num_checked, num_used;
1221
1222 if (n < min) {
1223 min = n;
1224 }
1225
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001226 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001227 if (!ret) {
1228 return ret;
1229 }
1230
1231 num_used = *pnum;
1232 buf += BDRV_SECTOR_SIZE * *pnum;
1233 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001234 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001235 num_checked = num_used;
1236
1237 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001238 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001239
1240 buf += BDRV_SECTOR_SIZE * *pnum;
1241 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001242 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001243 num_checked += *pnum;
1244 if (ret) {
1245 num_used = num_checked;
1246 } else if (*pnum >= min) {
1247 break;
1248 }
1249 }
1250
1251 *pnum = num_used;
1252 return 1;
1253}
1254
1255/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001256 * Compares two buffers sector by sector. Returns 0 if the first
1257 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001258 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001259 * pnum is set to the sector-aligned size of the buffer prefix that
1260 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001261 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001262static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1263 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001264{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001265 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001266 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001267
Eric Blakedc61cd32017-10-11 22:47:14 -05001268 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001269
Eric Blakedc61cd32017-10-11 22:47:14 -05001270 res = !!memcmp(buf1, buf2, i);
1271 while (i < bytes) {
1272 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001273
Eric Blakedc61cd32017-10-11 22:47:14 -05001274 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001275 break;
1276 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001277 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001278 }
1279
1280 *pnum = i;
1281 return res;
1282}
1283
Stefano Garzarella97ede572019-05-08 12:43:24 +02001284#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001285
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001286/*
1287 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1288 *
Eric Blake0608e402017-10-11 22:47:12 -05001289 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1290 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1291 * failure), and 4 on error (the exit status for read errors), after emitting
1292 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001293 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001294 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001295 * @param offset: Starting offset to check
1296 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001297 * @param filename: Name of disk file we are checking (logging purpose)
1298 * @param buffer: Allocated buffer for storing read data
1299 * @param quiet: Flag for quiet mode
1300 */
Eric Blakec41508e2017-10-11 22:47:13 -05001301static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1302 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001303 uint8_t *buffer, bool quiet)
1304{
Eric Blakedebb38a2017-10-11 22:47:11 -05001305 int ret = 0;
1306 int64_t idx;
1307
Eric Blakec41508e2017-10-11 22:47:13 -05001308 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001309 if (ret < 0) {
1310 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001311 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001312 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001313 }
Eric Blakec41508e2017-10-11 22:47:13 -05001314 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001315 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001316 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001317 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 return 1;
1319 }
1320
1321 return 0;
1322}
1323
1324/*
1325 * Compares two images. Exit codes:
1326 *
Kevin Wolf99b1e642021-02-17 12:56:45 +01001327 * 0 - Images are identical or the requested help was printed
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001328 * 1 - Images differ
1329 * >1 - Error occurred
1330 */
1331static int img_compare(int argc, char **argv)
1332{
Max Reitz40055952014-07-22 22:58:42 +02001333 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001334 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001336 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001337 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001338 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001339 int allocated1, allocated2;
1340 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1341 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001342 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001343 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001344 int64_t total_size;
1345 int64_t offset = 0;
1346 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001347 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001349 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001350 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001351
Max Reitz40055952014-07-22 22:58:42 +02001352 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001353 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001354 static const struct option long_options[] = {
1355 {"help", no_argument, 0, 'h'},
1356 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001357 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001358 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001359 {0, 0, 0, 0}
1360 };
Fam Zheng335e9932017-05-03 00:35:39 +08001361 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001362 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001363 if (c == -1) {
1364 break;
1365 }
1366 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001367 case ':':
1368 missing_argument(argv[optind - 1]);
1369 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001370 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001371 unrecognized_option(argv[optind - 1]);
1372 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001373 case 'h':
1374 help();
1375 break;
1376 case 'f':
1377 fmt1 = optarg;
1378 break;
1379 case 'F':
1380 fmt2 = optarg;
1381 break;
Max Reitz40055952014-07-22 22:58:42 +02001382 case 'T':
1383 cache = optarg;
1384 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001385 case 'p':
1386 progress = true;
1387 break;
1388 case 'q':
1389 quiet = true;
1390 break;
1391 case 's':
1392 strict = true;
1393 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001394 case 'U':
1395 force_share = true;
1396 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001397 case OPTION_OBJECT:
1398 {
1399 Error *local_err = NULL;
1400
1401 if (!user_creatable_add_from_str(optarg, &local_err)) {
1402 if (local_err) {
1403 error_report_err(local_err);
1404 exit(2);
1405 } else {
1406 /* Help was printed */
1407 exit(EXIT_SUCCESS);
1408 }
1409 }
1410 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001411 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001412 case OPTION_IMAGE_OPTS:
1413 image_opts = true;
1414 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415 }
1416 }
1417
1418 /* Progress is not shown in Quiet mode */
1419 if (quiet) {
1420 progress = false;
1421 }
1422
1423
Kevin Wolffc11eb22013-08-05 10:53:04 +02001424 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001425 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001426 }
1427 filename1 = argv[optind++];
1428 filename2 = argv[optind++];
1429
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001430 /* Initialize before goto out */
1431 qemu_progress_init(progress, 2.0);
1432
Kevin Wolfce099542016-03-15 13:01:04 +01001433 flags = 0;
1434 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001435 if (ret < 0) {
1436 error_report("Invalid source cache option: %s", cache);
1437 ret = 2;
1438 goto out3;
1439 }
1440
Fam Zheng335e9932017-05-03 00:35:39 +08001441 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1442 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001443 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001444 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001445 goto out3;
1446 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001447
Fam Zheng335e9932017-05-03 00:35:39 +08001448 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1449 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001450 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001451 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001452 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001453 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001454 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001455 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001456
Max Reitzf1d3cd72015-02-05 13:58:18 -05001457 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1458 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001459 total_size1 = blk_getlength(blk1);
1460 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001461 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001462 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001463 ret = 4;
1464 goto out;
1465 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001466 total_size2 = blk_getlength(blk2);
1467 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001468 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001469 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001470 ret = 4;
1471 goto out;
1472 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001473 total_size = MIN(total_size1, total_size2);
1474 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001475
1476 qemu_progress_print(0, 100);
1477
Eric Blake033d9fc2017-10-11 22:47:16 -05001478 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479 ret = 1;
1480 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1481 goto out;
1482 }
1483
Eric Blake033d9fc2017-10-11 22:47:16 -05001484 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001485 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001486
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 status1 = bdrv_block_status_above(bs1, NULL, offset,
1488 total_size1 - offset, &pnum1, NULL,
1489 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001490 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001491 ret = 3;
1492 error_report("Sector allocation test failed for %s", filename1);
1493 goto out;
1494 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001495 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496
Eric Blake033d9fc2017-10-11 22:47:16 -05001497 status2 = bdrv_block_status_above(bs2, NULL, offset,
1498 total_size2 - offset, &pnum2, NULL,
1499 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001500 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001501 ret = 3;
1502 error_report("Sector allocation test failed for %s", filename2);
1503 goto out;
1504 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001505 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001506
1507 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001508 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509
Fam Zheng25ad8e62016-01-13 16:37:41 +08001510 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001511 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001512 ret = 1;
1513 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001514 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001515 goto out;
1516 }
1517 }
1518 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001519 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001520 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001522 int64_t pnum;
1523
Eric Blake033d9fc2017-10-11 22:47:16 -05001524 chunk = MIN(chunk, IO_BUF_SIZE);
1525 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001526 if (ret < 0) {
1527 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001528 " of %s: %s",
1529 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530 ret = 4;
1531 goto out;
1532 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001533 ret = blk_pread(blk2, offset, buf2, chunk);
1534 if (ret < 0) {
1535 error_report("Error while reading offset %" PRId64
1536 " of %s: %s",
1537 offset, filename2, strerror(-ret));
1538 ret = 4;
1539 goto out;
1540 }
1541 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1542 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001543 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001544 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001545 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001546 goto out;
1547 }
1548 }
1549 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001550 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001552 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001553 filename1, buf1, quiet);
1554 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001555 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001556 filename2, buf1, quiet);
1557 }
1558 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001559 goto out;
1560 }
1561 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001562 offset += chunk;
1563 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001564 }
1565
Eric Blake033d9fc2017-10-11 22:47:16 -05001566 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001567 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001568 const char *filename_over;
1569
1570 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001571 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001572 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001573 filename_over = filename1;
1574 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001575 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001576 filename_over = filename2;
1577 }
1578
Eric Blake033d9fc2017-10-11 22:47:16 -05001579 while (offset < progress_base) {
1580 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1581 progress_base - offset, &chunk,
1582 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001583 if (ret < 0) {
1584 ret = 3;
1585 error_report("Sector allocation test failed for %s",
1586 filename_over);
1587 goto out;
1588
1589 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001590 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001591 chunk = MIN(chunk, IO_BUF_SIZE);
1592 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001593 filename_over, buf1, quiet);
1594 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001595 goto out;
1596 }
1597 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001598 offset += chunk;
1599 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001600 }
1601 }
1602
1603 qprintf(quiet, "Images are identical.\n");
1604 ret = 0;
1605
1606out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001607 qemu_vfree(buf1);
1608 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001609 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001610out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001611 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001612out3:
1613 qemu_progress_end();
1614 return ret;
1615}
1616
Eric Blake6c729dd2020-05-21 14:21:35 -05001617/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1618static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1619 const char *src_node, const char *src_name,
1620 Error **errp)
1621{
1622 BlockDirtyBitmapMergeSource *merge_src;
Eric Blake54aa3de2020-11-12 19:13:37 -06001623 BlockDirtyBitmapMergeSourceList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001624
1625 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1626 merge_src->type = QTYPE_QDICT;
1627 merge_src->u.external.node = g_strdup(src_node);
1628 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001629 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001630 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1631 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1632}
1633
Kevin Wolf690c7302015-03-19 13:33:32 +01001634enum ImgConvertBlockStatus {
1635 BLK_DATA,
1636 BLK_ZERO,
1637 BLK_BACKING_FILE,
1638};
1639
Peter Lieven2d9187b2017-02-28 13:40:07 +01001640#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001641#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001642
Kevin Wolf690c7302015-03-19 13:33:32 +01001643typedef struct ImgConvertState {
1644 BlockBackend **src;
1645 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001646 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001647 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001648 int64_t total_sectors;
1649 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001650 int64_t allocated_done;
1651 int64_t sector_num;
1652 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001653 enum ImgConvertBlockStatus status;
1654 int64_t sector_next_status;
1655 BlockBackend *target;
1656 bool has_zero_init;
1657 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001658 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001659 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001660 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001661 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001662 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001663 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001664 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001665 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001666 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001667 size_t cluster_sectors;
1668 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001669 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670 int running_coroutines;
1671 Coroutine *co[MAX_COROUTINES];
1672 int64_t wait_sector_num[MAX_COROUTINES];
1673 CoMutex lock;
1674 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001675} ImgConvertState;
1676
Peter Lieven2d9187b2017-02-28 13:40:07 +01001677static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1678 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001679{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001680 *src_cur = 0;
1681 *src_cur_offset = 0;
1682 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1683 *src_cur_offset += s->src_sectors[*src_cur];
1684 (*src_cur)++;
1685 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001686 }
1687}
1688
1689static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1690{
Eric Blake31826642017-10-11 22:47:08 -05001691 int64_t src_cur_offset;
1692 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001693 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001694
Peter Lieven2d9187b2017-02-28 13:40:07 +01001695 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001696
1697 assert(s->total_sectors > sector_num);
1698 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1699
Max Reitz351c8ef2018-05-01 18:57:49 +02001700 if (s->target_backing_sectors >= 0) {
1701 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001702 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001703 } else if (sector_num + n > s->target_backing_sectors) {
1704 /* Split requests around target_backing_sectors (because
1705 * starting from there, zeros are handled differently) */
1706 n = s->target_backing_sectors - sector_num;
1707 }
1708 }
1709
Kevin Wolf690c7302015-03-19 13:33:32 +01001710 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001711 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1712 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001713 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001714 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1715 BlockDriverState *base;
1716
1717 if (s->target_has_backing) {
1718 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1719 } else {
1720 base = NULL;
1721 }
Eric Blake31826642017-10-11 22:47:08 -05001722
Max Reitz8eaac022019-05-07 22:35:03 +02001723 do {
1724 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001725
Max Reitz4a2061e2019-06-12 19:00:30 +02001726 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1727 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001728
1729 if (ret < 0) {
1730 if (s->salvage) {
1731 if (n == 1) {
1732 if (!s->quiet) {
1733 warn_report("error while reading block status at "
1734 "offset %" PRIu64 ": %s", offset,
1735 strerror(-ret));
1736 }
1737 /* Just try to read the data, then */
1738 ret = BDRV_BLOCK_DATA;
1739 count = BDRV_SECTOR_SIZE;
1740 } else {
1741 /* Retry on a shorter range */
1742 n = DIV_ROUND_UP(n, 4);
1743 }
1744 } else {
1745 error_report("error while reading block status at offset "
1746 "%" PRIu64 ": %s", offset, strerror(-ret));
1747 return ret;
1748 }
1749 }
1750 } while (ret < 0);
1751
Eric Blake31826642017-10-11 22:47:08 -05001752 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001753
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001754 /*
1755 * Avoid that s->sector_next_status becomes unaligned to the source
1756 * request alignment and/or cluster size to avoid unnecessary read
1757 * cycles.
1758 */
1759 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1760 if (n > tail) {
1761 n -= tail;
1762 }
1763
Kevin Wolf690c7302015-03-19 13:33:32 +01001764 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001765 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001766 } else if (ret & BDRV_BLOCK_DATA) {
1767 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001768 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001769 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001770 }
1771
1772 s->sector_next_status = sector_num + n;
1773 }
1774
1775 n = MIN(n, s->sector_next_status - sector_num);
1776 if (s->status == BLK_DATA) {
1777 n = MIN(n, s->buf_sectors);
1778 }
1779
1780 /* We need to write complete clusters for compressed images, so if an
1781 * unallocated area is shorter than that, we must consider the whole
1782 * cluster allocated. */
1783 if (s->compressed) {
1784 if (n < s->cluster_sectors) {
1785 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1786 s->status = BLK_DATA;
1787 } else {
1788 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1789 }
1790 }
1791
1792 return n;
1793}
1794
Peter Lieven2d9187b2017-02-28 13:40:07 +01001795static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1796 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001797{
Max Reitz8eaac022019-05-07 22:35:03 +02001798 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001799 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001800
Kevin Wolf690c7302015-03-19 13:33:32 +01001801 assert(nb_sectors <= s->buf_sectors);
1802 while (nb_sectors > 0) {
1803 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001804 int src_cur;
1805 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001806 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001807
1808 /* In the case of compression with multiple source files, we can get a
1809 * nb_sectors that spreads into the next part. So we must be able to
1810 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001811 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1812 blk = s->src[src_cur];
1813 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001814
Max Reitz8eaac022019-05-07 22:35:03 +02001815 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001816
Max Reitz8eaac022019-05-07 22:35:03 +02001817 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1818 if (single_read_until > offset) {
1819 n = 1;
1820 }
1821
1822 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001823 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001824 if (s->salvage) {
1825 if (n > 1) {
1826 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1827 continue;
1828 } else {
1829 if (!s->quiet) {
1830 warn_report("error while reading offset %" PRIu64
1831 ": %s", offset, strerror(-ret));
1832 }
1833 memset(buf, 0, BDRV_SECTOR_SIZE);
1834 }
1835 } else {
1836 return ret;
1837 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001838 }
1839
1840 sector_num += n;
1841 nb_sectors -= n;
1842 buf += n * BDRV_SECTOR_SIZE;
1843 }
1844
1845 return 0;
1846}
1847
Peter Lieven2d9187b2017-02-28 13:40:07 +01001848
1849static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1850 int nb_sectors, uint8_t *buf,
1851 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001852{
1853 int ret;
1854
1855 while (nb_sectors > 0) {
1856 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001857 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1858
Peter Lieven2d9187b2017-02-28 13:40:07 +01001859 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001860 case BLK_BACKING_FILE:
1861 /* If we have a backing file, leave clusters unallocated that are
1862 * unallocated in the source image, so that the backing file is
1863 * visible at the respective offset. */
1864 assert(s->target_has_backing);
1865 break;
1866
1867 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001868 /* If we're told to keep the target fully allocated (-S 0) or there
1869 * is real non-zero data, we must write it. Otherwise we can treat
1870 * it as zero sectors.
1871 * Compressed clusters need to be written as a whole, so in that
1872 * case we can only save the write if the buffer is completely
1873 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001874 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001875 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001876 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1877 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001878 (s->compressed &&
1879 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001880 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001881 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1882 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001883 if (ret < 0) {
1884 return ret;
1885 }
1886 break;
1887 }
1888 /* fall-through */
1889
1890 case BLK_ZERO:
1891 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001892 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001893 break;
1894 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001895 ret = blk_co_pwrite_zeroes(s->target,
1896 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001897 n << BDRV_SECTOR_BITS,
1898 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001899 if (ret < 0) {
1900 return ret;
1901 }
1902 break;
1903 }
1904
1905 sector_num += n;
1906 nb_sectors -= n;
1907 buf += n * BDRV_SECTOR_SIZE;
1908 }
1909
1910 return 0;
1911}
1912
Fam Zhengee5306d2018-06-01 17:26:48 +08001913static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1914 int nb_sectors)
1915{
1916 int n, ret;
1917
1918 while (nb_sectors > 0) {
1919 BlockBackend *blk;
1920 int src_cur;
1921 int64_t bs_sectors, src_cur_offset;
1922 int64_t offset;
1923
1924 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1925 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1926 blk = s->src[src_cur];
1927 bs_sectors = s->src_sectors[src_cur];
1928
1929 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1930
1931 ret = blk_co_copy_range(blk, offset, s->target,
1932 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001933 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001934 if (ret < 0) {
1935 return ret;
1936 }
1937
1938 sector_num += n;
1939 nb_sectors -= n;
1940 }
1941 return 0;
1942}
1943
Peter Lieven2d9187b2017-02-28 13:40:07 +01001944static void coroutine_fn convert_co_do_copy(void *opaque)
1945{
1946 ImgConvertState *s = opaque;
1947 uint8_t *buf = NULL;
1948 int ret, i;
1949 int index = -1;
1950
1951 for (i = 0; i < s->num_coroutines; i++) {
1952 if (s->co[i] == qemu_coroutine_self()) {
1953 index = i;
1954 break;
1955 }
1956 }
1957 assert(index >= 0);
1958
1959 s->running_coroutines++;
1960 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1961
1962 while (1) {
1963 int n;
1964 int64_t sector_num;
1965 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001966 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001967
1968 qemu_co_mutex_lock(&s->lock);
1969 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1970 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001971 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001972 }
1973 n = convert_iteration_sectors(s, s->sector_num);
1974 if (n < 0) {
1975 qemu_co_mutex_unlock(&s->lock);
1976 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001977 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001978 }
1979 /* save current sector and allocation status to local variables */
1980 sector_num = s->sector_num;
1981 status = s->status;
1982 if (!s->min_sparse && s->status == BLK_ZERO) {
1983 n = MIN(n, s->buf_sectors);
1984 }
1985 /* increment global sector counter so that other coroutines can
1986 * already continue reading beyond this request */
1987 s->sector_num += n;
1988 qemu_co_mutex_unlock(&s->lock);
1989
1990 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
1991 s->allocated_done += n;
1992 qemu_progress_print(100.0 * s->allocated_done /
1993 s->allocated_sectors, 0);
1994 }
1995
Fam Zhengee5306d2018-06-01 17:26:48 +08001996retry:
1997 copy_range = s->copy_range && s->status == BLK_DATA;
1998 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01001999 ret = convert_co_read(s, sector_num, n, buf);
2000 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002001 error_report("error while reading at byte %lld: %s",
2002 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002003 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002004 }
2005 } else if (!s->min_sparse && status == BLK_ZERO) {
2006 status = BLK_DATA;
2007 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2008 }
2009
2010 if (s->wr_in_order) {
2011 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002012 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002013 s->wait_sector_num[index] = sector_num;
2014 qemu_coroutine_yield();
2015 }
2016 s->wait_sector_num[index] = -1;
2017 }
2018
Anton Nefedovb91127e2017-04-26 11:33:15 +03002019 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002020 if (copy_range) {
2021 ret = convert_co_copy_range(s, sector_num, n);
2022 if (ret) {
2023 s->copy_range = false;
2024 goto retry;
2025 }
2026 } else {
2027 ret = convert_co_write(s, sector_num, n, buf, status);
2028 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002029 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002030 error_report("error while writing at byte %lld: %s",
2031 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002032 s->ret = ret;
2033 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002034 }
2035
2036 if (s->wr_in_order) {
2037 /* reenter the coroutine that might have waited
2038 * for this write to complete */
2039 s->wr_offs = sector_num + n;
2040 for (i = 0; i < s->num_coroutines; i++) {
2041 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2042 /*
2043 * A -> B -> A cannot occur because A has
2044 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2045 * B will never enter A during this time window.
2046 */
2047 qemu_coroutine_enter(s->co[i]);
2048 break;
2049 }
2050 }
2051 }
2052 }
2053
Peter Lieven2d9187b2017-02-28 13:40:07 +01002054 qemu_vfree(buf);
2055 s->co[index] = NULL;
2056 s->running_coroutines--;
2057 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2058 /* the convert job finished successfully */
2059 s->ret = 0;
2060 }
2061}
2062
Kevin Wolf690c7302015-03-19 13:33:32 +01002063static int convert_do_copy(ImgConvertState *s)
2064{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002065 int ret, i, n;
2066 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002067
2068 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002069 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2070 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002071 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002072 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002073
Kevin Wolf690c7302015-03-19 13:33:32 +01002074 /* Allocate buffer for copied data. For compressed images, only one cluster
2075 * can be copied at a time. */
2076 if (s->compressed) {
2077 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2078 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002079 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002080 }
2081 s->buf_sectors = s->cluster_sectors;
2082 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002083
Kevin Wolf690c7302015-03-19 13:33:32 +01002084 while (sector_num < s->total_sectors) {
2085 n = convert_iteration_sectors(s, sector_num);
2086 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002087 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002088 }
Max Reitzaad15de2016-03-24 23:33:57 +01002089 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2090 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002091 s->allocated_sectors += n;
2092 }
2093 sector_num += n;
2094 }
2095
2096 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002097 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002098 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002099
Peter Lieven2d9187b2017-02-28 13:40:07 +01002100 qemu_co_mutex_init(&s->lock);
2101 for (i = 0; i < s->num_coroutines; i++) {
2102 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2103 s->wait_sector_num[i] = -1;
2104 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002105 }
2106
Anton Nefedovb91127e2017-04-26 11:33:15 +03002107 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002108 main_loop_wait(false);
2109 }
2110
2111 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002112 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002113 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002114 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002115 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002116 }
2117 }
2118
Peter Lieven2d9187b2017-02-28 13:40:07 +01002119 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002120}
2121
Eric Blake74a43202021-07-09 10:39:50 -05002122/* Check that bitmaps can be copied, or output an error */
Eric Blake955171e2021-07-21 10:53:48 -05002123static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
Eric Blake74a43202021-07-09 10:39:50 -05002124{
2125 BdrvDirtyBitmap *bm;
2126
2127 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2128 error_report("Source lacks bitmap support");
2129 return -1;
2130 }
2131 FOR_EACH_DIRTY_BITMAP(src, bm) {
2132 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2133 continue;
2134 }
Eric Blake955171e2021-07-21 10:53:48 -05002135 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
Eric Blake74a43202021-07-09 10:39:50 -05002136 error_report("Cannot copy inconsistent bitmap '%s'",
2137 bdrv_dirty_bitmap_name(bm));
Eric Blake955171e2021-07-21 10:53:48 -05002138 error_printf("Try --skip-broken-bitmaps, or "
2139 "use 'qemu-img bitmap --remove' to delete it\n");
Eric Blake74a43202021-07-09 10:39:50 -05002140 return -1;
2141 }
2142 }
2143 return 0;
2144}
2145
Eric Blake955171e2021-07-21 10:53:48 -05002146static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2147 bool skip_broken)
Eric Blake15e39ad2020-05-21 14:21:36 -05002148{
2149 BdrvDirtyBitmap *bm;
2150 Error *err = NULL;
2151
2152 FOR_EACH_DIRTY_BITMAP(src, bm) {
2153 const char *name;
2154
2155 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2156 continue;
2157 }
2158 name = bdrv_dirty_bitmap_name(bm);
Eric Blake955171e2021-07-21 10:53:48 -05002159 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2160 warn_report("Skipping inconsistent bitmap '%s'", name);
2161 continue;
2162 }
Eric Blake15e39ad2020-05-21 14:21:36 -05002163 qmp_block_dirty_bitmap_add(dst->node_name, name,
2164 true, bdrv_dirty_bitmap_granularity(bm),
2165 true, true,
2166 true, !bdrv_dirty_bitmap_enabled(bm),
2167 &err);
2168 if (err) {
2169 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2170 return -1;
2171 }
2172
2173 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2174 &err);
2175 if (err) {
2176 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
Eric Blake74a43202021-07-09 10:39:50 -05002177 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
Eric Blake15e39ad2020-05-21 14:21:36 -05002178 return -1;
2179 }
2180 }
2181
2182 return 0;
2183}
2184
Peter Lieven6360ab22018-07-13 09:15:39 +02002185#define MAX_BUF_SECTORS 32768
2186
Zhengui0c8c4892020-10-20 14:47:44 +00002187static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2188{
2189 ThrottleConfig cfg;
2190
2191 throttle_config_init(&cfg);
2192 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2193
2194 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2195 blk_set_io_limits(blk, &cfg);
2196}
2197
bellardea2384d2004-08-01 21:59:26 +00002198static int img_convert(int argc, char **argv)
2199{
Kevin Wolf0b8fb552021-04-22 18:43:44 +02002200 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002201 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002202 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
Eric Blake1899bf42021-09-13 08:17:35 -05002203 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2204 *backing_fmt = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002205 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002206 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002207 BlockDriverState *out_bs;
2208 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002209 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002210 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002211 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002212 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002213 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002214 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002215 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002216 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002217 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002218 bool bitmaps = false;
Eric Blake955171e2021-07-21 10:53:48 -05002219 bool skip_broken = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002220 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002221
Peter Lieven9fd77f92017-04-21 11:11:55 +02002222 ImgConvertState s = (ImgConvertState) {
2223 /* Need at least 4k of zeros for sparse detection */
2224 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002225 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2227 .wr_in_order = true,
2228 .num_coroutines = 8,
2229 };
2230
bellardea2384d2004-08-01 21:59:26 +00002231 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002232 static const struct option long_options[] = {
2233 {"help", no_argument, 0, 'h'},
2234 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002235 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002236 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002237 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002238 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002239 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002240 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Eric Blake955171e2021-07-21 10:53:48 -05002241 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002242 {0, 0, 0, 0}
2243 };
Eric Blake1899bf42021-09-13 08:17:35 -05002244 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002245 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002246 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002247 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002248 }
bellardea2384d2004-08-01 21:59:26 +00002249 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002250 case ':':
2251 missing_argument(argv[optind - 1]);
2252 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002253 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002254 unrecognized_option(argv[optind - 1]);
2255 break;
bellardea2384d2004-08-01 21:59:26 +00002256 case 'h':
2257 help();
2258 break;
2259 case 'f':
2260 fmt = optarg;
2261 break;
2262 case 'O':
2263 out_fmt = optarg;
2264 break;
thsf58c7b32008-06-05 21:53:49 +00002265 case 'B':
2266 out_baseimg = optarg;
2267 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002268 case 'C':
2269 s.copy_range = true;
2270 break;
bellardea2384d2004-08-01 21:59:26 +00002271 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002272 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002273 break;
Eric Blake1899bf42021-09-13 08:17:35 -05002274 case 'F':
2275 backing_fmt = optarg;
2276 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002277 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002278 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002279 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002280 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002281 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002282 case 'l':
2283 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002284 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2285 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002286 if (!sn_opts) {
2287 error_report("Failed in parsing snapshot param '%s'",
2288 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002289 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002290 }
2291 } else {
2292 snapshot_name = optarg;
2293 }
2294 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002295 case 'S':
2296 {
2297 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002298
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002299 sval = cvtnum("buffer size for sparse output", optarg);
2300 if (sval < 0) {
2301 goto fail_getopt;
2302 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002303 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2304 error_report("Invalid buffer size for sparse output specified. "
2305 "Valid sizes are multiples of %llu up to %llu. Select "
2306 "0 to disable sparse detection (fully allocates output).",
2307 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002308 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002309 }
2310
Peter Lieven9fd77f92017-04-21 11:11:55 +02002311 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002312 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002313 break;
2314 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002315 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002316 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002317 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002318 case 't':
2319 cache = optarg;
2320 break;
Max Reitz40055952014-07-22 22:58:42 +02002321 case 'T':
2322 src_cache = optarg;
2323 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002324 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002325 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002326 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002327 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002328 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002329 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002330 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002331 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2332 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002333 error_report("Invalid number of coroutines. Allowed number of"
2334 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002335 goto fail_getopt;
2336 }
2337 break;
2338 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002339 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002340 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002341 case 'U':
2342 force_share = true;
2343 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002344 case 'r':
2345 rate_limit = cvtnum("rate limit", optarg);
2346 if (rate_limit < 0) {
2347 goto fail_getopt;
2348 }
2349 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002350 case OPTION_OBJECT:
2351 user_creatable_process_cmdline(optarg);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002352 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002353 case OPTION_IMAGE_OPTS:
2354 image_opts = true;
2355 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002356 case OPTION_SALVAGE:
2357 s.salvage = true;
2358 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002359 case OPTION_TARGET_IMAGE_OPTS:
2360 tgt_image_opts = true;
2361 break;
David Edmondson168468f2020-02-05 11:02:48 +00002362 case OPTION_TARGET_IS_ZERO:
2363 /*
2364 * The user asserting that the target is blank has the
2365 * same effect as the target driver supporting zero
2366 * initialisation.
2367 */
2368 s.has_zero_init = true;
2369 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002370 case OPTION_BITMAPS:
2371 bitmaps = true;
2372 break;
Eric Blake955171e2021-07-21 10:53:48 -05002373 case OPTION_SKIP_BROKEN:
2374 skip_broken = true;
2375 break;
bellardea2384d2004-08-01 21:59:26 +00002376 }
2377 }
ths3b46e622007-09-17 08:09:54 +00002378
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002379 if (!out_fmt && !tgt_image_opts) {
2380 out_fmt = "raw";
2381 }
2382
Eric Blake955171e2021-07-21 10:53:48 -05002383 if (skip_broken && !bitmaps) {
2384 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2385 goto fail_getopt;
2386 }
2387
Fam Zhenge11ce122018-07-27 11:34:01 +08002388 if (s.compressed && s.copy_range) {
2389 error_report("Cannot enable copy offloading when -c is used");
2390 goto fail_getopt;
2391 }
2392
2393 if (explict_min_sparse && s.copy_range) {
2394 error_report("Cannot enable copy offloading when -S is used");
2395 goto fail_getopt;
2396 }
2397
Max Reitz8eaac022019-05-07 22:35:03 +02002398 if (s.copy_range && s.salvage) {
2399 error_report("Cannot use copy offloading in salvaging mode");
2400 goto fail_getopt;
2401 }
2402
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002403 if (tgt_image_opts && !skip_create) {
2404 error_report("--target-image-opts requires use of -n flag");
2405 goto fail_getopt;
2406 }
2407
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002408 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002409 error_report("-o has no effect when skipping image creation");
2410 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002411 }
2412
David Edmondson168468f2020-02-05 11:02:48 +00002413 if (s.has_zero_init && !skip_create) {
2414 error_report("--target-is-zero requires use of -n flag");
2415 goto fail_getopt;
2416 }
2417
Peter Lieven9fd77f92017-04-21 11:11:55 +02002418 s.src_num = argc - optind - 1;
2419 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2420
2421 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002422 if (out_fmt) {
2423 ret = print_block_option_help(out_filename, out_fmt);
2424 goto fail_getopt;
2425 } else {
2426 error_report("Option help requires a format be specified");
2427 goto fail_getopt;
2428 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002429 }
2430
2431 if (s.src_num < 1) {
2432 error_report("Must specify image file name");
2433 goto fail_getopt;
2434 }
2435
Peter Lieven9fd77f92017-04-21 11:11:55 +02002436 /* ret is still -EINVAL until here */
2437 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2438 if (ret < 0) {
2439 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002440 goto fail_getopt;
2441 }
2442
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002443 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002444 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002445 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002446 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002447 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002448 qemu_progress_print(0, 100);
2449
Peter Lieven9fd77f92017-04-21 11:11:55 +02002450 s.src = g_new0(BlockBackend *, s.src_num);
2451 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002452 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002453
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002455 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002456 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002457 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002458 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002459 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460 ret = -1;
2461 goto out;
2462 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002463 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2464 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002465 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002466 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002467 ret = -1;
2468 goto out;
2469 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002470 src_bs = blk_bs(s.src[bs_i]);
2471 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2472 BDRV_SECTOR_SIZE);
2473 if (!bdrv_get_info(src_bs, &bdi)) {
2474 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2475 bdi.cluster_size / BDRV_SECTOR_SIZE);
2476 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002477 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002478 }
bellardea2384d2004-08-01 21:59:26 +00002479
Wenchao Xiaef806542013-12-04 17:10:57 +08002480 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002481 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002482 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2483 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2484 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002485 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002486 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002487 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002488 ret = -1;
2489 goto out;
2490 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002491
Peter Lieven9fd77f92017-04-21 11:11:55 +02002492 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2493 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002494 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002495 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002496 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002497 ret = -1;
2498 goto out;
edison51ef6722010-09-21 19:58:41 -07002499 }
2500
Max Reitz2e024cd2015-02-11 09:58:46 -05002501 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002502 /* Find driver and parse its options */
2503 drv = bdrv_find_format(out_fmt);
2504 if (!drv) {
2505 error_report("Unknown file format '%s'", out_fmt);
2506 ret = -1;
2507 goto out;
2508 }
2509
2510 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2511 if (!proto_drv) {
2512 error_report_err(local_err);
2513 ret = -1;
2514 goto out;
2515 }
2516
Max Reitz2e024cd2015-02-11 09:58:46 -05002517 if (!drv->create_opts) {
2518 error_report("Format driver '%s' does not support image creation",
2519 drv->format_name);
2520 ret = -1;
2521 goto out;
2522 }
Max Reitzf75613c2014-12-02 18:32:46 +01002523
Max Reitz2e024cd2015-02-11 09:58:46 -05002524 if (!proto_drv->create_opts) {
2525 error_report("Protocol driver '%s' does not support image creation",
2526 proto_drv->format_name);
2527 ret = -1;
2528 goto out;
2529 }
Max Reitzf75613c2014-12-02 18:32:46 +01002530
Max Reitz2e024cd2015-02-11 09:58:46 -05002531 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2532 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002533
Max Reitz2e024cd2015-02-11 09:58:46 -05002534 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002535 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002536 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002537 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002538 ret = -1;
2539 goto out;
2540 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002541 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002542
Yi Lic075c422020-08-19 09:36:07 +08002543 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2544 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Eric Blake1899bf42021-09-13 08:17:35 -05002545 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
Max Reitz2e024cd2015-02-11 09:58:46 -05002546 if (ret < 0) {
2547 goto out;
2548 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002549 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002550
Kevin Wolfa18953f2010-10-14 15:46:04 +02002551 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002552 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002553 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002554 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002555 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002556 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002557
David Edmondson168468f2020-02-05 11:02:48 +00002558 if (s.has_zero_init && s.target_has_backing) {
2559 error_report("Cannot use --target-is-zero when the destination "
2560 "image has a backing file");
2561 goto out;
2562 }
2563
Max Reitz48758a82017-04-26 15:46:48 +02002564 if (s.src_num > 1 && out_baseimg) {
2565 error_report("Having a backing file for the target makes no sense when "
2566 "concatenating multiple input images");
2567 ret = -1;
2568 goto out;
2569 }
2570
Eric Blaked9f059a2020-07-06 15:39:54 -05002571 if (out_baseimg_param) {
2572 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
Eric Blake497a30d2021-05-03 14:36:00 -07002573 error_report("Use of backing file requires explicit "
2574 "backing format");
2575 ret = -1;
2576 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05002577 }
2578 }
2579
Kevin Wolfefa84d42009-05-18 16:42:12 +02002580 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002581 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002582 bool encryption =
2583 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002584 const char *encryptfmt =
2585 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002586 const char *preallocation =
2587 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002588
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002589 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002590 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002591 ret = -1;
2592 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002593 }
2594
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002595 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002596 error_report("Compression and encryption not supported at "
2597 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002598 ret = -1;
2599 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002600 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002601
Chunyan Liu83d05212014-06-05 17:20:51 +08002602 if (preallocation
2603 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002604 {
2605 error_report("Compression and preallocation not supported at "
2606 "the same time");
2607 ret = -1;
2608 goto out;
2609 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002610 }
2611
Eric Blake15e39ad2020-05-21 14:21:36 -05002612 /* Determine if bitmaps need copying */
2613 if (bitmaps) {
2614 if (s.src_num > 1) {
2615 error_report("Copying bitmaps only possible with single source");
2616 ret = -1;
2617 goto out;
2618 }
Eric Blake955171e2021-07-21 10:53:48 -05002619 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
Eric Blake74a43202021-07-09 10:39:50 -05002620 if (ret < 0) {
Eric Blake15e39ad2020-05-21 14:21:36 -05002621 goto out;
2622 }
2623 }
2624
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002625 /*
2626 * The later open call will need any decryption secrets, and
2627 * bdrv_create() will purge "opts", so extract them now before
2628 * they are lost.
2629 */
2630 if (!skip_create) {
2631 open_opts = qdict_new();
2632 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002633
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002634 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002635 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002636 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002637 error_reportf_err(local_err, "%s: error while converting %s: ",
2638 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002639 goto out;
bellardea2384d2004-08-01 21:59:26 +00002640 }
2641 }
ths3b46e622007-09-17 08:09:54 +00002642
Max Reitz4d7c4872019-07-24 19:12:29 +02002643 s.target_is_new = !skip_create;
2644
Peter Lieven9fd77f92017-04-21 11:11:55 +02002645 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002646 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002647 if (ret < 0) {
2648 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002649 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002650 }
2651
Hanna Reitza1c62432021-08-19 12:12:00 +02002652 if (flags & BDRV_O_NOCACHE) {
2653 /*
2654 * If we open the target with O_DIRECT, it may be necessary to
2655 * extend its size to align to the physical sector size.
2656 */
2657 flags |= BDRV_O_RESIZE;
2658 }
2659
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002660 if (skip_create) {
2661 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002662 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002663 } else {
2664 /* TODO ultimately we should allow --target-image-opts
2665 * to be used even when -n is not given.
2666 * That has to wait for bdrv_create to be improved
2667 * to allow filenames in option syntax
2668 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002669 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002670 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002671 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002672 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002673 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002674 ret = -1;
2675 goto out;
2676 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002677 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002678
Eric Blake15e39ad2020-05-21 14:21:36 -05002679 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2680 error_report("Format driver '%s' does not support bitmaps",
2681 out_bs->drv->format_name);
2682 ret = -1;
2683 goto out;
2684 }
2685
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002686 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002687 error_report("Compression not supported for this file format");
2688 ret = -1;
2689 goto out;
2690 }
2691
Eric Blake5def6b82016-06-23 16:37:19 -06002692 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002693 * or discard_alignment of the out_bs is greater. Limit to
2694 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2695 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002696 MAX(s.buf_sectors,
2697 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2698 out_bs->bl.pdiscard_alignment >>
2699 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002700
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002701 /* try to align the write requests to the destination to avoid unnecessary
2702 * RMW cycles. */
2703 s.alignment = MAX(pow2floor(s.min_sparse),
2704 DIV_ROUND_UP(out_bs->bl.request_alignment,
2705 BDRV_SECTOR_SIZE));
2706 assert(is_power_of_2(s.alignment));
2707
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002708 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002709 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002710 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002711 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002712 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002713 ret = -1;
2714 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002715 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002716 error_report("output file is smaller than input file");
2717 ret = -1;
2718 goto out;
2719 }
2720 }
2721
Max Reitzc69291e2020-01-21 16:59:14 +01002722 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002723 /* Errors are treated as "backing length unknown" (which means
2724 * s.target_backing_sectors has to be negative, which it will
2725 * be automatically). The backing file length is used only
2726 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002727 s.target_backing_sectors =
2728 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002729 } else {
2730 s.target_backing_sectors = -1;
2731 }
2732
Peter Lieven24f833c2013-11-27 11:07:07 +01002733 ret = bdrv_get_info(out_bs, &bdi);
2734 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002735 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002736 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002737 goto out;
2738 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002739 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002740 s.compressed = s.compressed || bdi.needs_compressed_writes;
2741 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002742 }
2743
Zhengui0c8c4892020-10-20 14:47:44 +00002744 if (rate_limit) {
2745 set_rate_limit(s.target, rate_limit);
2746 }
2747
Peter Lieven9fd77f92017-04-21 11:11:55 +02002748 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002749
2750 /* Now copy the bitmaps */
2751 if (bitmaps && ret == 0) {
Eric Blake955171e2021-07-21 10:53:48 -05002752 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
Eric Blake15e39ad2020-05-21 14:21:36 -05002753 }
2754
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002755out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002756 if (!ret) {
2757 qemu_progress_print(100, 0);
2758 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002759 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002760 qemu_opts_del(opts);
2761 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002762 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002763 blk_unref(s.target);
2764 if (s.src) {
2765 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2766 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002767 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002768 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002769 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002770 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002771 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002772fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002773 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002774 g_free(options);
2775
Peter Lieven9fd77f92017-04-21 11:11:55 +02002776 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002777}
2778
bellard57d1a2b2004-08-03 21:15:11 +00002779
bellardfaea38e2006-08-05 21:31:00 +00002780static void dump_snapshots(BlockDriverState *bs)
2781{
2782 QEMUSnapshotInfo *sn_tab, *sn;
2783 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002784
2785 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2786 if (nb_sns <= 0)
2787 return;
2788 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002789 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002790 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002791 for(i = 0; i < nb_sns; i++) {
2792 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002793 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002794 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002795 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002796 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002797}
2798
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002799static void dump_json_image_info_list(ImageInfoList *list)
2800{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002801 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002802 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002803 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002804
2805 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2806 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002807 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002808 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002809 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002810 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002811 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002812 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002813}
2814
Benoît Canetc054b3f2012-09-05 13:09:02 +02002815static void dump_json_image_info(ImageInfo *info)
2816{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002817 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002818 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002819 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002820
2821 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2822 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002823 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002824 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002825 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002826 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002827 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002828 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002829}
2830
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002831static void dump_human_image_info_list(ImageInfoList *list)
2832{
2833 ImageInfoList *elem;
2834 bool delim = false;
2835
2836 for (elem = list; elem; elem = elem->next) {
2837 if (delim) {
2838 printf("\n");
2839 }
2840 delim = true;
2841
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002842 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002843 }
2844}
2845
2846static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2847{
2848 return strcmp(a, b) == 0;
2849}
2850
2851/**
2852 * Open an image file chain and return an ImageInfoList
2853 *
2854 * @filename: topmost image filename
2855 * @fmt: topmost image format (may be NULL to autodetect)
2856 * @chain: true - enumerate entire backing file chain
2857 * false - only topmost image file
2858 *
2859 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2860 * image file. If there was an error a message will have been printed to
2861 * stderr.
2862 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002863static ImageInfoList *collect_image_info_list(bool image_opts,
2864 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002865 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002866 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002867{
2868 ImageInfoList *head = NULL;
Eric Blakec3033fd2021-01-13 16:10:12 -06002869 ImageInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002870 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002871 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002872
2873 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2874
2875 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002876 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002877 BlockDriverState *bs;
2878 ImageInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002879
2880 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2881 error_report("Backing file '%s' creates an infinite loop.",
2882 filename);
2883 goto err;
2884 }
2885 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2886
Max Reitzefaa7c42016-03-16 19:54:38 +01002887 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002888 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2889 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002890 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002891 goto err;
2892 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002893 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002894
Wenchao Xia43526ec2013-06-06 12:27:58 +08002895 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002896 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002897 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002898 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002899 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002900 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002901
Eric Blakec3033fd2021-01-13 16:10:12 -06002902 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002903
Markus Armbruster26f54e92014-10-07 13:59:04 +02002904 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002905
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002906 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002907 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002908 image_opts = false;
2909
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002910 if (chain) {
2911 if (info->has_full_backing_filename) {
2912 filename = info->full_backing_filename;
2913 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002914 error_report("Could not determine absolute backing filename,"
2915 " but backing filename '%s' present",
2916 info->backing_filename);
2917 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002918 }
2919 if (info->has_backing_filename_format) {
2920 fmt = info->backing_filename_format;
2921 }
2922 }
2923 }
2924 g_hash_table_destroy(filenames);
2925 return head;
2926
2927err:
2928 qapi_free_ImageInfoList(head);
2929 g_hash_table_destroy(filenames);
2930 return NULL;
2931}
2932
Benoît Canetc054b3f2012-09-05 13:09:02 +02002933static int img_info(int argc, char **argv)
2934{
2935 int c;
2936 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002937 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002938 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002939 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002940 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002941 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002942
bellardea2384d2004-08-01 21:59:26 +00002943 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002944 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002945 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002946 int option_index = 0;
2947 static const struct option long_options[] = {
2948 {"help", no_argument, 0, 'h'},
2949 {"format", required_argument, 0, 'f'},
2950 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002951 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002952 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002953 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002954 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002955 {0, 0, 0, 0}
2956 };
Fam Zheng335e9932017-05-03 00:35:39 +08002957 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002958 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002959 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002960 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002961 }
bellardea2384d2004-08-01 21:59:26 +00002962 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002963 case ':':
2964 missing_argument(argv[optind - 1]);
2965 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002966 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002967 unrecognized_option(argv[optind - 1]);
2968 break;
bellardea2384d2004-08-01 21:59:26 +00002969 case 'h':
2970 help();
2971 break;
2972 case 'f':
2973 fmt = optarg;
2974 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002975 case 'U':
2976 force_share = true;
2977 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002978 case OPTION_OUTPUT:
2979 output = optarg;
2980 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002981 case OPTION_BACKING_CHAIN:
2982 chain = true;
2983 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002984 case OPTION_OBJECT:
2985 user_creatable_process_cmdline(optarg);
2986 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002987 case OPTION_IMAGE_OPTS:
2988 image_opts = true;
2989 break;
bellardea2384d2004-08-01 21:59:26 +00002990 }
2991 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002992 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002993 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002994 }
bellardea2384d2004-08-01 21:59:26 +00002995 filename = argv[optind++];
2996
Benoît Canetc054b3f2012-09-05 13:09:02 +02002997 if (output && !strcmp(output, "json")) {
2998 output_format = OFORMAT_JSON;
2999 } else if (output && !strcmp(output, "human")) {
3000 output_format = OFORMAT_HUMAN;
3001 } else if (output) {
3002 error_report("--output must be used with human or json as argument.");
3003 return 1;
3004 }
3005
Fam Zheng335e9932017-05-03 00:35:39 +08003006 list = collect_image_info_list(image_opts, filename, fmt, chain,
3007 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003008 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003009 return 1;
3010 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003011
Benoît Canetc054b3f2012-09-05 13:09:02 +02003012 switch (output_format) {
3013 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003014 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003015 break;
3016 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003017 if (chain) {
3018 dump_json_image_info_list(list);
3019 } else {
3020 dump_json_image_info(list->value);
3021 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003022 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003023 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003024
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003025 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003026 return 0;
3027}
3028
Eric Blake30065d12019-03-26 13:40:43 -05003029static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3030 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003031{
3032 switch (output_format) {
3033 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003034 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003035 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003036 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003037 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003038 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003039 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003040 e->start, e->length,
3041 e->has_offset ? e->offset : 0,
3042 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003043 }
3044 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3045 * Modify the flags here to allow more coalescing.
3046 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003047 if (next && (!next->data || next->zero)) {
3048 next->data = false;
3049 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003050 }
3051 break;
3052 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003053 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Eric Blake8417e132021-07-01 14:06:55 -05003054 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
3055 " \"data\": %s", e->start, e->length, e->depth,
3056 e->present ? "true" : "false",
Fam Zheng16b0d552016-01-26 11:59:02 +08003057 e->zero ? "true" : "false",
3058 e->data ? "true" : "false");
3059 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003060 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003061 }
3062 putchar('}');
3063
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003064 if (next) {
3065 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003066 }
3067 break;
3068 }
Eric Blake30065d12019-03-26 13:40:43 -05003069 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003070}
3071
Eric Blake5e344dd2017-10-11 22:47:02 -05003072static int get_block_status(BlockDriverState *bs, int64_t offset,
3073 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003074{
Eric Blake237d78f2017-10-11 22:47:03 -05003075 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003076 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003077 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003078 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003079 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003080 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003081
3082 /* As an optimization, we could cache the current range of unallocated
3083 * clusters in each file of the chain, and avoid querying the same
3084 * range repeatedly.
3085 */
3086
3087 depth = 0;
3088 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003089 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003090 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003091 if (ret < 0) {
3092 return ret;
3093 }
Eric Blake237d78f2017-10-11 22:47:03 -05003094 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003095 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3096 break;
3097 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003098 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003099 if (bs == NULL) {
3100 ret = 0;
3101 break;
3102 }
3103
3104 depth++;
3105 }
3106
John Snow28756452016-02-05 13:12:33 -05003107 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3108
Max Reitzf30c66b2019-02-01 20:29:05 +01003109 if (file && has_offset) {
3110 bdrv_refresh_filename(file);
3111 filename = file->filename;
3112 }
3113
John Snow28756452016-02-05 13:12:33 -05003114 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003115 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003116 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003117 .data = !!(ret & BDRV_BLOCK_DATA),
3118 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003119 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003120 .has_offset = has_offset,
3121 .depth = depth,
Eric Blake8417e132021-07-01 14:06:55 -05003122 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
Max Reitzf30c66b2019-02-01 20:29:05 +01003123 .has_filename = filename,
3124 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003125 };
3126
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003127 return 0;
3128}
3129
Fam Zheng16b0d552016-01-26 11:59:02 +08003130static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3131{
3132 if (curr->length == 0) {
3133 return false;
3134 }
3135 if (curr->zero != next->zero ||
3136 curr->data != next->data ||
3137 curr->depth != next->depth ||
Eric Blake8417e132021-07-01 14:06:55 -05003138 curr->present != next->present ||
Fam Zheng16b0d552016-01-26 11:59:02 +08003139 curr->has_filename != next->has_filename ||
3140 curr->has_offset != next->has_offset) {
3141 return false;
3142 }
3143 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3144 return false;
3145 }
3146 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3147 return false;
3148 }
3149 return true;
3150}
3151
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003152static int img_map(int argc, char **argv)
3153{
3154 int c;
3155 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003156 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003157 BlockDriverState *bs;
3158 const char *filename, *fmt, *output;
3159 int64_t length;
3160 MapEntry curr = { .length = 0 }, next;
3161 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003162 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003163 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003164 int64_t start_offset = 0;
3165 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003166
3167 fmt = NULL;
3168 output = NULL;
3169 for (;;) {
3170 int option_index = 0;
3171 static const struct option long_options[] = {
3172 {"help", no_argument, 0, 'h'},
3173 {"format", required_argument, 0, 'f'},
3174 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003175 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003176 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003177 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003178 {"start-offset", required_argument, 0, 's'},
3179 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003180 {0, 0, 0, 0}
3181 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003182 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003183 long_options, &option_index);
3184 if (c == -1) {
3185 break;
3186 }
3187 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003188 case ':':
3189 missing_argument(argv[optind - 1]);
3190 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003191 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003192 unrecognized_option(argv[optind - 1]);
3193 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003194 case 'h':
3195 help();
3196 break;
3197 case 'f':
3198 fmt = optarg;
3199 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003200 case 'U':
3201 force_share = true;
3202 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003203 case OPTION_OUTPUT:
3204 output = optarg;
3205 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003206 case 's':
3207 start_offset = cvtnum("start offset", optarg);
3208 if (start_offset < 0) {
3209 return 1;
3210 }
3211 break;
3212 case 'l':
3213 max_length = cvtnum("max length", optarg);
3214 if (max_length < 0) {
3215 return 1;
3216 }
3217 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003218 case OPTION_OBJECT:
3219 user_creatable_process_cmdline(optarg);
3220 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003221 case OPTION_IMAGE_OPTS:
3222 image_opts = true;
3223 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003224 }
3225 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003226 if (optind != argc - 1) {
3227 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003228 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003229 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003230
3231 if (output && !strcmp(output, "json")) {
3232 output_format = OFORMAT_JSON;
3233 } else if (output && !strcmp(output, "human")) {
3234 output_format = OFORMAT_HUMAN;
3235 } else if (output) {
3236 error_report("--output must be used with human or json as argument.");
3237 return 1;
3238 }
3239
Fam Zheng335e9932017-05-03 00:35:39 +08003240 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003241 if (!blk) {
3242 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003243 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003244 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003245
3246 if (output_format == OFORMAT_HUMAN) {
3247 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003248 } else if (output_format == OFORMAT_JSON) {
3249 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003250 }
3251
Max Reitzf1d3cd72015-02-05 13:58:18 -05003252 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003253 if (length < 0) {
3254 error_report("Failed to get size for '%s'", filename);
3255 return 1;
3256 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003257 if (max_length != -1) {
3258 length = MIN(start_offset + max_length, length);
3259 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003260
Eyal Moscovicic0469492020-05-13 16:36:29 +03003261 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003262 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003263 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003264 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003265
Eric Blake5e344dd2017-10-11 22:47:02 -05003266 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003267 if (ret < 0) {
3268 error_report("Could not read file metadata: %s", strerror(-ret));
3269 goto out;
3270 }
3271
Fam Zheng16b0d552016-01-26 11:59:02 +08003272 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003273 curr.length += next.length;
3274 continue;
3275 }
3276
3277 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003278 ret = dump_map_entry(output_format, &curr, &next);
3279 if (ret < 0) {
3280 goto out;
3281 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003282 }
3283 curr = next;
3284 }
3285
Eric Blake30065d12019-03-26 13:40:43 -05003286 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003287 if (output_format == OFORMAT_JSON) {
3288 puts("]");
3289 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003290
3291out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003292 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003293 return ret < 0;
3294}
3295
aliguorif7b4a942009-01-07 17:40:15 +00003296#define SNAPSHOT_LIST 1
3297#define SNAPSHOT_CREATE 2
3298#define SNAPSHOT_APPLY 3
3299#define SNAPSHOT_DELETE 4
3300
Stuart Brady153859b2009-06-07 00:42:17 +01003301static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003302{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003303 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003304 BlockDriverState *bs;
3305 QEMUSnapshotInfo sn;
3306 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003307 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003308 int action = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003309 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003310 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003311 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003312 bool force_share = false;
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003313 int64_t rt;
aliguorif7b4a942009-01-07 17:40:15 +00003314
Kevin Wolfce099542016-03-15 13:01:04 +01003315 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003316 /* Parse commandline parameters */
3317 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003318 static const struct option long_options[] = {
3319 {"help", no_argument, 0, 'h'},
3320 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003321 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003322 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003323 {0, 0, 0, 0}
3324 };
Fam Zheng335e9932017-05-03 00:35:39 +08003325 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003326 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003327 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003328 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003329 }
aliguorif7b4a942009-01-07 17:40:15 +00003330 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003331 case ':':
3332 missing_argument(argv[optind - 1]);
3333 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003334 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003335 unrecognized_option(argv[optind - 1]);
3336 break;
aliguorif7b4a942009-01-07 17:40:15 +00003337 case 'h':
3338 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003339 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003340 case 'l':
3341 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003342 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003343 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003344 }
3345 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003346 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003347 break;
3348 case 'a':
3349 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003350 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003351 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003352 }
3353 action = SNAPSHOT_APPLY;
3354 snapshot_name = optarg;
3355 break;
3356 case 'c':
3357 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003358 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003359 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003360 }
3361 action = SNAPSHOT_CREATE;
3362 snapshot_name = optarg;
3363 break;
3364 case 'd':
3365 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003366 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003367 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003368 }
3369 action = SNAPSHOT_DELETE;
3370 snapshot_name = optarg;
3371 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003372 case 'q':
3373 quiet = true;
3374 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003375 case 'U':
3376 force_share = true;
3377 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003378 case OPTION_OBJECT:
3379 user_creatable_process_cmdline(optarg);
3380 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003381 case OPTION_IMAGE_OPTS:
3382 image_opts = true;
3383 break;
aliguorif7b4a942009-01-07 17:40:15 +00003384 }
3385 }
3386
Kevin Wolffc11eb22013-08-05 10:53:04 +02003387 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003388 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003389 }
aliguorif7b4a942009-01-07 17:40:15 +00003390 filename = argv[optind++];
3391
3392 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003393 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3394 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003395 if (!blk) {
3396 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003397 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003398 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003399
3400 /* Perform the requested action */
3401 switch(action) {
3402 case SNAPSHOT_LIST:
3403 dump_snapshots(bs);
3404 break;
3405
3406 case SNAPSHOT_CREATE:
3407 memset(&sn, 0, sizeof(sn));
3408 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3409
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003410 rt = g_get_real_time();
3411 sn.date_sec = rt / G_USEC_PER_SEC;
3412 sn.date_nsec = (rt % G_USEC_PER_SEC) * 1000;
aliguorif7b4a942009-01-07 17:40:15 +00003413
3414 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003415 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003416 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003417 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003418 }
aliguorif7b4a942009-01-07 17:40:15 +00003419 break;
3420
3421 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003422 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003423 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003424 error_reportf_err(err, "Could not apply snapshot '%s': ",
3425 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003426 }
aliguorif7b4a942009-01-07 17:40:15 +00003427 break;
3428
3429 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003430 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3431 if (ret < 0) {
3432 error_report("Could not delete snapshot '%s': snapshot not "
3433 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003434 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003435 } else {
3436 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3437 if (ret < 0) {
3438 error_reportf_err(err, "Could not delete snapshot '%s': ",
3439 snapshot_name);
3440 ret = 1;
3441 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003442 }
aliguorif7b4a942009-01-07 17:40:15 +00003443 break;
3444 }
3445
3446 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003447 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003448 if (ret) {
3449 return 1;
3450 }
Stuart Brady153859b2009-06-07 00:42:17 +01003451 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003452}
3453
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003454static int img_rebase(int argc, char **argv)
3455{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003456 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003457 uint8_t *buf_old = NULL;
3458 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003459 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003460 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003461 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003462 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3463 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003464 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003465 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003466 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003467 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003468 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003469 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003470 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003471
3472 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003473 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003474 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003475 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003476 out_baseimg = NULL;
3477 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003478 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003479 static const struct option long_options[] = {
3480 {"help", no_argument, 0, 'h'},
3481 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003482 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003483 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003484 {0, 0, 0, 0}
3485 };
Fam Zheng335e9932017-05-03 00:35:39 +08003486 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003487 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003488 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003489 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003490 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003491 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003492 case ':':
3493 missing_argument(argv[optind - 1]);
3494 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003495 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003496 unrecognized_option(argv[optind - 1]);
3497 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003498 case 'h':
3499 help();
3500 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003501 case 'f':
3502 fmt = optarg;
3503 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003504 case 'F':
3505 out_basefmt = optarg;
3506 break;
3507 case 'b':
3508 out_baseimg = optarg;
3509 break;
3510 case 'u':
3511 unsafe = 1;
3512 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003513 case 'p':
3514 progress = 1;
3515 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003516 case 't':
3517 cache = optarg;
3518 break;
Max Reitz40055952014-07-22 22:58:42 +02003519 case 'T':
3520 src_cache = optarg;
3521 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003522 case 'q':
3523 quiet = true;
3524 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003525 case OPTION_OBJECT:
3526 user_creatable_process_cmdline(optarg);
3527 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003528 case OPTION_IMAGE_OPTS:
3529 image_opts = true;
3530 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003531 case 'U':
3532 force_share = true;
3533 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003534 }
3535 }
3536
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003537 if (quiet) {
3538 progress = 0;
3539 }
3540
Fam Zhengac1307a2014-04-22 13:36:11 +08003541 if (optind != argc - 1) {
3542 error_exit("Expecting one image file name");
3543 }
3544 if (!unsafe && !out_baseimg) {
3545 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003546 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003547 filename = argv[optind++];
3548
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003549 qemu_progress_init(progress, 2.0);
3550 qemu_progress_print(0, 100);
3551
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003552 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003553 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003554 if (ret < 0) {
3555 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003556 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003557 }
3558
Kevin Wolfce099542016-03-15 13:01:04 +01003559 src_flags = 0;
3560 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003561 if (ret < 0) {
3562 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003563 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003564 }
3565
Kevin Wolfce099542016-03-15 13:01:04 +01003566 /* The source files are opened read-only, don't care about WCE */
3567 assert((src_flags & BDRV_O_RDWR) == 0);
3568 (void) src_writethrough;
3569
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003570 /*
3571 * Open the images.
3572 *
3573 * Ignore the old backing file for unsafe rebase in case we want to correct
3574 * the reference to a renamed or moved backing file.
3575 */
Fam Zheng335e9932017-05-03 00:35:39 +08003576 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3577 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003578 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003579 ret = -1;
3580 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003581 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003582 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003583
Max Reitz4a2061e2019-06-12 19:00:30 +02003584 unfiltered_bs = bdrv_skip_filters(bs);
3585
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003586 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003587 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003588 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003589 ret = -1;
3590 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003591 }
3592 }
3593
3594 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003595 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003596 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003597 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003598
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003599 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003600 blk_old_backing = blk_new(qemu_get_aio_context(),
3601 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003602 BLK_PERM_ALL);
3603 ret = blk_insert_bs(blk_old_backing, base_bs,
3604 &local_err);
3605 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003606 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003607 "Could not reuse old backing file '%s': ",
3608 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003609 goto out;
3610 }
3611 } else {
3612 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003613 }
Max Reitz644483d2015-02-05 13:58:17 -05003614
Alex Bligha6166732012-10-16 13:46:18 +01003615 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003616 const char *overlay_filename;
3617 char *out_real_path;
3618
Fam Zheng335e9932017-05-03 00:35:39 +08003619 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003620 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003621 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003622 }
3623 if (force_share) {
3624 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003625 }
3626
Max Reitzf30c66b2019-02-01 20:29:05 +01003627 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003628 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3629 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003630 out_real_path =
3631 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3632 out_baseimg,
3633 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003634 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003635 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003636 error_reportf_err(local_err,
3637 "Could not resolve backing filename: ");
3638 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003639 goto out;
3640 }
3641
Sam Eiderman863cc782019-05-23 19:33:36 +03003642 /*
3643 * Find out whether we rebase an image on top of a previous image
3644 * in its chain.
3645 */
3646 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003647 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003648 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003649 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003650
Kevin Wolfd861ab32019-04-25 14:25:10 +02003651 blk_new_backing = blk_new(qemu_get_aio_context(),
3652 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003653 BLK_PERM_ALL);
3654 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3655 &local_err);
3656 if (ret < 0) {
3657 error_reportf_err(local_err,
3658 "Could not reuse backing file '%s': ",
3659 out_baseimg);
3660 goto out;
3661 }
3662 } else {
3663 blk_new_backing = blk_new_open(out_real_path, NULL,
3664 options, src_flags, &local_err);
3665 g_free(out_real_path);
3666 if (!blk_new_backing) {
3667 error_reportf_err(local_err,
3668 "Could not open new backing file '%s': ",
3669 out_baseimg);
3670 ret = -1;
3671 goto out;
3672 }
Alex Bligha6166732012-10-16 13:46:18 +01003673 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003674 }
3675 }
3676
3677 /*
3678 * Check each unallocated cluster in the COW file. If it is unallocated,
3679 * accesses go to the backing file. We must therefore compare this cluster
3680 * in the old and new backing file, and if they differ we need to copy it
3681 * from the old backing file into the COW file.
3682 *
3683 * If qemu-img crashes during this step, no harm is done. The content of
3684 * the image is the same as the original one at any time.
3685 */
3686 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003687 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003688 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003689 int64_t new_backing_size = 0;
3690 uint64_t offset;
3691 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003692 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003693
Max Reitzf1d3cd72015-02-05 13:58:18 -05003694 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3695 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003696
Eric Blake41536282017-10-11 22:47:15 -05003697 size = blk_getlength(blk);
3698 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003699 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003700 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003701 ret = -1;
3702 goto out;
3703 }
Max Reitz35ddd932019-05-09 19:52:35 +02003704 if (blk_old_backing) {
3705 old_backing_size = blk_getlength(blk_old_backing);
3706 if (old_backing_size < 0) {
3707 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003708
Max Reitz35ddd932019-05-09 19:52:35 +02003709 bdrv_get_backing_filename(bs, backing_name,
3710 sizeof(backing_name));
3711 error_report("Could not get size of '%s': %s",
3712 backing_name, strerror(-old_backing_size));
3713 ret = -1;
3714 goto out;
3715 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003716 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003717 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003718 new_backing_size = blk_getlength(blk_new_backing);
3719 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003720 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003721 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003722 ret = -1;
3723 goto out;
3724 }
Alex Bligha6166732012-10-16 13:46:18 +01003725 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003726
Eric Blake41536282017-10-11 22:47:15 -05003727 if (size != 0) {
3728 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003729 }
3730
Eric Blake41536282017-10-11 22:47:15 -05003731 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003732 bool buf_old_is_zero = false;
3733
Eric Blake41536282017-10-11 22:47:15 -05003734 /* How many bytes can we handle with the next read? */
3735 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003736
3737 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003738 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003739 if (ret < 0) {
3740 error_report("error while reading image metadata: %s",
3741 strerror(-ret));
3742 goto out;
3743 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003744 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003745 continue;
3746 }
3747
Sam Eiderman863cc782019-05-23 19:33:36 +03003748 if (prefix_chain_bs) {
3749 /*
3750 * If cluster wasn't changed since prefix_chain, we don't need
3751 * to take action
3752 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003753 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3754 prefix_chain_bs, false,
3755 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003756 if (ret < 0) {
3757 error_report("error while reading image metadata: %s",
3758 strerror(-ret));
3759 goto out;
3760 }
3761 if (!ret) {
3762 continue;
3763 }
3764 }
3765
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003766 /*
3767 * Read old and new backing file and take into consideration that
3768 * backing files may be smaller than the COW image.
3769 */
Eric Blake41536282017-10-11 22:47:15 -05003770 if (offset >= old_backing_size) {
3771 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003772 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003773 } else {
Eric Blake41536282017-10-11 22:47:15 -05003774 if (offset + n > old_backing_size) {
3775 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003776 }
3777
Eric Blake41536282017-10-11 22:47:15 -05003778 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003779 if (ret < 0) {
3780 error_report("error while reading from old backing file");
3781 goto out;
3782 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003783 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003784
Eric Blake41536282017-10-11 22:47:15 -05003785 if (offset >= new_backing_size || !blk_new_backing) {
3786 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003787 } else {
Eric Blake41536282017-10-11 22:47:15 -05003788 if (offset + n > new_backing_size) {
3789 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003790 }
3791
Eric Blake41536282017-10-11 22:47:15 -05003792 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003793 if (ret < 0) {
3794 error_report("error while reading from new backing file");
3795 goto out;
3796 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003797 }
3798
3799 /* If they differ, we need to write to the COW file */
3800 uint64_t written = 0;
3801
Eric Blake41536282017-10-11 22:47:15 -05003802 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003803 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003804
Eric Blake41536282017-10-11 22:47:15 -05003805 if (compare_buffers(buf_old + written, buf_new + written,
3806 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003807 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003808 if (buf_old_is_zero) {
3809 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3810 } else {
3811 ret = blk_pwrite(blk, offset + written,
3812 buf_old + written, pnum, 0);
3813 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003814 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003815 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003816 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003817 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003818 }
3819 }
3820
3821 written += pnum;
3822 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003823 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003824 }
3825 }
3826
3827 /*
3828 * Change the backing file. All clusters that are different from the old
3829 * backing file are overwritten in the COW file now, so the visible content
3830 * doesn't change when we switch the backing file.
3831 */
Alex Bligha6166732012-10-16 13:46:18 +01003832 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003833 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3834 true);
Alex Bligha6166732012-10-16 13:46:18 +01003835 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003836 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003837 }
3838
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003839 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003840 error_report("Could not change the backing file to '%s': No "
3841 "space left in the file header", out_baseimg);
Eric Blakea7cd44b2021-07-08 10:52:28 -05003842 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3843 error_report("Could not change the backing file to '%s': backing "
3844 "format must be specified", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003845 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003846 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003847 out_baseimg, strerror(-ret));
3848 }
3849
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003850 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003851 /*
3852 * TODO At this point it is possible to check if any clusters that are
3853 * allocated in the COW file are the same in the backing file. If so, they
3854 * could be dropped from the COW file. Don't do this before switching the
3855 * backing file, in case of a crash this would lead to corruption.
3856 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003857out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003858 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003859 /* Cleanup */
3860 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003861 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003862 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003863 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003864 qemu_vfree(buf_old);
3865 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003866
Markus Armbruster26f54e92014-10-07 13:59:04 +02003867 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003868 if (ret) {
3869 return 1;
3870 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003871 return 0;
3872}
3873
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003874static int img_resize(int argc, char **argv)
3875{
Markus Armbruster6750e792015-02-12 17:43:08 +01003876 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003877 int c, ret, relative;
3878 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003879 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003880 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003881 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003882 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003883 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003884
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003885 static QemuOptsList resize_options = {
3886 .name = "resize_options",
3887 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3888 .desc = {
3889 {
3890 .name = BLOCK_OPT_SIZE,
3891 .type = QEMU_OPT_SIZE,
3892 .help = "Virtual disk size"
3893 }, {
3894 /* end of list */
3895 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003896 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003897 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003898 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003899 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003900
Kevin Wolfe80fec72011-04-29 10:58:12 +02003901 /* Remove size from argv manually so that negative numbers are not treated
3902 * as options by getopt. */
3903 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003904 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003905 return 1;
3906 }
3907
3908 size = argv[--argc];
3909
3910 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003911 fmt = NULL;
3912 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003913 static const struct option long_options[] = {
3914 {"help", no_argument, 0, 'h'},
3915 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003916 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003917 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003918 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003919 {0, 0, 0, 0}
3920 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003921 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003922 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003923 if (c == -1) {
3924 break;
3925 }
3926 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003927 case ':':
3928 missing_argument(argv[optind - 1]);
3929 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003930 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003931 unrecognized_option(argv[optind - 1]);
3932 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003933 case 'h':
3934 help();
3935 break;
3936 case 'f':
3937 fmt = optarg;
3938 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003939 case 'q':
3940 quiet = true;
3941 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003942 case OPTION_OBJECT:
3943 user_creatable_process_cmdline(optarg);
3944 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003945 case OPTION_IMAGE_OPTS:
3946 image_opts = true;
3947 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003948 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003949 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003950 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003951 if (prealloc == PREALLOC_MODE__MAX) {
3952 error_report("Invalid preallocation mode '%s'", optarg);
3953 return 1;
3954 }
3955 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003956 case OPTION_SHRINK:
3957 shrink = true;
3958 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003959 }
3960 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003961 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003962 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003963 }
3964 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003965
3966 /* Choose grow, shrink, or absolute resize mode */
3967 switch (size[0]) {
3968 case '+':
3969 relative = 1;
3970 size++;
3971 break;
3972 case '-':
3973 relative = -1;
3974 size++;
3975 break;
3976 default:
3977 relative = 0;
3978 break;
3979 }
3980
3981 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003982 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02003983 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01003984 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003985 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003986 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003987 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003988 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003989 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3990 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003991
Max Reitzefaa7c42016-03-16 19:54:38 +01003992 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003993 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3994 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003995 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003996 ret = -1;
3997 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003998 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003999
Max Reitzdc5f6902017-06-13 22:20:55 +02004000 current_size = blk_getlength(blk);
4001 if (current_size < 0) {
4002 error_report("Failed to inquire current image length: %s",
4003 strerror(-current_size));
4004 ret = -1;
4005 goto out;
4006 }
4007
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004008 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004009 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004010 } else {
4011 total_size = n;
4012 }
4013 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004014 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004015 ret = -1;
4016 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004017 }
4018
Max Reitzdc5f6902017-06-13 22:20:55 +02004019 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4020 error_report("Preallocation can only be used for growing images");
4021 ret = -1;
4022 goto out;
4023 }
4024
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004025 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004026 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004027 warn_report("Shrinking an image will delete all data beyond the "
4028 "shrunken image's end. Before performing such an "
4029 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004030 ret = -1;
4031 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004032 }
4033
Max Reitze8d04f92019-09-18 11:51:43 +02004034 /*
4035 * The user expects the image to have the desired size after
4036 * resizing, so pass @exact=true. It is of no use to report
4037 * success when the image has not actually been resized.
4038 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004039 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004040 if (!ret) {
4041 qprintf(quiet, "Image resized.\n");
4042 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004043 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004044 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004045out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004046 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004047 if (ret) {
4048 return 1;
4049 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004050 return 0;
4051}
4052
Max Reitz76a3a342014-10-27 11:12:51 +01004053static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004054 int64_t offset, int64_t total_work_size,
4055 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004056{
4057 qemu_progress_print(100.f * offset / total_work_size, 0);
4058}
4059
Max Reitz51641352018-05-09 23:00:20 +02004060static int print_amend_option_help(const char *format)
4061{
4062 BlockDriver *drv;
4063
4064 /* Find driver and parse its options */
4065 drv = bdrv_find_format(format);
4066 if (!drv) {
4067 error_report("Unknown file format '%s'", format);
4068 return 1;
4069 }
4070
4071 if (!drv->bdrv_amend_options) {
4072 error_report("Format driver '%s' does not support option amendment",
4073 format);
4074 return 1;
4075 }
4076
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004077 /* Every driver supporting amendment must have amend_opts */
4078 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004079
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004080 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004081 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004082 return 0;
4083}
4084
Max Reitz6f176b42013-09-03 10:09:50 +02004085static int img_amend(int argc, char **argv)
4086{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004087 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004088 int c, ret = 0;
4089 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004090 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004091 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004092 const char *fmt = NULL, *filename, *cache;
4093 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004094 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004095 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004096 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004097 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004098 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004099 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004100
Max Reitzbd39e6e2014-07-22 22:58:43 +02004101 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004102 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004103 static const struct option long_options[] = {
4104 {"help", no_argument, 0, 'h'},
4105 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004106 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004107 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004108 {0, 0, 0, 0}
4109 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004110 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004111 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004112 if (c == -1) {
4113 break;
4114 }
4115
4116 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004117 case ':':
4118 missing_argument(argv[optind - 1]);
4119 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004120 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004121 unrecognized_option(argv[optind - 1]);
4122 break;
4123 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004124 help();
4125 break;
4126 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004127 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004128 ret = -1;
4129 goto out_no_progress;
4130 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004131 break;
4132 case 'f':
4133 fmt = optarg;
4134 break;
4135 case 't':
4136 cache = optarg;
4137 break;
4138 case 'p':
4139 progress = true;
4140 break;
4141 case 'q':
4142 quiet = true;
4143 break;
4144 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004145 user_creatable_process_cmdline(optarg);
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004146 break;
4147 case OPTION_IMAGE_OPTS:
4148 image_opts = true;
4149 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004150 case OPTION_FORCE:
4151 force = true;
4152 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004153 }
4154 }
4155
Max Reitz6f176b42013-09-03 10:09:50 +02004156 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004157 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004158 }
4159
Max Reitz76a3a342014-10-27 11:12:51 +01004160 if (quiet) {
4161 progress = false;
4162 }
4163 qemu_progress_init(progress, 1.0);
4164
Kevin Wolfa283cb62014-02-21 16:24:07 +01004165 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4166 if (fmt && has_help_option(options)) {
4167 /* If a format is explicitly specified (and possibly no filename is
4168 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004169 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004170 goto out;
4171 }
4172
4173 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004174 error_report("Expecting one image file name");
4175 ret = -1;
4176 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004177 }
Max Reitz6f176b42013-09-03 10:09:50 +02004178
Kevin Wolfce099542016-03-15 13:01:04 +01004179 flags = BDRV_O_RDWR;
4180 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004181 if (ret < 0) {
4182 error_report("Invalid cache option: %s", cache);
4183 goto out;
4184 }
4185
Fam Zheng335e9932017-05-03 00:35:39 +08004186 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4187 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004188 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004189 ret = -1;
4190 goto out;
4191 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004192 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004193
4194 fmt = bs->drv->format_name;
4195
Kevin Wolf626f84f2014-02-21 16:24:06 +01004196 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004197 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004198 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004199 goto out;
4200 }
4201
Max Reitz1f996682018-05-09 23:00:17 +02004202 if (!bs->drv->bdrv_amend_options) {
4203 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004204 fmt);
4205 ret = -1;
4206 goto out;
4207 }
4208
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004209 /* Every driver supporting amendment must have amend_opts */
4210 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004211
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004212 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4213 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004214 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004215 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004216 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4217 qemu_opts_del(opts);
4218 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004219 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004220 error_append_hint(&err,
4221 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004222 }
4223
Paolo Bonziniece90862017-01-04 15:56:24 +01004224 error_report_err(err);
4225 ret = -1;
4226 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004227 }
4228
Max Reitz76a3a342014-10-27 11:12:51 +01004229 /* In case the driver does not call amend_status_cb() */
4230 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004231 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004232 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004233 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004234 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004235 goto out;
4236 }
4237
4238out:
Max Reitz76a3a342014-10-27 11:12:51 +01004239 qemu_progress_end();
4240
Max Reitze814dff2015-08-20 16:00:38 -07004241out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004242 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004243 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004244 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004245 g_free(options);
4246
Max Reitz6f176b42013-09-03 10:09:50 +02004247 if (ret) {
4248 return 1;
4249 }
4250 return 0;
4251}
4252
Kevin Wolfb6133b82014-08-05 14:17:13 +02004253typedef struct BenchData {
4254 BlockBackend *blk;
4255 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004256 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004257 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004258 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004259 int nrreq;
4260 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004261 int flush_interval;
4262 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004263 uint8_t *buf;
4264 QEMUIOVector *qiov;
4265
4266 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004267 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004268 uint64_t offset;
4269} BenchData;
4270
Kevin Wolf55d539c2016-06-03 13:59:41 +02004271static void bench_undrained_flush_cb(void *opaque, int ret)
4272{
4273 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004274 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004275 exit(EXIT_FAILURE);
4276 }
4277}
4278
Kevin Wolfb6133b82014-08-05 14:17:13 +02004279static void bench_cb(void *opaque, int ret)
4280{
4281 BenchData *b = opaque;
4282 BlockAIOCB *acb;
4283
4284 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004285 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004286 exit(EXIT_FAILURE);
4287 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004288
4289 if (b->in_flush) {
4290 /* Just finished a flush with drained queue: Start next requests */
4291 assert(b->in_flight == 0);
4292 b->in_flush = false;
4293 } else if (b->in_flight > 0) {
4294 int remaining = b->n - b->in_flight;
4295
Kevin Wolfb6133b82014-08-05 14:17:13 +02004296 b->n--;
4297 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004298
4299 /* Time for flush? Drain queue if requested, then flush */
4300 if (b->flush_interval && remaining % b->flush_interval == 0) {
4301 if (!b->in_flight || !b->drain_on_flush) {
4302 BlockCompletionFunc *cb;
4303
4304 if (b->drain_on_flush) {
4305 b->in_flush = true;
4306 cb = bench_cb;
4307 } else {
4308 cb = bench_undrained_flush_cb;
4309 }
4310
4311 acb = blk_aio_flush(b->blk, cb, b);
4312 if (!acb) {
4313 error_report("Failed to issue flush request");
4314 exit(EXIT_FAILURE);
4315 }
4316 }
4317 if (b->drain_on_flush) {
4318 return;
4319 }
4320 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004321 }
4322
4323 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004324 int64_t offset = b->offset;
4325 /* blk_aio_* might look for completed I/Os and kick bench_cb
4326 * again, so make sure this operation is counted by in_flight
4327 * and b->offset is ready for the next submission.
4328 */
4329 b->in_flight++;
4330 b->offset += b->step;
4331 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004332 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004333 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004334 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004335 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004336 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004337 if (!acb) {
4338 error_report("Failed to issue request");
4339 exit(EXIT_FAILURE);
4340 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004341 }
4342}
4343
4344static int img_bench(int argc, char **argv)
4345{
4346 int c, ret = 0;
4347 const char *fmt = NULL, *filename;
4348 bool quiet = false;
4349 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004350 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004351 int count = 75000;
4352 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004353 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004354 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004355 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004356 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004357 int flush_interval = 0;
4358 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004359 int64_t image_size;
4360 BlockBackend *blk = NULL;
4361 BenchData data = {};
4362 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004363 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004364 struct timeval t1, t2;
4365 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004366 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004367 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004368
4369 for (;;) {
4370 static const struct option long_options[] = {
4371 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004372 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004373 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004374 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004375 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004376 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004377 {0, 0, 0, 0}
4378 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004379 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4380 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004381 if (c == -1) {
4382 break;
4383 }
4384
4385 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004386 case ':':
4387 missing_argument(argv[optind - 1]);
4388 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004389 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004390 unrecognized_option(argv[optind - 1]);
4391 break;
4392 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004393 help();
4394 break;
4395 case 'c':
4396 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004397 unsigned long res;
4398
4399 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004400 error_report("Invalid request count specified");
4401 return 1;
4402 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004403 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004404 break;
4405 }
4406 case 'd':
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 queue depth specified");
4412 return 1;
4413 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004414 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004415 break;
4416 }
4417 case 'f':
4418 fmt = optarg;
4419 break;
4420 case 'n':
4421 flags |= BDRV_O_NATIVE_AIO;
4422 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004423 case 'i':
4424 ret = bdrv_parse_aio(optarg, &flags);
4425 if (ret < 0) {
4426 error_report("Invalid aio option: %s", optarg);
4427 ret = -1;
4428 goto out;
4429 }
4430 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004431 case 'o':
4432 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004433 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004434 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004435 return 1;
4436 }
4437 break;
4438 }
4439 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004440 case 'q':
4441 quiet = true;
4442 break;
4443 case 's':
4444 {
4445 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004446
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004447 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4448 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004449 return 1;
4450 }
4451
4452 bufsize = sval;
4453 break;
4454 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004455 case 'S':
4456 {
4457 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004458
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004459 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4460 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004461 return 1;
4462 }
4463
4464 step = sval;
4465 break;
4466 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004467 case 't':
4468 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4469 if (ret < 0) {
4470 error_report("Invalid cache mode");
4471 ret = -1;
4472 goto out;
4473 }
4474 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004475 case 'w':
4476 flags |= BDRV_O_RDWR;
4477 is_write = true;
4478 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004479 case 'U':
4480 force_share = true;
4481 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004482 case OPTION_PATTERN:
4483 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004484 unsigned long res;
4485
4486 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004487 error_report("Invalid pattern byte specified");
4488 return 1;
4489 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004490 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004491 break;
4492 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004493 case OPTION_FLUSH_INTERVAL:
4494 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004495 unsigned long res;
4496
4497 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004498 error_report("Invalid flush interval specified");
4499 return 1;
4500 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004501 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004502 break;
4503 }
4504 case OPTION_NO_DRAIN:
4505 drain_on_flush = false;
4506 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004507 case OPTION_IMAGE_OPTS:
4508 image_opts = true;
4509 break;
4510 }
4511 }
4512
4513 if (optind != argc - 1) {
4514 error_exit("Expecting one image file name");
4515 }
4516 filename = argv[argc - 1];
4517
Kevin Wolf55d539c2016-06-03 13:59:41 +02004518 if (!is_write && flush_interval) {
4519 error_report("--flush-interval is only available in write tests");
4520 ret = -1;
4521 goto out;
4522 }
4523 if (flush_interval && flush_interval < depth) {
4524 error_report("Flush interval can't be smaller than depth");
4525 ret = -1;
4526 goto out;
4527 }
4528
Fam Zheng335e9932017-05-03 00:35:39 +08004529 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4530 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004531 if (!blk) {
4532 ret = -1;
4533 goto out;
4534 }
4535
4536 image_size = blk_getlength(blk);
4537 if (image_size < 0) {
4538 ret = image_size;
4539 goto out;
4540 }
4541
4542 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004543 .blk = blk,
4544 .image_size = image_size,
4545 .bufsize = bufsize,
4546 .step = step ?: bufsize,
4547 .nrreq = depth,
4548 .n = count,
4549 .offset = offset,
4550 .write = is_write,
4551 .flush_interval = flush_interval,
4552 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004553 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004554 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004555 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004556 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004557 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004558 if (flush_interval) {
4559 printf("Sending flush every %d requests\n", flush_interval);
4560 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004561
Fam Zheng79d46582018-01-16 14:08:58 +08004562 buf_size = data.nrreq * data.bufsize;
4563 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004564 memset(data.buf, pattern, data.nrreq * data.bufsize);
4565
Fam Zheng79d46582018-01-16 14:08:58 +08004566 blk_register_buf(blk, data.buf, buf_size);
4567
Kevin Wolfb6133b82014-08-05 14:17:13 +02004568 data.qiov = g_new(QEMUIOVector, data.nrreq);
4569 for (i = 0; i < data.nrreq; i++) {
4570 qemu_iovec_init(&data.qiov[i], 1);
4571 qemu_iovec_add(&data.qiov[i],
4572 data.buf + i * data.bufsize, data.bufsize);
4573 }
4574
4575 gettimeofday(&t1, NULL);
4576 bench_cb(&data, 0);
4577
4578 while (data.n > 0) {
4579 main_loop_wait(false);
4580 }
4581 gettimeofday(&t2, NULL);
4582
4583 printf("Run completed in %3.3f seconds.\n",
4584 (t2.tv_sec - t1.tv_sec)
4585 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4586
4587out:
Fam Zheng79d46582018-01-16 14:08:58 +08004588 if (data.buf) {
4589 blk_unregister_buf(blk, data.buf);
4590 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004591 qemu_vfree(data.buf);
4592 blk_unref(blk);
4593
4594 if (ret) {
4595 return 1;
4596 }
4597 return 0;
4598}
4599
Eric Blake3b51ab42020-05-12 20:16:45 -05004600enum ImgBitmapAct {
4601 BITMAP_ADD,
4602 BITMAP_REMOVE,
4603 BITMAP_CLEAR,
4604 BITMAP_ENABLE,
4605 BITMAP_DISABLE,
4606 BITMAP_MERGE,
4607};
4608typedef struct ImgBitmapAction {
4609 enum ImgBitmapAct act;
4610 const char *src; /* only used for merge */
4611 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4612} ImgBitmapAction;
4613
4614static int img_bitmap(int argc, char **argv)
4615{
4616 Error *err = NULL;
4617 int c, ret = 1;
4618 QemuOpts *opts = NULL;
4619 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4620 const char *filename, *bitmap;
4621 BlockBackend *blk = NULL, *src = NULL;
4622 BlockDriverState *bs = NULL, *src_bs = NULL;
4623 bool image_opts = false;
4624 int64_t granularity = 0;
4625 bool add = false, merge = false;
4626 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4627 ImgBitmapAction *act, *act_next;
4628 const char *op;
4629
4630 QSIMPLEQ_INIT(&actions);
4631
4632 for (;;) {
4633 static const struct option long_options[] = {
4634 {"help", no_argument, 0, 'h'},
4635 {"object", required_argument, 0, OPTION_OBJECT},
4636 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4637 {"add", no_argument, 0, OPTION_ADD},
4638 {"remove", no_argument, 0, OPTION_REMOVE},
4639 {"clear", no_argument, 0, OPTION_CLEAR},
4640 {"enable", no_argument, 0, OPTION_ENABLE},
4641 {"disable", no_argument, 0, OPTION_DISABLE},
4642 {"merge", required_argument, 0, OPTION_MERGE},
4643 {"granularity", required_argument, 0, 'g'},
4644 {"source-file", required_argument, 0, 'b'},
4645 {"source-format", required_argument, 0, 'F'},
4646 {0, 0, 0, 0}
4647 };
4648 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4649 if (c == -1) {
4650 break;
4651 }
4652
4653 switch (c) {
4654 case ':':
4655 missing_argument(argv[optind - 1]);
4656 break;
4657 case '?':
4658 unrecognized_option(argv[optind - 1]);
4659 break;
4660 case 'h':
4661 help();
4662 break;
4663 case 'b':
4664 src_filename = optarg;
4665 break;
4666 case 'f':
4667 fmt = optarg;
4668 break;
4669 case 'F':
4670 src_fmt = optarg;
4671 break;
4672 case 'g':
4673 granularity = cvtnum("granularity", optarg);
4674 if (granularity < 0) {
4675 return 1;
4676 }
4677 break;
4678 case OPTION_ADD:
4679 act = g_new0(ImgBitmapAction, 1);
4680 act->act = BITMAP_ADD;
4681 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4682 add = true;
4683 break;
4684 case OPTION_REMOVE:
4685 act = g_new0(ImgBitmapAction, 1);
4686 act->act = BITMAP_REMOVE;
4687 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4688 break;
4689 case OPTION_CLEAR:
4690 act = g_new0(ImgBitmapAction, 1);
4691 act->act = BITMAP_CLEAR;
4692 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4693 break;
4694 case OPTION_ENABLE:
4695 act = g_new0(ImgBitmapAction, 1);
4696 act->act = BITMAP_ENABLE;
4697 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4698 break;
4699 case OPTION_DISABLE:
4700 act = g_new0(ImgBitmapAction, 1);
4701 act->act = BITMAP_DISABLE;
4702 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4703 break;
4704 case OPTION_MERGE:
4705 act = g_new0(ImgBitmapAction, 1);
4706 act->act = BITMAP_MERGE;
4707 act->src = optarg;
4708 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4709 merge = true;
4710 break;
4711 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004712 user_creatable_process_cmdline(optarg);
Eric Blake3b51ab42020-05-12 20:16:45 -05004713 break;
4714 case OPTION_IMAGE_OPTS:
4715 image_opts = true;
4716 break;
4717 }
4718 }
4719
Eric Blake3b51ab42020-05-12 20:16:45 -05004720 if (QSIMPLEQ_EMPTY(&actions)) {
4721 error_report("Need at least one of --add, --remove, --clear, "
4722 "--enable, --disable, or --merge");
4723 goto out;
4724 }
4725
4726 if (granularity && !add) {
4727 error_report("granularity only supported with --add");
4728 goto out;
4729 }
4730 if (src_fmt && !src_filename) {
4731 error_report("-F only supported with -b");
4732 goto out;
4733 }
4734 if (src_filename && !merge) {
4735 error_report("Merge bitmap source file only supported with "
4736 "--merge");
4737 goto out;
4738 }
4739
4740 if (optind != argc - 2) {
4741 error_report("Expecting filename and bitmap name");
4742 goto out;
4743 }
4744
4745 filename = argv[optind];
4746 bitmap = argv[optind + 1];
4747
Eric Blake14f16bf2020-09-14 14:10:09 -05004748 /*
4749 * No need to open backing chains; we will be manipulating bitmaps
4750 * directly in this image without reference to image contents.
4751 */
4752 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4753 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004754 if (!blk) {
4755 goto out;
4756 }
4757 bs = blk_bs(blk);
4758 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004759 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4760 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004761 if (!src) {
4762 goto out;
4763 }
4764 src_bs = blk_bs(src);
4765 } else {
4766 src_bs = bs;
4767 }
4768
4769 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4770 switch (act->act) {
4771 case BITMAP_ADD:
4772 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4773 !!granularity, granularity, true, true,
4774 false, false, &err);
4775 op = "add";
4776 break;
4777 case BITMAP_REMOVE:
4778 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4779 op = "remove";
4780 break;
4781 case BITMAP_CLEAR:
4782 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4783 op = "clear";
4784 break;
4785 case BITMAP_ENABLE:
4786 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4787 op = "enable";
4788 break;
4789 case BITMAP_DISABLE:
4790 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4791 op = "disable";
4792 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004793 case BITMAP_MERGE:
4794 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4795 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004796 op = "merge";
4797 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004798 default:
4799 g_assert_not_reached();
4800 }
4801
4802 if (err) {
4803 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4804 op, bitmap);
4805 goto out;
4806 }
4807 g_free(act);
4808 }
4809
4810 ret = 0;
4811
4812 out:
4813 blk_unref(src);
4814 blk_unref(blk);
4815 qemu_opts_del(opts);
4816 return ret;
4817}
4818
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004819#define C_BS 01
4820#define C_COUNT 02
4821#define C_IF 04
4822#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004823#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004824
4825struct DdInfo {
4826 unsigned int flags;
4827 int64_t count;
4828};
4829
4830struct DdIo {
4831 int bsz; /* Block size */
4832 char *filename;
4833 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004834 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004835};
4836
4837struct DdOpts {
4838 const char *name;
4839 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4840 unsigned int flag;
4841};
4842
4843static int img_dd_bs(const char *arg,
4844 struct DdIo *in, struct DdIo *out,
4845 struct DdInfo *dd)
4846{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004847 int64_t res;
4848
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004849 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004850
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004851 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004852 return 1;
4853 }
4854 in->bsz = out->bsz = res;
4855
4856 return 0;
4857}
4858
4859static int img_dd_count(const char *arg,
4860 struct DdIo *in, struct DdIo *out,
4861 struct DdInfo *dd)
4862{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004863 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004864
Markus Armbruster606caa02017-02-21 21:14:04 +01004865 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004866 return 1;
4867 }
4868
4869 return 0;
4870}
4871
4872static int img_dd_if(const char *arg,
4873 struct DdIo *in, struct DdIo *out,
4874 struct DdInfo *dd)
4875{
4876 in->filename = g_strdup(arg);
4877
4878 return 0;
4879}
4880
4881static int img_dd_of(const char *arg,
4882 struct DdIo *in, struct DdIo *out,
4883 struct DdInfo *dd)
4884{
4885 out->filename = g_strdup(arg);
4886
4887 return 0;
4888}
4889
Reda Sallahif7c15532016-08-10 16:16:09 +02004890static int img_dd_skip(const char *arg,
4891 struct DdIo *in, struct DdIo *out,
4892 struct DdInfo *dd)
4893{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004894 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004895
Markus Armbruster606caa02017-02-21 21:14:04 +01004896 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004897 return 1;
4898 }
4899
4900 return 0;
4901}
4902
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004903static int img_dd(int argc, char **argv)
4904{
4905 int ret = 0;
4906 char *arg = NULL;
4907 char *tmp;
4908 BlockDriver *drv = NULL, *proto_drv = NULL;
4909 BlockBackend *blk1 = NULL, *blk2 = NULL;
4910 QemuOpts *opts = NULL;
4911 QemuOptsList *create_opts = NULL;
4912 Error *local_err = NULL;
4913 bool image_opts = false;
4914 int c, i;
4915 const char *out_fmt = "raw";
4916 const char *fmt = NULL;
4917 int64_t size = 0;
4918 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004919 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004920 struct DdInfo dd = {
4921 .flags = 0,
4922 .count = 0,
4923 };
4924 struct DdIo in = {
4925 .bsz = 512, /* Block size is by default 512 bytes */
4926 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004927 .buf = NULL,
4928 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004929 };
4930 struct DdIo out = {
4931 .bsz = 512,
4932 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004933 .buf = NULL,
4934 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004935 };
4936
4937 const struct DdOpts options[] = {
4938 { "bs", img_dd_bs, C_BS },
4939 { "count", img_dd_count, C_COUNT },
4940 { "if", img_dd_if, C_IF },
4941 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004942 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004943 { NULL, NULL, 0 }
4944 };
4945 const struct option long_options[] = {
4946 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004947 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004948 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004949 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004950 { 0, 0, 0, 0 }
4951 };
4952
Fam Zheng335e9932017-05-03 00:35:39 +08004953 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004954 if (c == EOF) {
4955 break;
4956 }
4957 switch (c) {
4958 case 'O':
4959 out_fmt = optarg;
4960 break;
4961 case 'f':
4962 fmt = optarg;
4963 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004964 case ':':
4965 missing_argument(argv[optind - 1]);
4966 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004967 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004968 unrecognized_option(argv[optind - 1]);
4969 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004970 case 'h':
4971 help();
4972 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004973 case 'U':
4974 force_share = true;
4975 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004976 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004977 user_creatable_process_cmdline(optarg);
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004978 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004979 case OPTION_IMAGE_OPTS:
4980 image_opts = true;
4981 break;
4982 }
4983 }
4984
4985 for (i = optind; i < argc; i++) {
4986 int j;
4987 arg = g_strdup(argv[i]);
4988
4989 tmp = strchr(arg, '=');
4990 if (tmp == NULL) {
4991 error_report("unrecognized operand %s", arg);
4992 ret = -1;
4993 goto out;
4994 }
4995
4996 *tmp++ = '\0';
4997
4998 for (j = 0; options[j].name != NULL; j++) {
4999 if (!strcmp(arg, options[j].name)) {
5000 break;
5001 }
5002 }
5003 if (options[j].name == NULL) {
5004 error_report("unrecognized operand %s", arg);
5005 ret = -1;
5006 goto out;
5007 }
5008
5009 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5010 ret = -1;
5011 goto out;
5012 }
5013 dd.flags |= options[j].flag;
5014 g_free(arg);
5015 arg = NULL;
5016 }
5017
5018 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5019 error_report("Must specify both input and output files");
5020 ret = -1;
5021 goto out;
5022 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005023
Fam Zheng335e9932017-05-03 00:35:39 +08005024 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5025 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005026
5027 if (!blk1) {
5028 ret = -1;
5029 goto out;
5030 }
5031
5032 drv = bdrv_find_format(out_fmt);
5033 if (!drv) {
5034 error_report("Unknown file format");
5035 ret = -1;
5036 goto out;
5037 }
5038 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5039
5040 if (!proto_drv) {
5041 error_report_err(local_err);
5042 ret = -1;
5043 goto out;
5044 }
5045 if (!drv->create_opts) {
5046 error_report("Format driver '%s' does not support image creation",
5047 drv->format_name);
5048 ret = -1;
5049 goto out;
5050 }
5051 if (!proto_drv->create_opts) {
5052 error_report("Protocol driver '%s' does not support image creation",
5053 proto_drv->format_name);
5054 ret = -1;
5055 goto out;
5056 }
5057 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5058 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5059
5060 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5061
5062 size = blk_getlength(blk1);
5063 if (size < 0) {
5064 error_report("Failed to get size for '%s'", in.filename);
5065 ret = -1;
5066 goto out;
5067 }
5068
5069 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5070 dd.count * in.bsz < size) {
5071 size = dd.count * in.bsz;
5072 }
5073
Reda Sallahif7c15532016-08-10 16:16:09 +02005074 /* Overflow means the specified offset is beyond input image's size */
5075 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5076 size < in.bsz * in.offset)) {
5077 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5078 } else {
5079 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5080 size - in.bsz * in.offset, &error_abort);
5081 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005082
5083 ret = bdrv_create(drv, out.filename, opts, &local_err);
5084 if (ret < 0) {
5085 error_reportf_err(local_err,
5086 "%s: error while creating output image: ",
5087 out.filename);
5088 ret = -1;
5089 goto out;
5090 }
5091
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005092 /* TODO, we can't honour --image-opts for the target,
5093 * since it needs to be given in a format compatible
5094 * with the bdrv_create() call above which does not
5095 * support image-opts style.
5096 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005097 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005098 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005099
5100 if (!blk2) {
5101 ret = -1;
5102 goto out;
5103 }
5104
Reda Sallahif7c15532016-08-10 16:16:09 +02005105 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5106 size < in.offset * in.bsz)) {
5107 /* We give a warning if the skip option is bigger than the input
5108 * size and create an empty output disk image (i.e. like dd(1)).
5109 */
5110 error_report("%s: cannot skip to specified offset", in.filename);
5111 in_pos = size;
5112 } else {
5113 in_pos = in.offset * in.bsz;
5114 }
5115
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005116 in.buf = g_new(uint8_t, in.bsz);
5117
Reda Sallahif7c15532016-08-10 16:16:09 +02005118 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005119 int in_ret, out_ret;
5120
5121 if (in_pos + in.bsz > size) {
5122 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5123 } else {
5124 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5125 }
5126 if (in_ret < 0) {
5127 error_report("error while reading from input image file: %s",
5128 strerror(-in_ret));
5129 ret = -1;
5130 goto out;
5131 }
5132 in_pos += in_ret;
5133
5134 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5135
5136 if (out_ret < 0) {
5137 error_report("error while writing to output image file: %s",
5138 strerror(-out_ret));
5139 ret = -1;
5140 goto out;
5141 }
5142 out_pos += out_ret;
5143 }
5144
5145out:
5146 g_free(arg);
5147 qemu_opts_del(opts);
5148 qemu_opts_free(create_opts);
5149 blk_unref(blk1);
5150 blk_unref(blk2);
5151 g_free(in.filename);
5152 g_free(out.filename);
5153 g_free(in.buf);
5154 g_free(out.buf);
5155
5156 if (ret) {
5157 return 1;
5158 }
5159 return 0;
5160}
5161
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005162static void dump_json_block_measure_info(BlockMeasureInfo *info)
5163{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005164 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005165 QObject *obj;
5166 Visitor *v = qobject_output_visitor_new(&obj);
5167
5168 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5169 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005170 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005171 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005172 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005173 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005174 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005175 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005176}
5177
5178static int img_measure(int argc, char **argv)
5179{
5180 static const struct option long_options[] = {
5181 {"help", no_argument, 0, 'h'},
5182 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5183 {"object", required_argument, 0, OPTION_OBJECT},
5184 {"output", required_argument, 0, OPTION_OUTPUT},
5185 {"size", required_argument, 0, OPTION_SIZE},
5186 {"force-share", no_argument, 0, 'U'},
5187 {0, 0, 0, 0}
5188 };
5189 OutputFormat output_format = OFORMAT_HUMAN;
5190 BlockBackend *in_blk = NULL;
5191 BlockDriver *drv;
5192 const char *filename = NULL;
5193 const char *fmt = NULL;
5194 const char *out_fmt = "raw";
5195 char *options = NULL;
5196 char *snapshot_name = NULL;
5197 bool force_share = false;
5198 QemuOpts *opts = NULL;
5199 QemuOpts *object_opts = NULL;
5200 QemuOpts *sn_opts = NULL;
5201 QemuOptsList *create_opts = NULL;
5202 bool image_opts = false;
5203 uint64_t img_size = UINT64_MAX;
5204 BlockMeasureInfo *info = NULL;
5205 Error *local_err = NULL;
5206 int ret = 1;
5207 int c;
5208
5209 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5210 long_options, NULL)) != -1) {
5211 switch (c) {
5212 case '?':
5213 case 'h':
5214 help();
5215 break;
5216 case 'f':
5217 fmt = optarg;
5218 break;
5219 case 'O':
5220 out_fmt = optarg;
5221 break;
5222 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005223 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005224 goto out;
5225 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005226 break;
5227 case 'l':
5228 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5229 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5230 optarg, false);
5231 if (!sn_opts) {
5232 error_report("Failed in parsing snapshot param '%s'",
5233 optarg);
5234 goto out;
5235 }
5236 } else {
5237 snapshot_name = optarg;
5238 }
5239 break;
5240 case 'U':
5241 force_share = true;
5242 break;
5243 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005244 user_creatable_process_cmdline(optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005245 break;
5246 case OPTION_IMAGE_OPTS:
5247 image_opts = true;
5248 break;
5249 case OPTION_OUTPUT:
5250 if (!strcmp(optarg, "json")) {
5251 output_format = OFORMAT_JSON;
5252 } else if (!strcmp(optarg, "human")) {
5253 output_format = OFORMAT_HUMAN;
5254 } else {
5255 error_report("--output must be used with human or json "
5256 "as argument.");
5257 goto out;
5258 }
5259 break;
5260 case OPTION_SIZE:
5261 {
5262 int64_t sval;
5263
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005264 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005265 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005266 goto out;
5267 }
5268 img_size = (uint64_t)sval;
5269 }
5270 break;
5271 }
5272 }
5273
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005274 if (argc - optind > 1) {
5275 error_report("At most one filename argument is allowed.");
5276 goto out;
5277 } else if (argc - optind == 1) {
5278 filename = argv[optind];
5279 }
5280
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005281 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5282 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005283 goto out;
5284 }
5285 if (filename && img_size != UINT64_MAX) {
5286 error_report("--size N cannot be used together with a filename.");
5287 goto out;
5288 }
5289 if (!filename && img_size == UINT64_MAX) {
5290 error_report("Either --size N or one filename must be specified.");
5291 goto out;
5292 }
5293
5294 if (filename) {
5295 in_blk = img_open(image_opts, filename, fmt, 0,
5296 false, false, force_share);
5297 if (!in_blk) {
5298 goto out;
5299 }
5300
5301 if (sn_opts) {
5302 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5303 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5304 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5305 &local_err);
5306 } else if (snapshot_name != NULL) {
5307 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5308 snapshot_name, &local_err);
5309 }
5310 if (local_err) {
5311 error_reportf_err(local_err, "Failed to load snapshot: ");
5312 goto out;
5313 }
5314 }
5315
5316 drv = bdrv_find_format(out_fmt);
5317 if (!drv) {
5318 error_report("Unknown file format '%s'", out_fmt);
5319 goto out;
5320 }
5321 if (!drv->create_opts) {
5322 error_report("Format driver '%s' does not support image creation",
5323 drv->format_name);
5324 goto out;
5325 }
5326
5327 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5328 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5329 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5330 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005331 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005332 error_report_err(local_err);
5333 error_report("Invalid options for file format '%s'", out_fmt);
5334 goto out;
5335 }
5336 }
5337 if (img_size != UINT64_MAX) {
5338 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5339 }
5340
5341 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5342 if (local_err) {
5343 error_report_err(local_err);
5344 goto out;
5345 }
5346
5347 if (output_format == OFORMAT_HUMAN) {
5348 printf("required size: %" PRIu64 "\n", info->required);
5349 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005350 if (info->has_bitmaps) {
5351 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5352 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005353 } else {
5354 dump_json_block_measure_info(info);
5355 }
5356
5357 ret = 0;
5358
5359out:
5360 qapi_free_BlockMeasureInfo(info);
5361 qemu_opts_del(object_opts);
5362 qemu_opts_del(opts);
5363 qemu_opts_del(sn_opts);
5364 qemu_opts_free(create_opts);
5365 g_free(options);
5366 blk_unref(in_blk);
5367 return ret;
5368}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005369
Anthony Liguoric227f092009-10-01 16:12:16 -05005370static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005371#define DEF(option, callback, arg_string) \
5372 { option, callback },
5373#include "qemu-img-cmds.h"
5374#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005375 { NULL, NULL, },
5376};
5377
bellardea2384d2004-08-01 21:59:26 +00005378int main(int argc, char **argv)
5379{
Anthony Liguoric227f092009-10-01 16:12:16 -05005380 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005381 const char *cmdname;
Jeff Cody7db16892014-04-25 17:02:32 -04005382 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005383 static const struct option long_options[] = {
5384 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005385 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005386 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005387 {0, 0, 0, 0}
5388 };
bellardea2384d2004-08-01 21:59:26 +00005389
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005390#ifdef CONFIG_POSIX
5391 signal(SIGPIPE, SIG_IGN);
5392#endif
5393
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005394 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005395 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005396 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005397 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005398
Markus Armbrusterf9734d52021-07-20 14:53:53 +02005399 qemu_init_main_loop(&error_fatal);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005400
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005401 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005402
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005403 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005404 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005405 if (argc < 2) {
5406 error_exit("Not enough arguments");
5407 }
Stuart Brady153859b2009-06-07 00:42:17 +01005408
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005409 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005410 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005411
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005412 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005413 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005414 case ':':
5415 missing_argument(argv[optind - 1]);
5416 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005417 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005418 unrecognized_option(argv[optind - 1]);
5419 return 0;
5420 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005421 help();
5422 return 0;
5423 case 'V':
5424 printf(QEMU_IMG_VERSION);
5425 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005426 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005427 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005428 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005429 }
bellardea2384d2004-08-01 21:59:26 +00005430 }
Stuart Brady153859b2009-06-07 00:42:17 +01005431
Denis V. Lunev10985132016-06-17 17:44:13 +03005432 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005433
Denis V. Lunev10985132016-06-17 17:44:13 +03005434 /* reset getopt_long scanning */
5435 argc -= optind;
5436 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005437 return 0;
5438 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005439 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005440 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005441
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005442 if (!trace_init_backends()) {
5443 exit(1);
5444 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005445 trace_init_file();
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005446 qemu_set_log(LOG_TRACE);
5447
Denis V. Lunev10985132016-06-17 17:44:13 +03005448 /* find the command */
5449 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5450 if (!strcmp(cmdname, cmd->name)) {
5451 return cmd->handler(argc, argv);
5452 }
5453 }
Jeff Cody7db16892014-04-25 17:02:32 -04005454
Stuart Brady153859b2009-06-07 00:42:17 +01005455 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005456 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005457}