blob: d599659c7f2950028151e8d0d3491e9ddce9e0fa [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050031#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010032#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010033#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010035#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010036#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010044#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020045#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000046#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020047#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010048#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020049#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080050#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010051#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030052#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000053#include "qemu/throttle.h"
54#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000055
Thomas Huth7e563bf2018-02-15 12:06:47 +010056#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020057 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040058
Anthony Liguoric227f092009-10-01 16:12:16 -050059typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010060 const char *name;
61 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050062} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010063
Federico Simoncelli8599ea42013-01-28 06:59:47 -050064enum {
65 OPTION_OUTPUT = 256,
66 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000067 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000068 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020069 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020070 OPTION_FLUSH_INTERVAL = 261,
71 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010072 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010073 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020074 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030075 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020076 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000077 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050078 OPTION_ADD = 269,
79 OPTION_REMOVE = 270,
80 OPTION_CLEAR = 271,
81 OPTION_ENABLE = 272,
82 OPTION_DISABLE = 273,
83 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050084 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020085 OPTION_FORCE = 276,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050086};
87
88typedef enum OutputFormat {
89 OFORMAT_JSON,
90 OFORMAT_HUMAN,
91} OutputFormat;
92
Kevin Wolfe6996142016-03-15 13:03:11 +010093/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040094#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000095
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010096static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000097{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010098 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000099}
100
Fam Zhengac1307a2014-04-22 13:36:11 +0800101static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
102{
103 va_list ap;
104
Fam Zhengac1307a2014-04-22 13:36:11 +0800105 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200106 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800107 va_end(ap);
108
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200109 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800110 exit(EXIT_FAILURE);
111}
112
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800113static void QEMU_NORETURN missing_argument(const char *option)
114{
115 error_exit("missing argument for option '%s'", option);
116}
117
118static void QEMU_NORETURN unrecognized_option(const char *option)
119{
120 error_exit("unrecognized option '%s'", option);
121}
122
Eric Blake0562adf2020-05-12 20:16:41 -0500123/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800124static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000125{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100126 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400127 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300128 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300129 "QEMU disk image utility\n"
130 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300131 " '-h', '--help' display this help and exit\n"
132 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300133 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
134 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300135 "\n"
malc3f020d72010-02-08 12:04:56 +0300136 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100137#define DEF(option, callback, arg_string) \
138 " " arg_string "\n"
139#include "qemu-img-cmds.h"
140#undef DEF
malc3f020d72010-02-08 12:04:56 +0300141 "\n"
142 "Command parameters:\n"
143 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000144 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
145 " manual page for a description of the object properties. The most common\n"
146 " object type is a 'secret', which is used to supply passwords and/or\n"
147 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300148 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400149 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800150 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
151 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100152 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
153 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300154 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200155 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
156 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
157 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300158 " 'output_filename' is the destination disk image filename\n"
159 " 'output_fmt' is the destination format\n"
160 " 'options' is a comma separated list of format specific options in a\n"
161 " name=value format. Use -o ? for an overview of the options supported by the\n"
162 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800163 " 'snapshot_param' is param used for internal snapshot, format\n"
164 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
165 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300166 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400167 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
168 " new backing file match exactly. The image doesn't need a working\n"
169 " backing file before rebasing in this case (useful for renaming the\n"
170 " backing file). For image creation, allow creating without attempting\n"
171 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300172 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200173 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100174 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200175 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
176 " contain only zeros for qemu-img to create a sparse image during\n"
177 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
178 " unallocated or zero sectors, and the destination image will always be\n"
179 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200180 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100181 " '-n' skips the target volume creation (useful if the volume is created\n"
182 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300183 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500184 "Parameters to bitmap subcommand:\n"
185 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
186 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
187 " or '--merge source'\n"
188 " '-g granularity' sets the granularity for '--add' actions\n"
189 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
190 " bitmaps from an alternative file\n"
191 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200192 "Parameters to check subcommand:\n"
193 " '-r' tries to repair any inconsistencies that are found during the check.\n"
194 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
195 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200196 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200197 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100198 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500199 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100200 " '-m' specifies how many coroutines work in parallel during the convert\n"
201 " process (defaults to 8)\n"
202 " '-W' allow to write to the target out of order rather than sequential\n"
203 "\n"
malc3f020d72010-02-08 12:04:56 +0300204 "Parameters to snapshot subcommand:\n"
205 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
206 " '-a' applies a snapshot (revert disk to saved state)\n"
207 " '-c' creates a snapshot\n"
208 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100209 " '-l' lists all snapshots in the given image\n"
210 "\n"
211 "Parameters to compare subcommand:\n"
212 " '-f' first image format\n"
213 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200214 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
215 "\n"
216 "Parameters to dd subcommand:\n"
217 " 'bs=BYTES' read and write up to BYTES bytes at a time "
218 "(default: 512)\n"
219 " 'count=N' copy only N input blocks\n"
220 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200221 " 'of=FILE' write to FILE\n"
222 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100223
224 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300225 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500226 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800227 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000228}
229
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000230static QemuOptsList qemu_object_opts = {
231 .name = "object",
232 .implied_opt_name = "qom-type",
233 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
234 .desc = {
235 { }
236 },
237};
238
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200239static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
240{
241 if (user_creatable_print_help(type, opts)) {
242 exit(0);
243 }
244 return true;
245}
246
Markus Armbruster80c710c2020-04-15 09:49:26 +0200247/*
248 * Is @optarg safe for accumulate_options()?
249 * It is when multiple of them can be joined together separated by ','.
250 * To make that work, @optarg must not start with ',' (or else a
251 * separating ',' preceding it gets escaped), and it must not end with
252 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200253 * escaped), or be empty (or else a separating ',' preceding it can
254 * escape a separating ',' following it).
255 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200256 */
257static bool is_valid_option_list(const char *optarg)
258{
259 size_t len = strlen(optarg);
260 size_t i;
261
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200262 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200263 return false;
264 }
265
266 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
267 }
268 if ((len - i) % 2) {
269 return false;
270 }
271
272 return true;
273}
274
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200275static int accumulate_options(char **options, char *optarg)
276{
277 char *new_options;
278
279 if (!is_valid_option_list(optarg)) {
280 error_report("Invalid option list: %s", optarg);
281 return -1;
282 }
283
284 if (!*options) {
285 *options = g_strdup(optarg);
286 } else {
287 new_options = g_strdup_printf("%s,%s", *options, optarg);
288 g_free(*options);
289 *options = new_options;
290 }
291 return 0;
292}
293
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000294static QemuOptsList qemu_source_opts = {
295 .name = "source",
296 .implied_opt_name = "file",
297 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
298 .desc = {
299 { }
300 },
301};
302
Stefan Weil7c30f652013-06-16 17:01:05 +0200303static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100304{
305 int ret = 0;
306 if (!quiet) {
307 va_list args;
308 va_start(args, fmt);
309 ret = vprintf(fmt, args);
310 va_end(args);
311 }
312 return ret;
313}
314
bellardea2384d2004-08-01 21:59:26 +0000315
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100316static int print_block_option_help(const char *filename, const char *fmt)
317{
318 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800319 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500320 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100321
322 /* Find driver and parse its options */
323 drv = bdrv_find_format(fmt);
324 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100325 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100326 return 1;
327 }
328
Max Reitzd402b6a2018-05-09 23:00:21 +0200329 if (!drv->create_opts) {
330 error_report("Format driver '%s' does not support image creation", fmt);
331 return 1;
332 }
333
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800334 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100335 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500336 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100337 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100338 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800339 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100340 return 1;
341 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200342 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100343 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200344 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100345 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200346 return 1;
347 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800348 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100349 }
350
Max Reitzf4619af2019-04-13 17:20:37 +0200351 if (filename) {
352 printf("Supported options:\n");
353 } else {
354 printf("Supported %s options:\n", fmt);
355 }
Max Reitz63898712018-10-19 18:49:25 +0200356 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800357 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200358
359 if (!filename) {
360 printf("\n"
361 "The protocol level may support further options.\n"
362 "Specify the target filename to include those options.\n");
363 }
364
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100365 return 0;
366}
367
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000368
Max Reitzefaa7c42016-03-16 19:54:38 +0100369static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100370 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800371 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000372{
373 QDict *options;
374 Error *local_err = NULL;
375 BlockBackend *blk;
376 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800377 if (force_share) {
378 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200379 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800380 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200381 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800382 return NULL;
383 }
Max Reitz4615f872018-05-02 22:20:50 +0200384 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800385 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100386 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000387 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100388 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000389 return NULL;
390 }
Kevin Wolfce099542016-03-15 13:01:04 +0100391 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000392
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000393 return blk;
394}
395
Max Reitzefaa7c42016-03-16 19:54:38 +0100396static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100397 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000398 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800399 bool writethrough, bool quiet,
400 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000401{
402 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200403 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100404
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100405 if (!options) {
406 options = qdict_new();
407 }
bellard75c23802004-08-27 21:28:58 +0000408 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500409 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000410 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100411
Fam Zheng335e9932017-05-03 00:35:39 +0800412 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500413 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800414 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100415 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500416 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100417 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000418 return NULL;
bellard75c23802004-08-27 21:28:58 +0000419 }
Kevin Wolfce099542016-03-15 13:01:04 +0100420 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100421
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200422 return blk;
bellard75c23802004-08-27 21:28:58 +0000423}
424
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000425
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100426static int img_add_key_secrets(void *opaque,
427 const char *name, const char *value,
428 Error **errp)
429{
430 QDict *options = opaque;
431
432 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600433 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100434 }
435
436 return 0;
437}
438
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100439
Max Reitzefaa7c42016-03-16 19:54:38 +0100440static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000441 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100442 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800443 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000444{
445 BlockBackend *blk;
446 if (image_opts) {
447 QemuOpts *opts;
448 if (fmt) {
449 error_report("--image-opts and --format are mutually exclusive");
450 return NULL;
451 }
452 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
453 filename, true);
454 if (!opts) {
455 return NULL;
456 }
Fam Zheng335e9932017-05-03 00:35:39 +0800457 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
458 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000459 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100460 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800461 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000462 }
463 return blk;
464}
465
466
Chunyan Liu83d05212014-06-05 17:20:51 +0800467static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100468 const char *base_filename,
469 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200470{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200471 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200472 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200473 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100474 error_report("Backing file not supported for file format '%s'",
475 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900476 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200477 }
478 }
479 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200480 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100481 error_report("Backing file format not supported for file "
482 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900483 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200484 }
485 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900486 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200487}
488
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300489static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
490 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100491{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100492 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300493 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100494
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300495 err = qemu_strtosz(value, NULL, &res);
496 if (err < 0 && err != -ERANGE) {
497 error_report("Invalid %s specified. You may use "
498 "k, M, G, T, P or E suffixes for", name);
499 error_report("kilobytes, megabytes, gigabytes, terabytes, "
500 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100501 return err;
502 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300503 if (err == -ERANGE || res > max || res < min) {
504 error_report("Invalid %s specified. Must be between %" PRId64
505 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100506 return -ERANGE;
507 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300508 return res;
509}
510
511static int64_t cvtnum(const char *name, const char *value)
512{
513 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100514}
515
bellardea2384d2004-08-01 21:59:26 +0000516static int img_create(int argc, char **argv)
517{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200518 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100519 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000520 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000521 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000522 const char *filename;
523 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200524 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200525 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100526 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400527 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000528
bellardea2384d2004-08-01 21:59:26 +0000529 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000530 static const struct option long_options[] = {
531 {"help", no_argument, 0, 'h'},
532 {"object", required_argument, 0, OPTION_OBJECT},
533 {0, 0, 0, 0}
534 };
John Snow6e6e55f2017-07-17 20:34:22 -0400535 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000536 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100537 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000538 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100539 }
bellardea2384d2004-08-01 21:59:26 +0000540 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800541 case ':':
542 missing_argument(argv[optind - 1]);
543 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100544 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800545 unrecognized_option(argv[optind - 1]);
546 break;
bellardea2384d2004-08-01 21:59:26 +0000547 case 'h':
548 help();
549 break;
aliguori9230eaf2009-03-28 17:55:19 +0000550 case 'F':
551 base_fmt = optarg;
552 break;
bellardea2384d2004-08-01 21:59:26 +0000553 case 'b':
554 base_filename = optarg;
555 break;
556 case 'f':
557 fmt = optarg;
558 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200559 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200560 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100561 goto fail;
562 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200563 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100564 case 'q':
565 quiet = true;
566 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400567 case 'u':
568 flags |= BDRV_O_NO_BACKING;
569 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000570 case OPTION_OBJECT: {
571 QemuOpts *opts;
572 opts = qemu_opts_parse_noisily(&qemu_object_opts,
573 optarg, true);
574 if (!opts) {
575 goto fail;
576 }
577 } break;
bellardea2384d2004-08-01 21:59:26 +0000578 }
579 }
aliguori9230eaf2009-03-28 17:55:19 +0000580
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900581 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100582 filename = (optind < argc) ? argv[optind] : NULL;
583 if (options && has_help_option(options)) {
584 g_free(options);
585 return print_block_option_help(filename, fmt);
586 }
587
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100588 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800589 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100590 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100591 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900592
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000593 if (qemu_opts_foreach(&qemu_object_opts,
594 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200595 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000596 goto fail;
597 }
598
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100599 /* Get image size, if specified */
600 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100601 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100602
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300603 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100604 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100605 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100606 }
607 img_size = (uint64_t)sval;
608 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200609 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800610 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200611 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100612
Luiz Capitulino9b375252012-11-30 10:52:05 -0200613 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400614 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100615 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100616 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100617 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900618 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200619
Kevin Wolf77386bf2014-02-21 16:24:04 +0100620 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000621 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100622
623fail:
624 g_free(options);
625 return 1;
bellardea2384d2004-08-01 21:59:26 +0000626}
627
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100628static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500629{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500630 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500631 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100632 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600633
634 visit_type_ImageCheck(v, NULL, &check, &error_abort);
635 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500636 str = qobject_to_json_pretty(obj);
637 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100638 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200639 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600640 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200641 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500642}
643
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100644static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645{
646 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100647 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500648 } else {
649 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100650 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
651 "Data may be corrupted, or further writes to the image "
652 "may corrupt it.\n",
653 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500654 }
655
656 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100657 qprintf(quiet,
658 "\n%" PRId64 " leaked clusters were found on the image.\n"
659 "This means waste of disk space, but no harm to data.\n",
660 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500661 }
662
663 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100664 qprintf(quiet,
665 "\n%" PRId64
666 " internal errors have occurred during the check.\n",
667 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 }
669 }
670
671 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100672 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
673 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
674 check->allocated_clusters, check->total_clusters,
675 check->allocated_clusters * 100.0 / check->total_clusters,
676 check->fragmented_clusters * 100.0 / check->allocated_clusters,
677 check->compressed_clusters * 100.0 /
678 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500679 }
680
681 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100682 qprintf(quiet,
683 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500684 }
685}
686
687static int collect_image_check(BlockDriverState *bs,
688 ImageCheck *check,
689 const char *filename,
690 const char *fmt,
691 int fix)
692{
693 int ret;
694 BdrvCheckResult result;
695
696 ret = bdrv_check(bs, &result, fix);
697 if (ret < 0) {
698 return ret;
699 }
700
701 check->filename = g_strdup(filename);
702 check->format = g_strdup(bdrv_get_format_name(bs));
703 check->check_errors = result.check_errors;
704 check->corruptions = result.corruptions;
705 check->has_corruptions = result.corruptions != 0;
706 check->leaks = result.leaks;
707 check->has_leaks = result.leaks != 0;
708 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100709 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500710 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100711 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500712 check->image_end_offset = result.image_end_offset;
713 check->has_image_end_offset = result.image_end_offset != 0;
714 check->total_clusters = result.bfi.total_clusters;
715 check->has_total_clusters = result.bfi.total_clusters != 0;
716 check->allocated_clusters = result.bfi.allocated_clusters;
717 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
718 check->fragmented_clusters = result.bfi.fragmented_clusters;
719 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100720 check->compressed_clusters = result.bfi.compressed_clusters;
721 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500722
723 return 0;
724}
725
Kevin Wolfe076f332010-06-29 11:43:13 +0200726/*
727 * Checks an image for consistency. Exit codes:
728 *
Max Reitzd6635c42014-06-02 22:15:21 +0200729 * 0 - Check completed, image is good
730 * 1 - Check not completed because of internal errors
731 * 2 - Check completed, image is corrupted
732 * 3 - Check completed, image has leaked clusters, but is good otherwise
733 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200734 */
aliguori15859692009-04-21 23:11:53 +0000735static int img_check(int argc, char **argv)
736{
737 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500738 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200739 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200740 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000741 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200742 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100743 int flags = BDRV_O_CHECK;
744 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200745 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100746 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000747 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800748 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000749
750 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500751 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200752 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100753
aliguori15859692009-04-21 23:11:53 +0000754 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500755 int option_index = 0;
756 static const struct option long_options[] = {
757 {"help", no_argument, 0, 'h'},
758 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530759 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500760 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000761 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000762 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800763 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500764 {0, 0, 0, 0}
765 };
Fam Zheng335e9932017-05-03 00:35:39 +0800766 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500767 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100768 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000769 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100770 }
aliguori15859692009-04-21 23:11:53 +0000771 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800772 case ':':
773 missing_argument(argv[optind - 1]);
774 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100775 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800776 unrecognized_option(argv[optind - 1]);
777 break;
aliguori15859692009-04-21 23:11:53 +0000778 case 'h':
779 help();
780 break;
781 case 'f':
782 fmt = optarg;
783 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200784 case 'r':
785 flags |= BDRV_O_RDWR;
786
787 if (!strcmp(optarg, "leaks")) {
788 fix = BDRV_FIX_LEAKS;
789 } else if (!strcmp(optarg, "all")) {
790 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
791 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800792 error_exit("Unknown option value for -r "
793 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200794 }
795 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500796 case OPTION_OUTPUT:
797 output = optarg;
798 break;
Max Reitz40055952014-07-22 22:58:42 +0200799 case 'T':
800 cache = optarg;
801 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100802 case 'q':
803 quiet = true;
804 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800805 case 'U':
806 force_share = true;
807 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000808 case OPTION_OBJECT: {
809 QemuOpts *opts;
810 opts = qemu_opts_parse_noisily(&qemu_object_opts,
811 optarg, true);
812 if (!opts) {
813 return 1;
814 }
815 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000816 case OPTION_IMAGE_OPTS:
817 image_opts = true;
818 break;
aliguori15859692009-04-21 23:11:53 +0000819 }
820 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200821 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800822 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100823 }
aliguori15859692009-04-21 23:11:53 +0000824 filename = argv[optind++];
825
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826 if (output && !strcmp(output, "json")) {
827 output_format = OFORMAT_JSON;
828 } else if (output && !strcmp(output, "human")) {
829 output_format = OFORMAT_HUMAN;
830 } else if (output) {
831 error_report("--output must be used with human or json as argument.");
832 return 1;
833 }
834
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000835 if (qemu_opts_foreach(&qemu_object_opts,
836 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200837 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000838 return 1;
839 }
840
Kevin Wolfce099542016-03-15 13:01:04 +0100841 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200842 if (ret < 0) {
843 error_report("Invalid source cache option: %s", cache);
844 return 1;
845 }
846
Fam Zheng335e9932017-05-03 00:35:39 +0800847 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
848 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200849 if (!blk) {
850 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900851 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200852 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500853
854 check = g_new0(ImageCheck, 1);
855 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200856
857 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200858 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200859 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500860 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200861 }
862
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500863 if (check->corruptions_fixed || check->leaks_fixed) {
864 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100865 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500866
867 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100868 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500869 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100870 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500871
872 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100873 qprintf(quiet,
874 "The following inconsistencies were found and repaired:\n\n"
875 " %" PRId64 " leaked clusters\n"
876 " %" PRId64 " corruptions\n\n"
877 "Double checking the fixed image now...\n",
878 check->leaks_fixed,
879 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500880 }
881
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800882 qapi_free_ImageCheck(check);
883 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500884 ret = collect_image_check(bs, check, filename, fmt, 0);
885
886 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100887 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500888 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100889 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200890 }
891
Max Reitz832390a2014-10-23 15:29:12 +0200892 if (!ret) {
893 switch (output_format) {
894 case OFORMAT_HUMAN:
895 dump_human_image_check(check, quiet);
896 break;
897 case OFORMAT_JSON:
898 dump_json_image_check(check, quiet);
899 break;
900 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500901 }
902
903 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200904 if (ret) {
905 error_report("Check failed: %s", strerror(-ret));
906 } else {
907 error_report("Check failed");
908 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500909 ret = 1;
910 goto fail;
911 }
912
913 if (check->corruptions) {
914 ret = 2;
915 } else if (check->leaks) {
916 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200917 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500918 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000919 }
920
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500921fail:
922 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200923 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500924 return ret;
aliguori15859692009-04-21 23:11:53 +0000925}
926
Max Reitzd4a32382014-10-24 15:57:37 +0200927typedef struct CommonBlockJobCBInfo {
928 BlockDriverState *bs;
929 Error **errp;
930} CommonBlockJobCBInfo;
931
932static void common_block_job_cb(void *opaque, int ret)
933{
934 CommonBlockJobCBInfo *cbi = opaque;
935
936 if (ret < 0) {
937 error_setg_errno(cbi->errp, -ret, "Block job failed");
938 }
Max Reitzd4a32382014-10-24 15:57:37 +0200939}
940
941static void run_block_job(BlockJob *job, Error **errp)
942{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200943 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800944 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200945
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200946 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200947 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200948 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200949 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200950 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300951 if (job->job.progress.total) {
952 progress = (float)job->job.progress.current /
953 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200954 }
955 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200956 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200957
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200958 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200959 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800960 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200961 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800962 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200963 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200964 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200965
sochin.jiang4172a002017-06-15 14:47:33 +0800966 /* publish completion progress only when success */
967 if (!ret) {
968 qemu_progress_print(100.f, 0);
969 }
Max Reitzd4a32382014-10-24 15:57:37 +0200970}
971
bellardea2384d2004-08-01 21:59:26 +0000972static int img_commit(int argc, char **argv)
973{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400974 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200975 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200976 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200977 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100978 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200979 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100980 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200981 Error *local_err = NULL;
982 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000983 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200984 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000985 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000986
987 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400988 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200989 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000990 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000991 static const struct option long_options[] = {
992 {"help", no_argument, 0, 'h'},
993 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000994 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000995 {0, 0, 0, 0}
996 };
Zhenguia0441b62020-10-20 14:47:43 +0000997 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000998 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100999 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00001000 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001001 }
bellardea2384d2004-08-01 21:59:26 +00001002 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001003 case ':':
1004 missing_argument(argv[optind - 1]);
1005 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001006 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001007 unrecognized_option(argv[optind - 1]);
1008 break;
bellardea2384d2004-08-01 21:59:26 +00001009 case 'h':
1010 help();
1011 break;
1012 case 'f':
1013 fmt = optarg;
1014 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001015 case 't':
1016 cache = optarg;
1017 break;
Max Reitz1b22bff2014-10-24 15:57:40 +02001018 case 'b':
1019 base = optarg;
1020 /* -b implies -d */
1021 drop = true;
1022 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001023 case 'd':
1024 drop = true;
1025 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001026 case 'p':
1027 progress = true;
1028 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001029 case 'q':
1030 quiet = true;
1031 break;
Zhenguia0441b62020-10-20 14:47:43 +00001032 case 'r':
1033 rate_limit = cvtnum("rate limit", optarg);
1034 if (rate_limit < 0) {
1035 return 1;
1036 }
1037 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001038 case OPTION_OBJECT: {
1039 QemuOpts *opts;
1040 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1041 optarg, true);
1042 if (!opts) {
1043 return 1;
1044 }
1045 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001046 case OPTION_IMAGE_OPTS:
1047 image_opts = true;
1048 break;
bellardea2384d2004-08-01 21:59:26 +00001049 }
1050 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001051
1052 /* Progress is not shown in Quiet mode */
1053 if (quiet) {
1054 progress = false;
1055 }
1056
Kevin Wolffc11eb22013-08-05 10:53:04 +02001057 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001058 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001059 }
bellardea2384d2004-08-01 21:59:26 +00001060 filename = argv[optind++];
1061
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001062 if (qemu_opts_foreach(&qemu_object_opts,
1063 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001064 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001065 return 1;
1066 }
1067
Max Reitz9a86fe42014-10-24 15:57:38 +02001068 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001069 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001070 if (ret < 0) {
1071 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001072 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001073 }
1074
Fam Zheng335e9932017-05-03 00:35:39 +08001075 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1076 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001077 if (!blk) {
1078 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001079 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001080 bs = blk_bs(blk);
1081
Max Reitz687fa1d2014-10-24 15:57:39 +02001082 qemu_progress_init(progress, 1.f);
1083 qemu_progress_print(0.f, 100);
1084
Max Reitz1b22bff2014-10-24 15:57:40 +02001085 if (base) {
1086 base_bs = bdrv_find_backing_image(bs, base);
1087 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001088 error_setg(&local_err,
1089 "Did not find '%s' in the backing chain of '%s'",
1090 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001091 goto done;
1092 }
1093 } else {
1094 /* This is different from QMP, which by default uses the deepest file in
1095 * the backing chain (i.e., the very base); however, the traditional
1096 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001097 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001098 if (!base_bs) {
1099 error_setg(&local_err, "Image does not have a backing file");
1100 goto done;
1101 }
bellardea2384d2004-08-01 21:59:26 +00001102 }
1103
Max Reitzd4a32382014-10-24 15:57:37 +02001104 cbi = (CommonBlockJobCBInfo){
1105 .errp = &local_err,
1106 .bs = bs,
1107 };
1108
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001109 aio_context = bdrv_get_aio_context(bs);
1110 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001111 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001112 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001113 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001114 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001115 if (local_err) {
1116 goto done;
1117 }
1118
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001119 /* When the block job completes, the BlockBackend reference will point to
1120 * the old backing file. In order to avoid that the top image is already
1121 * deleted, so we can still empty it afterwards, increment the reference
1122 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001123 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001124 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001125 }
1126
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001127 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001128 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001129 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001130 if (local_err) {
1131 goto unref_backing;
1132 }
1133
Max Reitz2d97fde2020-04-29 16:11:26 +02001134 if (!drop) {
1135 BlockBackend *old_backing_blk;
1136
1137 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1138 &local_err);
1139 if (!old_backing_blk) {
1140 goto unref_backing;
1141 }
1142 ret = blk_make_empty(old_backing_blk, &local_err);
1143 blk_unref(old_backing_blk);
1144 if (ret == -ENOTSUP) {
1145 error_free(local_err);
1146 local_err = NULL;
1147 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001148 goto unref_backing;
1149 }
1150 }
1151
1152unref_backing:
1153 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001154 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001155 }
Max Reitzd4a32382014-10-24 15:57:37 +02001156
1157done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001158 qemu_progress_end();
1159
Markus Armbruster26f54e92014-10-07 13:59:04 +02001160 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001161
1162 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001163 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001164 return 1;
1165 }
Max Reitzd4a32382014-10-24 15:57:37 +02001166
1167 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001168 return 0;
1169}
1170
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001171/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001172 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1173 * of the first sector boundary within buf where the sector contains a
1174 * non-zero byte. This function is robust to a buffer that is not
1175 * sector-aligned.
1176 */
1177static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1178{
1179 int64_t i;
1180 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1181
1182 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1183 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1184 return i;
1185 }
1186 }
1187 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1188 return i;
1189 }
1190 return -1;
1191}
1192
1193/*
thsf58c7b32008-06-05 21:53:49 +00001194 * Returns true iff the first sector pointed to by 'buf' contains at least
1195 * a non-NUL byte.
1196 *
1197 * 'pnum' is set to the number of sectors (including and immediately following
1198 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001199 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001200 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001201 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001202 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001203static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1204 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001205{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001206 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001207 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001208
1209 if (n <= 0) {
1210 *pnum = 0;
1211 return 0;
1212 }
Yi Lic075c422020-08-19 09:36:07 +08001213 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001214 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001215 buf += BDRV_SECTOR_SIZE;
1216 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001217 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001218 }
bellardea2384d2004-08-01 21:59:26 +00001219 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001220
1221 tail = (sector_num + i) & (alignment - 1);
1222 if (tail) {
1223 if (is_zero && i <= tail) {
1224 /* treat unallocated areas which only consist
1225 * of a small tail as allocated. */
1226 is_zero = false;
1227 }
1228 if (!is_zero) {
1229 /* align up end offset of allocated areas. */
1230 i += alignment - tail;
1231 i = MIN(i, n);
1232 } else {
1233 /* align down end offset of zero areas. */
1234 i -= tail;
1235 }
1236 }
bellardea2384d2004-08-01 21:59:26 +00001237 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001238 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001239}
1240
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001241/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001242 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1243 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1244 * breaking up write requests for only small sparse areas.
1245 */
1246static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001247 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001248{
1249 int ret;
1250 int num_checked, num_used;
1251
1252 if (n < min) {
1253 min = n;
1254 }
1255
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001256 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001257 if (!ret) {
1258 return ret;
1259 }
1260
1261 num_used = *pnum;
1262 buf += BDRV_SECTOR_SIZE * *pnum;
1263 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001264 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001265 num_checked = num_used;
1266
1267 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001268 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001269
1270 buf += BDRV_SECTOR_SIZE * *pnum;
1271 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001272 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001273 num_checked += *pnum;
1274 if (ret) {
1275 num_used = num_checked;
1276 } else if (*pnum >= min) {
1277 break;
1278 }
1279 }
1280
1281 *pnum = num_used;
1282 return 1;
1283}
1284
1285/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001286 * Compares two buffers sector by sector. Returns 0 if the first
1287 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001288 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001289 * pnum is set to the sector-aligned size of the buffer prefix that
1290 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001291 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001292static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1293 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001294{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001295 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001296 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001297
Eric Blakedc61cd32017-10-11 22:47:14 -05001298 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001299
Eric Blakedc61cd32017-10-11 22:47:14 -05001300 res = !!memcmp(buf1, buf2, i);
1301 while (i < bytes) {
1302 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001303
Eric Blakedc61cd32017-10-11 22:47:14 -05001304 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001305 break;
1306 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001307 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001308 }
1309
1310 *pnum = i;
1311 return res;
1312}
1313
Stefano Garzarella97ede572019-05-08 12:43:24 +02001314#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001315
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001316/*
1317 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1318 *
Eric Blake0608e402017-10-11 22:47:12 -05001319 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1320 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1321 * failure), and 4 on error (the exit status for read errors), after emitting
1322 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001323 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001324 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001325 * @param offset: Starting offset to check
1326 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001327 * @param filename: Name of disk file we are checking (logging purpose)
1328 * @param buffer: Allocated buffer for storing read data
1329 * @param quiet: Flag for quiet mode
1330 */
Eric Blakec41508e2017-10-11 22:47:13 -05001331static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1332 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001333 uint8_t *buffer, bool quiet)
1334{
Eric Blakedebb38a2017-10-11 22:47:11 -05001335 int ret = 0;
1336 int64_t idx;
1337
Eric Blakec41508e2017-10-11 22:47:13 -05001338 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001339 if (ret < 0) {
1340 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001341 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001342 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001343 }
Eric Blakec41508e2017-10-11 22:47:13 -05001344 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001345 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001346 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001347 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001348 return 1;
1349 }
1350
1351 return 0;
1352}
1353
1354/*
1355 * Compares two images. Exit codes:
1356 *
1357 * 0 - Images are identical
1358 * 1 - Images differ
1359 * >1 - Error occurred
1360 */
1361static int img_compare(int argc, char **argv)
1362{
Max Reitz40055952014-07-22 22:58:42 +02001363 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001364 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001365 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001366 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001367 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001368 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001369 int allocated1, allocated2;
1370 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1371 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001372 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001373 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001374 int64_t total_size;
1375 int64_t offset = 0;
1376 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001377 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001378 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001379 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001380 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001381
Max Reitz40055952014-07-22 22:58:42 +02001382 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001383 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001384 static const struct option long_options[] = {
1385 {"help", no_argument, 0, 'h'},
1386 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001387 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001388 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001389 {0, 0, 0, 0}
1390 };
Fam Zheng335e9932017-05-03 00:35:39 +08001391 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001392 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001393 if (c == -1) {
1394 break;
1395 }
1396 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001397 case ':':
1398 missing_argument(argv[optind - 1]);
1399 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001400 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001401 unrecognized_option(argv[optind - 1]);
1402 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001403 case 'h':
1404 help();
1405 break;
1406 case 'f':
1407 fmt1 = optarg;
1408 break;
1409 case 'F':
1410 fmt2 = optarg;
1411 break;
Max Reitz40055952014-07-22 22:58:42 +02001412 case 'T':
1413 cache = optarg;
1414 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001415 case 'p':
1416 progress = true;
1417 break;
1418 case 'q':
1419 quiet = true;
1420 break;
1421 case 's':
1422 strict = true;
1423 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001424 case 'U':
1425 force_share = true;
1426 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001427 case OPTION_OBJECT: {
1428 QemuOpts *opts;
1429 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1430 optarg, true);
1431 if (!opts) {
1432 ret = 2;
1433 goto out4;
1434 }
1435 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001436 case OPTION_IMAGE_OPTS:
1437 image_opts = true;
1438 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001439 }
1440 }
1441
1442 /* Progress is not shown in Quiet mode */
1443 if (quiet) {
1444 progress = false;
1445 }
1446
1447
Kevin Wolffc11eb22013-08-05 10:53:04 +02001448 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001449 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001450 }
1451 filename1 = argv[optind++];
1452 filename2 = argv[optind++];
1453
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001454 if (qemu_opts_foreach(&qemu_object_opts,
1455 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001456 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001457 ret = 2;
1458 goto out4;
1459 }
1460
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001461 /* Initialize before goto out */
1462 qemu_progress_init(progress, 2.0);
1463
Kevin Wolfce099542016-03-15 13:01:04 +01001464 flags = 0;
1465 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001466 if (ret < 0) {
1467 error_report("Invalid source cache option: %s", cache);
1468 ret = 2;
1469 goto out3;
1470 }
1471
Fam Zheng335e9932017-05-03 00:35:39 +08001472 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1473 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001474 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001475 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001476 goto out3;
1477 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001478
Fam Zheng335e9932017-05-03 00:35:39 +08001479 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1480 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001481 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001482 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001483 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001484 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001485 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001486 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001487
Max Reitzf1d3cd72015-02-05 13:58:18 -05001488 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1489 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 total_size1 = blk_getlength(blk1);
1491 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001492 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001493 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001494 ret = 4;
1495 goto out;
1496 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001497 total_size2 = blk_getlength(blk2);
1498 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001499 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001500 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001501 ret = 4;
1502 goto out;
1503 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001504 total_size = MIN(total_size1, total_size2);
1505 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001506
1507 qemu_progress_print(0, 100);
1508
Eric Blake033d9fc2017-10-11 22:47:16 -05001509 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001510 ret = 1;
1511 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1512 goto out;
1513 }
1514
Eric Blake033d9fc2017-10-11 22:47:16 -05001515 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001516 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001517
Eric Blake033d9fc2017-10-11 22:47:16 -05001518 status1 = bdrv_block_status_above(bs1, NULL, offset,
1519 total_size1 - offset, &pnum1, NULL,
1520 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001521 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 ret = 3;
1523 error_report("Sector allocation test failed for %s", filename1);
1524 goto out;
1525 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001526 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001527
Eric Blake033d9fc2017-10-11 22:47:16 -05001528 status2 = bdrv_block_status_above(bs2, NULL, offset,
1529 total_size2 - offset, &pnum2, NULL,
1530 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001531 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532 ret = 3;
1533 error_report("Sector allocation test failed for %s", filename2);
1534 goto out;
1535 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001536 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001537
1538 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001539 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001540
Fam Zheng25ad8e62016-01-13 16:37:41 +08001541 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001542 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001543 ret = 1;
1544 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001545 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001546 goto out;
1547 }
1548 }
1549 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001550 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001551 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001552 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001553 int64_t pnum;
1554
Eric Blake033d9fc2017-10-11 22:47:16 -05001555 chunk = MIN(chunk, IO_BUF_SIZE);
1556 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001557 if (ret < 0) {
1558 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001559 " of %s: %s",
1560 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001561 ret = 4;
1562 goto out;
1563 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001564 ret = blk_pread(blk2, offset, buf2, chunk);
1565 if (ret < 0) {
1566 error_report("Error while reading offset %" PRId64
1567 " of %s: %s",
1568 offset, filename2, strerror(-ret));
1569 ret = 4;
1570 goto out;
1571 }
1572 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1573 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001574 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001575 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001576 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001577 goto out;
1578 }
1579 }
1580 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001581 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001582 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001583 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001584 filename1, buf1, quiet);
1585 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001586 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001587 filename2, buf1, quiet);
1588 }
1589 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001590 goto out;
1591 }
1592 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001593 offset += chunk;
1594 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001595 }
1596
Eric Blake033d9fc2017-10-11 22:47:16 -05001597 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001598 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001599 const char *filename_over;
1600
1601 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001602 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001603 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001604 filename_over = filename1;
1605 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001606 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001607 filename_over = filename2;
1608 }
1609
Eric Blake033d9fc2017-10-11 22:47:16 -05001610 while (offset < progress_base) {
1611 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1612 progress_base - offset, &chunk,
1613 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001614 if (ret < 0) {
1615 ret = 3;
1616 error_report("Sector allocation test failed for %s",
1617 filename_over);
1618 goto out;
1619
1620 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001621 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001622 chunk = MIN(chunk, IO_BUF_SIZE);
1623 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001624 filename_over, buf1, quiet);
1625 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001626 goto out;
1627 }
1628 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001629 offset += chunk;
1630 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001631 }
1632 }
1633
1634 qprintf(quiet, "Images are identical.\n");
1635 ret = 0;
1636
1637out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001638 qemu_vfree(buf1);
1639 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001640 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001641out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001642 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001643out3:
1644 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001645out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001646 return ret;
1647}
1648
Eric Blake6c729dd2020-05-21 14:21:35 -05001649/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1650static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1651 const char *src_node, const char *src_name,
1652 Error **errp)
1653{
1654 BlockDirtyBitmapMergeSource *merge_src;
Eric Blake54aa3de2020-11-12 19:13:37 -06001655 BlockDirtyBitmapMergeSourceList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001656
1657 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1658 merge_src->type = QTYPE_QDICT;
1659 merge_src->u.external.node = g_strdup(src_node);
1660 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001661 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001662 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1663 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1664}
1665
Kevin Wolf690c7302015-03-19 13:33:32 +01001666enum ImgConvertBlockStatus {
1667 BLK_DATA,
1668 BLK_ZERO,
1669 BLK_BACKING_FILE,
1670};
1671
Peter Lieven2d9187b2017-02-28 13:40:07 +01001672#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001673#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001674
Kevin Wolf690c7302015-03-19 13:33:32 +01001675typedef struct ImgConvertState {
1676 BlockBackend **src;
1677 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001678 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001679 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001680 int64_t total_sectors;
1681 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001682 int64_t allocated_done;
1683 int64_t sector_num;
1684 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001685 enum ImgConvertBlockStatus status;
1686 int64_t sector_next_status;
1687 BlockBackend *target;
1688 bool has_zero_init;
1689 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001690 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001691 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001692 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001693 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001694 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001695 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001696 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001697 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001698 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001699 size_t cluster_sectors;
1700 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001701 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001702 int running_coroutines;
1703 Coroutine *co[MAX_COROUTINES];
1704 int64_t wait_sector_num[MAX_COROUTINES];
1705 CoMutex lock;
1706 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001707} ImgConvertState;
1708
Peter Lieven2d9187b2017-02-28 13:40:07 +01001709static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1710 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001711{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001712 *src_cur = 0;
1713 *src_cur_offset = 0;
1714 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1715 *src_cur_offset += s->src_sectors[*src_cur];
1716 (*src_cur)++;
1717 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001718 }
1719}
1720
1721static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1722{
Eric Blake31826642017-10-11 22:47:08 -05001723 int64_t src_cur_offset;
1724 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001725 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001726
Peter Lieven2d9187b2017-02-28 13:40:07 +01001727 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001728
1729 assert(s->total_sectors > sector_num);
1730 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1731
Max Reitz351c8ef2018-05-01 18:57:49 +02001732 if (s->target_backing_sectors >= 0) {
1733 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001734 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001735 } else if (sector_num + n > s->target_backing_sectors) {
1736 /* Split requests around target_backing_sectors (because
1737 * starting from there, zeros are handled differently) */
1738 n = s->target_backing_sectors - sector_num;
1739 }
1740 }
1741
Kevin Wolf690c7302015-03-19 13:33:32 +01001742 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001743 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1744 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001745 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001746 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1747 BlockDriverState *base;
1748
1749 if (s->target_has_backing) {
1750 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1751 } else {
1752 base = NULL;
1753 }
Eric Blake31826642017-10-11 22:47:08 -05001754
Max Reitz8eaac022019-05-07 22:35:03 +02001755 do {
1756 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001757
Max Reitz4a2061e2019-06-12 19:00:30 +02001758 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1759 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001760
1761 if (ret < 0) {
1762 if (s->salvage) {
1763 if (n == 1) {
1764 if (!s->quiet) {
1765 warn_report("error while reading block status at "
1766 "offset %" PRIu64 ": %s", offset,
1767 strerror(-ret));
1768 }
1769 /* Just try to read the data, then */
1770 ret = BDRV_BLOCK_DATA;
1771 count = BDRV_SECTOR_SIZE;
1772 } else {
1773 /* Retry on a shorter range */
1774 n = DIV_ROUND_UP(n, 4);
1775 }
1776 } else {
1777 error_report("error while reading block status at offset "
1778 "%" PRIu64 ": %s", offset, strerror(-ret));
1779 return ret;
1780 }
1781 }
1782 } while (ret < 0);
1783
Eric Blake31826642017-10-11 22:47:08 -05001784 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001785
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001786 /*
1787 * Avoid that s->sector_next_status becomes unaligned to the source
1788 * request alignment and/or cluster size to avoid unnecessary read
1789 * cycles.
1790 */
1791 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1792 if (n > tail) {
1793 n -= tail;
1794 }
1795
Kevin Wolf690c7302015-03-19 13:33:32 +01001796 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001797 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001798 } else if (ret & BDRV_BLOCK_DATA) {
1799 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001800 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001801 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001802 }
1803
1804 s->sector_next_status = sector_num + n;
1805 }
1806
1807 n = MIN(n, s->sector_next_status - sector_num);
1808 if (s->status == BLK_DATA) {
1809 n = MIN(n, s->buf_sectors);
1810 }
1811
1812 /* We need to write complete clusters for compressed images, so if an
1813 * unallocated area is shorter than that, we must consider the whole
1814 * cluster allocated. */
1815 if (s->compressed) {
1816 if (n < s->cluster_sectors) {
1817 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1818 s->status = BLK_DATA;
1819 } else {
1820 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1821 }
1822 }
1823
1824 return n;
1825}
1826
Peter Lieven2d9187b2017-02-28 13:40:07 +01001827static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1828 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001829{
Max Reitz8eaac022019-05-07 22:35:03 +02001830 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001831 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001832
Kevin Wolf690c7302015-03-19 13:33:32 +01001833 assert(nb_sectors <= s->buf_sectors);
1834 while (nb_sectors > 0) {
1835 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001836 int src_cur;
1837 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001838 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001839
1840 /* In the case of compression with multiple source files, we can get a
1841 * nb_sectors that spreads into the next part. So we must be able to
1842 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001843 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1844 blk = s->src[src_cur];
1845 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001846
Max Reitz8eaac022019-05-07 22:35:03 +02001847 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001848
Max Reitz8eaac022019-05-07 22:35:03 +02001849 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1850 if (single_read_until > offset) {
1851 n = 1;
1852 }
1853
1854 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001855 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001856 if (s->salvage) {
1857 if (n > 1) {
1858 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1859 continue;
1860 } else {
1861 if (!s->quiet) {
1862 warn_report("error while reading offset %" PRIu64
1863 ": %s", offset, strerror(-ret));
1864 }
1865 memset(buf, 0, BDRV_SECTOR_SIZE);
1866 }
1867 } else {
1868 return ret;
1869 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001870 }
1871
1872 sector_num += n;
1873 nb_sectors -= n;
1874 buf += n * BDRV_SECTOR_SIZE;
1875 }
1876
1877 return 0;
1878}
1879
Peter Lieven2d9187b2017-02-28 13:40:07 +01001880
1881static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1882 int nb_sectors, uint8_t *buf,
1883 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001884{
1885 int ret;
1886
1887 while (nb_sectors > 0) {
1888 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001889 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1890
Peter Lieven2d9187b2017-02-28 13:40:07 +01001891 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001892 case BLK_BACKING_FILE:
1893 /* If we have a backing file, leave clusters unallocated that are
1894 * unallocated in the source image, so that the backing file is
1895 * visible at the respective offset. */
1896 assert(s->target_has_backing);
1897 break;
1898
1899 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001900 /* If we're told to keep the target fully allocated (-S 0) or there
1901 * is real non-zero data, we must write it. Otherwise we can treat
1902 * it as zero sectors.
1903 * Compressed clusters need to be written as a whole, so in that
1904 * case we can only save the write if the buffer is completely
1905 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001906 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001907 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001908 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1909 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001910 (s->compressed &&
1911 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001912 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001913 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1914 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001915 if (ret < 0) {
1916 return ret;
1917 }
1918 break;
1919 }
1920 /* fall-through */
1921
1922 case BLK_ZERO:
1923 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001924 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001925 break;
1926 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001927 ret = blk_co_pwrite_zeroes(s->target,
1928 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001929 n << BDRV_SECTOR_BITS,
1930 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001931 if (ret < 0) {
1932 return ret;
1933 }
1934 break;
1935 }
1936
1937 sector_num += n;
1938 nb_sectors -= n;
1939 buf += n * BDRV_SECTOR_SIZE;
1940 }
1941
1942 return 0;
1943}
1944
Fam Zhengee5306d2018-06-01 17:26:48 +08001945static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1946 int nb_sectors)
1947{
1948 int n, ret;
1949
1950 while (nb_sectors > 0) {
1951 BlockBackend *blk;
1952 int src_cur;
1953 int64_t bs_sectors, src_cur_offset;
1954 int64_t offset;
1955
1956 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1957 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1958 blk = s->src[src_cur];
1959 bs_sectors = s->src_sectors[src_cur];
1960
1961 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1962
1963 ret = blk_co_copy_range(blk, offset, s->target,
1964 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001965 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001966 if (ret < 0) {
1967 return ret;
1968 }
1969
1970 sector_num += n;
1971 nb_sectors -= n;
1972 }
1973 return 0;
1974}
1975
Peter Lieven2d9187b2017-02-28 13:40:07 +01001976static void coroutine_fn convert_co_do_copy(void *opaque)
1977{
1978 ImgConvertState *s = opaque;
1979 uint8_t *buf = NULL;
1980 int ret, i;
1981 int index = -1;
1982
1983 for (i = 0; i < s->num_coroutines; i++) {
1984 if (s->co[i] == qemu_coroutine_self()) {
1985 index = i;
1986 break;
1987 }
1988 }
1989 assert(index >= 0);
1990
1991 s->running_coroutines++;
1992 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1993
1994 while (1) {
1995 int n;
1996 int64_t sector_num;
1997 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001998 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001999
2000 qemu_co_mutex_lock(&s->lock);
2001 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
2002 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03002003 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002004 }
2005 n = convert_iteration_sectors(s, s->sector_num);
2006 if (n < 0) {
2007 qemu_co_mutex_unlock(&s->lock);
2008 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03002009 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002010 }
2011 /* save current sector and allocation status to local variables */
2012 sector_num = s->sector_num;
2013 status = s->status;
2014 if (!s->min_sparse && s->status == BLK_ZERO) {
2015 n = MIN(n, s->buf_sectors);
2016 }
2017 /* increment global sector counter so that other coroutines can
2018 * already continue reading beyond this request */
2019 s->sector_num += n;
2020 qemu_co_mutex_unlock(&s->lock);
2021
2022 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2023 s->allocated_done += n;
2024 qemu_progress_print(100.0 * s->allocated_done /
2025 s->allocated_sectors, 0);
2026 }
2027
Fam Zhengee5306d2018-06-01 17:26:48 +08002028retry:
2029 copy_range = s->copy_range && s->status == BLK_DATA;
2030 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002031 ret = convert_co_read(s, sector_num, n, buf);
2032 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002033 error_report("error while reading at byte %lld: %s",
2034 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002035 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002036 }
2037 } else if (!s->min_sparse && status == BLK_ZERO) {
2038 status = BLK_DATA;
2039 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2040 }
2041
2042 if (s->wr_in_order) {
2043 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002044 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002045 s->wait_sector_num[index] = sector_num;
2046 qemu_coroutine_yield();
2047 }
2048 s->wait_sector_num[index] = -1;
2049 }
2050
Anton Nefedovb91127e2017-04-26 11:33:15 +03002051 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002052 if (copy_range) {
2053 ret = convert_co_copy_range(s, sector_num, n);
2054 if (ret) {
2055 s->copy_range = false;
2056 goto retry;
2057 }
2058 } else {
2059 ret = convert_co_write(s, sector_num, n, buf, status);
2060 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002061 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002062 error_report("error while writing at byte %lld: %s",
2063 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002064 s->ret = ret;
2065 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002066 }
2067
2068 if (s->wr_in_order) {
2069 /* reenter the coroutine that might have waited
2070 * for this write to complete */
2071 s->wr_offs = sector_num + n;
2072 for (i = 0; i < s->num_coroutines; i++) {
2073 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2074 /*
2075 * A -> B -> A cannot occur because A has
2076 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2077 * B will never enter A during this time window.
2078 */
2079 qemu_coroutine_enter(s->co[i]);
2080 break;
2081 }
2082 }
2083 }
2084 }
2085
Peter Lieven2d9187b2017-02-28 13:40:07 +01002086 qemu_vfree(buf);
2087 s->co[index] = NULL;
2088 s->running_coroutines--;
2089 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2090 /* the convert job finished successfully */
2091 s->ret = 0;
2092 }
2093}
2094
Kevin Wolf690c7302015-03-19 13:33:32 +01002095static int convert_do_copy(ImgConvertState *s)
2096{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002097 int ret, i, n;
2098 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002099
2100 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002101 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2102 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002103 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002104 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002105
Kevin Wolf690c7302015-03-19 13:33:32 +01002106 /* Allocate buffer for copied data. For compressed images, only one cluster
2107 * can be copied at a time. */
2108 if (s->compressed) {
2109 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2110 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002111 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002112 }
2113 s->buf_sectors = s->cluster_sectors;
2114 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002115
Kevin Wolf690c7302015-03-19 13:33:32 +01002116 while (sector_num < s->total_sectors) {
2117 n = convert_iteration_sectors(s, sector_num);
2118 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002119 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002120 }
Max Reitzaad15de2016-03-24 23:33:57 +01002121 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2122 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002123 s->allocated_sectors += n;
2124 }
2125 sector_num += n;
2126 }
2127
2128 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002129 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002130 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002131
Peter Lieven2d9187b2017-02-28 13:40:07 +01002132 qemu_co_mutex_init(&s->lock);
2133 for (i = 0; i < s->num_coroutines; i++) {
2134 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2135 s->wait_sector_num[i] = -1;
2136 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002137 }
2138
Anton Nefedovb91127e2017-04-26 11:33:15 +03002139 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002140 main_loop_wait(false);
2141 }
2142
2143 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002144 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002145 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002146 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002147 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002148 }
2149 }
2150
Peter Lieven2d9187b2017-02-28 13:40:07 +01002151 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002152}
2153
Eric Blake15e39ad2020-05-21 14:21:36 -05002154static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst)
2155{
2156 BdrvDirtyBitmap *bm;
2157 Error *err = NULL;
2158
2159 FOR_EACH_DIRTY_BITMAP(src, bm) {
2160 const char *name;
2161
2162 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2163 continue;
2164 }
2165 name = bdrv_dirty_bitmap_name(bm);
2166 qmp_block_dirty_bitmap_add(dst->node_name, name,
2167 true, bdrv_dirty_bitmap_granularity(bm),
2168 true, true,
2169 true, !bdrv_dirty_bitmap_enabled(bm),
2170 &err);
2171 if (err) {
2172 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2173 return -1;
2174 }
2175
2176 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2177 &err);
2178 if (err) {
2179 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
2180 return -1;
2181 }
2182 }
2183
2184 return 0;
2185}
2186
Peter Lieven6360ab22018-07-13 09:15:39 +02002187#define MAX_BUF_SECTORS 32768
2188
Zhengui0c8c4892020-10-20 14:47:44 +00002189static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2190{
2191 ThrottleConfig cfg;
2192
2193 throttle_config_init(&cfg);
2194 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2195
2196 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2197 blk_set_io_limits(blk, &cfg);
2198}
2199
bellardea2384d2004-08-01 21:59:26 +00002200static int img_convert(int argc, char **argv)
2201{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002202 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002203 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002204 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2205 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002206 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002207 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002208 BlockDriverState *out_bs;
2209 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002210 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002211 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002212 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002213 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002214 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002215 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002216 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002217 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002218 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002219 bool bitmaps = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002220 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002221
Peter Lieven9fd77f92017-04-21 11:11:55 +02002222 ImgConvertState s = (ImgConvertState) {
2223 /* Need at least 4k of zeros for sparse detection */
2224 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002225 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002226 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2227 .wr_in_order = true,
2228 .num_coroutines = 8,
2229 };
2230
bellardea2384d2004-08-01 21:59:26 +00002231 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002232 static const struct option long_options[] = {
2233 {"help", no_argument, 0, 'h'},
2234 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002235 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002236 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002237 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002238 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002239 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002240 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002241 {0, 0, 0, 0}
2242 };
Zhengui0c8c4892020-10-20 14:47:44 +00002243 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002244 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002245 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002246 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002247 }
bellardea2384d2004-08-01 21:59:26 +00002248 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002249 case ':':
2250 missing_argument(argv[optind - 1]);
2251 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002252 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002253 unrecognized_option(argv[optind - 1]);
2254 break;
bellardea2384d2004-08-01 21:59:26 +00002255 case 'h':
2256 help();
2257 break;
2258 case 'f':
2259 fmt = optarg;
2260 break;
2261 case 'O':
2262 out_fmt = optarg;
2263 break;
thsf58c7b32008-06-05 21:53:49 +00002264 case 'B':
2265 out_baseimg = optarg;
2266 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002267 case 'C':
2268 s.copy_range = true;
2269 break;
bellardea2384d2004-08-01 21:59:26 +00002270 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002271 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002272 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002273 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002274 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002275 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002276 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002277 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002278 case 'l':
2279 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002280 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2281 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002282 if (!sn_opts) {
2283 error_report("Failed in parsing snapshot param '%s'",
2284 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002285 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002286 }
2287 } else {
2288 snapshot_name = optarg;
2289 }
2290 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002291 case 'S':
2292 {
2293 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002294
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002295 sval = cvtnum("buffer size for sparse output", optarg);
2296 if (sval < 0) {
2297 goto fail_getopt;
2298 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002299 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2300 error_report("Invalid buffer size for sparse output specified. "
2301 "Valid sizes are multiples of %llu up to %llu. Select "
2302 "0 to disable sparse detection (fully allocates output).",
2303 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002304 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002305 }
2306
Peter Lieven9fd77f92017-04-21 11:11:55 +02002307 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002308 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002309 break;
2310 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002311 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002312 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002313 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002314 case 't':
2315 cache = optarg;
2316 break;
Max Reitz40055952014-07-22 22:58:42 +02002317 case 'T':
2318 src_cache = optarg;
2319 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002320 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002321 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002322 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002323 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002324 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002325 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002326 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002327 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2328 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002329 error_report("Invalid number of coroutines. Allowed number of"
2330 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002331 goto fail_getopt;
2332 }
2333 break;
2334 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002335 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002336 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002337 case 'U':
2338 force_share = true;
2339 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002340 case 'r':
2341 rate_limit = cvtnum("rate limit", optarg);
2342 if (rate_limit < 0) {
2343 goto fail_getopt;
2344 }
2345 break;
Max Reitz3258b912017-04-26 15:46:47 +02002346 case OPTION_OBJECT: {
2347 QemuOpts *object_opts;
2348 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2349 optarg, true);
2350 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002351 goto fail_getopt;
2352 }
2353 break;
Max Reitz3258b912017-04-26 15:46:47 +02002354 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002355 case OPTION_IMAGE_OPTS:
2356 image_opts = true;
2357 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002358 case OPTION_SALVAGE:
2359 s.salvage = true;
2360 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002361 case OPTION_TARGET_IMAGE_OPTS:
2362 tgt_image_opts = true;
2363 break;
David Edmondson168468f2020-02-05 11:02:48 +00002364 case OPTION_TARGET_IS_ZERO:
2365 /*
2366 * The user asserting that the target is blank has the
2367 * same effect as the target driver supporting zero
2368 * initialisation.
2369 */
2370 s.has_zero_init = true;
2371 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002372 case OPTION_BITMAPS:
2373 bitmaps = true;
2374 break;
bellardea2384d2004-08-01 21:59:26 +00002375 }
2376 }
ths3b46e622007-09-17 08:09:54 +00002377
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002378 if (!out_fmt && !tgt_image_opts) {
2379 out_fmt = "raw";
2380 }
2381
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002382 if (qemu_opts_foreach(&qemu_object_opts,
2383 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002384 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002385 goto fail_getopt;
2386 }
2387
Fam Zhenge11ce122018-07-27 11:34:01 +08002388 if (s.compressed && s.copy_range) {
2389 error_report("Cannot enable copy offloading when -c is used");
2390 goto fail_getopt;
2391 }
2392
2393 if (explict_min_sparse && s.copy_range) {
2394 error_report("Cannot enable copy offloading when -S is used");
2395 goto fail_getopt;
2396 }
2397
Max Reitz8eaac022019-05-07 22:35:03 +02002398 if (s.copy_range && s.salvage) {
2399 error_report("Cannot use copy offloading in salvaging mode");
2400 goto fail_getopt;
2401 }
2402
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002403 if (tgt_image_opts && !skip_create) {
2404 error_report("--target-image-opts requires use of -n flag");
2405 goto fail_getopt;
2406 }
2407
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002408 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002409 error_report("-o has no effect when skipping image creation");
2410 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002411 }
2412
David Edmondson168468f2020-02-05 11:02:48 +00002413 if (s.has_zero_init && !skip_create) {
2414 error_report("--target-is-zero requires use of -n flag");
2415 goto fail_getopt;
2416 }
2417
Peter Lieven9fd77f92017-04-21 11:11:55 +02002418 s.src_num = argc - optind - 1;
2419 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2420
2421 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002422 if (out_fmt) {
2423 ret = print_block_option_help(out_filename, out_fmt);
2424 goto fail_getopt;
2425 } else {
2426 error_report("Option help requires a format be specified");
2427 goto fail_getopt;
2428 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002429 }
2430
2431 if (s.src_num < 1) {
2432 error_report("Must specify image file name");
2433 goto fail_getopt;
2434 }
2435
Peter Lieven9fd77f92017-04-21 11:11:55 +02002436 /* ret is still -EINVAL until here */
2437 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2438 if (ret < 0) {
2439 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002440 goto fail_getopt;
2441 }
2442
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002443 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002444 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002445 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002446 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002447 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002448 qemu_progress_print(0, 100);
2449
Peter Lieven9fd77f92017-04-21 11:11:55 +02002450 s.src = g_new0(BlockBackend *, s.src_num);
2451 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002452 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002453
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002455 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002456 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002457 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002458 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002459 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002460 ret = -1;
2461 goto out;
2462 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002463 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2464 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002465 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002466 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002467 ret = -1;
2468 goto out;
2469 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002470 src_bs = blk_bs(s.src[bs_i]);
2471 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2472 BDRV_SECTOR_SIZE);
2473 if (!bdrv_get_info(src_bs, &bdi)) {
2474 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2475 bdi.cluster_size / BDRV_SECTOR_SIZE);
2476 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002477 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002478 }
bellardea2384d2004-08-01 21:59:26 +00002479
Wenchao Xiaef806542013-12-04 17:10:57 +08002480 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002481 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002482 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2483 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2484 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002485 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002486 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002487 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002488 ret = -1;
2489 goto out;
2490 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002491
Peter Lieven9fd77f92017-04-21 11:11:55 +02002492 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2493 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002494 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002495 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002496 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002497 ret = -1;
2498 goto out;
edison51ef6722010-09-21 19:58:41 -07002499 }
2500
Max Reitz2e024cd2015-02-11 09:58:46 -05002501 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002502 /* Find driver and parse its options */
2503 drv = bdrv_find_format(out_fmt);
2504 if (!drv) {
2505 error_report("Unknown file format '%s'", out_fmt);
2506 ret = -1;
2507 goto out;
2508 }
2509
2510 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2511 if (!proto_drv) {
2512 error_report_err(local_err);
2513 ret = -1;
2514 goto out;
2515 }
2516
Max Reitz2e024cd2015-02-11 09:58:46 -05002517 if (!drv->create_opts) {
2518 error_report("Format driver '%s' does not support image creation",
2519 drv->format_name);
2520 ret = -1;
2521 goto out;
2522 }
Max Reitzf75613c2014-12-02 18:32:46 +01002523
Max Reitz2e024cd2015-02-11 09:58:46 -05002524 if (!proto_drv->create_opts) {
2525 error_report("Protocol driver '%s' does not support image creation",
2526 proto_drv->format_name);
2527 ret = -1;
2528 goto out;
2529 }
Max Reitzf75613c2014-12-02 18:32:46 +01002530
Max Reitz2e024cd2015-02-11 09:58:46 -05002531 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2532 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002533
Max Reitz2e024cd2015-02-11 09:58:46 -05002534 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002535 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002536 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002537 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002538 ret = -1;
2539 goto out;
2540 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002541 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002542
Yi Lic075c422020-08-19 09:36:07 +08002543 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2544 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002545 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2546 if (ret < 0) {
2547 goto out;
2548 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002549 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002550
Kevin Wolfa18953f2010-10-14 15:46:04 +02002551 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002552 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002553 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002554 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002555 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002556 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002557
David Edmondson168468f2020-02-05 11:02:48 +00002558 if (s.has_zero_init && s.target_has_backing) {
2559 error_report("Cannot use --target-is-zero when the destination "
2560 "image has a backing file");
2561 goto out;
2562 }
2563
Max Reitz48758a82017-04-26 15:46:48 +02002564 if (s.src_num > 1 && out_baseimg) {
2565 error_report("Having a backing file for the target makes no sense when "
2566 "concatenating multiple input images");
2567 ret = -1;
2568 goto out;
2569 }
2570
Eric Blaked9f059a2020-07-06 15:39:54 -05002571 if (out_baseimg_param) {
2572 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
2573 warn_report("Deprecated use of backing file without explicit "
2574 "backing format");
2575 }
2576 }
2577
Kevin Wolfefa84d42009-05-18 16:42:12 +02002578 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002579 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002580 bool encryption =
2581 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002582 const char *encryptfmt =
2583 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002584 const char *preallocation =
2585 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002586
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002587 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002588 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002589 ret = -1;
2590 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002591 }
2592
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002593 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002594 error_report("Compression and encryption not supported at "
2595 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002596 ret = -1;
2597 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002598 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002599
Chunyan Liu83d05212014-06-05 17:20:51 +08002600 if (preallocation
2601 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002602 {
2603 error_report("Compression and preallocation not supported at "
2604 "the same time");
2605 ret = -1;
2606 goto out;
2607 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002608 }
2609
Eric Blake15e39ad2020-05-21 14:21:36 -05002610 /* Determine if bitmaps need copying */
2611 if (bitmaps) {
2612 if (s.src_num > 1) {
2613 error_report("Copying bitmaps only possible with single source");
2614 ret = -1;
2615 goto out;
2616 }
2617 if (!bdrv_supports_persistent_dirty_bitmap(blk_bs(s.src[0]))) {
2618 error_report("Source lacks bitmap support");
2619 ret = -1;
2620 goto out;
2621 }
2622 }
2623
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002624 /*
2625 * The later open call will need any decryption secrets, and
2626 * bdrv_create() will purge "opts", so extract them now before
2627 * they are lost.
2628 */
2629 if (!skip_create) {
2630 open_opts = qdict_new();
2631 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002632
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002633 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002634 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002635 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002636 error_reportf_err(local_err, "%s: error while converting %s: ",
2637 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002638 goto out;
bellardea2384d2004-08-01 21:59:26 +00002639 }
2640 }
ths3b46e622007-09-17 08:09:54 +00002641
Max Reitz4d7c4872019-07-24 19:12:29 +02002642 s.target_is_new = !skip_create;
2643
Peter Lieven9fd77f92017-04-21 11:11:55 +02002644 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002645 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002646 if (ret < 0) {
2647 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002648 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002649 }
2650
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002651 if (skip_create) {
2652 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002653 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002654 } else {
2655 /* TODO ultimately we should allow --target-image-opts
2656 * to be used even when -n is not given.
2657 * That has to wait for bdrv_create to be improved
2658 * to allow filenames in option syntax
2659 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002660 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002661 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002662 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002663 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002664 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002665 ret = -1;
2666 goto out;
2667 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002668 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002669
Eric Blake15e39ad2020-05-21 14:21:36 -05002670 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2671 error_report("Format driver '%s' does not support bitmaps",
2672 out_bs->drv->format_name);
2673 ret = -1;
2674 goto out;
2675 }
2676
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002677 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002678 error_report("Compression not supported for this file format");
2679 ret = -1;
2680 goto out;
2681 }
2682
Eric Blake5def6b82016-06-23 16:37:19 -06002683 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002684 * or discard_alignment of the out_bs is greater. Limit to
2685 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2686 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002687 MAX(s.buf_sectors,
2688 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2689 out_bs->bl.pdiscard_alignment >>
2690 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002691
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002692 /* try to align the write requests to the destination to avoid unnecessary
2693 * RMW cycles. */
2694 s.alignment = MAX(pow2floor(s.min_sparse),
2695 DIV_ROUND_UP(out_bs->bl.request_alignment,
2696 BDRV_SECTOR_SIZE));
2697 assert(is_power_of_2(s.alignment));
2698
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002699 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002700 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002701 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002702 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002703 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002704 ret = -1;
2705 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002706 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002707 error_report("output file is smaller than input file");
2708 ret = -1;
2709 goto out;
2710 }
2711 }
2712
Max Reitzc69291e2020-01-21 16:59:14 +01002713 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002714 /* Errors are treated as "backing length unknown" (which means
2715 * s.target_backing_sectors has to be negative, which it will
2716 * be automatically). The backing file length is used only
2717 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002718 s.target_backing_sectors =
2719 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002720 } else {
2721 s.target_backing_sectors = -1;
2722 }
2723
Peter Lieven24f833c2013-11-27 11:07:07 +01002724 ret = bdrv_get_info(out_bs, &bdi);
2725 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002726 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002727 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002728 goto out;
2729 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002730 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002731 s.compressed = s.compressed || bdi.needs_compressed_writes;
2732 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002733 }
2734
Zhengui0c8c4892020-10-20 14:47:44 +00002735 if (rate_limit) {
2736 set_rate_limit(s.target, rate_limit);
2737 }
2738
Peter Lieven9fd77f92017-04-21 11:11:55 +02002739 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002740
2741 /* Now copy the bitmaps */
2742 if (bitmaps && ret == 0) {
2743 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs);
2744 }
2745
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002746out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002747 if (!ret) {
2748 qemu_progress_print(100, 0);
2749 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002750 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002751 qemu_opts_del(opts);
2752 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002753 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002754 blk_unref(s.target);
2755 if (s.src) {
2756 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2757 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002758 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002759 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002760 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002761 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002762 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002763fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002764 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002765 g_free(options);
2766
Peter Lieven9fd77f92017-04-21 11:11:55 +02002767 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002768}
2769
bellard57d1a2b2004-08-03 21:15:11 +00002770
bellardfaea38e2006-08-05 21:31:00 +00002771static void dump_snapshots(BlockDriverState *bs)
2772{
2773 QEMUSnapshotInfo *sn_tab, *sn;
2774 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002775
2776 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2777 if (nb_sns <= 0)
2778 return;
2779 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002780 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002781 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002782 for(i = 0; i < nb_sns; i++) {
2783 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002784 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002785 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002786 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002787 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002788}
2789
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002790static void dump_json_image_info_list(ImageInfoList *list)
2791{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002792 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002793 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002794 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002795
2796 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2797 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002798 str = qobject_to_json_pretty(obj);
2799 assert(str != NULL);
2800 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002801 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002802 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002803 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002804}
2805
Benoît Canetc054b3f2012-09-05 13:09:02 +02002806static void dump_json_image_info(ImageInfo *info)
2807{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002808 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002809 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002810 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002811
2812 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2813 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002814 str = qobject_to_json_pretty(obj);
2815 assert(str != NULL);
2816 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002817 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002818 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002819 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002820}
2821
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002822static void dump_human_image_info_list(ImageInfoList *list)
2823{
2824 ImageInfoList *elem;
2825 bool delim = false;
2826
2827 for (elem = list; elem; elem = elem->next) {
2828 if (delim) {
2829 printf("\n");
2830 }
2831 delim = true;
2832
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002833 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002834 }
2835}
2836
2837static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2838{
2839 return strcmp(a, b) == 0;
2840}
2841
2842/**
2843 * Open an image file chain and return an ImageInfoList
2844 *
2845 * @filename: topmost image filename
2846 * @fmt: topmost image format (may be NULL to autodetect)
2847 * @chain: true - enumerate entire backing file chain
2848 * false - only topmost image file
2849 *
2850 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2851 * image file. If there was an error a message will have been printed to
2852 * stderr.
2853 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002854static ImageInfoList *collect_image_info_list(bool image_opts,
2855 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002856 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002857 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002858{
2859 ImageInfoList *head = NULL;
2860 ImageInfoList **last = &head;
2861 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002862 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002863
2864 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2865
2866 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002867 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002868 BlockDriverState *bs;
2869 ImageInfo *info;
2870 ImageInfoList *elem;
2871
2872 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2873 error_report("Backing file '%s' creates an infinite loop.",
2874 filename);
2875 goto err;
2876 }
2877 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2878
Max Reitzefaa7c42016-03-16 19:54:38 +01002879 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002880 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2881 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002882 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002883 goto err;
2884 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002885 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002886
Wenchao Xia43526ec2013-06-06 12:27:58 +08002887 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002888 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002889 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002890 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002891 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002892 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002893
2894 elem = g_new0(ImageInfoList, 1);
2895 elem->value = info;
2896 *last = elem;
2897 last = &elem->next;
2898
Markus Armbruster26f54e92014-10-07 13:59:04 +02002899 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002900
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002901 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002902 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002903 image_opts = false;
2904
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002905 if (chain) {
2906 if (info->has_full_backing_filename) {
2907 filename = info->full_backing_filename;
2908 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002909 error_report("Could not determine absolute backing filename,"
2910 " but backing filename '%s' present",
2911 info->backing_filename);
2912 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002913 }
2914 if (info->has_backing_filename_format) {
2915 fmt = info->backing_filename_format;
2916 }
2917 }
2918 }
2919 g_hash_table_destroy(filenames);
2920 return head;
2921
2922err:
2923 qapi_free_ImageInfoList(head);
2924 g_hash_table_destroy(filenames);
2925 return NULL;
2926}
2927
Benoît Canetc054b3f2012-09-05 13:09:02 +02002928static int img_info(int argc, char **argv)
2929{
2930 int c;
2931 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002932 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002933 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002934 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002935 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002936 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002937
bellardea2384d2004-08-01 21:59:26 +00002938 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002939 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002940 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002941 int option_index = 0;
2942 static const struct option long_options[] = {
2943 {"help", no_argument, 0, 'h'},
2944 {"format", required_argument, 0, 'f'},
2945 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002946 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002947 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002948 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002949 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002950 {0, 0, 0, 0}
2951 };
Fam Zheng335e9932017-05-03 00:35:39 +08002952 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002953 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002954 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002955 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002956 }
bellardea2384d2004-08-01 21:59:26 +00002957 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002958 case ':':
2959 missing_argument(argv[optind - 1]);
2960 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002961 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002962 unrecognized_option(argv[optind - 1]);
2963 break;
bellardea2384d2004-08-01 21:59:26 +00002964 case 'h':
2965 help();
2966 break;
2967 case 'f':
2968 fmt = optarg;
2969 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002970 case 'U':
2971 force_share = true;
2972 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002973 case OPTION_OUTPUT:
2974 output = optarg;
2975 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002976 case OPTION_BACKING_CHAIN:
2977 chain = true;
2978 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002979 case OPTION_OBJECT: {
2980 QemuOpts *opts;
2981 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2982 optarg, true);
2983 if (!opts) {
2984 return 1;
2985 }
2986 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002987 case OPTION_IMAGE_OPTS:
2988 image_opts = true;
2989 break;
bellardea2384d2004-08-01 21:59:26 +00002990 }
2991 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002992 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002993 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002994 }
bellardea2384d2004-08-01 21:59:26 +00002995 filename = argv[optind++];
2996
Benoît Canetc054b3f2012-09-05 13:09:02 +02002997 if (output && !strcmp(output, "json")) {
2998 output_format = OFORMAT_JSON;
2999 } else if (output && !strcmp(output, "human")) {
3000 output_format = OFORMAT_HUMAN;
3001 } else if (output) {
3002 error_report("--output must be used with human or json as argument.");
3003 return 1;
3004 }
3005
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003006 if (qemu_opts_foreach(&qemu_object_opts,
3007 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003008 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003009 return 1;
3010 }
3011
Fam Zheng335e9932017-05-03 00:35:39 +08003012 list = collect_image_info_list(image_opts, filename, fmt, chain,
3013 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003014 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003015 return 1;
3016 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003017
Benoît Canetc054b3f2012-09-05 13:09:02 +02003018 switch (output_format) {
3019 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003020 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003021 break;
3022 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003023 if (chain) {
3024 dump_json_image_info_list(list);
3025 } else {
3026 dump_json_image_info(list->value);
3027 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003028 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003029 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003030
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003031 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003032 return 0;
3033}
3034
Eric Blake30065d12019-03-26 13:40:43 -05003035static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3036 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003037{
3038 switch (output_format) {
3039 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003040 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003041 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003042 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003043 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003044 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003045 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003046 e->start, e->length,
3047 e->has_offset ? e->offset : 0,
3048 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003049 }
3050 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3051 * Modify the flags here to allow more coalescing.
3052 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003053 if (next && (!next->data || next->zero)) {
3054 next->data = false;
3055 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003056 }
3057 break;
3058 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003059 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08003060 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003061 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08003062 e->zero ? "true" : "false",
3063 e->data ? "true" : "false");
3064 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003065 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003066 }
3067 putchar('}');
3068
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003069 if (next) {
3070 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003071 }
3072 break;
3073 }
Eric Blake30065d12019-03-26 13:40:43 -05003074 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003075}
3076
Eric Blake5e344dd2017-10-11 22:47:02 -05003077static int get_block_status(BlockDriverState *bs, int64_t offset,
3078 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003079{
Eric Blake237d78f2017-10-11 22:47:03 -05003080 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003081 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003082 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003083 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003084 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003085 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003086
3087 /* As an optimization, we could cache the current range of unallocated
3088 * clusters in each file of the chain, and avoid querying the same
3089 * range repeatedly.
3090 */
3091
3092 depth = 0;
3093 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003094 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003095 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003096 if (ret < 0) {
3097 return ret;
3098 }
Eric Blake237d78f2017-10-11 22:47:03 -05003099 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003100 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3101 break;
3102 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003103 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003104 if (bs == NULL) {
3105 ret = 0;
3106 break;
3107 }
3108
3109 depth++;
3110 }
3111
John Snow28756452016-02-05 13:12:33 -05003112 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3113
Max Reitzf30c66b2019-02-01 20:29:05 +01003114 if (file && has_offset) {
3115 bdrv_refresh_filename(file);
3116 filename = file->filename;
3117 }
3118
John Snow28756452016-02-05 13:12:33 -05003119 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003120 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003121 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003122 .data = !!(ret & BDRV_BLOCK_DATA),
3123 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003124 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003125 .has_offset = has_offset,
3126 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01003127 .has_filename = filename,
3128 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003129 };
3130
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003131 return 0;
3132}
3133
Fam Zheng16b0d552016-01-26 11:59:02 +08003134static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3135{
3136 if (curr->length == 0) {
3137 return false;
3138 }
3139 if (curr->zero != next->zero ||
3140 curr->data != next->data ||
3141 curr->depth != next->depth ||
3142 curr->has_filename != next->has_filename ||
3143 curr->has_offset != next->has_offset) {
3144 return false;
3145 }
3146 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3147 return false;
3148 }
3149 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3150 return false;
3151 }
3152 return true;
3153}
3154
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003155static int img_map(int argc, char **argv)
3156{
3157 int c;
3158 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003159 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003160 BlockDriverState *bs;
3161 const char *filename, *fmt, *output;
3162 int64_t length;
3163 MapEntry curr = { .length = 0 }, next;
3164 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003165 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003166 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003167 int64_t start_offset = 0;
3168 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003169
3170 fmt = NULL;
3171 output = NULL;
3172 for (;;) {
3173 int option_index = 0;
3174 static const struct option long_options[] = {
3175 {"help", no_argument, 0, 'h'},
3176 {"format", required_argument, 0, 'f'},
3177 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003178 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003179 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003180 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003181 {"start-offset", required_argument, 0, 's'},
3182 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003183 {0, 0, 0, 0}
3184 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003185 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003186 long_options, &option_index);
3187 if (c == -1) {
3188 break;
3189 }
3190 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003191 case ':':
3192 missing_argument(argv[optind - 1]);
3193 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003194 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003195 unrecognized_option(argv[optind - 1]);
3196 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003197 case 'h':
3198 help();
3199 break;
3200 case 'f':
3201 fmt = optarg;
3202 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003203 case 'U':
3204 force_share = true;
3205 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003206 case OPTION_OUTPUT:
3207 output = optarg;
3208 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003209 case 's':
3210 start_offset = cvtnum("start offset", optarg);
3211 if (start_offset < 0) {
3212 return 1;
3213 }
3214 break;
3215 case 'l':
3216 max_length = cvtnum("max length", optarg);
3217 if (max_length < 0) {
3218 return 1;
3219 }
3220 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003221 case OPTION_OBJECT: {
3222 QemuOpts *opts;
3223 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3224 optarg, true);
3225 if (!opts) {
3226 return 1;
3227 }
3228 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003229 case OPTION_IMAGE_OPTS:
3230 image_opts = true;
3231 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003232 }
3233 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003234 if (optind != argc - 1) {
3235 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003236 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003237 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003238
3239 if (output && !strcmp(output, "json")) {
3240 output_format = OFORMAT_JSON;
3241 } else if (output && !strcmp(output, "human")) {
3242 output_format = OFORMAT_HUMAN;
3243 } else if (output) {
3244 error_report("--output must be used with human or json as argument.");
3245 return 1;
3246 }
3247
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003248 if (qemu_opts_foreach(&qemu_object_opts,
3249 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003250 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003251 return 1;
3252 }
3253
Fam Zheng335e9932017-05-03 00:35:39 +08003254 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003255 if (!blk) {
3256 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003257 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003258 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003259
3260 if (output_format == OFORMAT_HUMAN) {
3261 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003262 } else if (output_format == OFORMAT_JSON) {
3263 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003264 }
3265
Max Reitzf1d3cd72015-02-05 13:58:18 -05003266 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003267 if (length < 0) {
3268 error_report("Failed to get size for '%s'", filename);
3269 return 1;
3270 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003271 if (max_length != -1) {
3272 length = MIN(start_offset + max_length, length);
3273 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003274
Eyal Moscovicic0469492020-05-13 16:36:29 +03003275 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003276 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003277 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003278 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003279
Eric Blake5e344dd2017-10-11 22:47:02 -05003280 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003281 if (ret < 0) {
3282 error_report("Could not read file metadata: %s", strerror(-ret));
3283 goto out;
3284 }
3285
Fam Zheng16b0d552016-01-26 11:59:02 +08003286 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003287 curr.length += next.length;
3288 continue;
3289 }
3290
3291 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003292 ret = dump_map_entry(output_format, &curr, &next);
3293 if (ret < 0) {
3294 goto out;
3295 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003296 }
3297 curr = next;
3298 }
3299
Eric Blake30065d12019-03-26 13:40:43 -05003300 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003301 if (output_format == OFORMAT_JSON) {
3302 puts("]");
3303 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003304
3305out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003306 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003307 return ret < 0;
3308}
3309
aliguorif7b4a942009-01-07 17:40:15 +00003310#define SNAPSHOT_LIST 1
3311#define SNAPSHOT_CREATE 2
3312#define SNAPSHOT_APPLY 3
3313#define SNAPSHOT_DELETE 4
3314
Stuart Brady153859b2009-06-07 00:42:17 +01003315static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003316{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003317 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003318 BlockDriverState *bs;
3319 QEMUSnapshotInfo sn;
3320 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003321 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003322 int action = 0;
3323 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003324 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003325 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003326 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003327 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003328
Kevin Wolfce099542016-03-15 13:01:04 +01003329 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003330 /* Parse commandline parameters */
3331 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003332 static const struct option long_options[] = {
3333 {"help", no_argument, 0, 'h'},
3334 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003335 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003336 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003337 {0, 0, 0, 0}
3338 };
Fam Zheng335e9932017-05-03 00:35:39 +08003339 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003340 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003341 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003342 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003343 }
aliguorif7b4a942009-01-07 17:40:15 +00003344 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003345 case ':':
3346 missing_argument(argv[optind - 1]);
3347 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003348 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003349 unrecognized_option(argv[optind - 1]);
3350 break;
aliguorif7b4a942009-01-07 17:40:15 +00003351 case 'h':
3352 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003353 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003354 case 'l':
3355 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003356 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003357 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003358 }
3359 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003360 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003361 break;
3362 case 'a':
3363 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003364 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003365 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003366 }
3367 action = SNAPSHOT_APPLY;
3368 snapshot_name = optarg;
3369 break;
3370 case 'c':
3371 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003372 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003373 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003374 }
3375 action = SNAPSHOT_CREATE;
3376 snapshot_name = optarg;
3377 break;
3378 case 'd':
3379 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003380 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003381 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003382 }
3383 action = SNAPSHOT_DELETE;
3384 snapshot_name = optarg;
3385 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003386 case 'q':
3387 quiet = true;
3388 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003389 case 'U':
3390 force_share = true;
3391 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003392 case OPTION_OBJECT: {
3393 QemuOpts *opts;
3394 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3395 optarg, true);
3396 if (!opts) {
3397 return 1;
3398 }
3399 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003400 case OPTION_IMAGE_OPTS:
3401 image_opts = true;
3402 break;
aliguorif7b4a942009-01-07 17:40:15 +00003403 }
3404 }
3405
Kevin Wolffc11eb22013-08-05 10:53:04 +02003406 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003407 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003408 }
aliguorif7b4a942009-01-07 17:40:15 +00003409 filename = argv[optind++];
3410
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003411 if (qemu_opts_foreach(&qemu_object_opts,
3412 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003413 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003414 return 1;
3415 }
3416
aliguorif7b4a942009-01-07 17:40:15 +00003417 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003418 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3419 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003420 if (!blk) {
3421 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003422 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003423 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003424
3425 /* Perform the requested action */
3426 switch(action) {
3427 case SNAPSHOT_LIST:
3428 dump_snapshots(bs);
3429 break;
3430
3431 case SNAPSHOT_CREATE:
3432 memset(&sn, 0, sizeof(sn));
3433 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3434
3435 qemu_gettimeofday(&tv);
3436 sn.date_sec = tv.tv_sec;
3437 sn.date_nsec = tv.tv_usec * 1000;
3438
3439 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003440 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003441 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003442 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003443 }
aliguorif7b4a942009-01-07 17:40:15 +00003444 break;
3445
3446 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003447 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003448 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003449 error_reportf_err(err, "Could not apply snapshot '%s': ",
3450 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003451 }
aliguorif7b4a942009-01-07 17:40:15 +00003452 break;
3453
3454 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003455 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3456 if (ret < 0) {
3457 error_report("Could not delete snapshot '%s': snapshot not "
3458 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003459 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003460 } else {
3461 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3462 if (ret < 0) {
3463 error_reportf_err(err, "Could not delete snapshot '%s': ",
3464 snapshot_name);
3465 ret = 1;
3466 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003467 }
aliguorif7b4a942009-01-07 17:40:15 +00003468 break;
3469 }
3470
3471 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003472 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003473 if (ret) {
3474 return 1;
3475 }
Stuart Brady153859b2009-06-07 00:42:17 +01003476 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003477}
3478
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003479static int img_rebase(int argc, char **argv)
3480{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003481 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003482 uint8_t *buf_old = NULL;
3483 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003484 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003485 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003486 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003487 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3488 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003489 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003490 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003491 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003492 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003493 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003494 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003495 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003496
3497 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003498 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003499 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003500 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003501 out_baseimg = NULL;
3502 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003503 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003504 static const struct option long_options[] = {
3505 {"help", no_argument, 0, 'h'},
3506 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003507 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003508 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003509 {0, 0, 0, 0}
3510 };
Fam Zheng335e9932017-05-03 00:35:39 +08003511 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003512 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003513 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003514 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003515 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003516 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003517 case ':':
3518 missing_argument(argv[optind - 1]);
3519 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003520 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003521 unrecognized_option(argv[optind - 1]);
3522 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003523 case 'h':
3524 help();
3525 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003526 case 'f':
3527 fmt = optarg;
3528 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003529 case 'F':
3530 out_basefmt = optarg;
3531 break;
3532 case 'b':
3533 out_baseimg = optarg;
3534 break;
3535 case 'u':
3536 unsafe = 1;
3537 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003538 case 'p':
3539 progress = 1;
3540 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003541 case 't':
3542 cache = optarg;
3543 break;
Max Reitz40055952014-07-22 22:58:42 +02003544 case 'T':
3545 src_cache = optarg;
3546 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003547 case 'q':
3548 quiet = true;
3549 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003550 case OPTION_OBJECT: {
3551 QemuOpts *opts;
3552 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3553 optarg, true);
3554 if (!opts) {
3555 return 1;
3556 }
3557 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003558 case OPTION_IMAGE_OPTS:
3559 image_opts = true;
3560 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003561 case 'U':
3562 force_share = true;
3563 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003564 }
3565 }
3566
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003567 if (quiet) {
3568 progress = 0;
3569 }
3570
Fam Zhengac1307a2014-04-22 13:36:11 +08003571 if (optind != argc - 1) {
3572 error_exit("Expecting one image file name");
3573 }
3574 if (!unsafe && !out_baseimg) {
3575 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003576 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003577 filename = argv[optind++];
3578
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003579 if (qemu_opts_foreach(&qemu_object_opts,
3580 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003581 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003582 return 1;
3583 }
3584
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003585 qemu_progress_init(progress, 2.0);
3586 qemu_progress_print(0, 100);
3587
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003588 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003589 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003590 if (ret < 0) {
3591 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003592 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003593 }
3594
Kevin Wolfce099542016-03-15 13:01:04 +01003595 src_flags = 0;
3596 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003597 if (ret < 0) {
3598 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003599 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003600 }
3601
Kevin Wolfce099542016-03-15 13:01:04 +01003602 /* The source files are opened read-only, don't care about WCE */
3603 assert((src_flags & BDRV_O_RDWR) == 0);
3604 (void) src_writethrough;
3605
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003606 /*
3607 * Open the images.
3608 *
3609 * Ignore the old backing file for unsafe rebase in case we want to correct
3610 * the reference to a renamed or moved backing file.
3611 */
Fam Zheng335e9932017-05-03 00:35:39 +08003612 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3613 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003614 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003615 ret = -1;
3616 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003617 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003618 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003619
Max Reitz4a2061e2019-06-12 19:00:30 +02003620 unfiltered_bs = bdrv_skip_filters(bs);
3621
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003622 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003623 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003624 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003625 ret = -1;
3626 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003627 }
3628 }
3629
3630 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003631 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003632 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003633 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003634
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003635 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003636 blk_old_backing = blk_new(qemu_get_aio_context(),
3637 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003638 BLK_PERM_ALL);
3639 ret = blk_insert_bs(blk_old_backing, base_bs,
3640 &local_err);
3641 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003642 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003643 "Could not reuse old backing file '%s': ",
3644 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003645 goto out;
3646 }
3647 } else {
3648 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003649 }
Max Reitz644483d2015-02-05 13:58:17 -05003650
Alex Bligha6166732012-10-16 13:46:18 +01003651 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003652 const char *overlay_filename;
3653 char *out_real_path;
3654
Fam Zheng335e9932017-05-03 00:35:39 +08003655 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003656 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003657 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003658 }
3659 if (force_share) {
3660 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003661 }
3662
Max Reitzf30c66b2019-02-01 20:29:05 +01003663 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003664 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3665 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003666 out_real_path =
3667 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3668 out_baseimg,
3669 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003670 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003671 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003672 error_reportf_err(local_err,
3673 "Could not resolve backing filename: ");
3674 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003675 goto out;
3676 }
3677
Sam Eiderman863cc782019-05-23 19:33:36 +03003678 /*
3679 * Find out whether we rebase an image on top of a previous image
3680 * in its chain.
3681 */
3682 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003683 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003684 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003685 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003686
Kevin Wolfd861ab32019-04-25 14:25:10 +02003687 blk_new_backing = blk_new(qemu_get_aio_context(),
3688 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003689 BLK_PERM_ALL);
3690 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3691 &local_err);
3692 if (ret < 0) {
3693 error_reportf_err(local_err,
3694 "Could not reuse backing file '%s': ",
3695 out_baseimg);
3696 goto out;
3697 }
3698 } else {
3699 blk_new_backing = blk_new_open(out_real_path, NULL,
3700 options, src_flags, &local_err);
3701 g_free(out_real_path);
3702 if (!blk_new_backing) {
3703 error_reportf_err(local_err,
3704 "Could not open new backing file '%s': ",
3705 out_baseimg);
3706 ret = -1;
3707 goto out;
3708 }
Alex Bligha6166732012-10-16 13:46:18 +01003709 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003710 }
3711 }
3712
3713 /*
3714 * Check each unallocated cluster in the COW file. If it is unallocated,
3715 * accesses go to the backing file. We must therefore compare this cluster
3716 * in the old and new backing file, and if they differ we need to copy it
3717 * from the old backing file into the COW file.
3718 *
3719 * If qemu-img crashes during this step, no harm is done. The content of
3720 * the image is the same as the original one at any time.
3721 */
3722 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003723 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003724 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003725 int64_t new_backing_size = 0;
3726 uint64_t offset;
3727 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003728 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003729
Max Reitzf1d3cd72015-02-05 13:58:18 -05003730 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3731 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003732
Eric Blake41536282017-10-11 22:47:15 -05003733 size = blk_getlength(blk);
3734 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003735 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003736 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003737 ret = -1;
3738 goto out;
3739 }
Max Reitz35ddd932019-05-09 19:52:35 +02003740 if (blk_old_backing) {
3741 old_backing_size = blk_getlength(blk_old_backing);
3742 if (old_backing_size < 0) {
3743 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003744
Max Reitz35ddd932019-05-09 19:52:35 +02003745 bdrv_get_backing_filename(bs, backing_name,
3746 sizeof(backing_name));
3747 error_report("Could not get size of '%s': %s",
3748 backing_name, strerror(-old_backing_size));
3749 ret = -1;
3750 goto out;
3751 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003752 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003753 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003754 new_backing_size = blk_getlength(blk_new_backing);
3755 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003756 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003757 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003758 ret = -1;
3759 goto out;
3760 }
Alex Bligha6166732012-10-16 13:46:18 +01003761 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003762
Eric Blake41536282017-10-11 22:47:15 -05003763 if (size != 0) {
3764 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003765 }
3766
Eric Blake41536282017-10-11 22:47:15 -05003767 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003768 bool buf_old_is_zero = false;
3769
Eric Blake41536282017-10-11 22:47:15 -05003770 /* How many bytes can we handle with the next read? */
3771 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003772
3773 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003774 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003775 if (ret < 0) {
3776 error_report("error while reading image metadata: %s",
3777 strerror(-ret));
3778 goto out;
3779 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003780 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003781 continue;
3782 }
3783
Sam Eiderman863cc782019-05-23 19:33:36 +03003784 if (prefix_chain_bs) {
3785 /*
3786 * If cluster wasn't changed since prefix_chain, we don't need
3787 * to take action
3788 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003789 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3790 prefix_chain_bs, false,
3791 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003792 if (ret < 0) {
3793 error_report("error while reading image metadata: %s",
3794 strerror(-ret));
3795 goto out;
3796 }
3797 if (!ret) {
3798 continue;
3799 }
3800 }
3801
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003802 /*
3803 * Read old and new backing file and take into consideration that
3804 * backing files may be smaller than the COW image.
3805 */
Eric Blake41536282017-10-11 22:47:15 -05003806 if (offset >= old_backing_size) {
3807 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003808 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003809 } else {
Eric Blake41536282017-10-11 22:47:15 -05003810 if (offset + n > old_backing_size) {
3811 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003812 }
3813
Eric Blake41536282017-10-11 22:47:15 -05003814 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003815 if (ret < 0) {
3816 error_report("error while reading from old backing file");
3817 goto out;
3818 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003819 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003820
Eric Blake41536282017-10-11 22:47:15 -05003821 if (offset >= new_backing_size || !blk_new_backing) {
3822 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003823 } else {
Eric Blake41536282017-10-11 22:47:15 -05003824 if (offset + n > new_backing_size) {
3825 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003826 }
3827
Eric Blake41536282017-10-11 22:47:15 -05003828 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003829 if (ret < 0) {
3830 error_report("error while reading from new backing file");
3831 goto out;
3832 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003833 }
3834
3835 /* If they differ, we need to write to the COW file */
3836 uint64_t written = 0;
3837
Eric Blake41536282017-10-11 22:47:15 -05003838 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003839 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003840
Eric Blake41536282017-10-11 22:47:15 -05003841 if (compare_buffers(buf_old + written, buf_new + written,
3842 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003843 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003844 if (buf_old_is_zero) {
3845 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3846 } else {
3847 ret = blk_pwrite(blk, offset + written,
3848 buf_old + written, pnum, 0);
3849 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003850 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003851 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003852 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003853 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003854 }
3855 }
3856
3857 written += pnum;
3858 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003859 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003860 }
3861 }
3862
3863 /*
3864 * Change the backing file. All clusters that are different from the old
3865 * backing file are overwritten in the COW file now, so the visible content
3866 * doesn't change when we switch the backing file.
3867 */
Alex Bligha6166732012-10-16 13:46:18 +01003868 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003869 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3870 true);
Alex Bligha6166732012-10-16 13:46:18 +01003871 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003872 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003873 }
3874
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003875 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003876 error_report("Could not change the backing file to '%s': No "
3877 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003878 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003879 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003880 out_baseimg, strerror(-ret));
3881 }
3882
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003883 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003884 /*
3885 * TODO At this point it is possible to check if any clusters that are
3886 * allocated in the COW file are the same in the backing file. If so, they
3887 * could be dropped from the COW file. Don't do this before switching the
3888 * backing file, in case of a crash this would lead to corruption.
3889 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003890out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003891 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003892 /* Cleanup */
3893 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003894 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003895 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003896 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003897 qemu_vfree(buf_old);
3898 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003899
Markus Armbruster26f54e92014-10-07 13:59:04 +02003900 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003901 if (ret) {
3902 return 1;
3903 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003904 return 0;
3905}
3906
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003907static int img_resize(int argc, char **argv)
3908{
Markus Armbruster6750e792015-02-12 17:43:08 +01003909 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003910 int c, ret, relative;
3911 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003912 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003913 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003914 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003915 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003916 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003917
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003918 static QemuOptsList resize_options = {
3919 .name = "resize_options",
3920 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3921 .desc = {
3922 {
3923 .name = BLOCK_OPT_SIZE,
3924 .type = QEMU_OPT_SIZE,
3925 .help = "Virtual disk size"
3926 }, {
3927 /* end of list */
3928 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003929 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003930 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003931 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003932 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003933
Kevin Wolfe80fec72011-04-29 10:58:12 +02003934 /* Remove size from argv manually so that negative numbers are not treated
3935 * as options by getopt. */
3936 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003937 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003938 return 1;
3939 }
3940
3941 size = argv[--argc];
3942
3943 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003944 fmt = NULL;
3945 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003946 static const struct option long_options[] = {
3947 {"help", no_argument, 0, 'h'},
3948 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003949 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003950 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003951 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003952 {0, 0, 0, 0}
3953 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003954 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003955 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003956 if (c == -1) {
3957 break;
3958 }
3959 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003960 case ':':
3961 missing_argument(argv[optind - 1]);
3962 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003963 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003964 unrecognized_option(argv[optind - 1]);
3965 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003966 case 'h':
3967 help();
3968 break;
3969 case 'f':
3970 fmt = optarg;
3971 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003972 case 'q':
3973 quiet = true;
3974 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003975 case OPTION_OBJECT: {
3976 QemuOpts *opts;
3977 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3978 optarg, true);
3979 if (!opts) {
3980 return 1;
3981 }
3982 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003983 case OPTION_IMAGE_OPTS:
3984 image_opts = true;
3985 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003986 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003987 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003988 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003989 if (prealloc == PREALLOC_MODE__MAX) {
3990 error_report("Invalid preallocation mode '%s'", optarg);
3991 return 1;
3992 }
3993 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003994 case OPTION_SHRINK:
3995 shrink = true;
3996 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003997 }
3998 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003999 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01004000 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004001 }
4002 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004003
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004004 if (qemu_opts_foreach(&qemu_object_opts,
4005 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004006 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004007 return 1;
4008 }
4009
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004010 /* Choose grow, shrink, or absolute resize mode */
4011 switch (size[0]) {
4012 case '+':
4013 relative = 1;
4014 size++;
4015 break;
4016 case '-':
4017 relative = -1;
4018 size++;
4019 break;
4020 default:
4021 relative = 0;
4022 break;
4023 }
4024
4025 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08004026 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004027 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01004028 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01004029 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004030 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01004031 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004032 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004033 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
4034 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004035
Max Reitzefaa7c42016-03-16 19:54:38 +01004036 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08004037 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4038 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004039 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01004040 ret = -1;
4041 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004042 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004043
Max Reitzdc5f6902017-06-13 22:20:55 +02004044 current_size = blk_getlength(blk);
4045 if (current_size < 0) {
4046 error_report("Failed to inquire current image length: %s",
4047 strerror(-current_size));
4048 ret = -1;
4049 goto out;
4050 }
4051
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004052 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004053 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004054 } else {
4055 total_size = n;
4056 }
4057 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004058 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004059 ret = -1;
4060 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004061 }
4062
Max Reitzdc5f6902017-06-13 22:20:55 +02004063 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4064 error_report("Preallocation can only be used for growing images");
4065 ret = -1;
4066 goto out;
4067 }
4068
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004069 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004070 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004071 warn_report("Shrinking an image will delete all data beyond the "
4072 "shrunken image's end. Before performing such an "
4073 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004074 ret = -1;
4075 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004076 }
4077
Max Reitze8d04f92019-09-18 11:51:43 +02004078 /*
4079 * The user expects the image to have the desired size after
4080 * resizing, so pass @exact=true. It is of no use to report
4081 * success when the image has not actually been resized.
4082 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004083 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004084 if (!ret) {
4085 qprintf(quiet, "Image resized.\n");
4086 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004087 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004088 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004089out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004090 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004091 if (ret) {
4092 return 1;
4093 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004094 return 0;
4095}
4096
Max Reitz76a3a342014-10-27 11:12:51 +01004097static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004098 int64_t offset, int64_t total_work_size,
4099 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004100{
4101 qemu_progress_print(100.f * offset / total_work_size, 0);
4102}
4103
Max Reitz51641352018-05-09 23:00:20 +02004104static int print_amend_option_help(const char *format)
4105{
4106 BlockDriver *drv;
4107
4108 /* Find driver and parse its options */
4109 drv = bdrv_find_format(format);
4110 if (!drv) {
4111 error_report("Unknown file format '%s'", format);
4112 return 1;
4113 }
4114
4115 if (!drv->bdrv_amend_options) {
4116 error_report("Format driver '%s' does not support option amendment",
4117 format);
4118 return 1;
4119 }
4120
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004121 /* Every driver supporting amendment must have amend_opts */
4122 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004123
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004124 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004125 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004126 return 0;
4127}
4128
Max Reitz6f176b42013-09-03 10:09:50 +02004129static int img_amend(int argc, char **argv)
4130{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004131 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004132 int c, ret = 0;
4133 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004134 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004135 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004136 const char *fmt = NULL, *filename, *cache;
4137 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004138 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004139 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004140 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004141 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004142 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004143 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004144
Max Reitzbd39e6e2014-07-22 22:58:43 +02004145 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004146 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004147 static const struct option long_options[] = {
4148 {"help", no_argument, 0, 'h'},
4149 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004150 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004151 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004152 {0, 0, 0, 0}
4153 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004154 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004155 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004156 if (c == -1) {
4157 break;
4158 }
4159
4160 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004161 case ':':
4162 missing_argument(argv[optind - 1]);
4163 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004164 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004165 unrecognized_option(argv[optind - 1]);
4166 break;
4167 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004168 help();
4169 break;
4170 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004171 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004172 ret = -1;
4173 goto out_no_progress;
4174 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004175 break;
4176 case 'f':
4177 fmt = optarg;
4178 break;
4179 case 't':
4180 cache = optarg;
4181 break;
4182 case 'p':
4183 progress = true;
4184 break;
4185 case 'q':
4186 quiet = true;
4187 break;
4188 case OPTION_OBJECT:
4189 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4190 optarg, true);
4191 if (!opts) {
4192 ret = -1;
4193 goto out_no_progress;
4194 }
4195 break;
4196 case OPTION_IMAGE_OPTS:
4197 image_opts = true;
4198 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004199 case OPTION_FORCE:
4200 force = true;
4201 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004202 }
4203 }
4204
Max Reitz6f176b42013-09-03 10:09:50 +02004205 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004206 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004207 }
4208
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004209 if (qemu_opts_foreach(&qemu_object_opts,
4210 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004211 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004212 ret = -1;
4213 goto out_no_progress;
4214 }
4215
Max Reitz76a3a342014-10-27 11:12:51 +01004216 if (quiet) {
4217 progress = false;
4218 }
4219 qemu_progress_init(progress, 1.0);
4220
Kevin Wolfa283cb62014-02-21 16:24:07 +01004221 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4222 if (fmt && has_help_option(options)) {
4223 /* If a format is explicitly specified (and possibly no filename is
4224 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004225 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004226 goto out;
4227 }
4228
4229 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004230 error_report("Expecting one image file name");
4231 ret = -1;
4232 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004233 }
Max Reitz6f176b42013-09-03 10:09:50 +02004234
Kevin Wolfce099542016-03-15 13:01:04 +01004235 flags = BDRV_O_RDWR;
4236 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004237 if (ret < 0) {
4238 error_report("Invalid cache option: %s", cache);
4239 goto out;
4240 }
4241
Fam Zheng335e9932017-05-03 00:35:39 +08004242 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4243 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004244 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004245 ret = -1;
4246 goto out;
4247 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004248 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004249
4250 fmt = bs->drv->format_name;
4251
Kevin Wolf626f84f2014-02-21 16:24:06 +01004252 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004253 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004254 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004255 goto out;
4256 }
4257
Max Reitz1f996682018-05-09 23:00:17 +02004258 if (!bs->drv->bdrv_amend_options) {
4259 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004260 fmt);
4261 ret = -1;
4262 goto out;
4263 }
4264
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004265 /* Every driver supporting amendment must have amend_opts */
4266 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004267
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004268 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4269 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004270 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004271 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004272 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4273 qemu_opts_del(opts);
4274 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004275 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004276 error_append_hint(&err,
4277 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004278 }
4279
Paolo Bonziniece90862017-01-04 15:56:24 +01004280 error_report_err(err);
4281 ret = -1;
4282 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004283 }
4284
Max Reitz76a3a342014-10-27 11:12:51 +01004285 /* In case the driver does not call amend_status_cb() */
4286 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004287 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004288 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004289 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004290 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004291 goto out;
4292 }
4293
4294out:
Max Reitz76a3a342014-10-27 11:12:51 +01004295 qemu_progress_end();
4296
Max Reitze814dff2015-08-20 16:00:38 -07004297out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004298 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004299 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004300 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004301 g_free(options);
4302
Max Reitz6f176b42013-09-03 10:09:50 +02004303 if (ret) {
4304 return 1;
4305 }
4306 return 0;
4307}
4308
Kevin Wolfb6133b82014-08-05 14:17:13 +02004309typedef struct BenchData {
4310 BlockBackend *blk;
4311 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004312 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004313 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004314 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004315 int nrreq;
4316 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004317 int flush_interval;
4318 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004319 uint8_t *buf;
4320 QEMUIOVector *qiov;
4321
4322 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004323 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004324 uint64_t offset;
4325} BenchData;
4326
Kevin Wolf55d539c2016-06-03 13:59:41 +02004327static void bench_undrained_flush_cb(void *opaque, int ret)
4328{
4329 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004330 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004331 exit(EXIT_FAILURE);
4332 }
4333}
4334
Kevin Wolfb6133b82014-08-05 14:17:13 +02004335static void bench_cb(void *opaque, int ret)
4336{
4337 BenchData *b = opaque;
4338 BlockAIOCB *acb;
4339
4340 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004341 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004342 exit(EXIT_FAILURE);
4343 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004344
4345 if (b->in_flush) {
4346 /* Just finished a flush with drained queue: Start next requests */
4347 assert(b->in_flight == 0);
4348 b->in_flush = false;
4349 } else if (b->in_flight > 0) {
4350 int remaining = b->n - b->in_flight;
4351
Kevin Wolfb6133b82014-08-05 14:17:13 +02004352 b->n--;
4353 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004354
4355 /* Time for flush? Drain queue if requested, then flush */
4356 if (b->flush_interval && remaining % b->flush_interval == 0) {
4357 if (!b->in_flight || !b->drain_on_flush) {
4358 BlockCompletionFunc *cb;
4359
4360 if (b->drain_on_flush) {
4361 b->in_flush = true;
4362 cb = bench_cb;
4363 } else {
4364 cb = bench_undrained_flush_cb;
4365 }
4366
4367 acb = blk_aio_flush(b->blk, cb, b);
4368 if (!acb) {
4369 error_report("Failed to issue flush request");
4370 exit(EXIT_FAILURE);
4371 }
4372 }
4373 if (b->drain_on_flush) {
4374 return;
4375 }
4376 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004377 }
4378
4379 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004380 int64_t offset = b->offset;
4381 /* blk_aio_* might look for completed I/Os and kick bench_cb
4382 * again, so make sure this operation is counted by in_flight
4383 * and b->offset is ready for the next submission.
4384 */
4385 b->in_flight++;
4386 b->offset += b->step;
4387 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004388 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004389 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004390 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004391 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004392 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004393 if (!acb) {
4394 error_report("Failed to issue request");
4395 exit(EXIT_FAILURE);
4396 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004397 }
4398}
4399
4400static int img_bench(int argc, char **argv)
4401{
4402 int c, ret = 0;
4403 const char *fmt = NULL, *filename;
4404 bool quiet = false;
4405 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004406 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004407 int count = 75000;
4408 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004409 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004410 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004411 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004412 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004413 int flush_interval = 0;
4414 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004415 int64_t image_size;
4416 BlockBackend *blk = NULL;
4417 BenchData data = {};
4418 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004419 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004420 struct timeval t1, t2;
4421 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004422 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004423 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004424
4425 for (;;) {
4426 static const struct option long_options[] = {
4427 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004428 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004429 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004430 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004431 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004432 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004433 {0, 0, 0, 0}
4434 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004435 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4436 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004437 if (c == -1) {
4438 break;
4439 }
4440
4441 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004442 case ':':
4443 missing_argument(argv[optind - 1]);
4444 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004445 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004446 unrecognized_option(argv[optind - 1]);
4447 break;
4448 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004449 help();
4450 break;
4451 case 'c':
4452 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004453 unsigned long res;
4454
4455 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004456 error_report("Invalid request count specified");
4457 return 1;
4458 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004459 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004460 break;
4461 }
4462 case 'd':
4463 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004464 unsigned long res;
4465
4466 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004467 error_report("Invalid queue depth specified");
4468 return 1;
4469 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004470 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004471 break;
4472 }
4473 case 'f':
4474 fmt = optarg;
4475 break;
4476 case 'n':
4477 flags |= BDRV_O_NATIVE_AIO;
4478 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004479 case 'i':
4480 ret = bdrv_parse_aio(optarg, &flags);
4481 if (ret < 0) {
4482 error_report("Invalid aio option: %s", optarg);
4483 ret = -1;
4484 goto out;
4485 }
4486 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004487 case 'o':
4488 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004489 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004490 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004491 return 1;
4492 }
4493 break;
4494 }
4495 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004496 case 'q':
4497 quiet = true;
4498 break;
4499 case 's':
4500 {
4501 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004502
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004503 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4504 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004505 return 1;
4506 }
4507
4508 bufsize = sval;
4509 break;
4510 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004511 case 'S':
4512 {
4513 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004514
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004515 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4516 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004517 return 1;
4518 }
4519
4520 step = sval;
4521 break;
4522 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004523 case 't':
4524 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4525 if (ret < 0) {
4526 error_report("Invalid cache mode");
4527 ret = -1;
4528 goto out;
4529 }
4530 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004531 case 'w':
4532 flags |= BDRV_O_RDWR;
4533 is_write = true;
4534 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004535 case 'U':
4536 force_share = true;
4537 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004538 case OPTION_PATTERN:
4539 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004540 unsigned long res;
4541
4542 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004543 error_report("Invalid pattern byte specified");
4544 return 1;
4545 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004546 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004547 break;
4548 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004549 case OPTION_FLUSH_INTERVAL:
4550 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004551 unsigned long res;
4552
4553 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004554 error_report("Invalid flush interval specified");
4555 return 1;
4556 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004557 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004558 break;
4559 }
4560 case OPTION_NO_DRAIN:
4561 drain_on_flush = false;
4562 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004563 case OPTION_IMAGE_OPTS:
4564 image_opts = true;
4565 break;
4566 }
4567 }
4568
4569 if (optind != argc - 1) {
4570 error_exit("Expecting one image file name");
4571 }
4572 filename = argv[argc - 1];
4573
Kevin Wolf55d539c2016-06-03 13:59:41 +02004574 if (!is_write && flush_interval) {
4575 error_report("--flush-interval is only available in write tests");
4576 ret = -1;
4577 goto out;
4578 }
4579 if (flush_interval && flush_interval < depth) {
4580 error_report("Flush interval can't be smaller than depth");
4581 ret = -1;
4582 goto out;
4583 }
4584
Fam Zheng335e9932017-05-03 00:35:39 +08004585 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4586 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004587 if (!blk) {
4588 ret = -1;
4589 goto out;
4590 }
4591
4592 image_size = blk_getlength(blk);
4593 if (image_size < 0) {
4594 ret = image_size;
4595 goto out;
4596 }
4597
4598 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004599 .blk = blk,
4600 .image_size = image_size,
4601 .bufsize = bufsize,
4602 .step = step ?: bufsize,
4603 .nrreq = depth,
4604 .n = count,
4605 .offset = offset,
4606 .write = is_write,
4607 .flush_interval = flush_interval,
4608 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004609 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004610 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004611 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004612 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004613 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004614 if (flush_interval) {
4615 printf("Sending flush every %d requests\n", flush_interval);
4616 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004617
Fam Zheng79d46582018-01-16 14:08:58 +08004618 buf_size = data.nrreq * data.bufsize;
4619 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004620 memset(data.buf, pattern, data.nrreq * data.bufsize);
4621
Fam Zheng79d46582018-01-16 14:08:58 +08004622 blk_register_buf(blk, data.buf, buf_size);
4623
Kevin Wolfb6133b82014-08-05 14:17:13 +02004624 data.qiov = g_new(QEMUIOVector, data.nrreq);
4625 for (i = 0; i < data.nrreq; i++) {
4626 qemu_iovec_init(&data.qiov[i], 1);
4627 qemu_iovec_add(&data.qiov[i],
4628 data.buf + i * data.bufsize, data.bufsize);
4629 }
4630
4631 gettimeofday(&t1, NULL);
4632 bench_cb(&data, 0);
4633
4634 while (data.n > 0) {
4635 main_loop_wait(false);
4636 }
4637 gettimeofday(&t2, NULL);
4638
4639 printf("Run completed in %3.3f seconds.\n",
4640 (t2.tv_sec - t1.tv_sec)
4641 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4642
4643out:
Fam Zheng79d46582018-01-16 14:08:58 +08004644 if (data.buf) {
4645 blk_unregister_buf(blk, data.buf);
4646 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004647 qemu_vfree(data.buf);
4648 blk_unref(blk);
4649
4650 if (ret) {
4651 return 1;
4652 }
4653 return 0;
4654}
4655
Eric Blake3b51ab42020-05-12 20:16:45 -05004656enum ImgBitmapAct {
4657 BITMAP_ADD,
4658 BITMAP_REMOVE,
4659 BITMAP_CLEAR,
4660 BITMAP_ENABLE,
4661 BITMAP_DISABLE,
4662 BITMAP_MERGE,
4663};
4664typedef struct ImgBitmapAction {
4665 enum ImgBitmapAct act;
4666 const char *src; /* only used for merge */
4667 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4668} ImgBitmapAction;
4669
4670static int img_bitmap(int argc, char **argv)
4671{
4672 Error *err = NULL;
4673 int c, ret = 1;
4674 QemuOpts *opts = NULL;
4675 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4676 const char *filename, *bitmap;
4677 BlockBackend *blk = NULL, *src = NULL;
4678 BlockDriverState *bs = NULL, *src_bs = NULL;
4679 bool image_opts = false;
4680 int64_t granularity = 0;
4681 bool add = false, merge = false;
4682 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4683 ImgBitmapAction *act, *act_next;
4684 const char *op;
4685
4686 QSIMPLEQ_INIT(&actions);
4687
4688 for (;;) {
4689 static const struct option long_options[] = {
4690 {"help", no_argument, 0, 'h'},
4691 {"object", required_argument, 0, OPTION_OBJECT},
4692 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4693 {"add", no_argument, 0, OPTION_ADD},
4694 {"remove", no_argument, 0, OPTION_REMOVE},
4695 {"clear", no_argument, 0, OPTION_CLEAR},
4696 {"enable", no_argument, 0, OPTION_ENABLE},
4697 {"disable", no_argument, 0, OPTION_DISABLE},
4698 {"merge", required_argument, 0, OPTION_MERGE},
4699 {"granularity", required_argument, 0, 'g'},
4700 {"source-file", required_argument, 0, 'b'},
4701 {"source-format", required_argument, 0, 'F'},
4702 {0, 0, 0, 0}
4703 };
4704 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4705 if (c == -1) {
4706 break;
4707 }
4708
4709 switch (c) {
4710 case ':':
4711 missing_argument(argv[optind - 1]);
4712 break;
4713 case '?':
4714 unrecognized_option(argv[optind - 1]);
4715 break;
4716 case 'h':
4717 help();
4718 break;
4719 case 'b':
4720 src_filename = optarg;
4721 break;
4722 case 'f':
4723 fmt = optarg;
4724 break;
4725 case 'F':
4726 src_fmt = optarg;
4727 break;
4728 case 'g':
4729 granularity = cvtnum("granularity", optarg);
4730 if (granularity < 0) {
4731 return 1;
4732 }
4733 break;
4734 case OPTION_ADD:
4735 act = g_new0(ImgBitmapAction, 1);
4736 act->act = BITMAP_ADD;
4737 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4738 add = true;
4739 break;
4740 case OPTION_REMOVE:
4741 act = g_new0(ImgBitmapAction, 1);
4742 act->act = BITMAP_REMOVE;
4743 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4744 break;
4745 case OPTION_CLEAR:
4746 act = g_new0(ImgBitmapAction, 1);
4747 act->act = BITMAP_CLEAR;
4748 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4749 break;
4750 case OPTION_ENABLE:
4751 act = g_new0(ImgBitmapAction, 1);
4752 act->act = BITMAP_ENABLE;
4753 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4754 break;
4755 case OPTION_DISABLE:
4756 act = g_new0(ImgBitmapAction, 1);
4757 act->act = BITMAP_DISABLE;
4758 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4759 break;
4760 case OPTION_MERGE:
4761 act = g_new0(ImgBitmapAction, 1);
4762 act->act = BITMAP_MERGE;
4763 act->src = optarg;
4764 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4765 merge = true;
4766 break;
4767 case OPTION_OBJECT:
4768 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4769 if (!opts) {
4770 goto out;
4771 }
4772 break;
4773 case OPTION_IMAGE_OPTS:
4774 image_opts = true;
4775 break;
4776 }
4777 }
4778
4779 if (qemu_opts_foreach(&qemu_object_opts,
4780 user_creatable_add_opts_foreach,
4781 qemu_img_object_print_help, &error_fatal)) {
4782 goto out;
4783 }
4784
4785 if (QSIMPLEQ_EMPTY(&actions)) {
4786 error_report("Need at least one of --add, --remove, --clear, "
4787 "--enable, --disable, or --merge");
4788 goto out;
4789 }
4790
4791 if (granularity && !add) {
4792 error_report("granularity only supported with --add");
4793 goto out;
4794 }
4795 if (src_fmt && !src_filename) {
4796 error_report("-F only supported with -b");
4797 goto out;
4798 }
4799 if (src_filename && !merge) {
4800 error_report("Merge bitmap source file only supported with "
4801 "--merge");
4802 goto out;
4803 }
4804
4805 if (optind != argc - 2) {
4806 error_report("Expecting filename and bitmap name");
4807 goto out;
4808 }
4809
4810 filename = argv[optind];
4811 bitmap = argv[optind + 1];
4812
Eric Blake14f16bf2020-09-14 14:10:09 -05004813 /*
4814 * No need to open backing chains; we will be manipulating bitmaps
4815 * directly in this image without reference to image contents.
4816 */
4817 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4818 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004819 if (!blk) {
4820 goto out;
4821 }
4822 bs = blk_bs(blk);
4823 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004824 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4825 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004826 if (!src) {
4827 goto out;
4828 }
4829 src_bs = blk_bs(src);
4830 } else {
4831 src_bs = bs;
4832 }
4833
4834 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4835 switch (act->act) {
4836 case BITMAP_ADD:
4837 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4838 !!granularity, granularity, true, true,
4839 false, false, &err);
4840 op = "add";
4841 break;
4842 case BITMAP_REMOVE:
4843 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4844 op = "remove";
4845 break;
4846 case BITMAP_CLEAR:
4847 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4848 op = "clear";
4849 break;
4850 case BITMAP_ENABLE:
4851 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4852 op = "enable";
4853 break;
4854 case BITMAP_DISABLE:
4855 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4856 op = "disable";
4857 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004858 case BITMAP_MERGE:
4859 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4860 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004861 op = "merge";
4862 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004863 default:
4864 g_assert_not_reached();
4865 }
4866
4867 if (err) {
4868 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4869 op, bitmap);
4870 goto out;
4871 }
4872 g_free(act);
4873 }
4874
4875 ret = 0;
4876
4877 out:
4878 blk_unref(src);
4879 blk_unref(blk);
4880 qemu_opts_del(opts);
4881 return ret;
4882}
4883
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004884#define C_BS 01
4885#define C_COUNT 02
4886#define C_IF 04
4887#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004888#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004889
4890struct DdInfo {
4891 unsigned int flags;
4892 int64_t count;
4893};
4894
4895struct DdIo {
4896 int bsz; /* Block size */
4897 char *filename;
4898 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004899 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004900};
4901
4902struct DdOpts {
4903 const char *name;
4904 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4905 unsigned int flag;
4906};
4907
4908static int img_dd_bs(const char *arg,
4909 struct DdIo *in, struct DdIo *out,
4910 struct DdInfo *dd)
4911{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004912 int64_t res;
4913
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004914 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004915
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004916 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004917 return 1;
4918 }
4919 in->bsz = out->bsz = res;
4920
4921 return 0;
4922}
4923
4924static int img_dd_count(const char *arg,
4925 struct DdIo *in, struct DdIo *out,
4926 struct DdInfo *dd)
4927{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004928 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004929
Markus Armbruster606caa02017-02-21 21:14:04 +01004930 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004931 return 1;
4932 }
4933
4934 return 0;
4935}
4936
4937static int img_dd_if(const char *arg,
4938 struct DdIo *in, struct DdIo *out,
4939 struct DdInfo *dd)
4940{
4941 in->filename = g_strdup(arg);
4942
4943 return 0;
4944}
4945
4946static int img_dd_of(const char *arg,
4947 struct DdIo *in, struct DdIo *out,
4948 struct DdInfo *dd)
4949{
4950 out->filename = g_strdup(arg);
4951
4952 return 0;
4953}
4954
Reda Sallahif7c15532016-08-10 16:16:09 +02004955static int img_dd_skip(const char *arg,
4956 struct DdIo *in, struct DdIo *out,
4957 struct DdInfo *dd)
4958{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004959 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004960
Markus Armbruster606caa02017-02-21 21:14:04 +01004961 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004962 return 1;
4963 }
4964
4965 return 0;
4966}
4967
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004968static int img_dd(int argc, char **argv)
4969{
4970 int ret = 0;
4971 char *arg = NULL;
4972 char *tmp;
4973 BlockDriver *drv = NULL, *proto_drv = NULL;
4974 BlockBackend *blk1 = NULL, *blk2 = NULL;
4975 QemuOpts *opts = NULL;
4976 QemuOptsList *create_opts = NULL;
4977 Error *local_err = NULL;
4978 bool image_opts = false;
4979 int c, i;
4980 const char *out_fmt = "raw";
4981 const char *fmt = NULL;
4982 int64_t size = 0;
4983 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004984 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004985 struct DdInfo dd = {
4986 .flags = 0,
4987 .count = 0,
4988 };
4989 struct DdIo in = {
4990 .bsz = 512, /* Block size is by default 512 bytes */
4991 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004992 .buf = NULL,
4993 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004994 };
4995 struct DdIo out = {
4996 .bsz = 512,
4997 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004998 .buf = NULL,
4999 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005000 };
5001
5002 const struct DdOpts options[] = {
5003 { "bs", img_dd_bs, C_BS },
5004 { "count", img_dd_count, C_COUNT },
5005 { "if", img_dd_if, C_IF },
5006 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02005007 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005008 { NULL, NULL, 0 }
5009 };
5010 const struct option long_options[] = {
5011 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005012 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005013 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08005014 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005015 { 0, 0, 0, 0 }
5016 };
5017
Fam Zheng335e9932017-05-03 00:35:39 +08005018 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005019 if (c == EOF) {
5020 break;
5021 }
5022 switch (c) {
5023 case 'O':
5024 out_fmt = optarg;
5025 break;
5026 case 'f':
5027 fmt = optarg;
5028 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005029 case ':':
5030 missing_argument(argv[optind - 1]);
5031 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005032 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005033 unrecognized_option(argv[optind - 1]);
5034 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005035 case 'h':
5036 help();
5037 break;
Fam Zheng335e9932017-05-03 00:35:39 +08005038 case 'U':
5039 force_share = true;
5040 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005041 case OPTION_OBJECT:
5042 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005043 ret = -1;
5044 goto out;
5045 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005046 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005047 case OPTION_IMAGE_OPTS:
5048 image_opts = true;
5049 break;
5050 }
5051 }
5052
5053 for (i = optind; i < argc; i++) {
5054 int j;
5055 arg = g_strdup(argv[i]);
5056
5057 tmp = strchr(arg, '=');
5058 if (tmp == NULL) {
5059 error_report("unrecognized operand %s", arg);
5060 ret = -1;
5061 goto out;
5062 }
5063
5064 *tmp++ = '\0';
5065
5066 for (j = 0; options[j].name != NULL; j++) {
5067 if (!strcmp(arg, options[j].name)) {
5068 break;
5069 }
5070 }
5071 if (options[j].name == NULL) {
5072 error_report("unrecognized operand %s", arg);
5073 ret = -1;
5074 goto out;
5075 }
5076
5077 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5078 ret = -1;
5079 goto out;
5080 }
5081 dd.flags |= options[j].flag;
5082 g_free(arg);
5083 arg = NULL;
5084 }
5085
5086 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5087 error_report("Must specify both input and output files");
5088 ret = -1;
5089 goto out;
5090 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005091
5092 if (qemu_opts_foreach(&qemu_object_opts,
5093 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005094 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005095 ret = -1;
5096 goto out;
5097 }
5098
Fam Zheng335e9932017-05-03 00:35:39 +08005099 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5100 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005101
5102 if (!blk1) {
5103 ret = -1;
5104 goto out;
5105 }
5106
5107 drv = bdrv_find_format(out_fmt);
5108 if (!drv) {
5109 error_report("Unknown file format");
5110 ret = -1;
5111 goto out;
5112 }
5113 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5114
5115 if (!proto_drv) {
5116 error_report_err(local_err);
5117 ret = -1;
5118 goto out;
5119 }
5120 if (!drv->create_opts) {
5121 error_report("Format driver '%s' does not support image creation",
5122 drv->format_name);
5123 ret = -1;
5124 goto out;
5125 }
5126 if (!proto_drv->create_opts) {
5127 error_report("Protocol driver '%s' does not support image creation",
5128 proto_drv->format_name);
5129 ret = -1;
5130 goto out;
5131 }
5132 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5133 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5134
5135 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5136
5137 size = blk_getlength(blk1);
5138 if (size < 0) {
5139 error_report("Failed to get size for '%s'", in.filename);
5140 ret = -1;
5141 goto out;
5142 }
5143
5144 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5145 dd.count * in.bsz < size) {
5146 size = dd.count * in.bsz;
5147 }
5148
Reda Sallahif7c15532016-08-10 16:16:09 +02005149 /* Overflow means the specified offset is beyond input image's size */
5150 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5151 size < in.bsz * in.offset)) {
5152 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5153 } else {
5154 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5155 size - in.bsz * in.offset, &error_abort);
5156 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005157
5158 ret = bdrv_create(drv, out.filename, opts, &local_err);
5159 if (ret < 0) {
5160 error_reportf_err(local_err,
5161 "%s: error while creating output image: ",
5162 out.filename);
5163 ret = -1;
5164 goto out;
5165 }
5166
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005167 /* TODO, we can't honour --image-opts for the target,
5168 * since it needs to be given in a format compatible
5169 * with the bdrv_create() call above which does not
5170 * support image-opts style.
5171 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005172 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005173 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005174
5175 if (!blk2) {
5176 ret = -1;
5177 goto out;
5178 }
5179
Reda Sallahif7c15532016-08-10 16:16:09 +02005180 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5181 size < in.offset * in.bsz)) {
5182 /* We give a warning if the skip option is bigger than the input
5183 * size and create an empty output disk image (i.e. like dd(1)).
5184 */
5185 error_report("%s: cannot skip to specified offset", in.filename);
5186 in_pos = size;
5187 } else {
5188 in_pos = in.offset * in.bsz;
5189 }
5190
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005191 in.buf = g_new(uint8_t, in.bsz);
5192
Reda Sallahif7c15532016-08-10 16:16:09 +02005193 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005194 int in_ret, out_ret;
5195
5196 if (in_pos + in.bsz > size) {
5197 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5198 } else {
5199 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5200 }
5201 if (in_ret < 0) {
5202 error_report("error while reading from input image file: %s",
5203 strerror(-in_ret));
5204 ret = -1;
5205 goto out;
5206 }
5207 in_pos += in_ret;
5208
5209 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5210
5211 if (out_ret < 0) {
5212 error_report("error while writing to output image file: %s",
5213 strerror(-out_ret));
5214 ret = -1;
5215 goto out;
5216 }
5217 out_pos += out_ret;
5218 }
5219
5220out:
5221 g_free(arg);
5222 qemu_opts_del(opts);
5223 qemu_opts_free(create_opts);
5224 blk_unref(blk1);
5225 blk_unref(blk2);
5226 g_free(in.filename);
5227 g_free(out.filename);
5228 g_free(in.buf);
5229 g_free(out.buf);
5230
5231 if (ret) {
5232 return 1;
5233 }
5234 return 0;
5235}
5236
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005237static void dump_json_block_measure_info(BlockMeasureInfo *info)
5238{
5239 QString *str;
5240 QObject *obj;
5241 Visitor *v = qobject_output_visitor_new(&obj);
5242
5243 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5244 visit_complete(v, &obj);
5245 str = qobject_to_json_pretty(obj);
5246 assert(str != NULL);
5247 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005248 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005249 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005250 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005251}
5252
5253static int img_measure(int argc, char **argv)
5254{
5255 static const struct option long_options[] = {
5256 {"help", no_argument, 0, 'h'},
5257 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5258 {"object", required_argument, 0, OPTION_OBJECT},
5259 {"output", required_argument, 0, OPTION_OUTPUT},
5260 {"size", required_argument, 0, OPTION_SIZE},
5261 {"force-share", no_argument, 0, 'U'},
5262 {0, 0, 0, 0}
5263 };
5264 OutputFormat output_format = OFORMAT_HUMAN;
5265 BlockBackend *in_blk = NULL;
5266 BlockDriver *drv;
5267 const char *filename = NULL;
5268 const char *fmt = NULL;
5269 const char *out_fmt = "raw";
5270 char *options = NULL;
5271 char *snapshot_name = NULL;
5272 bool force_share = false;
5273 QemuOpts *opts = NULL;
5274 QemuOpts *object_opts = NULL;
5275 QemuOpts *sn_opts = NULL;
5276 QemuOptsList *create_opts = NULL;
5277 bool image_opts = false;
5278 uint64_t img_size = UINT64_MAX;
5279 BlockMeasureInfo *info = NULL;
5280 Error *local_err = NULL;
5281 int ret = 1;
5282 int c;
5283
5284 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5285 long_options, NULL)) != -1) {
5286 switch (c) {
5287 case '?':
5288 case 'h':
5289 help();
5290 break;
5291 case 'f':
5292 fmt = optarg;
5293 break;
5294 case 'O':
5295 out_fmt = optarg;
5296 break;
5297 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005298 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005299 goto out;
5300 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005301 break;
5302 case 'l':
5303 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5304 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5305 optarg, false);
5306 if (!sn_opts) {
5307 error_report("Failed in parsing snapshot param '%s'",
5308 optarg);
5309 goto out;
5310 }
5311 } else {
5312 snapshot_name = optarg;
5313 }
5314 break;
5315 case 'U':
5316 force_share = true;
5317 break;
5318 case OPTION_OBJECT:
5319 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5320 optarg, true);
5321 if (!object_opts) {
5322 goto out;
5323 }
5324 break;
5325 case OPTION_IMAGE_OPTS:
5326 image_opts = true;
5327 break;
5328 case OPTION_OUTPUT:
5329 if (!strcmp(optarg, "json")) {
5330 output_format = OFORMAT_JSON;
5331 } else if (!strcmp(optarg, "human")) {
5332 output_format = OFORMAT_HUMAN;
5333 } else {
5334 error_report("--output must be used with human or json "
5335 "as argument.");
5336 goto out;
5337 }
5338 break;
5339 case OPTION_SIZE:
5340 {
5341 int64_t sval;
5342
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005343 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005344 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005345 goto out;
5346 }
5347 img_size = (uint64_t)sval;
5348 }
5349 break;
5350 }
5351 }
5352
5353 if (qemu_opts_foreach(&qemu_object_opts,
5354 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005355 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005356 goto out;
5357 }
5358
5359 if (argc - optind > 1) {
5360 error_report("At most one filename argument is allowed.");
5361 goto out;
5362 } else if (argc - optind == 1) {
5363 filename = argv[optind];
5364 }
5365
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005366 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5367 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005368 goto out;
5369 }
5370 if (filename && img_size != UINT64_MAX) {
5371 error_report("--size N cannot be used together with a filename.");
5372 goto out;
5373 }
5374 if (!filename && img_size == UINT64_MAX) {
5375 error_report("Either --size N or one filename must be specified.");
5376 goto out;
5377 }
5378
5379 if (filename) {
5380 in_blk = img_open(image_opts, filename, fmt, 0,
5381 false, false, force_share);
5382 if (!in_blk) {
5383 goto out;
5384 }
5385
5386 if (sn_opts) {
5387 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5388 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5389 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5390 &local_err);
5391 } else if (snapshot_name != NULL) {
5392 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5393 snapshot_name, &local_err);
5394 }
5395 if (local_err) {
5396 error_reportf_err(local_err, "Failed to load snapshot: ");
5397 goto out;
5398 }
5399 }
5400
5401 drv = bdrv_find_format(out_fmt);
5402 if (!drv) {
5403 error_report("Unknown file format '%s'", out_fmt);
5404 goto out;
5405 }
5406 if (!drv->create_opts) {
5407 error_report("Format driver '%s' does not support image creation",
5408 drv->format_name);
5409 goto out;
5410 }
5411
5412 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5413 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5414 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5415 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005416 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005417 error_report_err(local_err);
5418 error_report("Invalid options for file format '%s'", out_fmt);
5419 goto out;
5420 }
5421 }
5422 if (img_size != UINT64_MAX) {
5423 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5424 }
5425
5426 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5427 if (local_err) {
5428 error_report_err(local_err);
5429 goto out;
5430 }
5431
5432 if (output_format == OFORMAT_HUMAN) {
5433 printf("required size: %" PRIu64 "\n", info->required);
5434 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005435 if (info->has_bitmaps) {
5436 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5437 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005438 } else {
5439 dump_json_block_measure_info(info);
5440 }
5441
5442 ret = 0;
5443
5444out:
5445 qapi_free_BlockMeasureInfo(info);
5446 qemu_opts_del(object_opts);
5447 qemu_opts_del(opts);
5448 qemu_opts_del(sn_opts);
5449 qemu_opts_free(create_opts);
5450 g_free(options);
5451 blk_unref(in_blk);
5452 return ret;
5453}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005454
Anthony Liguoric227f092009-10-01 16:12:16 -05005455static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005456#define DEF(option, callback, arg_string) \
5457 { option, callback },
5458#include "qemu-img-cmds.h"
5459#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005460 { NULL, NULL, },
5461};
5462
bellardea2384d2004-08-01 21:59:26 +00005463int main(int argc, char **argv)
5464{
Anthony Liguoric227f092009-10-01 16:12:16 -05005465 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005466 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005467 Error *local_error = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005468 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005469 static const struct option long_options[] = {
5470 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005471 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005472 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005473 {0, 0, 0, 0}
5474 };
bellardea2384d2004-08-01 21:59:26 +00005475
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005476#ifdef CONFIG_POSIX
5477 signal(SIGPIPE, SIG_IGN);
5478#endif
5479
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005480 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005481 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005482 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005483 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005484
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005485 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005486 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005487 exit(EXIT_FAILURE);
5488 }
5489
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005490 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005491
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005492 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005493 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005494 if (argc < 2) {
5495 error_exit("Not enough arguments");
5496 }
Stuart Brady153859b2009-06-07 00:42:17 +01005497
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005498 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005499 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005500 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005501
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005502 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005503 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005504 case ':':
5505 missing_argument(argv[optind - 1]);
5506 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005507 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005508 unrecognized_option(argv[optind - 1]);
5509 return 0;
5510 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005511 help();
5512 return 0;
5513 case 'V':
5514 printf(QEMU_IMG_VERSION);
5515 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005516 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005517 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005518 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005519 }
bellardea2384d2004-08-01 21:59:26 +00005520 }
Stuart Brady153859b2009-06-07 00:42:17 +01005521
Denis V. Lunev10985132016-06-17 17:44:13 +03005522 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005523
Denis V. Lunev10985132016-06-17 17:44:13 +03005524 /* reset getopt_long scanning */
5525 argc -= optind;
5526 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005527 return 0;
5528 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005529 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005530 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005531
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005532 if (!trace_init_backends()) {
5533 exit(1);
5534 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005535 trace_init_file();
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005536 qemu_set_log(LOG_TRACE);
5537
Denis V. Lunev10985132016-06-17 17:44:13 +03005538 /* find the command */
5539 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5540 if (!strcmp(cmdname, cmd->name)) {
5541 return cmd->handler(argc, argv);
5542 }
5543 }
Jeff Cody7db16892014-04-25 17:02:32 -04005544
Stuart Brady153859b2009-06-07 00:42:17 +01005545 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005546 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005547}