blob: e2952fe955d1e1af77d4c3e9e08ff1bc1176fc09 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050031#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010032#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010033#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010035#include "qapi/qmp/qdict.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020036#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000037#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010038#include "qemu/option.h"
39#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030040#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020041#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020042#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010043#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020044#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000045#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020046#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010047#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020048#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080049#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010050#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030051#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000052#include "qemu/throttle.h"
53#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000054
Thomas Huth7e563bf2018-02-15 12:06:47 +010055#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020056 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040057
Anthony Liguoric227f092009-10-01 16:12:16 -050058typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010059 const char *name;
60 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050061} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010062
Federico Simoncelli8599ea42013-01-28 06:59:47 -050063enum {
64 OPTION_OUTPUT = 256,
65 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000066 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000067 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020068 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020069 OPTION_FLUSH_INTERVAL = 261,
70 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010071 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010072 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020073 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030074 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020075 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000076 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050077 OPTION_ADD = 269,
78 OPTION_REMOVE = 270,
79 OPTION_CLEAR = 271,
80 OPTION_ENABLE = 272,
81 OPTION_DISABLE = 273,
82 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050083 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020084 OPTION_FORCE = 276,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050085};
86
87typedef enum OutputFormat {
88 OFORMAT_JSON,
89 OFORMAT_HUMAN,
90} OutputFormat;
91
Kevin Wolfe6996142016-03-15 13:03:11 +010092/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040093#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000094
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010095static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000096{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010097 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000098}
99
Fam Zhengac1307a2014-04-22 13:36:11 +0800100static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
101{
102 va_list ap;
103
Fam Zhengac1307a2014-04-22 13:36:11 +0800104 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200105 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800106 va_end(ap);
107
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200108 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800109 exit(EXIT_FAILURE);
110}
111
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800112static void QEMU_NORETURN missing_argument(const char *option)
113{
114 error_exit("missing argument for option '%s'", option);
115}
116
117static void QEMU_NORETURN unrecognized_option(const char *option)
118{
119 error_exit("unrecognized option '%s'", option);
120}
121
Eric Blake0562adf2020-05-12 20:16:41 -0500122/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800123static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000124{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100125 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400126 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300127 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300128 "QEMU disk image utility\n"
129 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300130 " '-h', '--help' display this help and exit\n"
131 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300132 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
133 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300134 "\n"
malc3f020d72010-02-08 12:04:56 +0300135 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100136#define DEF(option, callback, arg_string) \
137 " " arg_string "\n"
138#include "qemu-img-cmds.h"
139#undef DEF
malc3f020d72010-02-08 12:04:56 +0300140 "\n"
141 "Command parameters:\n"
142 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000143 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
144 " manual page for a description of the object properties. The most common\n"
145 " object type is a 'secret', which is used to supply passwords and/or\n"
146 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300147 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400148 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800149 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
150 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100151 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
152 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300153 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200154 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
155 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
156 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300157 " 'output_filename' is the destination disk image filename\n"
158 " 'output_fmt' is the destination format\n"
159 " 'options' is a comma separated list of format specific options in a\n"
160 " name=value format. Use -o ? for an overview of the options supported by the\n"
161 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800162 " 'snapshot_param' is param used for internal snapshot, format\n"
163 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
164 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300165 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400166 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
167 " new backing file match exactly. The image doesn't need a working\n"
168 " backing file before rebasing in this case (useful for renaming the\n"
169 " backing file). For image creation, allow creating without attempting\n"
170 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300171 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200172 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100173 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200174 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
175 " contain only zeros for qemu-img to create a sparse image during\n"
176 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
177 " unallocated or zero sectors, and the destination image will always be\n"
178 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200179 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100180 " '-n' skips the target volume creation (useful if the volume is created\n"
181 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300182 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500183 "Parameters to bitmap subcommand:\n"
184 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
185 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
186 " or '--merge source'\n"
187 " '-g granularity' sets the granularity for '--add' actions\n"
188 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
189 " bitmaps from an alternative file\n"
190 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200191 "Parameters to check subcommand:\n"
192 " '-r' tries to repair any inconsistencies that are found during the check.\n"
193 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
194 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200195 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200196 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100197 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500198 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100199 " '-m' specifies how many coroutines work in parallel during the convert\n"
200 " process (defaults to 8)\n"
201 " '-W' allow to write to the target out of order rather than sequential\n"
202 "\n"
malc3f020d72010-02-08 12:04:56 +0300203 "Parameters to snapshot subcommand:\n"
204 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
205 " '-a' applies a snapshot (revert disk to saved state)\n"
206 " '-c' creates a snapshot\n"
207 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100208 " '-l' lists all snapshots in the given image\n"
209 "\n"
210 "Parameters to compare subcommand:\n"
211 " '-f' first image format\n"
212 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200213 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
214 "\n"
215 "Parameters to dd subcommand:\n"
216 " 'bs=BYTES' read and write up to BYTES bytes at a time "
217 "(default: 512)\n"
218 " 'count=N' copy only N input blocks\n"
219 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200220 " 'of=FILE' write to FILE\n"
221 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100222
223 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300224 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500225 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800226 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000227}
228
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000229static QemuOptsList qemu_object_opts = {
230 .name = "object",
231 .implied_opt_name = "qom-type",
232 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
233 .desc = {
234 { }
235 },
236};
237
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200238static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
239{
240 if (user_creatable_print_help(type, opts)) {
241 exit(0);
242 }
243 return true;
244}
245
Markus Armbruster80c710c2020-04-15 09:49:26 +0200246/*
247 * Is @optarg safe for accumulate_options()?
248 * It is when multiple of them can be joined together separated by ','.
249 * To make that work, @optarg must not start with ',' (or else a
250 * separating ',' preceding it gets escaped), and it must not end with
251 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200252 * escaped), or be empty (or else a separating ',' preceding it can
253 * escape a separating ',' following it).
254 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200255 */
256static bool is_valid_option_list(const char *optarg)
257{
258 size_t len = strlen(optarg);
259 size_t i;
260
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200261 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200262 return false;
263 }
264
265 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
266 }
267 if ((len - i) % 2) {
268 return false;
269 }
270
271 return true;
272}
273
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200274static int accumulate_options(char **options, char *optarg)
275{
276 char *new_options;
277
278 if (!is_valid_option_list(optarg)) {
279 error_report("Invalid option list: %s", optarg);
280 return -1;
281 }
282
283 if (!*options) {
284 *options = g_strdup(optarg);
285 } else {
286 new_options = g_strdup_printf("%s,%s", *options, optarg);
287 g_free(*options);
288 *options = new_options;
289 }
290 return 0;
291}
292
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000293static QemuOptsList qemu_source_opts = {
294 .name = "source",
295 .implied_opt_name = "file",
296 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
297 .desc = {
298 { }
299 },
300};
301
Stefan Weil7c30f652013-06-16 17:01:05 +0200302static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100303{
304 int ret = 0;
305 if (!quiet) {
306 va_list args;
307 va_start(args, fmt);
308 ret = vprintf(fmt, args);
309 va_end(args);
310 }
311 return ret;
312}
313
bellardea2384d2004-08-01 21:59:26 +0000314
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100315static int print_block_option_help(const char *filename, const char *fmt)
316{
317 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800318 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500319 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100320
321 /* Find driver and parse its options */
322 drv = bdrv_find_format(fmt);
323 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100324 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100325 return 1;
326 }
327
Max Reitzd402b6a2018-05-09 23:00:21 +0200328 if (!drv->create_opts) {
329 error_report("Format driver '%s' does not support image creation", fmt);
330 return 1;
331 }
332
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800333 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100334 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500335 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100336 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100337 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800338 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100339 return 1;
340 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200341 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100342 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200343 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100344 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200345 return 1;
346 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800347 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100348 }
349
Max Reitzf4619af2019-04-13 17:20:37 +0200350 if (filename) {
351 printf("Supported options:\n");
352 } else {
353 printf("Supported %s options:\n", fmt);
354 }
Max Reitz63898712018-10-19 18:49:25 +0200355 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800356 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200357
358 if (!filename) {
359 printf("\n"
360 "The protocol level may support further options.\n"
361 "Specify the target filename to include those options.\n");
362 }
363
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100364 return 0;
365}
366
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000367
Max Reitzefaa7c42016-03-16 19:54:38 +0100368static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100369 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800370 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000371{
372 QDict *options;
373 Error *local_err = NULL;
374 BlockBackend *blk;
375 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800376 if (force_share) {
377 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200378 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800379 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200380 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800381 return NULL;
382 }
Max Reitz4615f872018-05-02 22:20:50 +0200383 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800384 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100385 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000386 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100387 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000388 return NULL;
389 }
Kevin Wolfce099542016-03-15 13:01:04 +0100390 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000391
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000392 return blk;
393}
394
Max Reitzefaa7c42016-03-16 19:54:38 +0100395static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100396 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000397 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800398 bool writethrough, bool quiet,
399 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000400{
401 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200402 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100403
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100404 if (!options) {
405 options = qdict_new();
406 }
bellard75c23802004-08-27 21:28:58 +0000407 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500408 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000409 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100410
Fam Zheng335e9932017-05-03 00:35:39 +0800411 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500412 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800413 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100414 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500415 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100416 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000417 return NULL;
bellard75c23802004-08-27 21:28:58 +0000418 }
Kevin Wolfce099542016-03-15 13:01:04 +0100419 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100420
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200421 return blk;
bellard75c23802004-08-27 21:28:58 +0000422}
423
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000424
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100425static int img_add_key_secrets(void *opaque,
426 const char *name, const char *value,
427 Error **errp)
428{
429 QDict *options = opaque;
430
431 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600432 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100433 }
434
435 return 0;
436}
437
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100438
Max Reitzefaa7c42016-03-16 19:54:38 +0100439static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000440 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100441 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800442 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000443{
444 BlockBackend *blk;
445 if (image_opts) {
446 QemuOpts *opts;
447 if (fmt) {
448 error_report("--image-opts and --format are mutually exclusive");
449 return NULL;
450 }
451 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
452 filename, true);
453 if (!opts) {
454 return NULL;
455 }
Fam Zheng335e9932017-05-03 00:35:39 +0800456 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
457 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000458 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100459 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800460 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000461 }
462 return blk;
463}
464
465
Chunyan Liu83d05212014-06-05 17:20:51 +0800466static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100467 const char *base_filename,
468 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200469{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200470 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200471 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200472 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100473 error_report("Backing file not supported for file format '%s'",
474 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900475 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200476 }
477 }
478 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200479 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100480 error_report("Backing file format not supported for file "
481 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900482 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200483 }
484 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900485 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200486}
487
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300488static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
489 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100490{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100491 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300492 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100493
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300494 err = qemu_strtosz(value, NULL, &res);
495 if (err < 0 && err != -ERANGE) {
496 error_report("Invalid %s specified. You may use "
497 "k, M, G, T, P or E suffixes for", name);
498 error_report("kilobytes, megabytes, gigabytes, terabytes, "
499 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100500 return err;
501 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300502 if (err == -ERANGE || res > max || res < min) {
503 error_report("Invalid %s specified. Must be between %" PRId64
504 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100505 return -ERANGE;
506 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300507 return res;
508}
509
510static int64_t cvtnum(const char *name, const char *value)
511{
512 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100513}
514
bellardea2384d2004-08-01 21:59:26 +0000515static int img_create(int argc, char **argv)
516{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200517 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100518 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000519 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000520 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000521 const char *filename;
522 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200523 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200524 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100525 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400526 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000527
bellardea2384d2004-08-01 21:59:26 +0000528 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000529 static const struct option long_options[] = {
530 {"help", no_argument, 0, 'h'},
531 {"object", required_argument, 0, OPTION_OBJECT},
532 {0, 0, 0, 0}
533 };
John Snow6e6e55f2017-07-17 20:34:22 -0400534 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000535 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100536 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000537 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100538 }
bellardea2384d2004-08-01 21:59:26 +0000539 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800540 case ':':
541 missing_argument(argv[optind - 1]);
542 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100543 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800544 unrecognized_option(argv[optind - 1]);
545 break;
bellardea2384d2004-08-01 21:59:26 +0000546 case 'h':
547 help();
548 break;
aliguori9230eaf2009-03-28 17:55:19 +0000549 case 'F':
550 base_fmt = optarg;
551 break;
bellardea2384d2004-08-01 21:59:26 +0000552 case 'b':
553 base_filename = optarg;
554 break;
555 case 'f':
556 fmt = optarg;
557 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200558 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200559 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100560 goto fail;
561 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200562 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100563 case 'q':
564 quiet = true;
565 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400566 case 'u':
567 flags |= BDRV_O_NO_BACKING;
568 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000569 case OPTION_OBJECT: {
570 QemuOpts *opts;
571 opts = qemu_opts_parse_noisily(&qemu_object_opts,
572 optarg, true);
573 if (!opts) {
574 goto fail;
575 }
576 } break;
bellardea2384d2004-08-01 21:59:26 +0000577 }
578 }
aliguori9230eaf2009-03-28 17:55:19 +0000579
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900580 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100581 filename = (optind < argc) ? argv[optind] : NULL;
582 if (options && has_help_option(options)) {
583 g_free(options);
584 return print_block_option_help(filename, fmt);
585 }
586
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100587 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800588 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100589 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100590 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900591
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000592 if (qemu_opts_foreach(&qemu_object_opts,
593 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200594 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000595 goto fail;
596 }
597
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100598 /* Get image size, if specified */
599 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100600 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100601
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300602 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100603 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100604 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100605 }
606 img_size = (uint64_t)sval;
607 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200608 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800609 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200610 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100611
Luiz Capitulino9b375252012-11-30 10:52:05 -0200612 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400613 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100614 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100615 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100616 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900617 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200618
Kevin Wolf77386bf2014-02-21 16:24:04 +0100619 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000620 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100621
622fail:
623 g_free(options);
624 return 1;
bellardea2384d2004-08-01 21:59:26 +0000625}
626
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100627static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500628{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100629 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500630 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100631 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600632
633 visit_type_ImageCheck(v, NULL, &check, &error_abort);
634 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100635 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500636 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100637 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200638 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600639 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100640 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500641}
642
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100643static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500644{
645 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100646 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647 } else {
648 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100649 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
650 "Data may be corrupted, or further writes to the image "
651 "may corrupt it.\n",
652 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500653 }
654
655 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100656 qprintf(quiet,
657 "\n%" PRId64 " leaked clusters were found on the image.\n"
658 "This means waste of disk space, but no harm to data.\n",
659 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500660 }
661
662 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100663 qprintf(quiet,
664 "\n%" PRId64
665 " internal errors have occurred during the check.\n",
666 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667 }
668 }
669
670 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100671 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
672 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
673 check->allocated_clusters, check->total_clusters,
674 check->allocated_clusters * 100.0 / check->total_clusters,
675 check->fragmented_clusters * 100.0 / check->allocated_clusters,
676 check->compressed_clusters * 100.0 /
677 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 }
679
680 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100681 qprintf(quiet,
682 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 }
684}
685
686static int collect_image_check(BlockDriverState *bs,
687 ImageCheck *check,
688 const char *filename,
689 const char *fmt,
690 int fix)
691{
692 int ret;
693 BdrvCheckResult result;
694
695 ret = bdrv_check(bs, &result, fix);
696 if (ret < 0) {
697 return ret;
698 }
699
700 check->filename = g_strdup(filename);
701 check->format = g_strdup(bdrv_get_format_name(bs));
702 check->check_errors = result.check_errors;
703 check->corruptions = result.corruptions;
704 check->has_corruptions = result.corruptions != 0;
705 check->leaks = result.leaks;
706 check->has_leaks = result.leaks != 0;
707 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100708 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500709 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100710 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500711 check->image_end_offset = result.image_end_offset;
712 check->has_image_end_offset = result.image_end_offset != 0;
713 check->total_clusters = result.bfi.total_clusters;
714 check->has_total_clusters = result.bfi.total_clusters != 0;
715 check->allocated_clusters = result.bfi.allocated_clusters;
716 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
717 check->fragmented_clusters = result.bfi.fragmented_clusters;
718 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100719 check->compressed_clusters = result.bfi.compressed_clusters;
720 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500721
722 return 0;
723}
724
Kevin Wolfe076f332010-06-29 11:43:13 +0200725/*
726 * Checks an image for consistency. Exit codes:
727 *
Max Reitzd6635c42014-06-02 22:15:21 +0200728 * 0 - Check completed, image is good
729 * 1 - Check not completed because of internal errors
730 * 2 - Check completed, image is corrupted
731 * 3 - Check completed, image has leaked clusters, but is good otherwise
732 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200733 */
aliguori15859692009-04-21 23:11:53 +0000734static int img_check(int argc, char **argv)
735{
736 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500737 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200738 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200739 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000740 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200741 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100742 int flags = BDRV_O_CHECK;
743 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200744 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100745 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000746 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800747 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000748
749 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500750 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200751 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100752
aliguori15859692009-04-21 23:11:53 +0000753 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500754 int option_index = 0;
755 static const struct option long_options[] = {
756 {"help", no_argument, 0, 'h'},
757 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530758 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500759 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000760 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000761 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800762 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500763 {0, 0, 0, 0}
764 };
Fam Zheng335e9932017-05-03 00:35:39 +0800765 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500766 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100767 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000768 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100769 }
aliguori15859692009-04-21 23:11:53 +0000770 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800771 case ':':
772 missing_argument(argv[optind - 1]);
773 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100774 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800775 unrecognized_option(argv[optind - 1]);
776 break;
aliguori15859692009-04-21 23:11:53 +0000777 case 'h':
778 help();
779 break;
780 case 'f':
781 fmt = optarg;
782 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200783 case 'r':
784 flags |= BDRV_O_RDWR;
785
786 if (!strcmp(optarg, "leaks")) {
787 fix = BDRV_FIX_LEAKS;
788 } else if (!strcmp(optarg, "all")) {
789 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
790 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800791 error_exit("Unknown option value for -r "
792 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200793 }
794 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 case OPTION_OUTPUT:
796 output = optarg;
797 break;
Max Reitz40055952014-07-22 22:58:42 +0200798 case 'T':
799 cache = optarg;
800 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100801 case 'q':
802 quiet = true;
803 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800804 case 'U':
805 force_share = true;
806 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000807 case OPTION_OBJECT: {
808 QemuOpts *opts;
809 opts = qemu_opts_parse_noisily(&qemu_object_opts,
810 optarg, true);
811 if (!opts) {
812 return 1;
813 }
814 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000815 case OPTION_IMAGE_OPTS:
816 image_opts = true;
817 break;
aliguori15859692009-04-21 23:11:53 +0000818 }
819 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200820 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800821 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100822 }
aliguori15859692009-04-21 23:11:53 +0000823 filename = argv[optind++];
824
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500825 if (output && !strcmp(output, "json")) {
826 output_format = OFORMAT_JSON;
827 } else if (output && !strcmp(output, "human")) {
828 output_format = OFORMAT_HUMAN;
829 } else if (output) {
830 error_report("--output must be used with human or json as argument.");
831 return 1;
832 }
833
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000834 if (qemu_opts_foreach(&qemu_object_opts,
835 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200836 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000837 return 1;
838 }
839
Kevin Wolfce099542016-03-15 13:01:04 +0100840 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200841 if (ret < 0) {
842 error_report("Invalid source cache option: %s", cache);
843 return 1;
844 }
845
Fam Zheng335e9932017-05-03 00:35:39 +0800846 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
847 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200848 if (!blk) {
849 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900850 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200851 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500852
853 check = g_new0(ImageCheck, 1);
854 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200855
856 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200857 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200858 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500859 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200860 }
861
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500862 if (check->corruptions_fixed || check->leaks_fixed) {
863 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100864 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500865
866 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100867 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500868 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100869 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500870
871 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100872 qprintf(quiet,
873 "The following inconsistencies were found and repaired:\n\n"
874 " %" PRId64 " leaked clusters\n"
875 " %" PRId64 " corruptions\n\n"
876 "Double checking the fixed image now...\n",
877 check->leaks_fixed,
878 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500879 }
880
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800881 qapi_free_ImageCheck(check);
882 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500883 ret = collect_image_check(bs, check, filename, fmt, 0);
884
885 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100886 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500887 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100888 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200889 }
890
Max Reitz832390a2014-10-23 15:29:12 +0200891 if (!ret) {
892 switch (output_format) {
893 case OFORMAT_HUMAN:
894 dump_human_image_check(check, quiet);
895 break;
896 case OFORMAT_JSON:
897 dump_json_image_check(check, quiet);
898 break;
899 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500900 }
901
902 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200903 if (ret) {
904 error_report("Check failed: %s", strerror(-ret));
905 } else {
906 error_report("Check failed");
907 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500908 ret = 1;
909 goto fail;
910 }
911
912 if (check->corruptions) {
913 ret = 2;
914 } else if (check->leaks) {
915 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200916 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500917 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000918 }
919
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500920fail:
921 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200922 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500923 return ret;
aliguori15859692009-04-21 23:11:53 +0000924}
925
Max Reitzd4a32382014-10-24 15:57:37 +0200926typedef struct CommonBlockJobCBInfo {
927 BlockDriverState *bs;
928 Error **errp;
929} CommonBlockJobCBInfo;
930
931static void common_block_job_cb(void *opaque, int ret)
932{
933 CommonBlockJobCBInfo *cbi = opaque;
934
935 if (ret < 0) {
936 error_setg_errno(cbi->errp, -ret, "Block job failed");
937 }
Max Reitzd4a32382014-10-24 15:57:37 +0200938}
939
940static void run_block_job(BlockJob *job, Error **errp)
941{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200942 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800943 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200944
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200945 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200946 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200947 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200948 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200949 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300950 if (job->job.progress.total) {
951 progress = (float)job->job.progress.current /
952 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200953 }
954 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200955 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200956
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200957 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200958 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800959 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200960 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800961 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200962 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200963 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200964
sochin.jiang4172a002017-06-15 14:47:33 +0800965 /* publish completion progress only when success */
966 if (!ret) {
967 qemu_progress_print(100.f, 0);
968 }
Max Reitzd4a32382014-10-24 15:57:37 +0200969}
970
bellardea2384d2004-08-01 21:59:26 +0000971static int img_commit(int argc, char **argv)
972{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400973 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200974 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200975 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200976 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100977 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200978 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100979 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200980 Error *local_err = NULL;
981 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000982 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200983 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000984 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000985
986 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400987 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200988 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000989 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000990 static const struct option long_options[] = {
991 {"help", no_argument, 0, 'h'},
992 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000993 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000994 {0, 0, 0, 0}
995 };
Zhenguia0441b62020-10-20 14:47:43 +0000996 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000997 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100998 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000999 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001000 }
bellardea2384d2004-08-01 21:59:26 +00001001 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001002 case ':':
1003 missing_argument(argv[optind - 1]);
1004 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001005 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001006 unrecognized_option(argv[optind - 1]);
1007 break;
bellardea2384d2004-08-01 21:59:26 +00001008 case 'h':
1009 help();
1010 break;
1011 case 'f':
1012 fmt = optarg;
1013 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001014 case 't':
1015 cache = optarg;
1016 break;
Max Reitz1b22bff2014-10-24 15:57:40 +02001017 case 'b':
1018 base = optarg;
1019 /* -b implies -d */
1020 drop = true;
1021 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001022 case 'd':
1023 drop = true;
1024 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001025 case 'p':
1026 progress = true;
1027 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001028 case 'q':
1029 quiet = true;
1030 break;
Zhenguia0441b62020-10-20 14:47:43 +00001031 case 'r':
1032 rate_limit = cvtnum("rate limit", optarg);
1033 if (rate_limit < 0) {
1034 return 1;
1035 }
1036 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001037 case OPTION_OBJECT: {
1038 QemuOpts *opts;
1039 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1040 optarg, true);
1041 if (!opts) {
1042 return 1;
1043 }
1044 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001045 case OPTION_IMAGE_OPTS:
1046 image_opts = true;
1047 break;
bellardea2384d2004-08-01 21:59:26 +00001048 }
1049 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001050
1051 /* Progress is not shown in Quiet mode */
1052 if (quiet) {
1053 progress = false;
1054 }
1055
Kevin Wolffc11eb22013-08-05 10:53:04 +02001056 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001057 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001058 }
bellardea2384d2004-08-01 21:59:26 +00001059 filename = argv[optind++];
1060
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001061 if (qemu_opts_foreach(&qemu_object_opts,
1062 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001063 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001064 return 1;
1065 }
1066
Max Reitz9a86fe42014-10-24 15:57:38 +02001067 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001068 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001069 if (ret < 0) {
1070 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001071 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001072 }
1073
Fam Zheng335e9932017-05-03 00:35:39 +08001074 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1075 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001076 if (!blk) {
1077 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001078 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001079 bs = blk_bs(blk);
1080
Max Reitz687fa1d2014-10-24 15:57:39 +02001081 qemu_progress_init(progress, 1.f);
1082 qemu_progress_print(0.f, 100);
1083
Max Reitz1b22bff2014-10-24 15:57:40 +02001084 if (base) {
1085 base_bs = bdrv_find_backing_image(bs, base);
1086 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001087 error_setg(&local_err,
1088 "Did not find '%s' in the backing chain of '%s'",
1089 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001090 goto done;
1091 }
1092 } else {
1093 /* This is different from QMP, which by default uses the deepest file in
1094 * the backing chain (i.e., the very base); however, the traditional
1095 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001096 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001097 if (!base_bs) {
1098 error_setg(&local_err, "Image does not have a backing file");
1099 goto done;
1100 }
bellardea2384d2004-08-01 21:59:26 +00001101 }
1102
Max Reitzd4a32382014-10-24 15:57:37 +02001103 cbi = (CommonBlockJobCBInfo){
1104 .errp = &local_err,
1105 .bs = bs,
1106 };
1107
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001108 aio_context = bdrv_get_aio_context(bs);
1109 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001110 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001111 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001112 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001113 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001114 if (local_err) {
1115 goto done;
1116 }
1117
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001118 /* When the block job completes, the BlockBackend reference will point to
1119 * the old backing file. In order to avoid that the top image is already
1120 * deleted, so we can still empty it afterwards, increment the reference
1121 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001122 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001123 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001124 }
1125
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001126 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001127 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001128 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001129 if (local_err) {
1130 goto unref_backing;
1131 }
1132
Max Reitz2d97fde2020-04-29 16:11:26 +02001133 if (!drop) {
1134 BlockBackend *old_backing_blk;
1135
1136 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1137 &local_err);
1138 if (!old_backing_blk) {
1139 goto unref_backing;
1140 }
1141 ret = blk_make_empty(old_backing_blk, &local_err);
1142 blk_unref(old_backing_blk);
1143 if (ret == -ENOTSUP) {
1144 error_free(local_err);
1145 local_err = NULL;
1146 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001147 goto unref_backing;
1148 }
1149 }
1150
1151unref_backing:
1152 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001153 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001154 }
Max Reitzd4a32382014-10-24 15:57:37 +02001155
1156done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001157 qemu_progress_end();
1158
Markus Armbruster26f54e92014-10-07 13:59:04 +02001159 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001160
1161 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001162 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001163 return 1;
1164 }
Max Reitzd4a32382014-10-24 15:57:37 +02001165
1166 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001167 return 0;
1168}
1169
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001170/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001171 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1172 * of the first sector boundary within buf where the sector contains a
1173 * non-zero byte. This function is robust to a buffer that is not
1174 * sector-aligned.
1175 */
1176static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1177{
1178 int64_t i;
1179 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1180
1181 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1182 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1183 return i;
1184 }
1185 }
1186 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1187 return i;
1188 }
1189 return -1;
1190}
1191
1192/*
thsf58c7b32008-06-05 21:53:49 +00001193 * Returns true iff the first sector pointed to by 'buf' contains at least
1194 * a non-NUL byte.
1195 *
1196 * 'pnum' is set to the number of sectors (including and immediately following
1197 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001198 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001199 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001200 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001201 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001202static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1203 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001204{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001205 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001206 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001207
1208 if (n <= 0) {
1209 *pnum = 0;
1210 return 0;
1211 }
Yi Lic075c422020-08-19 09:36:07 +08001212 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001213 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001214 buf += BDRV_SECTOR_SIZE;
1215 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001216 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001217 }
bellardea2384d2004-08-01 21:59:26 +00001218 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001219
1220 tail = (sector_num + i) & (alignment - 1);
1221 if (tail) {
1222 if (is_zero && i <= tail) {
1223 /* treat unallocated areas which only consist
1224 * of a small tail as allocated. */
1225 is_zero = false;
1226 }
1227 if (!is_zero) {
1228 /* align up end offset of allocated areas. */
1229 i += alignment - tail;
1230 i = MIN(i, n);
1231 } else {
1232 /* align down end offset of zero areas. */
1233 i -= tail;
1234 }
1235 }
bellardea2384d2004-08-01 21:59:26 +00001236 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001237 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001238}
1239
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001240/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001241 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1242 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1243 * breaking up write requests for only small sparse areas.
1244 */
1245static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001246 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001247{
1248 int ret;
1249 int num_checked, num_used;
1250
1251 if (n < min) {
1252 min = n;
1253 }
1254
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001255 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001256 if (!ret) {
1257 return ret;
1258 }
1259
1260 num_used = *pnum;
1261 buf += BDRV_SECTOR_SIZE * *pnum;
1262 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001263 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001264 num_checked = num_used;
1265
1266 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001267 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001268
1269 buf += BDRV_SECTOR_SIZE * *pnum;
1270 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001271 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001272 num_checked += *pnum;
1273 if (ret) {
1274 num_used = num_checked;
1275 } else if (*pnum >= min) {
1276 break;
1277 }
1278 }
1279
1280 *pnum = num_used;
1281 return 1;
1282}
1283
1284/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001285 * Compares two buffers sector by sector. Returns 0 if the first
1286 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001287 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001288 * pnum is set to the sector-aligned size of the buffer prefix that
1289 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001290 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001291static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1292 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001293{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001294 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001295 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001296
Eric Blakedc61cd32017-10-11 22:47:14 -05001297 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001298
Eric Blakedc61cd32017-10-11 22:47:14 -05001299 res = !!memcmp(buf1, buf2, i);
1300 while (i < bytes) {
1301 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001302
Eric Blakedc61cd32017-10-11 22:47:14 -05001303 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001304 break;
1305 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001306 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001307 }
1308
1309 *pnum = i;
1310 return res;
1311}
1312
Stefano Garzarella97ede572019-05-08 12:43:24 +02001313#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001314
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001315/*
1316 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1317 *
Eric Blake0608e402017-10-11 22:47:12 -05001318 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1319 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1320 * failure), and 4 on error (the exit status for read errors), after emitting
1321 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001322 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001323 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001324 * @param offset: Starting offset to check
1325 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001326 * @param filename: Name of disk file we are checking (logging purpose)
1327 * @param buffer: Allocated buffer for storing read data
1328 * @param quiet: Flag for quiet mode
1329 */
Eric Blakec41508e2017-10-11 22:47:13 -05001330static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1331 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001332 uint8_t *buffer, bool quiet)
1333{
Eric Blakedebb38a2017-10-11 22:47:11 -05001334 int ret = 0;
1335 int64_t idx;
1336
Eric Blakec41508e2017-10-11 22:47:13 -05001337 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001338 if (ret < 0) {
1339 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001340 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001341 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001342 }
Eric Blakec41508e2017-10-11 22:47:13 -05001343 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001344 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001345 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001346 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001347 return 1;
1348 }
1349
1350 return 0;
1351}
1352
1353/*
1354 * Compares two images. Exit codes:
1355 *
1356 * 0 - Images are identical
1357 * 1 - Images differ
1358 * >1 - Error occurred
1359 */
1360static int img_compare(int argc, char **argv)
1361{
Max Reitz40055952014-07-22 22:58:42 +02001362 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001363 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001364 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001365 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001366 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001367 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001368 int allocated1, allocated2;
1369 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1370 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001371 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001372 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001373 int64_t total_size;
1374 int64_t offset = 0;
1375 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001376 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001377 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001378 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001379 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001380
Max Reitz40055952014-07-22 22:58:42 +02001381 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001382 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001383 static const struct option long_options[] = {
1384 {"help", no_argument, 0, 'h'},
1385 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001386 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001387 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001388 {0, 0, 0, 0}
1389 };
Fam Zheng335e9932017-05-03 00:35:39 +08001390 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001391 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 if (c == -1) {
1393 break;
1394 }
1395 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001396 case ':':
1397 missing_argument(argv[optind - 1]);
1398 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001399 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001400 unrecognized_option(argv[optind - 1]);
1401 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001402 case 'h':
1403 help();
1404 break;
1405 case 'f':
1406 fmt1 = optarg;
1407 break;
1408 case 'F':
1409 fmt2 = optarg;
1410 break;
Max Reitz40055952014-07-22 22:58:42 +02001411 case 'T':
1412 cache = optarg;
1413 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001414 case 'p':
1415 progress = true;
1416 break;
1417 case 'q':
1418 quiet = true;
1419 break;
1420 case 's':
1421 strict = true;
1422 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001423 case 'U':
1424 force_share = true;
1425 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001426 case OPTION_OBJECT: {
1427 QemuOpts *opts;
1428 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1429 optarg, true);
1430 if (!opts) {
1431 ret = 2;
1432 goto out4;
1433 }
1434 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001435 case OPTION_IMAGE_OPTS:
1436 image_opts = true;
1437 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001438 }
1439 }
1440
1441 /* Progress is not shown in Quiet mode */
1442 if (quiet) {
1443 progress = false;
1444 }
1445
1446
Kevin Wolffc11eb22013-08-05 10:53:04 +02001447 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001448 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001449 }
1450 filename1 = argv[optind++];
1451 filename2 = argv[optind++];
1452
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001453 if (qemu_opts_foreach(&qemu_object_opts,
1454 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001455 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001456 ret = 2;
1457 goto out4;
1458 }
1459
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001460 /* Initialize before goto out */
1461 qemu_progress_init(progress, 2.0);
1462
Kevin Wolfce099542016-03-15 13:01:04 +01001463 flags = 0;
1464 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001465 if (ret < 0) {
1466 error_report("Invalid source cache option: %s", cache);
1467 ret = 2;
1468 goto out3;
1469 }
1470
Fam Zheng335e9932017-05-03 00:35:39 +08001471 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1472 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001473 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001475 goto out3;
1476 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001477
Fam Zheng335e9932017-05-03 00:35:39 +08001478 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1479 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001480 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001481 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001482 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001483 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001484 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001485 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001486
Max Reitzf1d3cd72015-02-05 13:58:18 -05001487 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1488 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 total_size1 = blk_getlength(blk1);
1490 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001491 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001493 ret = 4;
1494 goto out;
1495 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001496 total_size2 = blk_getlength(blk2);
1497 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001498 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001500 ret = 4;
1501 goto out;
1502 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001503 total_size = MIN(total_size1, total_size2);
1504 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001505
1506 qemu_progress_print(0, 100);
1507
Eric Blake033d9fc2017-10-11 22:47:16 -05001508 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001509 ret = 1;
1510 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1511 goto out;
1512 }
1513
Eric Blake033d9fc2017-10-11 22:47:16 -05001514 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001515 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001516
Eric Blake033d9fc2017-10-11 22:47:16 -05001517 status1 = bdrv_block_status_above(bs1, NULL, offset,
1518 total_size1 - offset, &pnum1, NULL,
1519 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001520 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001521 ret = 3;
1522 error_report("Sector allocation test failed for %s", filename1);
1523 goto out;
1524 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001525 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001526
Eric Blake033d9fc2017-10-11 22:47:16 -05001527 status2 = bdrv_block_status_above(bs2, NULL, offset,
1528 total_size2 - offset, &pnum2, NULL,
1529 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001530 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001531 ret = 3;
1532 error_report("Sector allocation test failed for %s", filename2);
1533 goto out;
1534 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001535 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001536
1537 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001538 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001539
Fam Zheng25ad8e62016-01-13 16:37:41 +08001540 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001541 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001542 ret = 1;
1543 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001544 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001545 goto out;
1546 }
1547 }
1548 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001549 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001550 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001552 int64_t pnum;
1553
Eric Blake033d9fc2017-10-11 22:47:16 -05001554 chunk = MIN(chunk, IO_BUF_SIZE);
1555 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001556 if (ret < 0) {
1557 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001558 " of %s: %s",
1559 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001560 ret = 4;
1561 goto out;
1562 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001563 ret = blk_pread(blk2, offset, buf2, chunk);
1564 if (ret < 0) {
1565 error_report("Error while reading offset %" PRId64
1566 " of %s: %s",
1567 offset, filename2, strerror(-ret));
1568 ret = 4;
1569 goto out;
1570 }
1571 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1572 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001573 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001574 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001575 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001576 goto out;
1577 }
1578 }
1579 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001580 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001581 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001582 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001583 filename1, buf1, quiet);
1584 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001585 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001586 filename2, buf1, quiet);
1587 }
1588 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001589 goto out;
1590 }
1591 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001592 offset += chunk;
1593 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001594 }
1595
Eric Blake033d9fc2017-10-11 22:47:16 -05001596 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001597 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001598 const char *filename_over;
1599
1600 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001601 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001602 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001603 filename_over = filename1;
1604 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001605 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001606 filename_over = filename2;
1607 }
1608
Eric Blake033d9fc2017-10-11 22:47:16 -05001609 while (offset < progress_base) {
1610 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1611 progress_base - offset, &chunk,
1612 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001613 if (ret < 0) {
1614 ret = 3;
1615 error_report("Sector allocation test failed for %s",
1616 filename_over);
1617 goto out;
1618
1619 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001620 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001621 chunk = MIN(chunk, IO_BUF_SIZE);
1622 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001623 filename_over, buf1, quiet);
1624 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001625 goto out;
1626 }
1627 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001628 offset += chunk;
1629 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001630 }
1631 }
1632
1633 qprintf(quiet, "Images are identical.\n");
1634 ret = 0;
1635
1636out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001637 qemu_vfree(buf1);
1638 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001639 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001640out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001641 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001642out3:
1643 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001644out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001645 return ret;
1646}
1647
Eric Blake6c729dd2020-05-21 14:21:35 -05001648/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1649static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1650 const char *src_node, const char *src_name,
1651 Error **errp)
1652{
1653 BlockDirtyBitmapMergeSource *merge_src;
Eric Blake54aa3de2020-11-12 19:13:37 -06001654 BlockDirtyBitmapMergeSourceList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001655
1656 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1657 merge_src->type = QTYPE_QDICT;
1658 merge_src->u.external.node = g_strdup(src_node);
1659 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001660 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001661 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1662 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1663}
1664
Kevin Wolf690c7302015-03-19 13:33:32 +01001665enum ImgConvertBlockStatus {
1666 BLK_DATA,
1667 BLK_ZERO,
1668 BLK_BACKING_FILE,
1669};
1670
Peter Lieven2d9187b2017-02-28 13:40:07 +01001671#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001672#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001673
Kevin Wolf690c7302015-03-19 13:33:32 +01001674typedef struct ImgConvertState {
1675 BlockBackend **src;
1676 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001677 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001678 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001679 int64_t total_sectors;
1680 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001681 int64_t allocated_done;
1682 int64_t sector_num;
1683 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001684 enum ImgConvertBlockStatus status;
1685 int64_t sector_next_status;
1686 BlockBackend *target;
1687 bool has_zero_init;
1688 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001689 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001690 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001691 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001692 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001693 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001694 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001695 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001696 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001697 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001698 size_t cluster_sectors;
1699 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001700 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 int running_coroutines;
1702 Coroutine *co[MAX_COROUTINES];
1703 int64_t wait_sector_num[MAX_COROUTINES];
1704 CoMutex lock;
1705 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001706} ImgConvertState;
1707
Peter Lieven2d9187b2017-02-28 13:40:07 +01001708static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1709 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001710{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001711 *src_cur = 0;
1712 *src_cur_offset = 0;
1713 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1714 *src_cur_offset += s->src_sectors[*src_cur];
1715 (*src_cur)++;
1716 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001717 }
1718}
1719
1720static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1721{
Eric Blake31826642017-10-11 22:47:08 -05001722 int64_t src_cur_offset;
1723 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001724 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001725
Peter Lieven2d9187b2017-02-28 13:40:07 +01001726 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001727
1728 assert(s->total_sectors > sector_num);
1729 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1730
Max Reitz351c8ef2018-05-01 18:57:49 +02001731 if (s->target_backing_sectors >= 0) {
1732 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001733 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001734 } else if (sector_num + n > s->target_backing_sectors) {
1735 /* Split requests around target_backing_sectors (because
1736 * starting from there, zeros are handled differently) */
1737 n = s->target_backing_sectors - sector_num;
1738 }
1739 }
1740
Kevin Wolf690c7302015-03-19 13:33:32 +01001741 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001742 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1743 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001744 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001745 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1746 BlockDriverState *base;
1747
1748 if (s->target_has_backing) {
1749 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1750 } else {
1751 base = NULL;
1752 }
Eric Blake31826642017-10-11 22:47:08 -05001753
Max Reitz8eaac022019-05-07 22:35:03 +02001754 do {
1755 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001756
Max Reitz4a2061e2019-06-12 19:00:30 +02001757 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1758 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001759
1760 if (ret < 0) {
1761 if (s->salvage) {
1762 if (n == 1) {
1763 if (!s->quiet) {
1764 warn_report("error while reading block status at "
1765 "offset %" PRIu64 ": %s", offset,
1766 strerror(-ret));
1767 }
1768 /* Just try to read the data, then */
1769 ret = BDRV_BLOCK_DATA;
1770 count = BDRV_SECTOR_SIZE;
1771 } else {
1772 /* Retry on a shorter range */
1773 n = DIV_ROUND_UP(n, 4);
1774 }
1775 } else {
1776 error_report("error while reading block status at offset "
1777 "%" PRIu64 ": %s", offset, strerror(-ret));
1778 return ret;
1779 }
1780 }
1781 } while (ret < 0);
1782
Eric Blake31826642017-10-11 22:47:08 -05001783 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001784
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001785 /*
1786 * Avoid that s->sector_next_status becomes unaligned to the source
1787 * request alignment and/or cluster size to avoid unnecessary read
1788 * cycles.
1789 */
1790 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1791 if (n > tail) {
1792 n -= tail;
1793 }
1794
Kevin Wolf690c7302015-03-19 13:33:32 +01001795 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001796 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001797 } else if (ret & BDRV_BLOCK_DATA) {
1798 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001799 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001800 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001801 }
1802
1803 s->sector_next_status = sector_num + n;
1804 }
1805
1806 n = MIN(n, s->sector_next_status - sector_num);
1807 if (s->status == BLK_DATA) {
1808 n = MIN(n, s->buf_sectors);
1809 }
1810
1811 /* We need to write complete clusters for compressed images, so if an
1812 * unallocated area is shorter than that, we must consider the whole
1813 * cluster allocated. */
1814 if (s->compressed) {
1815 if (n < s->cluster_sectors) {
1816 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1817 s->status = BLK_DATA;
1818 } else {
1819 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1820 }
1821 }
1822
1823 return n;
1824}
1825
Peter Lieven2d9187b2017-02-28 13:40:07 +01001826static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1827 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001828{
Max Reitz8eaac022019-05-07 22:35:03 +02001829 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001830 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001831
Kevin Wolf690c7302015-03-19 13:33:32 +01001832 assert(nb_sectors <= s->buf_sectors);
1833 while (nb_sectors > 0) {
1834 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001835 int src_cur;
1836 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001837 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001838
1839 /* In the case of compression with multiple source files, we can get a
1840 * nb_sectors that spreads into the next part. So we must be able to
1841 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001842 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1843 blk = s->src[src_cur];
1844 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001845
Max Reitz8eaac022019-05-07 22:35:03 +02001846 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001847
Max Reitz8eaac022019-05-07 22:35:03 +02001848 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1849 if (single_read_until > offset) {
1850 n = 1;
1851 }
1852
1853 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001854 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001855 if (s->salvage) {
1856 if (n > 1) {
1857 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1858 continue;
1859 } else {
1860 if (!s->quiet) {
1861 warn_report("error while reading offset %" PRIu64
1862 ": %s", offset, strerror(-ret));
1863 }
1864 memset(buf, 0, BDRV_SECTOR_SIZE);
1865 }
1866 } else {
1867 return ret;
1868 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001869 }
1870
1871 sector_num += n;
1872 nb_sectors -= n;
1873 buf += n * BDRV_SECTOR_SIZE;
1874 }
1875
1876 return 0;
1877}
1878
Peter Lieven2d9187b2017-02-28 13:40:07 +01001879
1880static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1881 int nb_sectors, uint8_t *buf,
1882 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001883{
1884 int ret;
1885
1886 while (nb_sectors > 0) {
1887 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001888 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1889
Peter Lieven2d9187b2017-02-28 13:40:07 +01001890 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001891 case BLK_BACKING_FILE:
1892 /* If we have a backing file, leave clusters unallocated that are
1893 * unallocated in the source image, so that the backing file is
1894 * visible at the respective offset. */
1895 assert(s->target_has_backing);
1896 break;
1897
1898 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001899 /* If we're told to keep the target fully allocated (-S 0) or there
1900 * is real non-zero data, we must write it. Otherwise we can treat
1901 * it as zero sectors.
1902 * Compressed clusters need to be written as a whole, so in that
1903 * case we can only save the write if the buffer is completely
1904 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001905 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001906 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001907 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1908 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001909 (s->compressed &&
1910 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001911 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001912 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1913 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001914 if (ret < 0) {
1915 return ret;
1916 }
1917 break;
1918 }
1919 /* fall-through */
1920
1921 case BLK_ZERO:
1922 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001923 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001924 break;
1925 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001926 ret = blk_co_pwrite_zeroes(s->target,
1927 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001928 n << BDRV_SECTOR_BITS,
1929 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001930 if (ret < 0) {
1931 return ret;
1932 }
1933 break;
1934 }
1935
1936 sector_num += n;
1937 nb_sectors -= n;
1938 buf += n * BDRV_SECTOR_SIZE;
1939 }
1940
1941 return 0;
1942}
1943
Fam Zhengee5306d2018-06-01 17:26:48 +08001944static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1945 int nb_sectors)
1946{
1947 int n, ret;
1948
1949 while (nb_sectors > 0) {
1950 BlockBackend *blk;
1951 int src_cur;
1952 int64_t bs_sectors, src_cur_offset;
1953 int64_t offset;
1954
1955 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1956 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1957 blk = s->src[src_cur];
1958 bs_sectors = s->src_sectors[src_cur];
1959
1960 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1961
1962 ret = blk_co_copy_range(blk, offset, s->target,
1963 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001964 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001965 if (ret < 0) {
1966 return ret;
1967 }
1968
1969 sector_num += n;
1970 nb_sectors -= n;
1971 }
1972 return 0;
1973}
1974
Peter Lieven2d9187b2017-02-28 13:40:07 +01001975static void coroutine_fn convert_co_do_copy(void *opaque)
1976{
1977 ImgConvertState *s = opaque;
1978 uint8_t *buf = NULL;
1979 int ret, i;
1980 int index = -1;
1981
1982 for (i = 0; i < s->num_coroutines; i++) {
1983 if (s->co[i] == qemu_coroutine_self()) {
1984 index = i;
1985 break;
1986 }
1987 }
1988 assert(index >= 0);
1989
1990 s->running_coroutines++;
1991 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1992
1993 while (1) {
1994 int n;
1995 int64_t sector_num;
1996 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001997 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001998
1999 qemu_co_mutex_lock(&s->lock);
2000 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
2001 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03002002 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002003 }
2004 n = convert_iteration_sectors(s, s->sector_num);
2005 if (n < 0) {
2006 qemu_co_mutex_unlock(&s->lock);
2007 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03002008 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002009 }
2010 /* save current sector and allocation status to local variables */
2011 sector_num = s->sector_num;
2012 status = s->status;
2013 if (!s->min_sparse && s->status == BLK_ZERO) {
2014 n = MIN(n, s->buf_sectors);
2015 }
2016 /* increment global sector counter so that other coroutines can
2017 * already continue reading beyond this request */
2018 s->sector_num += n;
2019 qemu_co_mutex_unlock(&s->lock);
2020
2021 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2022 s->allocated_done += n;
2023 qemu_progress_print(100.0 * s->allocated_done /
2024 s->allocated_sectors, 0);
2025 }
2026
Fam Zhengee5306d2018-06-01 17:26:48 +08002027retry:
2028 copy_range = s->copy_range && s->status == BLK_DATA;
2029 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002030 ret = convert_co_read(s, sector_num, n, buf);
2031 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002032 error_report("error while reading at byte %lld: %s",
2033 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002034 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002035 }
2036 } else if (!s->min_sparse && status == BLK_ZERO) {
2037 status = BLK_DATA;
2038 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2039 }
2040
2041 if (s->wr_in_order) {
2042 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002043 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002044 s->wait_sector_num[index] = sector_num;
2045 qemu_coroutine_yield();
2046 }
2047 s->wait_sector_num[index] = -1;
2048 }
2049
Anton Nefedovb91127e2017-04-26 11:33:15 +03002050 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002051 if (copy_range) {
2052 ret = convert_co_copy_range(s, sector_num, n);
2053 if (ret) {
2054 s->copy_range = false;
2055 goto retry;
2056 }
2057 } else {
2058 ret = convert_co_write(s, sector_num, n, buf, status);
2059 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002060 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002061 error_report("error while writing at byte %lld: %s",
2062 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002063 s->ret = ret;
2064 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002065 }
2066
2067 if (s->wr_in_order) {
2068 /* reenter the coroutine that might have waited
2069 * for this write to complete */
2070 s->wr_offs = sector_num + n;
2071 for (i = 0; i < s->num_coroutines; i++) {
2072 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2073 /*
2074 * A -> B -> A cannot occur because A has
2075 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2076 * B will never enter A during this time window.
2077 */
2078 qemu_coroutine_enter(s->co[i]);
2079 break;
2080 }
2081 }
2082 }
2083 }
2084
Peter Lieven2d9187b2017-02-28 13:40:07 +01002085 qemu_vfree(buf);
2086 s->co[index] = NULL;
2087 s->running_coroutines--;
2088 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2089 /* the convert job finished successfully */
2090 s->ret = 0;
2091 }
2092}
2093
Kevin Wolf690c7302015-03-19 13:33:32 +01002094static int convert_do_copy(ImgConvertState *s)
2095{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002096 int ret, i, n;
2097 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002098
2099 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002100 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2101 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002102 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002103 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002104
Kevin Wolf690c7302015-03-19 13:33:32 +01002105 /* Allocate buffer for copied data. For compressed images, only one cluster
2106 * can be copied at a time. */
2107 if (s->compressed) {
2108 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2109 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002110 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002111 }
2112 s->buf_sectors = s->cluster_sectors;
2113 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002114
Kevin Wolf690c7302015-03-19 13:33:32 +01002115 while (sector_num < s->total_sectors) {
2116 n = convert_iteration_sectors(s, sector_num);
2117 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002118 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002119 }
Max Reitzaad15de2016-03-24 23:33:57 +01002120 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2121 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002122 s->allocated_sectors += n;
2123 }
2124 sector_num += n;
2125 }
2126
2127 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002128 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002129 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002130
Peter Lieven2d9187b2017-02-28 13:40:07 +01002131 qemu_co_mutex_init(&s->lock);
2132 for (i = 0; i < s->num_coroutines; i++) {
2133 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2134 s->wait_sector_num[i] = -1;
2135 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002136 }
2137
Anton Nefedovb91127e2017-04-26 11:33:15 +03002138 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002139 main_loop_wait(false);
2140 }
2141
2142 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002143 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002144 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002145 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002146 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002147 }
2148 }
2149
Peter Lieven2d9187b2017-02-28 13:40:07 +01002150 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002151}
2152
Eric Blake15e39ad2020-05-21 14:21:36 -05002153static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2154{
2155 BdrvDirtyBitmap *bm;
2156 Error *err = NULL;
2157
2158 FOR_EACH_DIRTY_BITMAP(src, bm) {
2159 const char *name;
2160
2161 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2162 continue;
2163 }
2164 name = bdrv_dirty_bitmap_name(bm);
2165 qmp_block_dirty_bitmap_add(dst->node_name, name,
2166 true, bdrv_dirty_bitmap_granularity(bm),
2167 true, true,
2168 true, !bdrv_dirty_bitmap_enabled(bm),
2169 &err);
2170 if (err) {
2171 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2172 return -1;
2173 }
2174
2175 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2176 &err);
2177 if (err) {
2178 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2179 return -1;
2180 }
2181 }
2182
2183 return 0;
2184}
2185
Peter Lieven6360ab22018-07-13 09:15:39 +02002186#define MAX_BUF_SECTORS 32768
2187
Zhengui0c8c4892020-10-20 14:47:44 +00002188static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2189{
2190 ThrottleConfig cfg;
2191
2192 throttle_config_init(&cfg);
2193 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2194
2195 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2196 blk_set_io_limits(blk, &cfg);
2197}
2198
bellardea2384d2004-08-01 21:59:26 +00002199static int img_convert(int argc, char **argv)
2200{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002201 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002202 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002203 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2204 *out_filename, *out_baseimg_param, *snapshot_name = 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;
Zhengui0c8c4892020-10-20 14:47:44 +00002219 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002220
Peter Lieven9fd77f92017-04-21 11:11:55 +02002221 ImgConvertState s = (ImgConvertState) {
2222 /* Need at least 4k of zeros for sparse detection */
2223 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002224 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002225 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2226 .wr_in_order = true,
2227 .num_coroutines = 8,
2228 };
2229
bellardea2384d2004-08-01 21:59:26 +00002230 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002231 static const struct option long_options[] = {
2232 {"help", no_argument, 0, 'h'},
2233 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002234 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002235 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002236 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002237 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002238 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002239 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002240 {0, 0, 0, 0}
2241 };
Zhengui0c8c4892020-10-20 14:47:44 +00002242 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002243 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002244 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002245 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002246 }
bellardea2384d2004-08-01 21:59:26 +00002247 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002248 case ':':
2249 missing_argument(argv[optind - 1]);
2250 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002251 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002252 unrecognized_option(argv[optind - 1]);
2253 break;
bellardea2384d2004-08-01 21:59:26 +00002254 case 'h':
2255 help();
2256 break;
2257 case 'f':
2258 fmt = optarg;
2259 break;
2260 case 'O':
2261 out_fmt = optarg;
2262 break;
thsf58c7b32008-06-05 21:53:49 +00002263 case 'B':
2264 out_baseimg = optarg;
2265 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002266 case 'C':
2267 s.copy_range = true;
2268 break;
bellardea2384d2004-08-01 21:59:26 +00002269 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002270 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002271 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002272 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002273 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002274 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002275 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002276 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002277 case 'l':
2278 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002279 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2280 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002281 if (!sn_opts) {
2282 error_report("Failed in parsing snapshot param '%s'",
2283 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002284 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002285 }
2286 } else {
2287 snapshot_name = optarg;
2288 }
2289 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002290 case 'S':
2291 {
2292 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002293
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002294 sval = cvtnum("buffer size for sparse output", optarg);
2295 if (sval < 0) {
2296 goto fail_getopt;
2297 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002298 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2299 error_report("Invalid buffer size for sparse output specified. "
2300 "Valid sizes are multiples of %llu up to %llu. Select "
2301 "0 to disable sparse detection (fully allocates output).",
2302 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002303 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002304 }
2305
Peter Lieven9fd77f92017-04-21 11:11:55 +02002306 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002307 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002308 break;
2309 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002310 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002311 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002312 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002313 case 't':
2314 cache = optarg;
2315 break;
Max Reitz40055952014-07-22 22:58:42 +02002316 case 'T':
2317 src_cache = optarg;
2318 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002319 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002320 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002321 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002322 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002323 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002324 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002325 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002326 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2327 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002328 error_report("Invalid number of coroutines. Allowed number of"
2329 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002330 goto fail_getopt;
2331 }
2332 break;
2333 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002334 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002335 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002336 case 'U':
2337 force_share = true;
2338 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002339 case 'r':
2340 rate_limit = cvtnum("rate limit", optarg);
2341 if (rate_limit < 0) {
2342 goto fail_getopt;
2343 }
2344 break;
Max Reitz3258b912017-04-26 15:46:47 +02002345 case OPTION_OBJECT: {
2346 QemuOpts *object_opts;
2347 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2348 optarg, true);
2349 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002350 goto fail_getopt;
2351 }
2352 break;
Max Reitz3258b912017-04-26 15:46:47 +02002353 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002354 case OPTION_IMAGE_OPTS:
2355 image_opts = true;
2356 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002357 case OPTION_SALVAGE:
2358 s.salvage = true;
2359 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002360 case OPTION_TARGET_IMAGE_OPTS:
2361 tgt_image_opts = true;
2362 break;
David Edmondson168468f2020-02-05 11:02:48 +00002363 case OPTION_TARGET_IS_ZERO:
2364 /*
2365 * The user asserting that the target is blank has the
2366 * same effect as the target driver supporting zero
2367 * initialisation.
2368 */
2369 s.has_zero_init = true;
2370 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002371 case OPTION_BITMAPS:
2372 bitmaps = true;
2373 break;
bellardea2384d2004-08-01 21:59:26 +00002374 }
2375 }
ths3b46e622007-09-17 08:09:54 +00002376
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002377 if (!out_fmt && !tgt_image_opts) {
2378 out_fmt = "raw";
2379 }
2380
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002381 if (qemu_opts_foreach(&qemu_object_opts,
2382 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002383 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002384 goto fail_getopt;
2385 }
2386
Fam Zhenge11ce122018-07-27 11:34:01 +08002387 if (s.compressed && s.copy_range) {
2388 error_report("Cannot enable copy offloading when -c is used");
2389 goto fail_getopt;
2390 }
2391
2392 if (explict_min_sparse && s.copy_range) {
2393 error_report("Cannot enable copy offloading when -S is used");
2394 goto fail_getopt;
2395 }
2396
Max Reitz8eaac022019-05-07 22:35:03 +02002397 if (s.copy_range && s.salvage) {
2398 error_report("Cannot use copy offloading in salvaging mode");
2399 goto fail_getopt;
2400 }
2401
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002402 if (tgt_image_opts && !skip_create) {
2403 error_report("--target-image-opts requires use of -n flag");
2404 goto fail_getopt;
2405 }
2406
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002407 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002408 error_report("-o has no effect when skipping image creation");
2409 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002410 }
2411
David Edmondson168468f2020-02-05 11:02:48 +00002412 if (s.has_zero_init && !skip_create) {
2413 error_report("--target-is-zero requires use of -n flag");
2414 goto fail_getopt;
2415 }
2416
Peter Lieven9fd77f92017-04-21 11:11:55 +02002417 s.src_num = argc - optind - 1;
2418 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2419
2420 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002421 if (out_fmt) {
2422 ret = print_block_option_help(out_filename, out_fmt);
2423 goto fail_getopt;
2424 } else {
2425 error_report("Option help requires a format be specified");
2426 goto fail_getopt;
2427 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002428 }
2429
2430 if (s.src_num < 1) {
2431 error_report("Must specify image file name");
2432 goto fail_getopt;
2433 }
2434
Peter Lieven9fd77f92017-04-21 11:11:55 +02002435 /* ret is still -EINVAL until here */
2436 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2437 if (ret < 0) {
2438 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002439 goto fail_getopt;
2440 }
2441
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002442 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002443 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002444 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002445 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002446 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002447 qemu_progress_print(0, 100);
2448
Peter Lieven9fd77f92017-04-21 11:11:55 +02002449 s.src = g_new0(BlockBackend *, s.src_num);
2450 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002451 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002452
Peter Lieven9fd77f92017-04-21 11:11:55 +02002453 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002454 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002455 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002456 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002457 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002458 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002459 ret = -1;
2460 goto out;
2461 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002462 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2463 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002464 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002465 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002466 ret = -1;
2467 goto out;
2468 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002469 src_bs = blk_bs(s.src[bs_i]);
2470 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2471 BDRV_SECTOR_SIZE);
2472 if (!bdrv_get_info(src_bs, &bdi)) {
2473 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2474 bdi.cluster_size / BDRV_SECTOR_SIZE);
2475 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002476 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002477 }
bellardea2384d2004-08-01 21:59:26 +00002478
Wenchao Xiaef806542013-12-04 17:10:57 +08002479 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002480 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002481 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2482 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2483 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002484 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002485 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002486 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002487 ret = -1;
2488 goto out;
2489 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002490
Peter Lieven9fd77f92017-04-21 11:11:55 +02002491 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2492 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002493 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002494 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002495 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002496 ret = -1;
2497 goto out;
edison51ef6722010-09-21 19:58:41 -07002498 }
2499
Max Reitz2e024cd2015-02-11 09:58:46 -05002500 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002501 /* Find driver and parse its options */
2502 drv = bdrv_find_format(out_fmt);
2503 if (!drv) {
2504 error_report("Unknown file format '%s'", out_fmt);
2505 ret = -1;
2506 goto out;
2507 }
2508
2509 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2510 if (!proto_drv) {
2511 error_report_err(local_err);
2512 ret = -1;
2513 goto out;
2514 }
2515
Max Reitz2e024cd2015-02-11 09:58:46 -05002516 if (!drv->create_opts) {
2517 error_report("Format driver '%s' does not support image creation",
2518 drv->format_name);
2519 ret = -1;
2520 goto out;
2521 }
Max Reitzf75613c2014-12-02 18:32:46 +01002522
Max Reitz2e024cd2015-02-11 09:58:46 -05002523 if (!proto_drv->create_opts) {
2524 error_report("Protocol driver '%s' does not support image creation",
2525 proto_drv->format_name);
2526 ret = -1;
2527 goto out;
2528 }
Max Reitzf75613c2014-12-02 18:32:46 +01002529
Max Reitz2e024cd2015-02-11 09:58:46 -05002530 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2531 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002532
Max Reitz2e024cd2015-02-11 09:58:46 -05002533 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002534 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002535 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002536 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002537 ret = -1;
2538 goto out;
2539 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002540 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002541
Yi Lic075c422020-08-19 09:36:07 +08002542 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2543 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002544 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2545 if (ret < 0) {
2546 goto out;
2547 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002548 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002549
Kevin Wolfa18953f2010-10-14 15:46:04 +02002550 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002551 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002552 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002553 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002554 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002555 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002556
David Edmondson168468f2020-02-05 11:02:48 +00002557 if (s.has_zero_init && s.target_has_backing) {
2558 error_report("Cannot use --target-is-zero when the destination "
2559 "image has a backing file");
2560 goto out;
2561 }
2562
Max Reitz48758a82017-04-26 15:46:48 +02002563 if (s.src_num > 1 && out_baseimg) {
2564 error_report("Having a backing file for the target makes no sense when "
2565 "concatenating multiple input images");
2566 ret = -1;
2567 goto out;
2568 }
2569
Eric Blaked9f059a2020-07-06 15:39:54 -05002570 if (out_baseimg_param) {
2571 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2572 warn_report("Deprecated use of backing file without explicit "
2573 "backing format");
2574 }
2575 }
2576
Kevin Wolfefa84d42009-05-18 16:42:12 +02002577 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002578 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002579 bool encryption =
2580 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002581 const char *encryptfmt =
2582 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002583 const char *preallocation =
2584 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002585
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002586 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002587 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002588 ret = -1;
2589 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002590 }
2591
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002592 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002593 error_report("Compression and encryption not supported at "
2594 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002595 ret = -1;
2596 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002597 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002598
Chunyan Liu83d05212014-06-05 17:20:51 +08002599 if (preallocation
2600 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002601 {
2602 error_report("Compression and preallocation not supported at "
2603 "the same time");
2604 ret = -1;
2605 goto out;
2606 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002607 }
2608
Eric Blake15e39ad2020-05-21 14:21:36 -05002609 /* Determine if bitmaps need copying */
2610 if (bitmaps) {
2611 if (s.src_num > 1) {
2612 error_report("Copying bitmaps only possible with single source");
2613 ret = -1;
2614 goto out;
2615 }
2616 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2617 error_report("Source lacks bitmap support");
2618 ret = -1;
2619 goto out;
2620 }
2621 }
2622
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002623 /*
2624 * The later open call will need any decryption secrets, and
2625 * bdrv_create() will purge "opts", so extract them now before
2626 * they are lost.
2627 */
2628 if (!skip_create) {
2629 open_opts = qdict_new();
2630 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002631
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002632 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002633 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002634 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002635 error_reportf_err(local_err, "%s: error while converting %s: ",
2636 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002637 goto out;
bellardea2384d2004-08-01 21:59:26 +00002638 }
2639 }
ths3b46e622007-09-17 08:09:54 +00002640
Max Reitz4d7c4872019-07-24 19:12:29 +02002641 s.target_is_new = !skip_create;
2642
Peter Lieven9fd77f92017-04-21 11:11:55 +02002643 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002644 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002645 if (ret < 0) {
2646 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002647 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002648 }
2649
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002650 if (skip_create) {
2651 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002652 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002653 } else {
2654 /* TODO ultimately we should allow --target-image-opts
2655 * to be used even when -n is not given.
2656 * That has to wait for bdrv_create to be improved
2657 * to allow filenames in option syntax
2658 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002659 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002660 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002661 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002662 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002663 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002664 ret = -1;
2665 goto out;
2666 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002667 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002668
Eric Blake15e39ad2020-05-21 14:21:36 -05002669 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2670 error_report("Format driver '%s' does not support bitmaps",
2671 out_bs->drv->format_name);
2672 ret = -1;
2673 goto out;
2674 }
2675
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002676 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002677 error_report("Compression not supported for this file format");
2678 ret = -1;
2679 goto out;
2680 }
2681
Eric Blake5def6b82016-06-23 16:37:19 -06002682 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002683 * or discard_alignment of the out_bs is greater. Limit to
2684 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2685 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002686 MAX(s.buf_sectors,
2687 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2688 out_bs->bl.pdiscard_alignment >>
2689 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002690
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002691 /* try to align the write requests to the destination to avoid unnecessary
2692 * RMW cycles. */
2693 s.alignment = MAX(pow2floor(s.min_sparse),
2694 DIV_ROUND_UP(out_bs->bl.request_alignment,
2695 BDRV_SECTOR_SIZE));
2696 assert(is_power_of_2(s.alignment));
2697
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002698 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002699 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002700 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002701 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002702 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002703 ret = -1;
2704 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002705 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002706 error_report("output file is smaller than input file");
2707 ret = -1;
2708 goto out;
2709 }
2710 }
2711
Max Reitzc69291e2020-01-21 16:59:14 +01002712 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002713 /* Errors are treated as "backing length unknown" (which means
2714 * s.target_backing_sectors has to be negative, which it will
2715 * be automatically). The backing file length is used only
2716 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002717 s.target_backing_sectors =
2718 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002719 } else {
2720 s.target_backing_sectors = -1;
2721 }
2722
Peter Lieven24f833c2013-11-27 11:07:07 +01002723 ret = bdrv_get_info(out_bs, &bdi);
2724 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002725 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002726 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002727 goto out;
2728 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002729 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002730 s.compressed = s.compressed || bdi.needs_compressed_writes;
2731 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002732 }
2733
Zhengui0c8c4892020-10-20 14:47:44 +00002734 if (rate_limit) {
2735 set_rate_limit(s.target, rate_limit);
2736 }
2737
Peter Lieven9fd77f92017-04-21 11:11:55 +02002738 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002739
2740 /* Now copy the bitmaps */
2741 if (bitmaps && ret == 0) {
2742 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2743 }
2744
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002745out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002746 if (!ret) {
2747 qemu_progress_print(100, 0);
2748 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002749 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002750 qemu_opts_del(opts);
2751 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002752 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002753 blk_unref(s.target);
2754 if (s.src) {
2755 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2756 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002757 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002758 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002759 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002760 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002761 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002762fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002763 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002764 g_free(options);
2765
Peter Lieven9fd77f92017-04-21 11:11:55 +02002766 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002767}
2768
bellard57d1a2b2004-08-03 21:15:11 +00002769
bellardfaea38e2006-08-05 21:31:00 +00002770static void dump_snapshots(BlockDriverState *bs)
2771{
2772 QEMUSnapshotInfo *sn_tab, *sn;
2773 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002774
2775 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2776 if (nb_sns <= 0)
2777 return;
2778 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002779 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002780 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002781 for(i = 0; i < nb_sns; i++) {
2782 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002783 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002784 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002785 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002786 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002787}
2788
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002789static void dump_json_image_info_list(ImageInfoList *list)
2790{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002791 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002792 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002793 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002794
2795 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2796 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002797 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002798 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002799 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002800 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002801 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002802 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002803}
2804
Benoît Canetc054b3f2012-09-05 13:09:02 +02002805static void dump_json_image_info(ImageInfo *info)
2806{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002807 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002808 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002809 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002810
2811 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2812 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002813 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002814 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002815 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002816 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002817 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002818 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002819}
2820
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002821static void dump_human_image_info_list(ImageInfoList *list)
2822{
2823 ImageInfoList *elem;
2824 bool delim = false;
2825
2826 for (elem = list; elem; elem = elem->next) {
2827 if (delim) {
2828 printf("\n");
2829 }
2830 delim = true;
2831
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002832 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002833 }
2834}
2835
2836static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2837{
2838 return strcmp(a, b) == 0;
2839}
2840
2841/**
2842 * Open an image file chain and return an ImageInfoList
2843 *
2844 * @filename: topmost image filename
2845 * @fmt: topmost image format (may be NULL to autodetect)
2846 * @chain: true - enumerate entire backing file chain
2847 * false - only topmost image file
2848 *
2849 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2850 * image file. If there was an error a message will have been printed to
2851 * stderr.
2852 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002853static ImageInfoList *collect_image_info_list(bool image_opts,
2854 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002855 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002856 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002857{
2858 ImageInfoList *head = NULL;
Eric Blakec3033fd2021-01-13 16:10:12 -06002859 ImageInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002860 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002861 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002862
2863 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2864
2865 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002866 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002867 BlockDriverState *bs;
2868 ImageInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002869
2870 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2871 error_report("Backing file '%s' creates an infinite loop.",
2872 filename);
2873 goto err;
2874 }
2875 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2876
Max Reitzefaa7c42016-03-16 19:54:38 +01002877 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002878 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2879 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002880 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002881 goto err;
2882 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002883 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002884
Wenchao Xia43526ec2013-06-06 12:27:58 +08002885 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002886 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002887 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002888 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002889 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002890 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002891
Eric Blakec3033fd2021-01-13 16:10:12 -06002892 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002893
Markus Armbruster26f54e92014-10-07 13:59:04 +02002894 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002895
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002896 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002897 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002898 image_opts = false;
2899
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002900 if (chain) {
2901 if (info->has_full_backing_filename) {
2902 filename = info->full_backing_filename;
2903 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002904 error_report("Could not determine absolute backing filename,"
2905 " but backing filename '%s' present",
2906 info->backing_filename);
2907 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002908 }
2909 if (info->has_backing_filename_format) {
2910 fmt = info->backing_filename_format;
2911 }
2912 }
2913 }
2914 g_hash_table_destroy(filenames);
2915 return head;
2916
2917err:
2918 qapi_free_ImageInfoList(head);
2919 g_hash_table_destroy(filenames);
2920 return NULL;
2921}
2922
Benoît Canetc054b3f2012-09-05 13:09:02 +02002923static int img_info(int argc, char **argv)
2924{
2925 int c;
2926 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002927 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002928 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002929 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002930 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002931 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002932
bellardea2384d2004-08-01 21:59:26 +00002933 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002934 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002935 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002936 int option_index = 0;
2937 static const struct option long_options[] = {
2938 {"help", no_argument, 0, 'h'},
2939 {"format", required_argument, 0, 'f'},
2940 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002941 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002942 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002943 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002944 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002945 {0, 0, 0, 0}
2946 };
Fam Zheng335e9932017-05-03 00:35:39 +08002947 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002948 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002949 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002950 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002951 }
bellardea2384d2004-08-01 21:59:26 +00002952 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002953 case ':':
2954 missing_argument(argv[optind - 1]);
2955 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002956 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002957 unrecognized_option(argv[optind - 1]);
2958 break;
bellardea2384d2004-08-01 21:59:26 +00002959 case 'h':
2960 help();
2961 break;
2962 case 'f':
2963 fmt = optarg;
2964 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002965 case 'U':
2966 force_share = true;
2967 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002968 case OPTION_OUTPUT:
2969 output = optarg;
2970 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002971 case OPTION_BACKING_CHAIN:
2972 chain = true;
2973 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002974 case OPTION_OBJECT: {
2975 QemuOpts *opts;
2976 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2977 optarg, true);
2978 if (!opts) {
2979 return 1;
2980 }
2981 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002982 case OPTION_IMAGE_OPTS:
2983 image_opts = true;
2984 break;
bellardea2384d2004-08-01 21:59:26 +00002985 }
2986 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002987 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002988 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002989 }
bellardea2384d2004-08-01 21:59:26 +00002990 filename = argv[optind++];
2991
Benoît Canetc054b3f2012-09-05 13:09:02 +02002992 if (output && !strcmp(output, "json")) {
2993 output_format = OFORMAT_JSON;
2994 } else if (output && !strcmp(output, "human")) {
2995 output_format = OFORMAT_HUMAN;
2996 } else if (output) {
2997 error_report("--output must be used with human or json as argument.");
2998 return 1;
2999 }
3000
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003001 if (qemu_opts_foreach(&qemu_object_opts,
3002 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003003 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003004 return 1;
3005 }
3006
Fam Zheng335e9932017-05-03 00:35:39 +08003007 list = collect_image_info_list(image_opts, filename, fmt, chain,
3008 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003009 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003010 return 1;
3011 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003012
Benoît Canetc054b3f2012-09-05 13:09:02 +02003013 switch (output_format) {
3014 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003015 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003016 break;
3017 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003018 if (chain) {
3019 dump_json_image_info_list(list);
3020 } else {
3021 dump_json_image_info(list->value);
3022 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003023 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003024 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003025
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003026 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003027 return 0;
3028}
3029
Eric Blake30065d12019-03-26 13:40:43 -05003030static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3031 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003032{
3033 switch (output_format) {
3034 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003035 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003036 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003037 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003038 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003039 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003040 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003041 e->start, e->length,
3042 e->has_offset ? e->offset : 0,
3043 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003044 }
3045 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3046 * Modify the flags here to allow more coalescing.
3047 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003048 if (next && (!next->data || next->zero)) {
3049 next->data = false;
3050 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003051 }
3052 break;
3053 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003054 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08003055 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003056 e->start, e->length, e->depth,
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,
Max Reitzf30c66b2019-02-01 20:29:05 +01003122 .has_filename = filename,
3123 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003124 };
3125
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003126 return 0;
3127}
3128
Fam Zheng16b0d552016-01-26 11:59:02 +08003129static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3130{
3131 if (curr->length == 0) {
3132 return false;
3133 }
3134 if (curr->zero != next->zero ||
3135 curr->data != next->data ||
3136 curr->depth != next->depth ||
3137 curr->has_filename != next->has_filename ||
3138 curr->has_offset != next->has_offset) {
3139 return false;
3140 }
3141 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3142 return false;
3143 }
3144 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3145 return false;
3146 }
3147 return true;
3148}
3149
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003150static int img_map(int argc, char **argv)
3151{
3152 int c;
3153 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003154 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003155 BlockDriverState *bs;
3156 const char *filename, *fmt, *output;
3157 int64_t length;
3158 MapEntry curr = { .length = 0 }, next;
3159 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003160 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003161 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003162 int64_t start_offset = 0;
3163 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003164
3165 fmt = NULL;
3166 output = NULL;
3167 for (;;) {
3168 int option_index = 0;
3169 static const struct option long_options[] = {
3170 {"help", no_argument, 0, 'h'},
3171 {"format", required_argument, 0, 'f'},
3172 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003173 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003174 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003175 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003176 {"start-offset", required_argument, 0, 's'},
3177 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003178 {0, 0, 0, 0}
3179 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003180 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003181 long_options, &option_index);
3182 if (c == -1) {
3183 break;
3184 }
3185 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003186 case ':':
3187 missing_argument(argv[optind - 1]);
3188 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003189 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003190 unrecognized_option(argv[optind - 1]);
3191 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003192 case 'h':
3193 help();
3194 break;
3195 case 'f':
3196 fmt = optarg;
3197 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003198 case 'U':
3199 force_share = true;
3200 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003201 case OPTION_OUTPUT:
3202 output = optarg;
3203 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003204 case 's':
3205 start_offset = cvtnum("start offset", optarg);
3206 if (start_offset < 0) {
3207 return 1;
3208 }
3209 break;
3210 case 'l':
3211 max_length = cvtnum("max length", optarg);
3212 if (max_length < 0) {
3213 return 1;
3214 }
3215 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003216 case OPTION_OBJECT: {
3217 QemuOpts *opts;
3218 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3219 optarg, true);
3220 if (!opts) {
3221 return 1;
3222 }
3223 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003224 case OPTION_IMAGE_OPTS:
3225 image_opts = true;
3226 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003227 }
3228 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003229 if (optind != argc - 1) {
3230 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003231 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003232 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003233
3234 if (output && !strcmp(output, "json")) {
3235 output_format = OFORMAT_JSON;
3236 } else if (output && !strcmp(output, "human")) {
3237 output_format = OFORMAT_HUMAN;
3238 } else if (output) {
3239 error_report("--output must be used with human or json as argument.");
3240 return 1;
3241 }
3242
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003243 if (qemu_opts_foreach(&qemu_object_opts,
3244 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003245 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003246 return 1;
3247 }
3248
Fam Zheng335e9932017-05-03 00:35:39 +08003249 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003250 if (!blk) {
3251 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003252 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003253 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003254
3255 if (output_format == OFORMAT_HUMAN) {
3256 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003257 } else if (output_format == OFORMAT_JSON) {
3258 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003259 }
3260
Max Reitzf1d3cd72015-02-05 13:58:18 -05003261 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003262 if (length < 0) {
3263 error_report("Failed to get size for '%s'", filename);
3264 return 1;
3265 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003266 if (max_length != -1) {
3267 length = MIN(start_offset + max_length, length);
3268 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003269
Eyal Moscovicic0469492020-05-13 16:36:29 +03003270 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003271 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003272 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003273 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003274
Eric Blake5e344dd2017-10-11 22:47:02 -05003275 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003276 if (ret < 0) {
3277 error_report("Could not read file metadata: %s", strerror(-ret));
3278 goto out;
3279 }
3280
Fam Zheng16b0d552016-01-26 11:59:02 +08003281 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003282 curr.length += next.length;
3283 continue;
3284 }
3285
3286 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003287 ret = dump_map_entry(output_format, &curr, &next);
3288 if (ret < 0) {
3289 goto out;
3290 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003291 }
3292 curr = next;
3293 }
3294
Eric Blake30065d12019-03-26 13:40:43 -05003295 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003296 if (output_format == OFORMAT_JSON) {
3297 puts("]");
3298 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003299
3300out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003301 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003302 return ret < 0;
3303}
3304
aliguorif7b4a942009-01-07 17:40:15 +00003305#define SNAPSHOT_LIST 1
3306#define SNAPSHOT_CREATE 2
3307#define SNAPSHOT_APPLY 3
3308#define SNAPSHOT_DELETE 4
3309
Stuart Brady153859b2009-06-07 00:42:17 +01003310static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003311{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003312 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003313 BlockDriverState *bs;
3314 QEMUSnapshotInfo sn;
3315 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003316 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003317 int action = 0;
3318 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003319 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003320 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003321 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003322 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003323
Kevin Wolfce099542016-03-15 13:01:04 +01003324 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003325 /* Parse commandline parameters */
3326 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003327 static const struct option long_options[] = {
3328 {"help", no_argument, 0, 'h'},
3329 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003330 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003331 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003332 {0, 0, 0, 0}
3333 };
Fam Zheng335e9932017-05-03 00:35:39 +08003334 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003335 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003336 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003337 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003338 }
aliguorif7b4a942009-01-07 17:40:15 +00003339 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003340 case ':':
3341 missing_argument(argv[optind - 1]);
3342 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003343 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003344 unrecognized_option(argv[optind - 1]);
3345 break;
aliguorif7b4a942009-01-07 17:40:15 +00003346 case 'h':
3347 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003348 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003349 case 'l':
3350 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003351 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003352 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003353 }
3354 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003355 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003356 break;
3357 case 'a':
3358 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003359 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003360 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003361 }
3362 action = SNAPSHOT_APPLY;
3363 snapshot_name = optarg;
3364 break;
3365 case 'c':
3366 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003367 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003368 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003369 }
3370 action = SNAPSHOT_CREATE;
3371 snapshot_name = optarg;
3372 break;
3373 case 'd':
3374 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003375 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003376 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003377 }
3378 action = SNAPSHOT_DELETE;
3379 snapshot_name = optarg;
3380 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003381 case 'q':
3382 quiet = true;
3383 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003384 case 'U':
3385 force_share = true;
3386 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003387 case OPTION_OBJECT: {
3388 QemuOpts *opts;
3389 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3390 optarg, true);
3391 if (!opts) {
3392 return 1;
3393 }
3394 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003395 case OPTION_IMAGE_OPTS:
3396 image_opts = true;
3397 break;
aliguorif7b4a942009-01-07 17:40:15 +00003398 }
3399 }
3400
Kevin Wolffc11eb22013-08-05 10:53:04 +02003401 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003402 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003403 }
aliguorif7b4a942009-01-07 17:40:15 +00003404 filename = argv[optind++];
3405
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003406 if (qemu_opts_foreach(&qemu_object_opts,
3407 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003408 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003409 return 1;
3410 }
3411
aliguorif7b4a942009-01-07 17:40:15 +00003412 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003413 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3414 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003415 if (!blk) {
3416 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003417 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003418 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003419
3420 /* Perform the requested action */
3421 switch(action) {
3422 case SNAPSHOT_LIST:
3423 dump_snapshots(bs);
3424 break;
3425
3426 case SNAPSHOT_CREATE:
3427 memset(&sn, 0, sizeof(sn));
3428 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3429
3430 qemu_gettimeofday(&tv);
3431 sn.date_sec = tv.tv_sec;
3432 sn.date_nsec = tv.tv_usec * 1000;
3433
3434 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003435 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003436 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003437 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003438 }
aliguorif7b4a942009-01-07 17:40:15 +00003439 break;
3440
3441 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003442 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003443 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003444 error_reportf_err(err, "Could not apply snapshot '%s': ",
3445 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003446 }
aliguorif7b4a942009-01-07 17:40:15 +00003447 break;
3448
3449 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003450 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3451 if (ret < 0) {
3452 error_report("Could not delete snapshot '%s': snapshot not "
3453 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003454 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003455 } else {
3456 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3457 if (ret < 0) {
3458 error_reportf_err(err, "Could not delete snapshot '%s': ",
3459 snapshot_name);
3460 ret = 1;
3461 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003462 }
aliguorif7b4a942009-01-07 17:40:15 +00003463 break;
3464 }
3465
3466 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003467 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003468 if (ret) {
3469 return 1;
3470 }
Stuart Brady153859b2009-06-07 00:42:17 +01003471 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003472}
3473
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003474static int img_rebase(int argc, char **argv)
3475{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003476 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003477 uint8_t *buf_old = NULL;
3478 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003479 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003480 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003481 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003482 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3483 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003484 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003485 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003486 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003487 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003488 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003489 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003490 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003491
3492 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003493 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003494 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003495 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496 out_baseimg = NULL;
3497 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003498 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003499 static const struct option long_options[] = {
3500 {"help", no_argument, 0, 'h'},
3501 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003502 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003503 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003504 {0, 0, 0, 0}
3505 };
Fam Zheng335e9932017-05-03 00:35:39 +08003506 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003507 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003508 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003510 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003511 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003512 case ':':
3513 missing_argument(argv[optind - 1]);
3514 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003515 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003516 unrecognized_option(argv[optind - 1]);
3517 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003518 case 'h':
3519 help();
3520 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003521 case 'f':
3522 fmt = optarg;
3523 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003524 case 'F':
3525 out_basefmt = optarg;
3526 break;
3527 case 'b':
3528 out_baseimg = optarg;
3529 break;
3530 case 'u':
3531 unsafe = 1;
3532 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003533 case 'p':
3534 progress = 1;
3535 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003536 case 't':
3537 cache = optarg;
3538 break;
Max Reitz40055952014-07-22 22:58:42 +02003539 case 'T':
3540 src_cache = optarg;
3541 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003542 case 'q':
3543 quiet = true;
3544 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003545 case OPTION_OBJECT: {
3546 QemuOpts *opts;
3547 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3548 optarg, true);
3549 if (!opts) {
3550 return 1;
3551 }
3552 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003553 case OPTION_IMAGE_OPTS:
3554 image_opts = true;
3555 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003556 case 'U':
3557 force_share = true;
3558 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003559 }
3560 }
3561
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003562 if (quiet) {
3563 progress = 0;
3564 }
3565
Fam Zhengac1307a2014-04-22 13:36:11 +08003566 if (optind != argc - 1) {
3567 error_exit("Expecting one image file name");
3568 }
3569 if (!unsafe && !out_baseimg) {
3570 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003571 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003572 filename = argv[optind++];
3573
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003574 if (qemu_opts_foreach(&qemu_object_opts,
3575 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003576 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003577 return 1;
3578 }
3579
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003580 qemu_progress_init(progress, 2.0);
3581 qemu_progress_print(0, 100);
3582
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003583 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003584 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003585 if (ret < 0) {
3586 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003587 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003588 }
3589
Kevin Wolfce099542016-03-15 13:01:04 +01003590 src_flags = 0;
3591 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003592 if (ret < 0) {
3593 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003594 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003595 }
3596
Kevin Wolfce099542016-03-15 13:01:04 +01003597 /* The source files are opened read-only, don't care about WCE */
3598 assert((src_flags & BDRV_O_RDWR) == 0);
3599 (void) src_writethrough;
3600
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003601 /*
3602 * Open the images.
3603 *
3604 * Ignore the old backing file for unsafe rebase in case we want to correct
3605 * the reference to a renamed or moved backing file.
3606 */
Fam Zheng335e9932017-05-03 00:35:39 +08003607 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3608 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003609 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003610 ret = -1;
3611 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003612 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003613 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003614
Max Reitz4a2061e2019-06-12 19:00:30 +02003615 unfiltered_bs = bdrv_skip_filters(bs);
3616
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003617 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003618 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003619 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003620 ret = -1;
3621 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003622 }
3623 }
3624
3625 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003626 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003627 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003628 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003629
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003630 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003631 blk_old_backing = blk_new(qemu_get_aio_context(),
3632 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003633 BLK_PERM_ALL);
3634 ret = blk_insert_bs(blk_old_backing, base_bs,
3635 &local_err);
3636 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003637 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003638 "Could not reuse old backing file '%s': ",
3639 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003640 goto out;
3641 }
3642 } else {
3643 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003644 }
Max Reitz644483d2015-02-05 13:58:17 -05003645
Alex Bligha6166732012-10-16 13:46:18 +01003646 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003647 const char *overlay_filename;
3648 char *out_real_path;
3649
Fam Zheng335e9932017-05-03 00:35:39 +08003650 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003651 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003652 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003653 }
3654 if (force_share) {
3655 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003656 }
3657
Max Reitzf30c66b2019-02-01 20:29:05 +01003658 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003659 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3660 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003661 out_real_path =
3662 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3663 out_baseimg,
3664 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003665 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003666 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003667 error_reportf_err(local_err,
3668 "Could not resolve backing filename: ");
3669 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003670 goto out;
3671 }
3672
Sam Eiderman863cc782019-05-23 19:33:36 +03003673 /*
3674 * Find out whether we rebase an image on top of a previous image
3675 * in its chain.
3676 */
3677 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003678 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003679 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003680 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003681
Kevin Wolfd861ab32019-04-25 14:25:10 +02003682 blk_new_backing = blk_new(qemu_get_aio_context(),
3683 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003684 BLK_PERM_ALL);
3685 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3686 &local_err);
3687 if (ret < 0) {
3688 error_reportf_err(local_err,
3689 "Could not reuse backing file '%s': ",
3690 out_baseimg);
3691 goto out;
3692 }
3693 } else {
3694 blk_new_backing = blk_new_open(out_real_path, NULL,
3695 options, src_flags, &local_err);
3696 g_free(out_real_path);
3697 if (!blk_new_backing) {
3698 error_reportf_err(local_err,
3699 "Could not open new backing file '%s': ",
3700 out_baseimg);
3701 ret = -1;
3702 goto out;
3703 }
Alex Bligha6166732012-10-16 13:46:18 +01003704 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003705 }
3706 }
3707
3708 /*
3709 * Check each unallocated cluster in the COW file. If it is unallocated,
3710 * accesses go to the backing file. We must therefore compare this cluster
3711 * in the old and new backing file, and if they differ we need to copy it
3712 * from the old backing file into the COW file.
3713 *
3714 * If qemu-img crashes during this step, no harm is done. The content of
3715 * the image is the same as the original one at any time.
3716 */
3717 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003718 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003719 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003720 int64_t new_backing_size = 0;
3721 uint64_t offset;
3722 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003723 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003724
Max Reitzf1d3cd72015-02-05 13:58:18 -05003725 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3726 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003727
Eric Blake41536282017-10-11 22:47:15 -05003728 size = blk_getlength(blk);
3729 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003730 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003731 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003732 ret = -1;
3733 goto out;
3734 }
Max Reitz35ddd932019-05-09 19:52:35 +02003735 if (blk_old_backing) {
3736 old_backing_size = blk_getlength(blk_old_backing);
3737 if (old_backing_size < 0) {
3738 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003739
Max Reitz35ddd932019-05-09 19:52:35 +02003740 bdrv_get_backing_filename(bs, backing_name,
3741 sizeof(backing_name));
3742 error_report("Could not get size of '%s': %s",
3743 backing_name, strerror(-old_backing_size));
3744 ret = -1;
3745 goto out;
3746 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003747 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003748 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003749 new_backing_size = blk_getlength(blk_new_backing);
3750 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003751 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003752 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003753 ret = -1;
3754 goto out;
3755 }
Alex Bligha6166732012-10-16 13:46:18 +01003756 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003757
Eric Blake41536282017-10-11 22:47:15 -05003758 if (size != 0) {
3759 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003760 }
3761
Eric Blake41536282017-10-11 22:47:15 -05003762 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003763 bool buf_old_is_zero = false;
3764
Eric Blake41536282017-10-11 22:47:15 -05003765 /* How many bytes can we handle with the next read? */
3766 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003767
3768 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003769 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003770 if (ret < 0) {
3771 error_report("error while reading image metadata: %s",
3772 strerror(-ret));
3773 goto out;
3774 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003775 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003776 continue;
3777 }
3778
Sam Eiderman863cc782019-05-23 19:33:36 +03003779 if (prefix_chain_bs) {
3780 /*
3781 * If cluster wasn't changed since prefix_chain, we don't need
3782 * to take action
3783 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003784 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3785 prefix_chain_bs, false,
3786 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003787 if (ret < 0) {
3788 error_report("error while reading image metadata: %s",
3789 strerror(-ret));
3790 goto out;
3791 }
3792 if (!ret) {
3793 continue;
3794 }
3795 }
3796
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003797 /*
3798 * Read old and new backing file and take into consideration that
3799 * backing files may be smaller than the COW image.
3800 */
Eric Blake41536282017-10-11 22:47:15 -05003801 if (offset >= old_backing_size) {
3802 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003803 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003804 } else {
Eric Blake41536282017-10-11 22:47:15 -05003805 if (offset + n > old_backing_size) {
3806 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003807 }
3808
Eric Blake41536282017-10-11 22:47:15 -05003809 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003810 if (ret < 0) {
3811 error_report("error while reading from old backing file");
3812 goto out;
3813 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003814 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003815
Eric Blake41536282017-10-11 22:47:15 -05003816 if (offset >= new_backing_size || !blk_new_backing) {
3817 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003818 } else {
Eric Blake41536282017-10-11 22:47:15 -05003819 if (offset + n > new_backing_size) {
3820 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003821 }
3822
Eric Blake41536282017-10-11 22:47:15 -05003823 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003824 if (ret < 0) {
3825 error_report("error while reading from new backing file");
3826 goto out;
3827 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003828 }
3829
3830 /* If they differ, we need to write to the COW file */
3831 uint64_t written = 0;
3832
Eric Blake41536282017-10-11 22:47:15 -05003833 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003834 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003835
Eric Blake41536282017-10-11 22:47:15 -05003836 if (compare_buffers(buf_old + written, buf_new + written,
3837 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003838 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003839 if (buf_old_is_zero) {
3840 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3841 } else {
3842 ret = blk_pwrite(blk, offset + written,
3843 buf_old + written, pnum, 0);
3844 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003845 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003846 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003847 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003848 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003849 }
3850 }
3851
3852 written += pnum;
3853 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003854 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003855 }
3856 }
3857
3858 /*
3859 * Change the backing file. All clusters that are different from the old
3860 * backing file are overwritten in the COW file now, so the visible content
3861 * doesn't change when we switch the backing file.
3862 */
Alex Bligha6166732012-10-16 13:46:18 +01003863 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003864 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3865 true);
Alex Bligha6166732012-10-16 13:46:18 +01003866 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003867 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003868 }
3869
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003870 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003871 error_report("Could not change the backing file to '%s': No "
3872 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003873 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003874 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003875 out_baseimg, strerror(-ret));
3876 }
3877
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003878 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003879 /*
3880 * TODO At this point it is possible to check if any clusters that are
3881 * allocated in the COW file are the same in the backing file. If so, they
3882 * could be dropped from the COW file. Don't do this before switching the
3883 * backing file, in case of a crash this would lead to corruption.
3884 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003885out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003886 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003887 /* Cleanup */
3888 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003889 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003890 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003891 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003892 qemu_vfree(buf_old);
3893 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003894
Markus Armbruster26f54e92014-10-07 13:59:04 +02003895 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003896 if (ret) {
3897 return 1;
3898 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003899 return 0;
3900}
3901
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003902static int img_resize(int argc, char **argv)
3903{
Markus Armbruster6750e792015-02-12 17:43:08 +01003904 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003905 int c, ret, relative;
3906 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003907 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003908 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003909 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003910 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003911 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003912
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003913 static QemuOptsList resize_options = {
3914 .name = "resize_options",
3915 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3916 .desc = {
3917 {
3918 .name = BLOCK_OPT_SIZE,
3919 .type = QEMU_OPT_SIZE,
3920 .help = "Virtual disk size"
3921 }, {
3922 /* end of list */
3923 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003924 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003925 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003926 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003927 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003928
Kevin Wolfe80fec72011-04-29 10:58:12 +02003929 /* Remove size from argv manually so that negative numbers are not treated
3930 * as options by getopt. */
3931 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003932 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003933 return 1;
3934 }
3935
3936 size = argv[--argc];
3937
3938 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003939 fmt = NULL;
3940 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003941 static const struct option long_options[] = {
3942 {"help", no_argument, 0, 'h'},
3943 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003944 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003945 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003946 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003947 {0, 0, 0, 0}
3948 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003949 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003950 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003951 if (c == -1) {
3952 break;
3953 }
3954 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003955 case ':':
3956 missing_argument(argv[optind - 1]);
3957 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003958 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003959 unrecognized_option(argv[optind - 1]);
3960 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003961 case 'h':
3962 help();
3963 break;
3964 case 'f':
3965 fmt = optarg;
3966 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003967 case 'q':
3968 quiet = true;
3969 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003970 case OPTION_OBJECT: {
3971 QemuOpts *opts;
3972 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3973 optarg, true);
3974 if (!opts) {
3975 return 1;
3976 }
3977 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003978 case OPTION_IMAGE_OPTS:
3979 image_opts = true;
3980 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003981 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003982 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003983 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003984 if (prealloc == PREALLOC_MODE__MAX) {
3985 error_report("Invalid preallocation mode '%s'", optarg);
3986 return 1;
3987 }
3988 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003989 case OPTION_SHRINK:
3990 shrink = true;
3991 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003992 }
3993 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003994 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003995 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003996 }
3997 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003998
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003999 if (qemu_opts_foreach(&qemu_object_opts,
4000 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004001 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004002 return 1;
4003 }
4004
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004005 /* Choose grow, shrink, or absolute resize mode */
4006 switch (size[0]) {
4007 case '+':
4008 relative = 1;
4009 size++;
4010 break;
4011 case '-':
4012 relative = -1;
4013 size++;
4014 break;
4015 default:
4016 relative = 0;
4017 break;
4018 }
4019
4020 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08004021 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004022 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01004023 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01004024 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004025 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01004026 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004027 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004028 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
4029 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004030
Max Reitzefaa7c42016-03-16 19:54:38 +01004031 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08004032 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4033 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004034 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01004035 ret = -1;
4036 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004037 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004038
Max Reitzdc5f6902017-06-13 22:20:55 +02004039 current_size = blk_getlength(blk);
4040 if (current_size < 0) {
4041 error_report("Failed to inquire current image length: %s",
4042 strerror(-current_size));
4043 ret = -1;
4044 goto out;
4045 }
4046
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004047 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004048 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004049 } else {
4050 total_size = n;
4051 }
4052 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004053 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004054 ret = -1;
4055 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004056 }
4057
Max Reitzdc5f6902017-06-13 22:20:55 +02004058 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4059 error_report("Preallocation can only be used for growing images");
4060 ret = -1;
4061 goto out;
4062 }
4063
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004064 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004065 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004066 warn_report("Shrinking an image will delete all data beyond the "
4067 "shrunken image's end. Before performing such an "
4068 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004069 ret = -1;
4070 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004071 }
4072
Max Reitze8d04f92019-09-18 11:51:43 +02004073 /*
4074 * The user expects the image to have the desired size after
4075 * resizing, so pass @exact=true. It is of no use to report
4076 * success when the image has not actually been resized.
4077 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004078 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004079 if (!ret) {
4080 qprintf(quiet, "Image resized.\n");
4081 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004082 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004083 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004084out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004085 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004086 if (ret) {
4087 return 1;
4088 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004089 return 0;
4090}
4091
Max Reitz76a3a342014-10-27 11:12:51 +01004092static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004093 int64_t offset, int64_t total_work_size,
4094 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004095{
4096 qemu_progress_print(100.f * offset / total_work_size, 0);
4097}
4098
Max Reitz51641352018-05-09 23:00:20 +02004099static int print_amend_option_help(const char *format)
4100{
4101 BlockDriver *drv;
4102
4103 /* Find driver and parse its options */
4104 drv = bdrv_find_format(format);
4105 if (!drv) {
4106 error_report("Unknown file format '%s'", format);
4107 return 1;
4108 }
4109
4110 if (!drv->bdrv_amend_options) {
4111 error_report("Format driver '%s' does not support option amendment",
4112 format);
4113 return 1;
4114 }
4115
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004116 /* Every driver supporting amendment must have amend_opts */
4117 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004118
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004119 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004120 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004121 return 0;
4122}
4123
Max Reitz6f176b42013-09-03 10:09:50 +02004124static int img_amend(int argc, char **argv)
4125{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004126 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004127 int c, ret = 0;
4128 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004129 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004130 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004131 const char *fmt = NULL, *filename, *cache;
4132 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004133 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004134 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004135 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004136 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004137 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004138 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004139
Max Reitzbd39e6e2014-07-22 22:58:43 +02004140 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004141 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004142 static const struct option long_options[] = {
4143 {"help", no_argument, 0, 'h'},
4144 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004145 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004146 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004147 {0, 0, 0, 0}
4148 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004149 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004150 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004151 if (c == -1) {
4152 break;
4153 }
4154
4155 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004156 case ':':
4157 missing_argument(argv[optind - 1]);
4158 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004159 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004160 unrecognized_option(argv[optind - 1]);
4161 break;
4162 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004163 help();
4164 break;
4165 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004166 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004167 ret = -1;
4168 goto out_no_progress;
4169 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004170 break;
4171 case 'f':
4172 fmt = optarg;
4173 break;
4174 case 't':
4175 cache = optarg;
4176 break;
4177 case 'p':
4178 progress = true;
4179 break;
4180 case 'q':
4181 quiet = true;
4182 break;
4183 case OPTION_OBJECT:
4184 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4185 optarg, true);
4186 if (!opts) {
4187 ret = -1;
4188 goto out_no_progress;
4189 }
4190 break;
4191 case OPTION_IMAGE_OPTS:
4192 image_opts = true;
4193 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004194 case OPTION_FORCE:
4195 force = true;
4196 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004197 }
4198 }
4199
Max Reitz6f176b42013-09-03 10:09:50 +02004200 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004201 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004202 }
4203
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004204 if (qemu_opts_foreach(&qemu_object_opts,
4205 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004206 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004207 ret = -1;
4208 goto out_no_progress;
4209 }
4210
Max Reitz76a3a342014-10-27 11:12:51 +01004211 if (quiet) {
4212 progress = false;
4213 }
4214 qemu_progress_init(progress, 1.0);
4215
Kevin Wolfa283cb62014-02-21 16:24:07 +01004216 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4217 if (fmt && has_help_option(options)) {
4218 /* If a format is explicitly specified (and possibly no filename is
4219 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004220 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004221 goto out;
4222 }
4223
4224 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004225 error_report("Expecting one image file name");
4226 ret = -1;
4227 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004228 }
Max Reitz6f176b42013-09-03 10:09:50 +02004229
Kevin Wolfce099542016-03-15 13:01:04 +01004230 flags = BDRV_O_RDWR;
4231 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004232 if (ret < 0) {
4233 error_report("Invalid cache option: %s", cache);
4234 goto out;
4235 }
4236
Fam Zheng335e9932017-05-03 00:35:39 +08004237 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4238 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004239 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004240 ret = -1;
4241 goto out;
4242 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004243 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004244
4245 fmt = bs->drv->format_name;
4246
Kevin Wolf626f84f2014-02-21 16:24:06 +01004247 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004248 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004249 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004250 goto out;
4251 }
4252
Max Reitz1f996682018-05-09 23:00:17 +02004253 if (!bs->drv->bdrv_amend_options) {
4254 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004255 fmt);
4256 ret = -1;
4257 goto out;
4258 }
4259
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004260 /* Every driver supporting amendment must have amend_opts */
4261 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004262
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004263 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4264 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004265 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004266 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004267 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4268 qemu_opts_del(opts);
4269 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004270 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004271 error_append_hint(&err,
4272 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004273 }
4274
Paolo Bonziniece90862017-01-04 15:56:24 +01004275 error_report_err(err);
4276 ret = -1;
4277 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004278 }
4279
Max Reitz76a3a342014-10-27 11:12:51 +01004280 /* In case the driver does not call amend_status_cb() */
4281 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004282 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004283 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004284 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004285 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004286 goto out;
4287 }
4288
4289out:
Max Reitz76a3a342014-10-27 11:12:51 +01004290 qemu_progress_end();
4291
Max Reitze814dff2015-08-20 16:00:38 -07004292out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004293 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004294 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004295 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004296 g_free(options);
4297
Max Reitz6f176b42013-09-03 10:09:50 +02004298 if (ret) {
4299 return 1;
4300 }
4301 return 0;
4302}
4303
Kevin Wolfb6133b82014-08-05 14:17:13 +02004304typedef struct BenchData {
4305 BlockBackend *blk;
4306 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004307 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004308 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004309 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004310 int nrreq;
4311 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004312 int flush_interval;
4313 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004314 uint8_t *buf;
4315 QEMUIOVector *qiov;
4316
4317 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004318 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004319 uint64_t offset;
4320} BenchData;
4321
Kevin Wolf55d539c2016-06-03 13:59:41 +02004322static void bench_undrained_flush_cb(void *opaque, int ret)
4323{
4324 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004325 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004326 exit(EXIT_FAILURE);
4327 }
4328}
4329
Kevin Wolfb6133b82014-08-05 14:17:13 +02004330static void bench_cb(void *opaque, int ret)
4331{
4332 BenchData *b = opaque;
4333 BlockAIOCB *acb;
4334
4335 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004336 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004337 exit(EXIT_FAILURE);
4338 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004339
4340 if (b->in_flush) {
4341 /* Just finished a flush with drained queue: Start next requests */
4342 assert(b->in_flight == 0);
4343 b->in_flush = false;
4344 } else if (b->in_flight > 0) {
4345 int remaining = b->n - b->in_flight;
4346
Kevin Wolfb6133b82014-08-05 14:17:13 +02004347 b->n--;
4348 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004349
4350 /* Time for flush? Drain queue if requested, then flush */
4351 if (b->flush_interval && remaining % b->flush_interval == 0) {
4352 if (!b->in_flight || !b->drain_on_flush) {
4353 BlockCompletionFunc *cb;
4354
4355 if (b->drain_on_flush) {
4356 b->in_flush = true;
4357 cb = bench_cb;
4358 } else {
4359 cb = bench_undrained_flush_cb;
4360 }
4361
4362 acb = blk_aio_flush(b->blk, cb, b);
4363 if (!acb) {
4364 error_report("Failed to issue flush request");
4365 exit(EXIT_FAILURE);
4366 }
4367 }
4368 if (b->drain_on_flush) {
4369 return;
4370 }
4371 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004372 }
4373
4374 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004375 int64_t offset = b->offset;
4376 /* blk_aio_* might look for completed I/Os and kick bench_cb
4377 * again, so make sure this operation is counted by in_flight
4378 * and b->offset is ready for the next submission.
4379 */
4380 b->in_flight++;
4381 b->offset += b->step;
4382 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004383 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004384 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004385 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004386 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004387 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004388 if (!acb) {
4389 error_report("Failed to issue request");
4390 exit(EXIT_FAILURE);
4391 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004392 }
4393}
4394
4395static int img_bench(int argc, char **argv)
4396{
4397 int c, ret = 0;
4398 const char *fmt = NULL, *filename;
4399 bool quiet = false;
4400 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004401 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004402 int count = 75000;
4403 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004404 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004405 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004406 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004407 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004408 int flush_interval = 0;
4409 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004410 int64_t image_size;
4411 BlockBackend *blk = NULL;
4412 BenchData data = {};
4413 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004414 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004415 struct timeval t1, t2;
4416 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004417 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004418 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004419
4420 for (;;) {
4421 static const struct option long_options[] = {
4422 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004423 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004424 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004425 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004426 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004427 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004428 {0, 0, 0, 0}
4429 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004430 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4431 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004432 if (c == -1) {
4433 break;
4434 }
4435
4436 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004437 case ':':
4438 missing_argument(argv[optind - 1]);
4439 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004440 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004441 unrecognized_option(argv[optind - 1]);
4442 break;
4443 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004444 help();
4445 break;
4446 case 'c':
4447 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004448 unsigned long res;
4449
4450 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004451 error_report("Invalid request count specified");
4452 return 1;
4453 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004454 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004455 break;
4456 }
4457 case 'd':
4458 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004459 unsigned long res;
4460
4461 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004462 error_report("Invalid queue depth specified");
4463 return 1;
4464 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004465 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004466 break;
4467 }
4468 case 'f':
4469 fmt = optarg;
4470 break;
4471 case 'n':
4472 flags |= BDRV_O_NATIVE_AIO;
4473 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004474 case 'i':
4475 ret = bdrv_parse_aio(optarg, &flags);
4476 if (ret < 0) {
4477 error_report("Invalid aio option: %s", optarg);
4478 ret = -1;
4479 goto out;
4480 }
4481 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004482 case 'o':
4483 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004484 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004485 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004486 return 1;
4487 }
4488 break;
4489 }
4490 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004491 case 'q':
4492 quiet = true;
4493 break;
4494 case 's':
4495 {
4496 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004497
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004498 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4499 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004500 return 1;
4501 }
4502
4503 bufsize = sval;
4504 break;
4505 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004506 case 'S':
4507 {
4508 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004509
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004510 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4511 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004512 return 1;
4513 }
4514
4515 step = sval;
4516 break;
4517 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004518 case 't':
4519 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4520 if (ret < 0) {
4521 error_report("Invalid cache mode");
4522 ret = -1;
4523 goto out;
4524 }
4525 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004526 case 'w':
4527 flags |= BDRV_O_RDWR;
4528 is_write = true;
4529 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004530 case 'U':
4531 force_share = true;
4532 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004533 case OPTION_PATTERN:
4534 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004535 unsigned long res;
4536
4537 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004538 error_report("Invalid pattern byte specified");
4539 return 1;
4540 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004541 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004542 break;
4543 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004544 case OPTION_FLUSH_INTERVAL:
4545 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004546 unsigned long res;
4547
4548 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004549 error_report("Invalid flush interval specified");
4550 return 1;
4551 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004552 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004553 break;
4554 }
4555 case OPTION_NO_DRAIN:
4556 drain_on_flush = false;
4557 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004558 case OPTION_IMAGE_OPTS:
4559 image_opts = true;
4560 break;
4561 }
4562 }
4563
4564 if (optind != argc - 1) {
4565 error_exit("Expecting one image file name");
4566 }
4567 filename = argv[argc - 1];
4568
Kevin Wolf55d539c2016-06-03 13:59:41 +02004569 if (!is_write && flush_interval) {
4570 error_report("--flush-interval is only available in write tests");
4571 ret = -1;
4572 goto out;
4573 }
4574 if (flush_interval && flush_interval < depth) {
4575 error_report("Flush interval can't be smaller than depth");
4576 ret = -1;
4577 goto out;
4578 }
4579
Fam Zheng335e9932017-05-03 00:35:39 +08004580 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4581 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004582 if (!blk) {
4583 ret = -1;
4584 goto out;
4585 }
4586
4587 image_size = blk_getlength(blk);
4588 if (image_size < 0) {
4589 ret = image_size;
4590 goto out;
4591 }
4592
4593 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004594 .blk = blk,
4595 .image_size = image_size,
4596 .bufsize = bufsize,
4597 .step = step ?: bufsize,
4598 .nrreq = depth,
4599 .n = count,
4600 .offset = offset,
4601 .write = is_write,
4602 .flush_interval = flush_interval,
4603 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004604 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004605 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004606 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004607 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004608 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004609 if (flush_interval) {
4610 printf("Sending flush every %d requests\n", flush_interval);
4611 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004612
Fam Zheng79d46582018-01-16 14:08:58 +08004613 buf_size = data.nrreq * data.bufsize;
4614 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004615 memset(data.buf, pattern, data.nrreq * data.bufsize);
4616
Fam Zheng79d46582018-01-16 14:08:58 +08004617 blk_register_buf(blk, data.buf, buf_size);
4618
Kevin Wolfb6133b82014-08-05 14:17:13 +02004619 data.qiov = g_new(QEMUIOVector, data.nrreq);
4620 for (i = 0; i < data.nrreq; i++) {
4621 qemu_iovec_init(&data.qiov[i], 1);
4622 qemu_iovec_add(&data.qiov[i],
4623 data.buf + i * data.bufsize, data.bufsize);
4624 }
4625
4626 gettimeofday(&t1, NULL);
4627 bench_cb(&data, 0);
4628
4629 while (data.n > 0) {
4630 main_loop_wait(false);
4631 }
4632 gettimeofday(&t2, NULL);
4633
4634 printf("Run completed in %3.3f seconds.\n",
4635 (t2.tv_sec - t1.tv_sec)
4636 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4637
4638out:
Fam Zheng79d46582018-01-16 14:08:58 +08004639 if (data.buf) {
4640 blk_unregister_buf(blk, data.buf);
4641 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004642 qemu_vfree(data.buf);
4643 blk_unref(blk);
4644
4645 if (ret) {
4646 return 1;
4647 }
4648 return 0;
4649}
4650
Eric Blake3b51ab42020-05-12 20:16:45 -05004651enum ImgBitmapAct {
4652 BITMAP_ADD,
4653 BITMAP_REMOVE,
4654 BITMAP_CLEAR,
4655 BITMAP_ENABLE,
4656 BITMAP_DISABLE,
4657 BITMAP_MERGE,
4658};
4659typedef struct ImgBitmapAction {
4660 enum ImgBitmapAct act;
4661 const char *src; /* only used for merge */
4662 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4663} ImgBitmapAction;
4664
4665static int img_bitmap(int argc, char **argv)
4666{
4667 Error *err = NULL;
4668 int c, ret = 1;
4669 QemuOpts *opts = NULL;
4670 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4671 const char *filename, *bitmap;
4672 BlockBackend *blk = NULL, *src = NULL;
4673 BlockDriverState *bs = NULL, *src_bs = NULL;
4674 bool image_opts = false;
4675 int64_t granularity = 0;
4676 bool add = false, merge = false;
4677 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4678 ImgBitmapAction *act, *act_next;
4679 const char *op;
4680
4681 QSIMPLEQ_INIT(&actions);
4682
4683 for (;;) {
4684 static const struct option long_options[] = {
4685 {"help", no_argument, 0, 'h'},
4686 {"object", required_argument, 0, OPTION_OBJECT},
4687 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4688 {"add", no_argument, 0, OPTION_ADD},
4689 {"remove", no_argument, 0, OPTION_REMOVE},
4690 {"clear", no_argument, 0, OPTION_CLEAR},
4691 {"enable", no_argument, 0, OPTION_ENABLE},
4692 {"disable", no_argument, 0, OPTION_DISABLE},
4693 {"merge", required_argument, 0, OPTION_MERGE},
4694 {"granularity", required_argument, 0, 'g'},
4695 {"source-file", required_argument, 0, 'b'},
4696 {"source-format", required_argument, 0, 'F'},
4697 {0, 0, 0, 0}
4698 };
4699 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4700 if (c == -1) {
4701 break;
4702 }
4703
4704 switch (c) {
4705 case ':':
4706 missing_argument(argv[optind - 1]);
4707 break;
4708 case '?':
4709 unrecognized_option(argv[optind - 1]);
4710 break;
4711 case 'h':
4712 help();
4713 break;
4714 case 'b':
4715 src_filename = optarg;
4716 break;
4717 case 'f':
4718 fmt = optarg;
4719 break;
4720 case 'F':
4721 src_fmt = optarg;
4722 break;
4723 case 'g':
4724 granularity = cvtnum("granularity", optarg);
4725 if (granularity < 0) {
4726 return 1;
4727 }
4728 break;
4729 case OPTION_ADD:
4730 act = g_new0(ImgBitmapAction, 1);
4731 act->act = BITMAP_ADD;
4732 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4733 add = true;
4734 break;
4735 case OPTION_REMOVE:
4736 act = g_new0(ImgBitmapAction, 1);
4737 act->act = BITMAP_REMOVE;
4738 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4739 break;
4740 case OPTION_CLEAR:
4741 act = g_new0(ImgBitmapAction, 1);
4742 act->act = BITMAP_CLEAR;
4743 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4744 break;
4745 case OPTION_ENABLE:
4746 act = g_new0(ImgBitmapAction, 1);
4747 act->act = BITMAP_ENABLE;
4748 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4749 break;
4750 case OPTION_DISABLE:
4751 act = g_new0(ImgBitmapAction, 1);
4752 act->act = BITMAP_DISABLE;
4753 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4754 break;
4755 case OPTION_MERGE:
4756 act = g_new0(ImgBitmapAction, 1);
4757 act->act = BITMAP_MERGE;
4758 act->src = optarg;
4759 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4760 merge = true;
4761 break;
4762 case OPTION_OBJECT:
4763 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4764 if (!opts) {
4765 goto out;
4766 }
4767 break;
4768 case OPTION_IMAGE_OPTS:
4769 image_opts = true;
4770 break;
4771 }
4772 }
4773
4774 if (qemu_opts_foreach(&qemu_object_opts,
4775 user_creatable_add_opts_foreach,
4776 qemu_img_object_print_help, &error_fatal)) {
4777 goto out;
4778 }
4779
4780 if (QSIMPLEQ_EMPTY(&actions)) {
4781 error_report("Need at least one of --add, --remove, --clear, "
4782 "--enable, --disable, or --merge");
4783 goto out;
4784 }
4785
4786 if (granularity && !add) {
4787 error_report("granularity only supported with --add");
4788 goto out;
4789 }
4790 if (src_fmt && !src_filename) {
4791 error_report("-F only supported with -b");
4792 goto out;
4793 }
4794 if (src_filename && !merge) {
4795 error_report("Merge bitmap source file only supported with "
4796 "--merge");
4797 goto out;
4798 }
4799
4800 if (optind != argc - 2) {
4801 error_report("Expecting filename and bitmap name");
4802 goto out;
4803 }
4804
4805 filename = argv[optind];
4806 bitmap = argv[optind + 1];
4807
Eric Blake14f16bf2020-09-14 14:10:09 -05004808 /*
4809 * No need to open backing chains; we will be manipulating bitmaps
4810 * directly in this image without reference to image contents.
4811 */
4812 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4813 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004814 if (!blk) {
4815 goto out;
4816 }
4817 bs = blk_bs(blk);
4818 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004819 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4820 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004821 if (!src) {
4822 goto out;
4823 }
4824 src_bs = blk_bs(src);
4825 } else {
4826 src_bs = bs;
4827 }
4828
4829 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4830 switch (act->act) {
4831 case BITMAP_ADD:
4832 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4833 !!granularity, granularity, true, true,
4834 false, false, &err);
4835 op = "add";
4836 break;
4837 case BITMAP_REMOVE:
4838 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4839 op = "remove";
4840 break;
4841 case BITMAP_CLEAR:
4842 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4843 op = "clear";
4844 break;
4845 case BITMAP_ENABLE:
4846 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4847 op = "enable";
4848 break;
4849 case BITMAP_DISABLE:
4850 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4851 op = "disable";
4852 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004853 case BITMAP_MERGE:
4854 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4855 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004856 op = "merge";
4857 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004858 default:
4859 g_assert_not_reached();
4860 }
4861
4862 if (err) {
4863 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4864 op, bitmap);
4865 goto out;
4866 }
4867 g_free(act);
4868 }
4869
4870 ret = 0;
4871
4872 out:
4873 blk_unref(src);
4874 blk_unref(blk);
4875 qemu_opts_del(opts);
4876 return ret;
4877}
4878
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004879#define C_BS 01
4880#define C_COUNT 02
4881#define C_IF 04
4882#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004883#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004884
4885struct DdInfo {
4886 unsigned int flags;
4887 int64_t count;
4888};
4889
4890struct DdIo {
4891 int bsz; /* Block size */
4892 char *filename;
4893 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004894 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004895};
4896
4897struct DdOpts {
4898 const char *name;
4899 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4900 unsigned int flag;
4901};
4902
4903static int img_dd_bs(const char *arg,
4904 struct DdIo *in, struct DdIo *out,
4905 struct DdInfo *dd)
4906{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004907 int64_t res;
4908
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004909 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004910
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004911 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004912 return 1;
4913 }
4914 in->bsz = out->bsz = res;
4915
4916 return 0;
4917}
4918
4919static int img_dd_count(const char *arg,
4920 struct DdIo *in, struct DdIo *out,
4921 struct DdInfo *dd)
4922{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004923 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004924
Markus Armbruster606caa02017-02-21 21:14:04 +01004925 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004926 return 1;
4927 }
4928
4929 return 0;
4930}
4931
4932static int img_dd_if(const char *arg,
4933 struct DdIo *in, struct DdIo *out,
4934 struct DdInfo *dd)
4935{
4936 in->filename = g_strdup(arg);
4937
4938 return 0;
4939}
4940
4941static int img_dd_of(const char *arg,
4942 struct DdIo *in, struct DdIo *out,
4943 struct DdInfo *dd)
4944{
4945 out->filename = g_strdup(arg);
4946
4947 return 0;
4948}
4949
Reda Sallahif7c15532016-08-10 16:16:09 +02004950static int img_dd_skip(const char *arg,
4951 struct DdIo *in, struct DdIo *out,
4952 struct DdInfo *dd)
4953{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004954 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004955
Markus Armbruster606caa02017-02-21 21:14:04 +01004956 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004957 return 1;
4958 }
4959
4960 return 0;
4961}
4962
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004963static int img_dd(int argc, char **argv)
4964{
4965 int ret = 0;
4966 char *arg = NULL;
4967 char *tmp;
4968 BlockDriver *drv = NULL, *proto_drv = NULL;
4969 BlockBackend *blk1 = NULL, *blk2 = NULL;
4970 QemuOpts *opts = NULL;
4971 QemuOptsList *create_opts = NULL;
4972 Error *local_err = NULL;
4973 bool image_opts = false;
4974 int c, i;
4975 const char *out_fmt = "raw";
4976 const char *fmt = NULL;
4977 int64_t size = 0;
4978 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004979 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004980 struct DdInfo dd = {
4981 .flags = 0,
4982 .count = 0,
4983 };
4984 struct DdIo in = {
4985 .bsz = 512, /* Block size is by default 512 bytes */
4986 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004987 .buf = NULL,
4988 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004989 };
4990 struct DdIo out = {
4991 .bsz = 512,
4992 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004993 .buf = NULL,
4994 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004995 };
4996
4997 const struct DdOpts options[] = {
4998 { "bs", img_dd_bs, C_BS },
4999 { "count", img_dd_count, C_COUNT },
5000 { "if", img_dd_if, C_IF },
5001 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02005002 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005003 { NULL, NULL, 0 }
5004 };
5005 const struct option long_options[] = {
5006 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005007 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005008 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08005009 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005010 { 0, 0, 0, 0 }
5011 };
5012
Fam Zheng335e9932017-05-03 00:35:39 +08005013 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005014 if (c == EOF) {
5015 break;
5016 }
5017 switch (c) {
5018 case 'O':
5019 out_fmt = optarg;
5020 break;
5021 case 'f':
5022 fmt = optarg;
5023 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005024 case ':':
5025 missing_argument(argv[optind - 1]);
5026 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005027 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005028 unrecognized_option(argv[optind - 1]);
5029 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005030 case 'h':
5031 help();
5032 break;
Fam Zheng335e9932017-05-03 00:35:39 +08005033 case 'U':
5034 force_share = true;
5035 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005036 case OPTION_OBJECT:
5037 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005038 ret = -1;
5039 goto out;
5040 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005041 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005042 case OPTION_IMAGE_OPTS:
5043 image_opts = true;
5044 break;
5045 }
5046 }
5047
5048 for (i = optind; i < argc; i++) {
5049 int j;
5050 arg = g_strdup(argv[i]);
5051
5052 tmp = strchr(arg, '=');
5053 if (tmp == NULL) {
5054 error_report("unrecognized operand %s", arg);
5055 ret = -1;
5056 goto out;
5057 }
5058
5059 *tmp++ = '\0';
5060
5061 for (j = 0; options[j].name != NULL; j++) {
5062 if (!strcmp(arg, options[j].name)) {
5063 break;
5064 }
5065 }
5066 if (options[j].name == NULL) {
5067 error_report("unrecognized operand %s", arg);
5068 ret = -1;
5069 goto out;
5070 }
5071
5072 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5073 ret = -1;
5074 goto out;
5075 }
5076 dd.flags |= options[j].flag;
5077 g_free(arg);
5078 arg = NULL;
5079 }
5080
5081 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5082 error_report("Must specify both input and output files");
5083 ret = -1;
5084 goto out;
5085 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005086
5087 if (qemu_opts_foreach(&qemu_object_opts,
5088 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005089 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005090 ret = -1;
5091 goto out;
5092 }
5093
Fam Zheng335e9932017-05-03 00:35:39 +08005094 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5095 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005096
5097 if (!blk1) {
5098 ret = -1;
5099 goto out;
5100 }
5101
5102 drv = bdrv_find_format(out_fmt);
5103 if (!drv) {
5104 error_report("Unknown file format");
5105 ret = -1;
5106 goto out;
5107 }
5108 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5109
5110 if (!proto_drv) {
5111 error_report_err(local_err);
5112 ret = -1;
5113 goto out;
5114 }
5115 if (!drv->create_opts) {
5116 error_report("Format driver '%s' does not support image creation",
5117 drv->format_name);
5118 ret = -1;
5119 goto out;
5120 }
5121 if (!proto_drv->create_opts) {
5122 error_report("Protocol driver '%s' does not support image creation",
5123 proto_drv->format_name);
5124 ret = -1;
5125 goto out;
5126 }
5127 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5128 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5129
5130 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5131
5132 size = blk_getlength(blk1);
5133 if (size < 0) {
5134 error_report("Failed to get size for '%s'", in.filename);
5135 ret = -1;
5136 goto out;
5137 }
5138
5139 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5140 dd.count * in.bsz < size) {
5141 size = dd.count * in.bsz;
5142 }
5143
Reda Sallahif7c15532016-08-10 16:16:09 +02005144 /* Overflow means the specified offset is beyond input image's size */
5145 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5146 size < in.bsz * in.offset)) {
5147 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5148 } else {
5149 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5150 size - in.bsz * in.offset, &error_abort);
5151 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005152
5153 ret = bdrv_create(drv, out.filename, opts, &local_err);
5154 if (ret < 0) {
5155 error_reportf_err(local_err,
5156 "%s: error while creating output image: ",
5157 out.filename);
5158 ret = -1;
5159 goto out;
5160 }
5161
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005162 /* TODO, we can't honour --image-opts for the target,
5163 * since it needs to be given in a format compatible
5164 * with the bdrv_create() call above which does not
5165 * support image-opts style.
5166 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005167 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005168 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005169
5170 if (!blk2) {
5171 ret = -1;
5172 goto out;
5173 }
5174
Reda Sallahif7c15532016-08-10 16:16:09 +02005175 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5176 size < in.offset * in.bsz)) {
5177 /* We give a warning if the skip option is bigger than the input
5178 * size and create an empty output disk image (i.e. like dd(1)).
5179 */
5180 error_report("%s: cannot skip to specified offset", in.filename);
5181 in_pos = size;
5182 } else {
5183 in_pos = in.offset * in.bsz;
5184 }
5185
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005186 in.buf = g_new(uint8_t, in.bsz);
5187
Reda Sallahif7c15532016-08-10 16:16:09 +02005188 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005189 int in_ret, out_ret;
5190
5191 if (in_pos + in.bsz > size) {
5192 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5193 } else {
5194 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5195 }
5196 if (in_ret < 0) {
5197 error_report("error while reading from input image file: %s",
5198 strerror(-in_ret));
5199 ret = -1;
5200 goto out;
5201 }
5202 in_pos += in_ret;
5203
5204 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5205
5206 if (out_ret < 0) {
5207 error_report("error while writing to output image file: %s",
5208 strerror(-out_ret));
5209 ret = -1;
5210 goto out;
5211 }
5212 out_pos += out_ret;
5213 }
5214
5215out:
5216 g_free(arg);
5217 qemu_opts_del(opts);
5218 qemu_opts_free(create_opts);
5219 blk_unref(blk1);
5220 blk_unref(blk2);
5221 g_free(in.filename);
5222 g_free(out.filename);
5223 g_free(in.buf);
5224 g_free(out.buf);
5225
5226 if (ret) {
5227 return 1;
5228 }
5229 return 0;
5230}
5231
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005232static void dump_json_block_measure_info(BlockMeasureInfo *info)
5233{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005234 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005235 QObject *obj;
5236 Visitor *v = qobject_output_visitor_new(&obj);
5237
5238 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5239 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005240 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005241 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005242 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005243 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005244 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005245 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005246}
5247
5248static int img_measure(int argc, char **argv)
5249{
5250 static const struct option long_options[] = {
5251 {"help", no_argument, 0, 'h'},
5252 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5253 {"object", required_argument, 0, OPTION_OBJECT},
5254 {"output", required_argument, 0, OPTION_OUTPUT},
5255 {"size", required_argument, 0, OPTION_SIZE},
5256 {"force-share", no_argument, 0, 'U'},
5257 {0, 0, 0, 0}
5258 };
5259 OutputFormat output_format = OFORMAT_HUMAN;
5260 BlockBackend *in_blk = NULL;
5261 BlockDriver *drv;
5262 const char *filename = NULL;
5263 const char *fmt = NULL;
5264 const char *out_fmt = "raw";
5265 char *options = NULL;
5266 char *snapshot_name = NULL;
5267 bool force_share = false;
5268 QemuOpts *opts = NULL;
5269 QemuOpts *object_opts = NULL;
5270 QemuOpts *sn_opts = NULL;
5271 QemuOptsList *create_opts = NULL;
5272 bool image_opts = false;
5273 uint64_t img_size = UINT64_MAX;
5274 BlockMeasureInfo *info = NULL;
5275 Error *local_err = NULL;
5276 int ret = 1;
5277 int c;
5278
5279 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5280 long_options, NULL)) != -1) {
5281 switch (c) {
5282 case '?':
5283 case 'h':
5284 help();
5285 break;
5286 case 'f':
5287 fmt = optarg;
5288 break;
5289 case 'O':
5290 out_fmt = optarg;
5291 break;
5292 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005293 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005294 goto out;
5295 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005296 break;
5297 case 'l':
5298 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5299 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5300 optarg, false);
5301 if (!sn_opts) {
5302 error_report("Failed in parsing snapshot param '%s'",
5303 optarg);
5304 goto out;
5305 }
5306 } else {
5307 snapshot_name = optarg;
5308 }
5309 break;
5310 case 'U':
5311 force_share = true;
5312 break;
5313 case OPTION_OBJECT:
5314 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5315 optarg, true);
5316 if (!object_opts) {
5317 goto out;
5318 }
5319 break;
5320 case OPTION_IMAGE_OPTS:
5321 image_opts = true;
5322 break;
5323 case OPTION_OUTPUT:
5324 if (!strcmp(optarg, "json")) {
5325 output_format = OFORMAT_JSON;
5326 } else if (!strcmp(optarg, "human")) {
5327 output_format = OFORMAT_HUMAN;
5328 } else {
5329 error_report("--output must be used with human or json "
5330 "as argument.");
5331 goto out;
5332 }
5333 break;
5334 case OPTION_SIZE:
5335 {
5336 int64_t sval;
5337
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005338 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005339 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005340 goto out;
5341 }
5342 img_size = (uint64_t)sval;
5343 }
5344 break;
5345 }
5346 }
5347
5348 if (qemu_opts_foreach(&qemu_object_opts,
5349 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005350 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005351 goto out;
5352 }
5353
5354 if (argc - optind > 1) {
5355 error_report("At most one filename argument is allowed.");
5356 goto out;
5357 } else if (argc - optind == 1) {
5358 filename = argv[optind];
5359 }
5360
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005361 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5362 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005363 goto out;
5364 }
5365 if (filename && img_size != UINT64_MAX) {
5366 error_report("--size N cannot be used together with a filename.");
5367 goto out;
5368 }
5369 if (!filename && img_size == UINT64_MAX) {
5370 error_report("Either --size N or one filename must be specified.");
5371 goto out;
5372 }
5373
5374 if (filename) {
5375 in_blk = img_open(image_opts, filename, fmt, 0,
5376 false, false, force_share);
5377 if (!in_blk) {
5378 goto out;
5379 }
5380
5381 if (sn_opts) {
5382 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5383 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5384 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5385 &local_err);
5386 } else if (snapshot_name != NULL) {
5387 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5388 snapshot_name, &local_err);
5389 }
5390 if (local_err) {
5391 error_reportf_err(local_err, "Failed to load snapshot: ");
5392 goto out;
5393 }
5394 }
5395
5396 drv = bdrv_find_format(out_fmt);
5397 if (!drv) {
5398 error_report("Unknown file format '%s'", out_fmt);
5399 goto out;
5400 }
5401 if (!drv->create_opts) {
5402 error_report("Format driver '%s' does not support image creation",
5403 drv->format_name);
5404 goto out;
5405 }
5406
5407 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5408 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5409 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5410 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005411 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005412 error_report_err(local_err);
5413 error_report("Invalid options for file format '%s'", out_fmt);
5414 goto out;
5415 }
5416 }
5417 if (img_size != UINT64_MAX) {
5418 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5419 }
5420
5421 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5422 if (local_err) {
5423 error_report_err(local_err);
5424 goto out;
5425 }
5426
5427 if (output_format == OFORMAT_HUMAN) {
5428 printf("required size: %" PRIu64 "\n", info->required);
5429 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005430 if (info->has_bitmaps) {
5431 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5432 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005433 } else {
5434 dump_json_block_measure_info(info);
5435 }
5436
5437 ret = 0;
5438
5439out:
5440 qapi_free_BlockMeasureInfo(info);
5441 qemu_opts_del(object_opts);
5442 qemu_opts_del(opts);
5443 qemu_opts_del(sn_opts);
5444 qemu_opts_free(create_opts);
5445 g_free(options);
5446 blk_unref(in_blk);
5447 return ret;
5448}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005449
Anthony Liguoric227f092009-10-01 16:12:16 -05005450static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005451#define DEF(option, callback, arg_string) \
5452 { option, callback },
5453#include "qemu-img-cmds.h"
5454#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005455 { NULL, NULL, },
5456};
5457
bellardea2384d2004-08-01 21:59:26 +00005458int main(int argc, char **argv)
5459{
Anthony Liguoric227f092009-10-01 16:12:16 -05005460 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005461 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005462 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005463 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005464 static const struct option long_options[] = {
5465 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005466 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005467 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005468 {0, 0, 0, 0}
5469 };
bellardea2384d2004-08-01 21:59:26 +00005470
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005471#ifdef CONFIG_POSIX
5472 signal(SIGPIPE, SIG_IGN);
5473#endif
5474
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005475 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005476 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005477 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005478 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005479
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005480 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005481 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005482 exit(EXIT_FAILURE);
5483 }
5484
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005485 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005486
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005487 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005488 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005489 if (argc < 2) {
5490 error_exit("Not enough arguments");
5491 }
Stuart Brady153859b2009-06-07 00:42:17 +01005492
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005493 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005494 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005495 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005496
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005497 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005498 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005499 case ':':
5500 missing_argument(argv[optind - 1]);
5501 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005502 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005503 unrecognized_option(argv[optind - 1]);
5504 return 0;
5505 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005506 help();
5507 return 0;
5508 case 'V':
5509 printf(QEMU_IMG_VERSION);
5510 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005511 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005512 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005513 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005514 }
bellardea2384d2004-08-01 21:59:26 +00005515 }
Stuart Brady153859b2009-06-07 00:42:17 +01005516
Denis V. Lunev10985132016-06-17 17:44:13 +03005517 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005518
Denis V. Lunev10985132016-06-17 17:44:13 +03005519 /* reset getopt_long scanning */
5520 argc -= optind;
5521 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005522 return 0;
5523 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005524 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005525 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005526
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005527 if (!trace_init_backends()) {
5528 exit(1);
5529 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005530 trace_init_file();
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005531 qemu_set_log(LOG_TRACE);
5532
Denis V. Lunev10985132016-06-17 17:44:13 +03005533 /* find the command */
5534 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5535 if (!strcmp(cmdname, cmd->name)) {
5536 return cmd->handler(argc, argv);
5537 }
5538 }
Jeff Cody7db16892014-04-25 17:02:32 -04005539
Stuart Brady153859b2009-06-07 00:42:17 +01005540 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005541 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005542}