blob: e61d996e0f13a8e9d1689ac94255ed62936be357 [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
Marc-André Lureau49f95222022-04-20 17:25:49 +040028#include "qemu/help-texts.h"
Marc-André Lureau16a18f22022-03-23 19:57:35 +040029#include "qemu/qemu-progress.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080030#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010031#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050032#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010033#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010034#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010035#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010036#include "qapi/qmp/qdict.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +010044#include "qemu/sockets.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020045#include "qemu/units.h"
Peter Maydell5df022c2022-02-26 18:07:23 +000046#include "qemu/memalign.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000047#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020048#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010049#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020050#include "block/blockjob.h"
Markus Armbrustere2c1c342022-12-21 14:35:49 +010051#include "block/dirty-bitmap.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080052#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010053#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030054#include "trace/control.h"
Zhengui0c8c4892020-10-20 14:47:44 +000055#include "qemu/throttle.h"
56#include "block/throttle-groups.h"
bellarde8445332006-06-14 15:32:10 +000057
Thomas Huth7e563bf2018-02-15 12:06:47 +010058#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020059 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040060
Anthony Liguoric227f092009-10-01 16:12:16 -050061typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010062 const char *name;
63 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050064} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010065
Federico Simoncelli8599ea42013-01-28 06:59:47 -050066enum {
67 OPTION_OUTPUT = 256,
68 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000069 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000070 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020071 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020072 OPTION_FLUSH_INTERVAL = 261,
73 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010074 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010075 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020076 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030077 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020078 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000079 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050080 OPTION_ADD = 269,
81 OPTION_REMOVE = 270,
82 OPTION_CLEAR = 271,
83 OPTION_ENABLE = 272,
84 OPTION_DISABLE = 273,
85 OPTION_MERGE = 274,
Eric Blake15e39ad2020-05-21 14:21:36 -050086 OPTION_BITMAPS = 275,
Maxim Levitskya3579bf2020-06-25 14:55:38 +020087 OPTION_FORCE = 276,
Eric Blake955171e2021-07-21 10:53:48 -050088 OPTION_SKIP_BROKEN = 277,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050089};
90
91typedef enum OutputFormat {
92 OFORMAT_JSON,
93 OFORMAT_HUMAN,
94} OutputFormat;
95
Kevin Wolfe6996142016-03-15 13:03:11 +010096/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040097#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000098
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010099static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +0000100{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +0100101 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +0000102}
103
Marc-André Lureau89057702022-04-20 17:26:02 +0400104static G_NORETURN G_GNUC_PRINTF(1, 2)
105void error_exit(const char *fmt, ...)
Fam Zhengac1307a2014-04-22 13:36:11 +0800106{
107 va_list ap;
108
Fam Zhengac1307a2014-04-22 13:36:11 +0800109 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200110 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800111 va_end(ap);
112
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200113 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800114 exit(EXIT_FAILURE);
115}
116
Marc-André Lureau89057702022-04-20 17:26:02 +0400117static G_NORETURN
118void missing_argument(const char *option)
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800119{
120 error_exit("missing argument for option '%s'", option);
121}
122
Marc-André Lureau89057702022-04-20 17:26:02 +0400123static G_NORETURN
124void unrecognized_option(const char *option)
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800125{
126 error_exit("unrecognized option '%s'", option);
127}
128
Eric Blake0562adf2020-05-12 20:16:41 -0500129/* Please keep in synch with docs/tools/qemu-img.rst */
Marc-André Lureau89057702022-04-20 17:26:02 +0400130static G_NORETURN
131void help(void)
bellardea2384d2004-08-01 21:59:26 +0000132{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100133 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400134 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300135 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300136 "QEMU disk image utility\n"
137 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300138 " '-h', '--help' display this help and exit\n"
139 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300140 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
141 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300142 "\n"
malc3f020d72010-02-08 12:04:56 +0300143 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100144#define DEF(option, callback, arg_string) \
145 " " arg_string "\n"
146#include "qemu-img-cmds.h"
147#undef DEF
malc3f020d72010-02-08 12:04:56 +0300148 "\n"
149 "Command parameters:\n"
150 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000151 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
152 " manual page for a description of the object properties. The most common\n"
153 " object type is a 'secret', which is used to supply passwords and/or\n"
154 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300155 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400156 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800157 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
158 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100159 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
160 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300161 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200162 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
163 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
164 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300165 " 'output_filename' is the destination disk image filename\n"
166 " 'output_fmt' is the destination format\n"
167 " 'options' is a comma separated list of format specific options in a\n"
Markus Armbruster7f118b42022-09-08 15:08:42 +0200168 " name=value format. Use -o help for an overview of the options supported by\n"
169 " the used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800170 " 'snapshot_param' is param used for internal snapshot, format\n"
171 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
172 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300173 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400174 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
175 " new backing file match exactly. The image doesn't need a working\n"
176 " backing file before rebasing in this case (useful for renaming the\n"
177 " backing file). For image creation, allow creating without attempting\n"
178 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300179 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200180 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100181 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200182 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
183 " contain only zeros for qemu-img to create a sparse image during\n"
184 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
185 " unallocated or zero sectors, and the destination image will always be\n"
186 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200187 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100188 " '-n' skips the target volume creation (useful if the volume is created\n"
189 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300190 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500191 "Parameters to bitmap subcommand:\n"
192 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
193 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
194 " or '--merge source'\n"
195 " '-g granularity' sets the granularity for '--add' actions\n"
196 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
197 " bitmaps from an alternative file\n"
198 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200199 "Parameters to check subcommand:\n"
200 " '-r' tries to repair any inconsistencies that are found during the check.\n"
201 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
202 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200203 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200204 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100205 "Parameters to convert subcommand:\n"
Eric Blake15e39ad2020-05-21 14:21:36 -0500206 " '--bitmaps' copies all top-level persistent bitmaps to destination\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100207 " '-m' specifies how many coroutines work in parallel during the convert\n"
208 " process (defaults to 8)\n"
209 " '-W' allow to write to the target out of order rather than sequential\n"
210 "\n"
malc3f020d72010-02-08 12:04:56 +0300211 "Parameters to snapshot subcommand:\n"
212 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
213 " '-a' applies a snapshot (revert disk to saved state)\n"
214 " '-c' creates a snapshot\n"
215 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100216 " '-l' lists all snapshots in the given image\n"
217 "\n"
218 "Parameters to compare subcommand:\n"
219 " '-f' first image format\n"
220 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200221 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
222 "\n"
223 "Parameters to dd subcommand:\n"
224 " 'bs=BYTES' read and write up to BYTES bytes at a time "
225 "(default: 512)\n"
226 " 'count=N' copy only N input blocks\n"
227 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200228 " 'of=FILE' write to FILE\n"
229 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100230
231 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300232 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500233 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800234 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000235}
236
Markus Armbruster80c710c2020-04-15 09:49:26 +0200237/*
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200238 * Is @list safe for accumulate_options()?
Markus Armbruster80c710c2020-04-15 09:49:26 +0200239 * It is when multiple of them can be joined together separated by ','.
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200240 * To make that work, @list must not start with ',' (or else a
Markus Armbruster80c710c2020-04-15 09:49:26 +0200241 * separating ',' preceding it gets escaped), and it must not end with
242 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200243 * escaped), or be empty (or else a separating ',' preceding it can
244 * escape a separating ',' following it).
245 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200246 */
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200247static bool is_valid_option_list(const char *list)
Markus Armbruster80c710c2020-04-15 09:49:26 +0200248{
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200249 size_t len = strlen(list);
Markus Armbruster80c710c2020-04-15 09:49:26 +0200250 size_t i;
251
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200252 if (!list[0] || list[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200253 return false;
254 }
255
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200256 for (i = len; i > 0 && list[i - 1] == ','; i--) {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200257 }
258 if ((len - i) % 2) {
259 return false;
260 }
261
262 return true;
263}
264
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200265static int accumulate_options(char **options, char *list)
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200266{
267 char *new_options;
268
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200269 if (!is_valid_option_list(list)) {
270 error_report("Invalid option list: %s", list);
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200271 return -1;
272 }
273
274 if (!*options) {
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200275 *options = g_strdup(list);
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200276 } else {
Philippe Mathieu-Daudé46bb9442023-10-04 14:00:09 +0200277 new_options = g_strdup_printf("%s,%s", *options, list);
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200278 g_free(*options);
279 *options = new_options;
280 }
281 return 0;
282}
283
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000284static QemuOptsList qemu_source_opts = {
285 .name = "source",
286 .implied_opt_name = "file",
287 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
288 .desc = {
289 { }
290 },
291};
292
Marc-André Lureau9edc6312022-02-20 20:39:25 +0400293static int G_GNUC_PRINTF(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100294{
295 int ret = 0;
296 if (!quiet) {
297 va_list args;
298 va_start(args, fmt);
299 ret = vprintf(fmt, args);
300 va_end(args);
301 }
302 return ret;
303}
304
bellardea2384d2004-08-01 21:59:26 +0000305
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100306static int print_block_option_help(const char *filename, const char *fmt)
307{
308 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800309 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500310 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100311
312 /* Find driver and parse its options */
313 drv = bdrv_find_format(fmt);
314 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100315 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100316 return 1;
317 }
318
Max Reitzd402b6a2018-05-09 23:00:21 +0200319 if (!drv->create_opts) {
320 error_report("Format driver '%s' does not support image creation", fmt);
321 return 1;
322 }
323
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800324 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100325 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500326 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100327 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100328 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800329 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100330 return 1;
331 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200332 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100333 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200334 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100335 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200336 return 1;
337 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800338 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100339 }
340
Max Reitzf4619af2019-04-13 17:20:37 +0200341 if (filename) {
342 printf("Supported options:\n");
343 } else {
344 printf("Supported %s options:\n", fmt);
345 }
Max Reitz63898712018-10-19 18:49:25 +0200346 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800347 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200348
349 if (!filename) {
350 printf("\n"
351 "The protocol level may support further options.\n"
352 "Specify the target filename to include those options.\n");
353 }
354
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100355 return 0;
356}
357
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000358
Max Reitzefaa7c42016-03-16 19:54:38 +0100359static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100360 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800361 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000362{
363 QDict *options;
364 Error *local_err = NULL;
365 BlockBackend *blk;
366 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800367 if (force_share) {
368 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200369 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800370 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200371 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800372 return NULL;
373 }
Max Reitz4615f872018-05-02 22:20:50 +0200374 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800375 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100376 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000377 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100378 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000379 return NULL;
380 }
Kevin Wolfce099542016-03-15 13:01:04 +0100381 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000382
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 return blk;
384}
385
Max Reitzefaa7c42016-03-16 19:54:38 +0100386static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100387 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000388 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800389 bool writethrough, bool quiet,
390 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000391{
392 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200393 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100394
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100395 if (!options) {
396 options = qdict_new();
397 }
bellard75c23802004-08-27 21:28:58 +0000398 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500399 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000400 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100401
Fam Zheng335e9932017-05-03 00:35:39 +0800402 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500403 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800404 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100405 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500406 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100407 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000408 return NULL;
bellard75c23802004-08-27 21:28:58 +0000409 }
Kevin Wolfce099542016-03-15 13:01:04 +0100410 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100411
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200412 return blk;
bellard75c23802004-08-27 21:28:58 +0000413}
414
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000415
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100416static int img_add_key_secrets(void *opaque,
417 const char *name, const char *value,
418 Error **errp)
419{
420 QDict *options = opaque;
421
422 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600423 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100424 }
425
426 return 0;
427}
428
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100429
Max Reitzefaa7c42016-03-16 19:54:38 +0100430static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000431 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100432 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800433 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000434{
435 BlockBackend *blk;
436 if (image_opts) {
437 QemuOpts *opts;
438 if (fmt) {
439 error_report("--image-opts and --format are mutually exclusive");
440 return NULL;
441 }
442 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
443 filename, true);
444 if (!opts) {
445 return NULL;
446 }
Fam Zheng335e9932017-05-03 00:35:39 +0800447 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
448 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000449 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100450 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800451 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000452 }
Kevin Wolf44efba22023-01-12 20:14:52 +0100453
454 if (blk) {
455 blk_set_force_allow_inactivate(blk);
456 }
457
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000458 return blk;
459}
460
461
Chunyan Liu83d05212014-06-05 17:20:51 +0800462static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100463 const char *base_filename,
464 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200465{
Kevin Wolfefa84d42009-05-18 16:42:12 +0200466 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +0200467 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster9e194e02020-07-07 18:06:11 +0200468 NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100469 error_report("Backing file not supported for file format '%s'",
470 fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900471 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200472 }
473 }
474 if (base_fmt) {
Markus Armbruster9e194e02020-07-07 18:06:11 +0200475 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100476 error_report("Backing file format not supported for file "
477 "format '%s'", fmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900478 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200479 }
480 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900481 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200482}
483
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300484static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
485 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100486{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100487 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300488 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100489
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300490 err = qemu_strtosz(value, NULL, &res);
491 if (err < 0 && err != -ERANGE) {
492 error_report("Invalid %s specified. You may use "
493 "k, M, G, T, P or E suffixes for", name);
494 error_report("kilobytes, megabytes, gigabytes, terabytes, "
495 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100496 return err;
497 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300498 if (err == -ERANGE || res > max || res < min) {
499 error_report("Invalid %s specified. Must be between %" PRId64
500 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100501 return -ERANGE;
502 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300503 return res;
504}
505
506static int64_t cvtnum(const char *name, const char *value)
507{
508 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100509}
510
bellardea2384d2004-08-01 21:59:26 +0000511static int img_create(int argc, char **argv)
512{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200513 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100514 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000515 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000516 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000517 const char *filename;
518 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200519 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200520 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100521 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400522 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000523
bellardea2384d2004-08-01 21:59:26 +0000524 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000525 static const struct option long_options[] = {
526 {"help", no_argument, 0, 'h'},
527 {"object", required_argument, 0, OPTION_OBJECT},
528 {0, 0, 0, 0}
529 };
John Snow6e6e55f2017-07-17 20:34:22 -0400530 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000531 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100532 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000533 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100534 }
bellardea2384d2004-08-01 21:59:26 +0000535 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800536 case ':':
537 missing_argument(argv[optind - 1]);
538 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100539 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800540 unrecognized_option(argv[optind - 1]);
541 break;
bellardea2384d2004-08-01 21:59:26 +0000542 case 'h':
543 help();
544 break;
aliguori9230eaf2009-03-28 17:55:19 +0000545 case 'F':
546 base_fmt = optarg;
547 break;
bellardea2384d2004-08-01 21:59:26 +0000548 case 'b':
549 base_filename = optarg;
550 break;
551 case 'f':
552 fmt = optarg;
553 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200554 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200555 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100556 goto fail;
557 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200558 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100559 case 'q':
560 quiet = true;
561 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400562 case 'u':
563 flags |= BDRV_O_NO_BACKING;
564 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100565 case OPTION_OBJECT:
566 user_creatable_process_cmdline(optarg);
567 break;
bellardea2384d2004-08-01 21:59:26 +0000568 }
569 }
aliguori9230eaf2009-03-28 17:55:19 +0000570
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900571 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100572 filename = (optind < argc) ? argv[optind] : NULL;
573 if (options && has_help_option(options)) {
574 g_free(options);
575 return print_block_option_help(filename, fmt);
576 }
577
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100578 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800579 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100580 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100581 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900582
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100583 /* Get image size, if specified */
584 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100585 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100586
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300587 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100588 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100589 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100590 }
591 img_size = (uint64_t)sval;
592 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200593 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800594 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200595 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100596
Luiz Capitulino9b375252012-11-30 10:52:05 -0200597 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400598 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100599 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100600 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100601 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900602 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200603
Kevin Wolf77386bf2014-02-21 16:24:04 +0100604 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000605 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100606
607fail:
608 g_free(options);
609 return 1;
bellardea2384d2004-08-01 21:59:26 +0000610}
611
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100612static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500613{
Markus Armbrustereab3a462020-12-11 18:11:37 +0100614 GString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500615 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100616 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600617
618 visit_type_ImageCheck(v, NULL, &check, &error_abort);
619 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +0100620 str = qobject_to_json_pretty(obj, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500621 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100622 qprintf(quiet, "%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200623 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600624 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +0100625 g_string_free(str, true);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500626}
627
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100628static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500629{
630 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100631 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500632 } else {
633 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100634 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
635 "Data may be corrupted, or further writes to the image "
636 "may corrupt it.\n",
637 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500638 }
639
640 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100641 qprintf(quiet,
642 "\n%" PRId64 " leaked clusters were found on the image.\n"
643 "This means waste of disk space, but no harm to data.\n",
644 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500645 }
646
647 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100648 qprintf(quiet,
649 "\n%" PRId64
650 " internal errors have occurred during the check.\n",
651 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500652 }
653 }
654
655 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100656 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
657 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
658 check->allocated_clusters, check->total_clusters,
659 check->allocated_clusters * 100.0 / check->total_clusters,
660 check->fragmented_clusters * 100.0 / check->allocated_clusters,
661 check->compressed_clusters * 100.0 /
662 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500663 }
664
665 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100666 qprintf(quiet,
667 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500668 }
669}
670
671static int collect_image_check(BlockDriverState *bs,
672 ImageCheck *check,
673 const char *filename,
674 const char *fmt,
675 int fix)
676{
677 int ret;
678 BdrvCheckResult result;
679
680 ret = bdrv_check(bs, &result, fix);
681 if (ret < 0) {
682 return ret;
683 }
684
685 check->filename = g_strdup(filename);
686 check->format = g_strdup(bdrv_get_format_name(bs));
687 check->check_errors = result.check_errors;
688 check->corruptions = result.corruptions;
689 check->has_corruptions = result.corruptions != 0;
690 check->leaks = result.leaks;
691 check->has_leaks = result.leaks != 0;
692 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100693 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500694 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100695 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500696 check->image_end_offset = result.image_end_offset;
697 check->has_image_end_offset = result.image_end_offset != 0;
698 check->total_clusters = result.bfi.total_clusters;
699 check->has_total_clusters = result.bfi.total_clusters != 0;
700 check->allocated_clusters = result.bfi.allocated_clusters;
701 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
702 check->fragmented_clusters = result.bfi.fragmented_clusters;
703 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100704 check->compressed_clusters = result.bfi.compressed_clusters;
705 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500706
707 return 0;
708}
709
Kevin Wolfe076f332010-06-29 11:43:13 +0200710/*
711 * Checks an image for consistency. Exit codes:
712 *
Max Reitzd6635c42014-06-02 22:15:21 +0200713 * 0 - Check completed, image is good
714 * 1 - Check not completed because of internal errors
715 * 2 - Check completed, image is corrupted
716 * 3 - Check completed, image has leaked clusters, but is good otherwise
717 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200718 */
aliguori15859692009-04-21 23:11:53 +0000719static int img_check(int argc, char **argv)
720{
721 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500722 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200723 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200724 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000725 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200726 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100727 int flags = BDRV_O_CHECK;
728 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200729 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100730 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000731 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800732 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000733
734 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500735 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200736 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100737
aliguori15859692009-04-21 23:11:53 +0000738 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500739 int option_index = 0;
740 static const struct option long_options[] = {
741 {"help", no_argument, 0, 'h'},
742 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530743 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500744 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000745 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000746 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800747 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500748 {0, 0, 0, 0}
749 };
Fam Zheng335e9932017-05-03 00:35:39 +0800750 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500751 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100752 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000753 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100754 }
aliguori15859692009-04-21 23:11:53 +0000755 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800756 case ':':
757 missing_argument(argv[optind - 1]);
758 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100759 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800760 unrecognized_option(argv[optind - 1]);
761 break;
aliguori15859692009-04-21 23:11:53 +0000762 case 'h':
763 help();
764 break;
765 case 'f':
766 fmt = optarg;
767 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200768 case 'r':
769 flags |= BDRV_O_RDWR;
770
771 if (!strcmp(optarg, "leaks")) {
772 fix = BDRV_FIX_LEAKS;
773 } else if (!strcmp(optarg, "all")) {
774 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
775 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800776 error_exit("Unknown option value for -r "
777 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200778 }
779 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500780 case OPTION_OUTPUT:
781 output = optarg;
782 break;
Max Reitz40055952014-07-22 22:58:42 +0200783 case 'T':
784 cache = optarg;
785 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100786 case 'q':
787 quiet = true;
788 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800789 case 'U':
790 force_share = true;
791 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +0100792 case OPTION_OBJECT:
793 user_creatable_process_cmdline(optarg);
794 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000795 case OPTION_IMAGE_OPTS:
796 image_opts = true;
797 break;
aliguori15859692009-04-21 23:11:53 +0000798 }
799 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200800 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800801 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100802 }
aliguori15859692009-04-21 23:11:53 +0000803 filename = argv[optind++];
804
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500805 if (output && !strcmp(output, "json")) {
806 output_format = OFORMAT_JSON;
807 } else if (output && !strcmp(output, "human")) {
808 output_format = OFORMAT_HUMAN;
809 } else if (output) {
810 error_report("--output must be used with human or json as argument.");
811 return 1;
812 }
813
Kevin Wolfce099542016-03-15 13:01:04 +0100814 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200815 if (ret < 0) {
816 error_report("Invalid source cache option: %s", cache);
817 return 1;
818 }
819
Fam Zheng335e9932017-05-03 00:35:39 +0800820 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
821 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200822 if (!blk) {
823 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900824 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200825 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500826
827 check = g_new0(ImageCheck, 1);
828 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200829
830 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200831 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200832 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500833 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200834 }
835
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500836 if (check->corruptions_fixed || check->leaks_fixed) {
837 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100838 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500839
840 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100841 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500842 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100843 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500844
845 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100846 qprintf(quiet,
847 "The following inconsistencies were found and repaired:\n\n"
848 " %" PRId64 " leaked clusters\n"
849 " %" PRId64 " corruptions\n\n"
850 "Double checking the fixed image now...\n",
851 check->leaks_fixed,
852 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500853 }
854
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800855 qapi_free_ImageCheck(check);
856 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500857 ret = collect_image_check(bs, check, filename, fmt, 0);
858
859 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100860 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500861 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100862 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200863 }
864
Max Reitz832390a2014-10-23 15:29:12 +0200865 if (!ret) {
866 switch (output_format) {
867 case OFORMAT_HUMAN:
868 dump_human_image_check(check, quiet);
869 break;
870 case OFORMAT_JSON:
871 dump_json_image_check(check, quiet);
872 break;
873 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500874 }
875
876 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200877 if (ret) {
878 error_report("Check failed: %s", strerror(-ret));
879 } else {
880 error_report("Check failed");
881 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500882 ret = 1;
883 goto fail;
884 }
885
886 if (check->corruptions) {
887 ret = 2;
888 } else if (check->leaks) {
889 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200890 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500891 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000892 }
893
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500894fail:
895 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200896 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500897 return ret;
aliguori15859692009-04-21 23:11:53 +0000898}
899
Max Reitzd4a32382014-10-24 15:57:37 +0200900typedef struct CommonBlockJobCBInfo {
901 BlockDriverState *bs;
902 Error **errp;
903} CommonBlockJobCBInfo;
904
905static void common_block_job_cb(void *opaque, int ret)
906{
907 CommonBlockJobCBInfo *cbi = opaque;
908
909 if (ret < 0) {
910 error_setg_errno(cbi->errp, -ret, "Block job failed");
911 }
Max Reitzd4a32382014-10-24 15:57:37 +0200912}
913
914static void run_block_job(BlockJob *job, Error **errp)
915{
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200916 uint64_t progress_current, progress_total;
Vladimir Sementsov-Ogievskiydf9a3162021-05-06 17:13:53 +0300917 AioContext *aio_context = block_job_get_aio_context(job);
sochin.jiang4172a002017-06-15 14:47:33 +0800918 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200919
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400920 job_lock();
921 job_ref_locked(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200922 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200923 float progress = 0.0f;
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400924 job_unlock();
Max Reitzd4a32382014-10-24 15:57:37 +0200925 aio_poll(aio_context, true);
Emanuele Giuseppe Espositoa7b4f8f2021-06-14 10:11:29 +0200926
927 progress_get_snapshot(&job->job.progress, &progress_current,
928 &progress_total);
929 if (progress_total) {
930 progress = (float)progress_current / progress_total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200931 }
932 qemu_progress_print(progress, 0);
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400933 job_lock();
934 } while (!job_is_ready_locked(&job->job) &&
935 !job_is_completed_locked(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200936
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400937 if (!job_is_completed_locked(&job->job)) {
938 ret = job_complete_sync_locked(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800939 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200940 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800941 }
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -0400942 job_unref_locked(&job->job);
943 job_unlock();
Max Reitz687fa1d2014-10-24 15:57:39 +0200944
sochin.jiang4172a002017-06-15 14:47:33 +0800945 /* publish completion progress only when success */
946 if (!ret) {
947 qemu_progress_print(100.f, 0);
948 }
Max Reitzd4a32382014-10-24 15:57:37 +0200949}
950
bellardea2384d2004-08-01 21:59:26 +0000951static int img_commit(int argc, char **argv)
952{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400953 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200954 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200955 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200956 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100957 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200958 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100959 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200960 Error *local_err = NULL;
961 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000962 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200963 AioContext *aio_context;
Zhenguia0441b62020-10-20 14:47:43 +0000964 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +0000965
966 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400967 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200968 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000969 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000970 static const struct option long_options[] = {
971 {"help", no_argument, 0, 'h'},
972 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000973 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000974 {0, 0, 0, 0}
975 };
Zhenguia0441b62020-10-20 14:47:43 +0000976 c = getopt_long(argc, argv, ":f:ht:b:dpqr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000977 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100978 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000979 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100980 }
bellardea2384d2004-08-01 21:59:26 +0000981 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800982 case ':':
983 missing_argument(argv[optind - 1]);
984 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100985 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800986 unrecognized_option(argv[optind - 1]);
987 break;
bellardea2384d2004-08-01 21:59:26 +0000988 case 'h':
989 help();
990 break;
991 case 'f':
992 fmt = optarg;
993 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400994 case 't':
995 cache = optarg;
996 break;
Max Reitz1b22bff2014-10-24 15:57:40 +0200997 case 'b':
998 base = optarg;
999 /* -b implies -d */
1000 drop = true;
1001 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001002 case 'd':
1003 drop = true;
1004 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001005 case 'p':
1006 progress = true;
1007 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001008 case 'q':
1009 quiet = true;
1010 break;
Zhenguia0441b62020-10-20 14:47:43 +00001011 case 'r':
1012 rate_limit = cvtnum("rate limit", optarg);
1013 if (rate_limit < 0) {
1014 return 1;
1015 }
1016 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001017 case OPTION_OBJECT:
1018 user_creatable_process_cmdline(optarg);
1019 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001020 case OPTION_IMAGE_OPTS:
1021 image_opts = true;
1022 break;
bellardea2384d2004-08-01 21:59:26 +00001023 }
1024 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001025
1026 /* Progress is not shown in Quiet mode */
1027 if (quiet) {
1028 progress = false;
1029 }
1030
Kevin Wolffc11eb22013-08-05 10:53:04 +02001031 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001032 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001033 }
bellardea2384d2004-08-01 21:59:26 +00001034 filename = argv[optind++];
1035
Max Reitz9a86fe42014-10-24 15:57:38 +02001036 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001037 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001038 if (ret < 0) {
1039 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001040 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001041 }
1042
Fam Zheng335e9932017-05-03 00:35:39 +08001043 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1044 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001045 if (!blk) {
1046 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001047 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001048 bs = blk_bs(blk);
1049
Max Reitz687fa1d2014-10-24 15:57:39 +02001050 qemu_progress_init(progress, 1.f);
1051 qemu_progress_print(0.f, 100);
1052
Max Reitz1b22bff2014-10-24 15:57:40 +02001053 if (base) {
1054 base_bs = bdrv_find_backing_image(bs, base);
1055 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001056 error_setg(&local_err,
1057 "Did not find '%s' in the backing chain of '%s'",
1058 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001059 goto done;
1060 }
1061 } else {
1062 /* This is different from QMP, which by default uses the deepest file in
1063 * the backing chain (i.e., the very base); however, the traditional
1064 * behavior of qemu-img commit is using the immediate backing file. */
Max Reitz4a2061e2019-06-12 19:00:30 +02001065 base_bs = bdrv_backing_chain_next(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001066 if (!base_bs) {
1067 error_setg(&local_err, "Image does not have a backing file");
1068 goto done;
1069 }
bellardea2384d2004-08-01 21:59:26 +00001070 }
1071
Max Reitzd4a32382014-10-24 15:57:37 +02001072 cbi = (CommonBlockJobCBInfo){
1073 .errp = &local_err,
1074 .bs = bs,
1075 };
1076
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001077 aio_context = bdrv_get_aio_context(bs);
1078 aio_context_acquire(aio_context);
Zhenguia0441b62020-10-20 14:47:43 +00001079 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, rate_limit,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001080 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001081 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001082 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001083 if (local_err) {
1084 goto done;
1085 }
1086
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001087 /* When the block job completes, the BlockBackend reference will point to
1088 * the old backing file. In order to avoid that the top image is already
1089 * deleted, so we can still empty it afterwards, increment the reference
1090 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001091 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001092 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001093 }
1094
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001095 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001096 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001097 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001098 if (local_err) {
1099 goto unref_backing;
1100 }
1101
Max Reitz2d97fde2020-04-29 16:11:26 +02001102 if (!drop) {
1103 BlockBackend *old_backing_blk;
1104
1105 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1106 &local_err);
1107 if (!old_backing_blk) {
1108 goto unref_backing;
1109 }
1110 ret = blk_make_empty(old_backing_blk, &local_err);
1111 blk_unref(old_backing_blk);
1112 if (ret == -ENOTSUP) {
1113 error_free(local_err);
1114 local_err = NULL;
1115 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001116 goto unref_backing;
1117 }
1118 }
1119
1120unref_backing:
1121 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001122 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001123 }
Max Reitzd4a32382014-10-24 15:57:37 +02001124
1125done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001126 qemu_progress_end();
1127
Kevin Wolf44efba22023-01-12 20:14:52 +01001128 /*
1129 * Manually inactivate the image first because this way we can know whether
1130 * an error occurred. blk_unref() doesn't tell us about failures.
1131 */
1132 ret = bdrv_inactivate_all();
1133 if (ret < 0 && !local_err) {
1134 error_setg_errno(&local_err, -ret, "Error while closing the image");
1135 }
Markus Armbruster26f54e92014-10-07 13:59:04 +02001136 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001137
1138 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001139 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001140 return 1;
1141 }
Max Reitzd4a32382014-10-24 15:57:37 +02001142
1143 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001144 return 0;
1145}
1146
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001147/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001148 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1149 * of the first sector boundary within buf where the sector contains a
1150 * non-zero byte. This function is robust to a buffer that is not
1151 * sector-aligned.
1152 */
1153static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1154{
1155 int64_t i;
1156 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1157
1158 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1159 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1160 return i;
1161 }
1162 }
1163 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1164 return i;
1165 }
1166 return -1;
1167}
1168
1169/*
thsf58c7b32008-06-05 21:53:49 +00001170 * Returns true iff the first sector pointed to by 'buf' contains at least
1171 * a non-NUL byte.
1172 *
1173 * 'pnum' is set to the number of sectors (including and immediately following
1174 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001175 * The function will try to align the end offset to alignment boundaries so
zhaolichange3a6e0d2020-09-17 15:50:20 +08001176 * that the request will at least end aligned and consecutive requests will
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001177 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001178 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001179static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1180 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001181{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001182 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001183 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001184
1185 if (n <= 0) {
1186 *pnum = 0;
1187 return 0;
1188 }
Yi Lic075c422020-08-19 09:36:07 +08001189 is_zero = buffer_is_zero(buf, BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001190 for(i = 1; i < n; i++) {
Yi Lic075c422020-08-19 09:36:07 +08001191 buf += BDRV_SECTOR_SIZE;
1192 if (is_zero != buffer_is_zero(buf, BDRV_SECTOR_SIZE)) {
bellardea2384d2004-08-01 21:59:26 +00001193 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001194 }
bellardea2384d2004-08-01 21:59:26 +00001195 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001196
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001197 if (i == n) {
1198 /*
1199 * The whole buf is the same.
1200 * No reason to split it into chunks, so return now.
1201 */
1202 *pnum = i;
1203 return !is_zero;
1204 }
1205
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001206 tail = (sector_num + i) & (alignment - 1);
1207 if (tail) {
1208 if (is_zero && i <= tail) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001209 /*
1210 * For sure next sector after i is data, and it will rewrite this
1211 * tail anyway due to RMW. So, let's just write data now.
1212 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001213 is_zero = false;
1214 }
1215 if (!is_zero) {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001216 /* If possible, align up end offset of allocated areas. */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001217 i += alignment - tail;
1218 i = MIN(i, n);
1219 } else {
Vladimir Sementsov-Ogievskiy96054c72021-12-17 17:46:54 +01001220 /*
1221 * For sure next sector after i is data, and it will rewrite this
1222 * tail anyway due to RMW. Better is avoid RMW and write zeroes up
1223 * to aligned bound.
1224 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001225 i -= tail;
1226 }
1227 }
bellardea2384d2004-08-01 21:59:26 +00001228 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001229 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001230}
1231
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001232/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001233 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1234 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1235 * breaking up write requests for only small sparse areas.
1236 */
1237static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001238 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001239{
1240 int ret;
1241 int num_checked, num_used;
1242
1243 if (n < min) {
1244 min = n;
1245 }
1246
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001247 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001248 if (!ret) {
1249 return ret;
1250 }
1251
1252 num_used = *pnum;
1253 buf += BDRV_SECTOR_SIZE * *pnum;
1254 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001255 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001256 num_checked = num_used;
1257
1258 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001259 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001260
1261 buf += BDRV_SECTOR_SIZE * *pnum;
1262 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001263 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001264 num_checked += *pnum;
1265 if (ret) {
1266 num_used = num_checked;
1267 } else if (*pnum >= min) {
1268 break;
1269 }
1270 }
1271
1272 *pnum = num_used;
1273 return 1;
1274}
1275
1276/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001277 * Compares two buffers sector by sector. Returns 0 if the first
1278 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001279 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001280 * pnum is set to the sector-aligned size of the buffer prefix that
1281 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001282 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001283static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1284 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001285{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001286 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001287 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001288
Eric Blakedc61cd32017-10-11 22:47:14 -05001289 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001290
Eric Blakedc61cd32017-10-11 22:47:14 -05001291 res = !!memcmp(buf1, buf2, i);
1292 while (i < bytes) {
1293 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001294
Eric Blakedc61cd32017-10-11 22:47:14 -05001295 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001296 break;
1297 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001298 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001299 }
1300
1301 *pnum = i;
1302 return res;
1303}
1304
Stefano Garzarella97ede572019-05-08 12:43:24 +02001305#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001306
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001307/*
1308 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1309 *
Eric Blake0608e402017-10-11 22:47:12 -05001310 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1311 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1312 * failure), and 4 on error (the exit status for read errors), after emitting
1313 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001314 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001315 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001316 * @param offset: Starting offset to check
1317 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001318 * @param filename: Name of disk file we are checking (logging purpose)
1319 * @param buffer: Allocated buffer for storing read data
1320 * @param quiet: Flag for quiet mode
1321 */
Eric Blakec41508e2017-10-11 22:47:13 -05001322static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1323 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001324 uint8_t *buffer, bool quiet)
1325{
Eric Blakedebb38a2017-10-11 22:47:11 -05001326 int ret = 0;
1327 int64_t idx;
1328
Alberto Fariaa9262f52022-07-05 17:15:11 +01001329 ret = blk_pread(blk, offset, bytes, buffer, 0);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001330 if (ret < 0) {
1331 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001332 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001333 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001334 }
Eric Blakec41508e2017-10-11 22:47:13 -05001335 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001336 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001337 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001338 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001339 return 1;
1340 }
1341
1342 return 0;
1343}
1344
1345/*
1346 * Compares two images. Exit codes:
1347 *
Kevin Wolf99b1e642021-02-17 12:56:45 +01001348 * 0 - Images are identical or the requested help was printed
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001349 * 1 - Images differ
1350 * >1 - Error occurred
1351 */
1352static int img_compare(int argc, char **argv)
1353{
Max Reitz40055952014-07-22 22:58:42 +02001354 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001355 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001356 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001357 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001358 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001359 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001360 int allocated1, allocated2;
1361 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1362 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001363 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001364 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001365 int64_t total_size;
1366 int64_t offset = 0;
1367 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001368 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001369 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001370 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001371 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001372
Max Reitz40055952014-07-22 22:58:42 +02001373 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001374 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001375 static const struct option long_options[] = {
1376 {"help", no_argument, 0, 'h'},
1377 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001378 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001379 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001380 {0, 0, 0, 0}
1381 };
Fam Zheng335e9932017-05-03 00:35:39 +08001382 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001383 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001384 if (c == -1) {
1385 break;
1386 }
1387 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001388 case ':':
1389 missing_argument(argv[optind - 1]);
1390 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001391 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001392 unrecognized_option(argv[optind - 1]);
1393 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001394 case 'h':
1395 help();
1396 break;
1397 case 'f':
1398 fmt1 = optarg;
1399 break;
1400 case 'F':
1401 fmt2 = optarg;
1402 break;
Max Reitz40055952014-07-22 22:58:42 +02001403 case 'T':
1404 cache = optarg;
1405 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001406 case 'p':
1407 progress = true;
1408 break;
1409 case 'q':
1410 quiet = true;
1411 break;
1412 case 's':
1413 strict = true;
1414 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001415 case 'U':
1416 force_share = true;
1417 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01001418 case OPTION_OBJECT:
1419 {
1420 Error *local_err = NULL;
1421
1422 if (!user_creatable_add_from_str(optarg, &local_err)) {
1423 if (local_err) {
1424 error_report_err(local_err);
1425 exit(2);
1426 } else {
1427 /* Help was printed */
1428 exit(EXIT_SUCCESS);
1429 }
1430 }
1431 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001432 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001433 case OPTION_IMAGE_OPTS:
1434 image_opts = true;
1435 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001436 }
1437 }
1438
1439 /* Progress is not shown in Quiet mode */
1440 if (quiet) {
1441 progress = false;
1442 }
1443
1444
Kevin Wolffc11eb22013-08-05 10:53:04 +02001445 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001446 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001447 }
1448 filename1 = argv[optind++];
1449 filename2 = argv[optind++];
1450
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001451 /* Initialize before goto out */
1452 qemu_progress_init(progress, 2.0);
1453
Kevin Wolfce099542016-03-15 13:01:04 +01001454 flags = 0;
1455 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001456 if (ret < 0) {
1457 error_report("Invalid source cache option: %s", cache);
1458 ret = 2;
1459 goto out3;
1460 }
1461
Fam Zheng335e9932017-05-03 00:35:39 +08001462 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1463 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001464 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001465 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001466 goto out3;
1467 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001468
Fam Zheng335e9932017-05-03 00:35:39 +08001469 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1470 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001471 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001472 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001473 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001474 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001475 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001476 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001477
Max Reitzf1d3cd72015-02-05 13:58:18 -05001478 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1479 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001480 total_size1 = blk_getlength(blk1);
1481 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001482 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001483 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001484 ret = 4;
1485 goto out;
1486 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001487 total_size2 = blk_getlength(blk2);
1488 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001489 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001490 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001491 ret = 4;
1492 goto out;
1493 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001494 total_size = MIN(total_size1, total_size2);
1495 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001496
1497 qemu_progress_print(0, 100);
1498
Eric Blake033d9fc2017-10-11 22:47:16 -05001499 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001500 ret = 1;
1501 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1502 goto out;
1503 }
1504
Eric Blake033d9fc2017-10-11 22:47:16 -05001505 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001506 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001507
Eric Blake033d9fc2017-10-11 22:47:16 -05001508 status1 = bdrv_block_status_above(bs1, NULL, offset,
1509 total_size1 - offset, &pnum1, NULL,
1510 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001511 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001512 ret = 3;
1513 error_report("Sector allocation test failed for %s", filename1);
1514 goto out;
1515 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001516 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001517
Eric Blake033d9fc2017-10-11 22:47:16 -05001518 status2 = bdrv_block_status_above(bs2, NULL, offset,
1519 total_size2 - offset, &pnum2, NULL,
1520 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001521 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001522 ret = 3;
1523 error_report("Sector allocation test failed for %s", filename2);
1524 goto out;
1525 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001526 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001527
1528 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001529 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001530
Fam Zheng25ad8e62016-01-13 16:37:41 +08001531 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001532 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001533 ret = 1;
1534 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001535 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001536 goto out;
1537 }
1538 }
1539 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001540 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001541 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001542 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001543 int64_t pnum;
1544
Eric Blake033d9fc2017-10-11 22:47:16 -05001545 chunk = MIN(chunk, IO_BUF_SIZE);
Alberto Fariaa9262f52022-07-05 17:15:11 +01001546 ret = blk_pread(blk1, offset, chunk, buf1, 0);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001547 if (ret < 0) {
1548 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001549 " of %s: %s",
1550 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001551 ret = 4;
1552 goto out;
1553 }
Alberto Fariaa9262f52022-07-05 17:15:11 +01001554 ret = blk_pread(blk2, offset, chunk, buf2, 0);
Eric Blake033d9fc2017-10-11 22:47:16 -05001555 if (ret < 0) {
1556 error_report("Error while reading offset %" PRId64
1557 " of %s: %s",
1558 offset, filename2, strerror(-ret));
1559 ret = 4;
1560 goto out;
1561 }
1562 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1563 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001564 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001565 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001566 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001567 goto out;
1568 }
1569 }
1570 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001571 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001572 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001573 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001574 filename1, buf1, quiet);
1575 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001576 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001577 filename2, buf1, quiet);
1578 }
1579 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001580 goto out;
1581 }
1582 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001583 offset += chunk;
1584 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001585 }
1586
Eric Blake033d9fc2017-10-11 22:47:16 -05001587 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001588 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001589 const char *filename_over;
1590
1591 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001592 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001593 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001594 filename_over = filename1;
1595 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001596 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001597 filename_over = filename2;
1598 }
1599
Eric Blake033d9fc2017-10-11 22:47:16 -05001600 while (offset < progress_base) {
1601 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1602 progress_base - offset, &chunk,
1603 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001604 if (ret < 0) {
1605 ret = 3;
1606 error_report("Sector allocation test failed for %s",
1607 filename_over);
1608 goto out;
1609
1610 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001611 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001612 chunk = MIN(chunk, IO_BUF_SIZE);
1613 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001614 filename_over, buf1, quiet);
1615 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001616 goto out;
1617 }
1618 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001619 offset += chunk;
1620 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001621 }
1622 }
1623
1624 qprintf(quiet, "Images are identical.\n");
1625 ret = 0;
1626
1627out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001628 qemu_vfree(buf1);
1629 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001630 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001631out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001632 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001633out3:
1634 qemu_progress_end();
1635 return ret;
1636}
1637
Eric Blake6c729dd2020-05-21 14:21:35 -05001638/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1639static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1640 const char *src_node, const char *src_name,
1641 Error **errp)
1642{
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001643 BlockDirtyBitmapOrStr *merge_src;
1644 BlockDirtyBitmapOrStrList *list = NULL;
Eric Blake6c729dd2020-05-21 14:21:35 -05001645
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001646 merge_src = g_new0(BlockDirtyBitmapOrStr, 1);
Eric Blake6c729dd2020-05-21 14:21:35 -05001647 merge_src->type = QTYPE_QDICT;
1648 merge_src->u.external.node = g_strdup(src_node);
1649 merge_src->u.external.name = g_strdup(src_name);
Eric Blake54aa3de2020-11-12 19:13:37 -06001650 QAPI_LIST_PREPEND(list, merge_src);
Eric Blake6c729dd2020-05-21 14:21:35 -05001651 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
Vladimir Sementsov-Ogievskiy1466ef62022-03-15 00:32:24 +03001652 qapi_free_BlockDirtyBitmapOrStrList(list);
Eric Blake6c729dd2020-05-21 14:21:35 -05001653}
1654
Kevin Wolf690c7302015-03-19 13:33:32 +01001655enum ImgConvertBlockStatus {
1656 BLK_DATA,
1657 BLK_ZERO,
1658 BLK_BACKING_FILE,
1659};
1660
Peter Lieven2d9187b2017-02-28 13:40:07 +01001661#define MAX_COROUTINES 16
Zhengui0c8c4892020-10-20 14:47:44 +00001662#define CONVERT_THROTTLE_GROUP "img_convert"
Peter Lieven2d9187b2017-02-28 13:40:07 +01001663
Kevin Wolf690c7302015-03-19 13:33:32 +01001664typedef struct ImgConvertState {
1665 BlockBackend **src;
1666 int64_t *src_sectors;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001667 int *src_alignment;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001668 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001669 int64_t total_sectors;
1670 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001671 int64_t allocated_done;
1672 int64_t sector_num;
1673 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001674 enum ImgConvertBlockStatus status;
1675 int64_t sector_next_status;
1676 BlockBackend *target;
1677 bool has_zero_init;
1678 bool compressed;
Max Reitz4d7c4872019-07-24 19:12:29 +02001679 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001680 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001681 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001682 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001683 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001684 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001685 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001686 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001687 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001688 size_t cluster_sectors;
1689 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001690 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001691 int running_coroutines;
1692 Coroutine *co[MAX_COROUTINES];
1693 int64_t wait_sector_num[MAX_COROUTINES];
1694 CoMutex lock;
1695 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001696} ImgConvertState;
1697
Peter Lieven2d9187b2017-02-28 13:40:07 +01001698static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1699 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001700{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701 *src_cur = 0;
1702 *src_cur_offset = 0;
1703 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1704 *src_cur_offset += s->src_sectors[*src_cur];
1705 (*src_cur)++;
1706 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001707 }
1708}
1709
1710static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1711{
Eric Blake31826642017-10-11 22:47:08 -05001712 int64_t src_cur_offset;
1713 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001714 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001715
Peter Lieven2d9187b2017-02-28 13:40:07 +01001716 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001717
1718 assert(s->total_sectors > sector_num);
1719 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1720
Max Reitz351c8ef2018-05-01 18:57:49 +02001721 if (s->target_backing_sectors >= 0) {
1722 if (sector_num >= s->target_backing_sectors) {
Vladimir Sementsov-Ogievskiy2253d862020-05-28 12:43:56 +03001723 post_backing_zero = true;
Max Reitz351c8ef2018-05-01 18:57:49 +02001724 } else if (sector_num + n > s->target_backing_sectors) {
1725 /* Split requests around target_backing_sectors (because
1726 * starting from there, zeros are handled differently) */
1727 n = s->target_backing_sectors - sector_num;
1728 }
1729 }
1730
Kevin Wolf690c7302015-03-19 13:33:32 +01001731 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001732 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1733 int64_t count;
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001734 int tail;
Max Reitz4a2061e2019-06-12 19:00:30 +02001735 BlockDriverState *src_bs = blk_bs(s->src[src_cur]);
1736 BlockDriverState *base;
1737
1738 if (s->target_has_backing) {
1739 base = bdrv_cow_bs(bdrv_skip_filters(src_bs));
1740 } else {
1741 base = NULL;
1742 }
Eric Blake31826642017-10-11 22:47:08 -05001743
Max Reitz8eaac022019-05-07 22:35:03 +02001744 do {
1745 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001746
Max Reitz4a2061e2019-06-12 19:00:30 +02001747 ret = bdrv_block_status_above(src_bs, base, offset, count, &count,
1748 NULL, NULL);
Max Reitz8eaac022019-05-07 22:35:03 +02001749
1750 if (ret < 0) {
1751 if (s->salvage) {
1752 if (n == 1) {
1753 if (!s->quiet) {
1754 warn_report("error while reading block status at "
1755 "offset %" PRIu64 ": %s", offset,
1756 strerror(-ret));
1757 }
1758 /* Just try to read the data, then */
1759 ret = BDRV_BLOCK_DATA;
1760 count = BDRV_SECTOR_SIZE;
1761 } else {
1762 /* Retry on a shorter range */
1763 n = DIV_ROUND_UP(n, 4);
1764 }
1765 } else {
1766 error_report("error while reading block status at offset "
1767 "%" PRIu64 ": %s", offset, strerror(-ret));
1768 return ret;
1769 }
1770 }
1771 } while (ret < 0);
1772
Eric Blake31826642017-10-11 22:47:08 -05001773 n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
Kevin Wolf690c7302015-03-19 13:33:32 +01001774
Peter Lievenaf8d43d2020-09-01 14:51:29 +02001775 /*
1776 * Avoid that s->sector_next_status becomes unaligned to the source
1777 * request alignment and/or cluster size to avoid unnecessary read
1778 * cycles.
1779 */
1780 tail = (sector_num - src_cur_offset + n) % s->src_alignment[src_cur];
1781 if (n > tail) {
1782 n -= tail;
1783 }
1784
Kevin Wolf690c7302015-03-19 13:33:32 +01001785 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001786 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001787 } else if (ret & BDRV_BLOCK_DATA) {
1788 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001789 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001790 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001791 }
1792
1793 s->sector_next_status = sector_num + n;
1794 }
1795
1796 n = MIN(n, s->sector_next_status - sector_num);
1797 if (s->status == BLK_DATA) {
1798 n = MIN(n, s->buf_sectors);
1799 }
1800
1801 /* We need to write complete clusters for compressed images, so if an
1802 * unallocated area is shorter than that, we must consider the whole
1803 * cluster allocated. */
1804 if (s->compressed) {
1805 if (n < s->cluster_sectors) {
1806 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1807 s->status = BLK_DATA;
1808 } else {
1809 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1810 }
1811 }
1812
1813 return n;
1814}
1815
Peter Lieven2d9187b2017-02-28 13:40:07 +01001816static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1817 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001818{
Max Reitz8eaac022019-05-07 22:35:03 +02001819 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001820 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001821
Kevin Wolf690c7302015-03-19 13:33:32 +01001822 assert(nb_sectors <= s->buf_sectors);
1823 while (nb_sectors > 0) {
1824 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001825 int src_cur;
1826 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001827 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001828
1829 /* In the case of compression with multiple source files, we can get a
1830 * nb_sectors that spreads into the next part. So we must be able to
1831 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001832 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1833 blk = s->src[src_cur];
1834 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001835
Max Reitz8eaac022019-05-07 22:35:03 +02001836 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001837
Max Reitz8eaac022019-05-07 22:35:03 +02001838 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1839 if (single_read_until > offset) {
1840 n = 1;
1841 }
1842
1843 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001844 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001845 if (s->salvage) {
1846 if (n > 1) {
1847 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1848 continue;
1849 } else {
1850 if (!s->quiet) {
1851 warn_report("error while reading offset %" PRIu64
1852 ": %s", offset, strerror(-ret));
1853 }
1854 memset(buf, 0, BDRV_SECTOR_SIZE);
1855 }
1856 } else {
1857 return ret;
1858 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001859 }
1860
1861 sector_num += n;
1862 nb_sectors -= n;
1863 buf += n * BDRV_SECTOR_SIZE;
1864 }
1865
1866 return 0;
1867}
1868
Peter Lieven2d9187b2017-02-28 13:40:07 +01001869
1870static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1871 int nb_sectors, uint8_t *buf,
1872 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001873{
1874 int ret;
1875
1876 while (nb_sectors > 0) {
1877 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001878 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1879
Peter Lieven2d9187b2017-02-28 13:40:07 +01001880 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001881 case BLK_BACKING_FILE:
1882 /* If we have a backing file, leave clusters unallocated that are
1883 * unallocated in the source image, so that the backing file is
1884 * visible at the respective offset. */
1885 assert(s->target_has_backing);
1886 break;
1887
1888 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001889 /* If we're told to keep the target fully allocated (-S 0) or there
1890 * is real non-zero data, we must write it. Otherwise we can treat
1891 * it as zero sectors.
1892 * Compressed clusters need to be written as a whole, so in that
1893 * case we can only save the write if the buffer is completely
1894 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001895 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001896 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001897 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1898 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001899 (s->compressed &&
1900 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001901 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001902 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1903 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001904 if (ret < 0) {
1905 return ret;
1906 }
1907 break;
1908 }
1909 /* fall-through */
1910
1911 case BLK_ZERO:
1912 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001913 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001914 break;
1915 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001916 ret = blk_co_pwrite_zeroes(s->target,
1917 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001918 n << BDRV_SECTOR_BITS,
1919 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001920 if (ret < 0) {
1921 return ret;
1922 }
1923 break;
1924 }
1925
1926 sector_num += n;
1927 nb_sectors -= n;
1928 buf += n * BDRV_SECTOR_SIZE;
1929 }
1930
1931 return 0;
1932}
1933
Fam Zhengee5306d2018-06-01 17:26:48 +08001934static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1935 int nb_sectors)
1936{
1937 int n, ret;
1938
1939 while (nb_sectors > 0) {
1940 BlockBackend *blk;
1941 int src_cur;
1942 int64_t bs_sectors, src_cur_offset;
1943 int64_t offset;
1944
1945 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1946 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1947 blk = s->src[src_cur];
1948 bs_sectors = s->src_sectors[src_cur];
1949
1950 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1951
1952 ret = blk_co_copy_range(blk, offset, s->target,
1953 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001954 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001955 if (ret < 0) {
1956 return ret;
1957 }
1958
1959 sector_num += n;
1960 nb_sectors -= n;
1961 }
1962 return 0;
1963}
1964
Peter Lieven2d9187b2017-02-28 13:40:07 +01001965static void coroutine_fn convert_co_do_copy(void *opaque)
1966{
1967 ImgConvertState *s = opaque;
1968 uint8_t *buf = NULL;
1969 int ret, i;
1970 int index = -1;
1971
1972 for (i = 0; i < s->num_coroutines; i++) {
1973 if (s->co[i] == qemu_coroutine_self()) {
1974 index = i;
1975 break;
1976 }
1977 }
1978 assert(index >= 0);
1979
1980 s->running_coroutines++;
1981 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1982
1983 while (1) {
1984 int n;
1985 int64_t sector_num;
1986 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001987 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001988
1989 qemu_co_mutex_lock(&s->lock);
1990 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1991 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001992 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001993 }
Kevin Wolf7ff95792023-02-03 16:21:43 +01001994 WITH_GRAPH_RDLOCK_GUARD() {
1995 n = convert_iteration_sectors(s, s->sector_num);
1996 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001997 if (n < 0) {
1998 qemu_co_mutex_unlock(&s->lock);
1999 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03002000 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002001 }
2002 /* save current sector and allocation status to local variables */
2003 sector_num = s->sector_num;
2004 status = s->status;
2005 if (!s->min_sparse && s->status == BLK_ZERO) {
2006 n = MIN(n, s->buf_sectors);
2007 }
2008 /* increment global sector counter so that other coroutines can
2009 * already continue reading beyond this request */
2010 s->sector_num += n;
2011 qemu_co_mutex_unlock(&s->lock);
2012
2013 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2014 s->allocated_done += n;
2015 qemu_progress_print(100.0 * s->allocated_done /
2016 s->allocated_sectors, 0);
2017 }
2018
Fam Zhengee5306d2018-06-01 17:26:48 +08002019retry:
2020 copy_range = s->copy_range && s->status == BLK_DATA;
2021 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002022 ret = convert_co_read(s, sector_num, n, buf);
2023 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002024 error_report("error while reading at byte %lld: %s",
2025 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002026 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002027 }
2028 } else if (!s->min_sparse && status == BLK_ZERO) {
2029 status = BLK_DATA;
2030 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2031 }
2032
2033 if (s->wr_in_order) {
2034 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002035 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002036 s->wait_sector_num[index] = sector_num;
2037 qemu_coroutine_yield();
2038 }
2039 s->wait_sector_num[index] = -1;
2040 }
2041
Anton Nefedovb91127e2017-04-26 11:33:15 +03002042 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002043 if (copy_range) {
Emanuele Giuseppe Esposito742bf092023-02-03 16:21:53 +01002044 WITH_GRAPH_RDLOCK_GUARD() {
2045 ret = convert_co_copy_range(s, sector_num, n);
2046 }
Fam Zhengee5306d2018-06-01 17:26:48 +08002047 if (ret) {
2048 s->copy_range = false;
2049 goto retry;
2050 }
2051 } else {
2052 ret = convert_co_write(s, sector_num, n, buf, status);
2053 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002054 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002055 error_report("error while writing at byte %lld: %s",
2056 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002057 s->ret = ret;
2058 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002059 }
2060
2061 if (s->wr_in_order) {
2062 /* reenter the coroutine that might have waited
2063 * for this write to complete */
2064 s->wr_offs = sector_num + n;
2065 for (i = 0; i < s->num_coroutines; i++) {
2066 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2067 /*
2068 * A -> B -> A cannot occur because A has
2069 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2070 * B will never enter A during this time window.
2071 */
2072 qemu_coroutine_enter(s->co[i]);
2073 break;
2074 }
2075 }
2076 }
2077 }
2078
Peter Lieven2d9187b2017-02-28 13:40:07 +01002079 qemu_vfree(buf);
2080 s->co[index] = NULL;
2081 s->running_coroutines--;
2082 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2083 /* the convert job finished successfully */
2084 s->ret = 0;
2085 }
2086}
2087
Kevin Wolf690c7302015-03-19 13:33:32 +01002088static int convert_do_copy(ImgConvertState *s)
2089{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002090 int ret, i, n;
2091 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002092
2093 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002094 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2095 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002096 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002097 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002098
Kevin Wolf690c7302015-03-19 13:33:32 +01002099 /* Allocate buffer for copied data. For compressed images, only one cluster
2100 * can be copied at a time. */
2101 if (s->compressed) {
2102 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2103 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002104 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002105 }
2106 s->buf_sectors = s->cluster_sectors;
2107 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002108
Kevin Wolf690c7302015-03-19 13:33:32 +01002109 while (sector_num < s->total_sectors) {
2110 n = convert_iteration_sectors(s, sector_num);
2111 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002112 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002113 }
Max Reitzaad15de2016-03-24 23:33:57 +01002114 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2115 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002116 s->allocated_sectors += n;
2117 }
2118 sector_num += n;
2119 }
2120
2121 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002122 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002123 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002124
Peter Lieven2d9187b2017-02-28 13:40:07 +01002125 qemu_co_mutex_init(&s->lock);
2126 for (i = 0; i < s->num_coroutines; i++) {
2127 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2128 s->wait_sector_num[i] = -1;
2129 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002130 }
2131
Anton Nefedovb91127e2017-04-26 11:33:15 +03002132 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002133 main_loop_wait(false);
2134 }
2135
2136 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002137 /* signal EOF to align */
Alberto Faria0cadf2c2022-07-05 17:15:18 +01002138 ret = blk_pwrite_compressed(s->target, 0, 0, NULL);
Kevin Wolf690c7302015-03-19 13:33:32 +01002139 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002140 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002141 }
2142 }
2143
Peter Lieven2d9187b2017-02-28 13:40:07 +01002144 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002145}
2146
Eric Blake74a43202021-07-09 10:39:50 -05002147/* Check that bitmaps can be copied, or output an error */
Eric Blake955171e2021-07-21 10:53:48 -05002148static int convert_check_bitmaps(BlockDriverState *src, bool skip_broken)
Eric Blake74a43202021-07-09 10:39:50 -05002149{
2150 BdrvDirtyBitmap *bm;
2151
2152 if (!bdrv_supports_persistent_dirty_bitmap(src)) {
2153 error_report("Source lacks bitmap support");
2154 return -1;
2155 }
2156 FOR_EACH_DIRTY_BITMAP(src, bm) {
2157 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2158 continue;
2159 }
Eric Blake955171e2021-07-21 10:53:48 -05002160 if (!skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
Eric Blake74a43202021-07-09 10:39:50 -05002161 error_report("Cannot copy inconsistent bitmap '%s'",
2162 bdrv_dirty_bitmap_name(bm));
Eric Blake955171e2021-07-21 10:53:48 -05002163 error_printf("Try --skip-broken-bitmaps, or "
2164 "use 'qemu-img bitmap --remove' to delete it\n");
Eric Blake74a43202021-07-09 10:39:50 -05002165 return -1;
2166 }
2167 }
2168 return 0;
2169}
2170
Eric Blake955171e2021-07-21 10:53:48 -05002171static int convert_copy_bitmaps(BlockDriverState *src, BlockDriverState *dst,
2172 bool skip_broken)
Eric Blake15e39ad2020-05-21 14:21:36 -05002173{
2174 BdrvDirtyBitmap *bm;
2175 Error *err = NULL;
2176
2177 FOR_EACH_DIRTY_BITMAP(src, bm) {
2178 const char *name;
2179
2180 if (!bdrv_dirty_bitmap_get_persistence(bm)) {
2181 continue;
2182 }
2183 name = bdrv_dirty_bitmap_name(bm);
Eric Blake955171e2021-07-21 10:53:48 -05002184 if (skip_broken && bdrv_dirty_bitmap_inconsistent(bm)) {
2185 warn_report("Skipping inconsistent bitmap '%s'", name);
2186 continue;
2187 }
Eric Blake15e39ad2020-05-21 14:21:36 -05002188 qmp_block_dirty_bitmap_add(dst->node_name, name,
2189 true, bdrv_dirty_bitmap_granularity(bm),
2190 true, true,
2191 true, !bdrv_dirty_bitmap_enabled(bm),
2192 &err);
2193 if (err) {
2194 error_reportf_err(err, "Failed to create bitmap %s: ", name);
2195 return -1;
2196 }
2197
2198 do_dirty_bitmap_merge(dst->node_name, name, src->node_name, name,
2199 &err);
2200 if (err) {
2201 error_reportf_err(err, "Failed to populate bitmap %s: ", name);
Eric Blake74a43202021-07-09 10:39:50 -05002202 qmp_block_dirty_bitmap_remove(dst->node_name, name, NULL);
Eric Blake15e39ad2020-05-21 14:21:36 -05002203 return -1;
2204 }
2205 }
2206
2207 return 0;
2208}
2209
Peter Lieven6360ab22018-07-13 09:15:39 +02002210#define MAX_BUF_SECTORS 32768
2211
Zhengui0c8c4892020-10-20 14:47:44 +00002212static void set_rate_limit(BlockBackend *blk, int64_t rate_limit)
2213{
2214 ThrottleConfig cfg;
2215
2216 throttle_config_init(&cfg);
2217 cfg.buckets[THROTTLE_BPS_WRITE].avg = rate_limit;
2218
2219 blk_io_limits_enable(blk, CONVERT_THROTTLE_GROUP);
2220 blk_set_io_limits(blk, &cfg);
2221}
2222
bellardea2384d2004-08-01 21:59:26 +00002223static int img_convert(int argc, char **argv)
2224{
Kevin Wolf0b8fb552021-04-22 18:43:44 +02002225 int c, bs_i, flags, src_flags = BDRV_O_NO_SHARE;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002226 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002227 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
Eric Blake1899bf42021-09-13 08:17:35 -05002228 *out_filename, *out_baseimg_param, *snapshot_name = NULL,
2229 *backing_fmt = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002230 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002231 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002232 BlockDriverState *out_bs;
2233 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002234 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002235 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002236 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002237 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002238 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002239 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002240 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002241 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002242 bool explict_min_sparse = false;
Eric Blake15e39ad2020-05-21 14:21:36 -05002243 bool bitmaps = false;
Eric Blake955171e2021-07-21 10:53:48 -05002244 bool skip_broken = false;
Zhengui0c8c4892020-10-20 14:47:44 +00002245 int64_t rate_limit = 0;
bellardea2384d2004-08-01 21:59:26 +00002246
Peter Lieven9fd77f92017-04-21 11:11:55 +02002247 ImgConvertState s = (ImgConvertState) {
2248 /* Need at least 4k of zeros for sparse detection */
2249 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002250 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002251 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2252 .wr_in_order = true,
2253 .num_coroutines = 8,
2254 };
2255
bellardea2384d2004-08-01 21:59:26 +00002256 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002257 static const struct option long_options[] = {
2258 {"help", no_argument, 0, 'h'},
2259 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002260 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002261 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002262 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002263 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002264 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Eric Blake15e39ad2020-05-21 14:21:36 -05002265 {"bitmaps", no_argument, 0, OPTION_BITMAPS},
Eric Blake955171e2021-07-21 10:53:48 -05002266 {"skip-broken-bitmaps", no_argument, 0, OPTION_SKIP_BROKEN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002267 {0, 0, 0, 0}
2268 };
Eric Blake1899bf42021-09-13 08:17:35 -05002269 c = getopt_long(argc, argv, ":hf:O:B:CcF:o:l:S:pt:T:qnm:WUr:",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002270 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002271 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002272 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002273 }
bellardea2384d2004-08-01 21:59:26 +00002274 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002275 case ':':
2276 missing_argument(argv[optind - 1]);
2277 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002278 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002279 unrecognized_option(argv[optind - 1]);
2280 break;
bellardea2384d2004-08-01 21:59:26 +00002281 case 'h':
2282 help();
2283 break;
2284 case 'f':
2285 fmt = optarg;
2286 break;
2287 case 'O':
2288 out_fmt = optarg;
2289 break;
thsf58c7b32008-06-05 21:53:49 +00002290 case 'B':
2291 out_baseimg = optarg;
2292 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002293 case 'C':
2294 s.copy_range = true;
2295 break;
bellardea2384d2004-08-01 21:59:26 +00002296 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002297 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002298 break;
Eric Blake1899bf42021-09-13 08:17:35 -05002299 case 'F':
2300 backing_fmt = optarg;
2301 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002302 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002303 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002304 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002305 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002306 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002307 case 'l':
2308 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002309 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2310 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002311 if (!sn_opts) {
2312 error_report("Failed in parsing snapshot param '%s'",
2313 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002314 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002315 }
2316 } else {
2317 snapshot_name = optarg;
2318 }
2319 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002320 case 'S':
2321 {
2322 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002323
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002324 sval = cvtnum("buffer size for sparse output", optarg);
2325 if (sval < 0) {
2326 goto fail_getopt;
2327 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002328 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2329 error_report("Invalid buffer size for sparse output specified. "
2330 "Valid sizes are multiples of %llu up to %llu. Select "
2331 "0 to disable sparse detection (fully allocates output).",
2332 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002333 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002334 }
2335
Peter Lieven9fd77f92017-04-21 11:11:55 +02002336 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002337 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002338 break;
2339 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002340 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002341 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002342 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002343 case 't':
2344 cache = optarg;
2345 break;
Max Reitz40055952014-07-22 22:58:42 +02002346 case 'T':
2347 src_cache = optarg;
2348 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002349 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002350 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002351 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002352 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002353 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002354 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002355 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002356 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2357 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002358 error_report("Invalid number of coroutines. Allowed number of"
2359 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002360 goto fail_getopt;
2361 }
2362 break;
2363 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002364 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002365 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002366 case 'U':
2367 force_share = true;
2368 break;
Zhengui0c8c4892020-10-20 14:47:44 +00002369 case 'r':
2370 rate_limit = cvtnum("rate limit", optarg);
2371 if (rate_limit < 0) {
2372 goto fail_getopt;
2373 }
2374 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01002375 case OPTION_OBJECT:
2376 user_creatable_process_cmdline(optarg);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002377 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002378 case OPTION_IMAGE_OPTS:
2379 image_opts = true;
2380 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002381 case OPTION_SALVAGE:
2382 s.salvage = true;
2383 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002384 case OPTION_TARGET_IMAGE_OPTS:
2385 tgt_image_opts = true;
2386 break;
David Edmondson168468f2020-02-05 11:02:48 +00002387 case OPTION_TARGET_IS_ZERO:
2388 /*
2389 * The user asserting that the target is blank has the
2390 * same effect as the target driver supporting zero
2391 * initialisation.
2392 */
2393 s.has_zero_init = true;
2394 break;
Eric Blake15e39ad2020-05-21 14:21:36 -05002395 case OPTION_BITMAPS:
2396 bitmaps = true;
2397 break;
Eric Blake955171e2021-07-21 10:53:48 -05002398 case OPTION_SKIP_BROKEN:
2399 skip_broken = true;
2400 break;
bellardea2384d2004-08-01 21:59:26 +00002401 }
2402 }
ths3b46e622007-09-17 08:09:54 +00002403
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002404 if (!out_fmt && !tgt_image_opts) {
2405 out_fmt = "raw";
2406 }
2407
Eric Blake955171e2021-07-21 10:53:48 -05002408 if (skip_broken && !bitmaps) {
2409 error_report("Use of --skip-broken-bitmaps requires --bitmaps");
2410 goto fail_getopt;
2411 }
2412
Fam Zhenge11ce122018-07-27 11:34:01 +08002413 if (s.compressed && s.copy_range) {
2414 error_report("Cannot enable copy offloading when -c is used");
2415 goto fail_getopt;
2416 }
2417
2418 if (explict_min_sparse && s.copy_range) {
2419 error_report("Cannot enable copy offloading when -S is used");
2420 goto fail_getopt;
2421 }
2422
Max Reitz8eaac022019-05-07 22:35:03 +02002423 if (s.copy_range && s.salvage) {
2424 error_report("Cannot use copy offloading in salvaging mode");
2425 goto fail_getopt;
2426 }
2427
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002428 if (tgt_image_opts && !skip_create) {
2429 error_report("--target-image-opts requires use of -n flag");
2430 goto fail_getopt;
2431 }
2432
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002433 if (skip_create && options) {
Eric Blake25956af2020-07-06 15:39:46 -05002434 error_report("-o has no effect when skipping image creation");
2435 goto fail_getopt;
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002436 }
2437
David Edmondson168468f2020-02-05 11:02:48 +00002438 if (s.has_zero_init && !skip_create) {
2439 error_report("--target-is-zero requires use of -n flag");
2440 goto fail_getopt;
2441 }
2442
Peter Lieven9fd77f92017-04-21 11:11:55 +02002443 s.src_num = argc - optind - 1;
2444 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2445
2446 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002447 if (out_fmt) {
2448 ret = print_block_option_help(out_filename, out_fmt);
2449 goto fail_getopt;
2450 } else {
2451 error_report("Option help requires a format be specified");
2452 goto fail_getopt;
2453 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002454 }
2455
2456 if (s.src_num < 1) {
2457 error_report("Must specify image file name");
2458 goto fail_getopt;
2459 }
2460
Peter Lieven9fd77f92017-04-21 11:11:55 +02002461 /* ret is still -EINVAL until here */
2462 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2463 if (ret < 0) {
2464 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002465 goto fail_getopt;
2466 }
2467
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002468 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002469 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002470 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002471 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002472 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002473 qemu_progress_print(0, 100);
2474
Peter Lieven9fd77f92017-04-21 11:11:55 +02002475 s.src = g_new0(BlockBackend *, s.src_num);
2476 s.src_sectors = g_new(int64_t, s.src_num);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002477 s.src_alignment = g_new(int, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002478
Peter Lieven9fd77f92017-04-21 11:11:55 +02002479 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002480 BlockDriverState *src_bs;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002481 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002482 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002483 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002484 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002485 ret = -1;
2486 goto out;
2487 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002488 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2489 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002490 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002491 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002492 ret = -1;
2493 goto out;
2494 }
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002495 src_bs = blk_bs(s.src[bs_i]);
2496 s.src_alignment[bs_i] = DIV_ROUND_UP(src_bs->bl.request_alignment,
2497 BDRV_SECTOR_SIZE);
2498 if (!bdrv_get_info(src_bs, &bdi)) {
2499 s.src_alignment[bs_i] = MAX(s.src_alignment[bs_i],
2500 bdi.cluster_size / BDRV_SECTOR_SIZE);
2501 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002502 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002503 }
bellardea2384d2004-08-01 21:59:26 +00002504
Wenchao Xiaef806542013-12-04 17:10:57 +08002505 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002506 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002507 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2508 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2509 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002510 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002511 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002512 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002513 ret = -1;
2514 goto out;
2515 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002516
Peter Lieven9fd77f92017-04-21 11:11:55 +02002517 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2518 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002519 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002520 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002521 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002522 ret = -1;
2523 goto out;
edison51ef6722010-09-21 19:58:41 -07002524 }
2525
Max Reitz2e024cd2015-02-11 09:58:46 -05002526 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002527 /* Find driver and parse its options */
2528 drv = bdrv_find_format(out_fmt);
2529 if (!drv) {
2530 error_report("Unknown file format '%s'", out_fmt);
2531 ret = -1;
2532 goto out;
2533 }
2534
2535 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2536 if (!proto_drv) {
2537 error_report_err(local_err);
2538 ret = -1;
2539 goto out;
2540 }
2541
Max Reitz2e024cd2015-02-11 09:58:46 -05002542 if (!drv->create_opts) {
2543 error_report("Format driver '%s' does not support image creation",
2544 drv->format_name);
2545 ret = -1;
2546 goto out;
2547 }
Max Reitzf75613c2014-12-02 18:32:46 +01002548
Max Reitz2e024cd2015-02-11 09:58:46 -05002549 if (!proto_drv->create_opts) {
2550 error_report("Protocol driver '%s' does not support image creation",
2551 proto_drv->format_name);
2552 ret = -1;
2553 goto out;
2554 }
Max Reitzf75613c2014-12-02 18:32:46 +01002555
Max Reitz2e024cd2015-02-11 09:58:46 -05002556 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2557 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002558
Max Reitz2e024cd2015-02-11 09:58:46 -05002559 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002560 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02002561 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002562 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002563 ret = -1;
2564 goto out;
2565 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002566 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002567
Yi Lic075c422020-08-19 09:36:07 +08002568 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2569 s.total_sectors * BDRV_SECTOR_SIZE, &error_abort);
Eric Blake1899bf42021-09-13 08:17:35 -05002570 ret = add_old_style_options(out_fmt, opts, out_baseimg, backing_fmt);
Max Reitz2e024cd2015-02-11 09:58:46 -05002571 if (ret < 0) {
2572 goto out;
2573 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002574 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002575
Kevin Wolfa18953f2010-10-14 15:46:04 +02002576 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002577 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002578 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002579 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002580 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002581 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002582
David Edmondson168468f2020-02-05 11:02:48 +00002583 if (s.has_zero_init && s.target_has_backing) {
2584 error_report("Cannot use --target-is-zero when the destination "
2585 "image has a backing file");
2586 goto out;
2587 }
2588
Max Reitz48758a82017-04-26 15:46:48 +02002589 if (s.src_num > 1 && out_baseimg) {
2590 error_report("Having a backing file for the target makes no sense when "
2591 "concatenating multiple input images");
2592 ret = -1;
2593 goto out;
2594 }
2595
Eric Blaked9f059a2020-07-06 15:39:54 -05002596 if (out_baseimg_param) {
2597 if (!qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT)) {
Eric Blake497a30d2021-05-03 14:36:00 -07002598 error_report("Use of backing file requires explicit "
2599 "backing format");
2600 ret = -1;
2601 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05002602 }
2603 }
2604
Kevin Wolfefa84d42009-05-18 16:42:12 +02002605 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002606 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002607 bool encryption =
2608 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002609 const char *encryptfmt =
2610 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002611 const char *preallocation =
2612 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002613
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002614 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002615 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002616 ret = -1;
2617 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002618 }
2619
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002620 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002621 error_report("Compression and encryption not supported at "
2622 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002623 ret = -1;
2624 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002625 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002626
Chunyan Liu83d05212014-06-05 17:20:51 +08002627 if (preallocation
2628 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002629 {
2630 error_report("Compression and preallocation not supported at "
2631 "the same time");
2632 ret = -1;
2633 goto out;
2634 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002635 }
2636
Eric Blake15e39ad2020-05-21 14:21:36 -05002637 /* Determine if bitmaps need copying */
2638 if (bitmaps) {
2639 if (s.src_num > 1) {
2640 error_report("Copying bitmaps only possible with single source");
2641 ret = -1;
2642 goto out;
2643 }
Eric Blake955171e2021-07-21 10:53:48 -05002644 ret = convert_check_bitmaps(blk_bs(s.src[0]), skip_broken);
Eric Blake74a43202021-07-09 10:39:50 -05002645 if (ret < 0) {
Eric Blake15e39ad2020-05-21 14:21:36 -05002646 goto out;
2647 }
2648 }
2649
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002650 /*
2651 * The later open call will need any decryption secrets, and
2652 * bdrv_create() will purge "opts", so extract them now before
2653 * they are lost.
2654 */
2655 if (!skip_create) {
2656 open_opts = qdict_new();
2657 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002658
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002659 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002660 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002661 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002662 error_reportf_err(local_err, "%s: error while converting %s: ",
2663 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002664 goto out;
bellardea2384d2004-08-01 21:59:26 +00002665 }
2666 }
ths3b46e622007-09-17 08:09:54 +00002667
Max Reitz4d7c4872019-07-24 19:12:29 +02002668 s.target_is_new = !skip_create;
2669
Peter Lieven9fd77f92017-04-21 11:11:55 +02002670 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002671 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002672 if (ret < 0) {
2673 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002674 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002675 }
2676
Hanna Reitza1c62432021-08-19 12:12:00 +02002677 if (flags & BDRV_O_NOCACHE) {
2678 /*
2679 * If we open the target with O_DIRECT, it may be necessary to
2680 * extend its size to align to the physical sector size.
2681 */
2682 flags |= BDRV_O_RESIZE;
2683 }
2684
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002685 if (skip_create) {
2686 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002687 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002688 } else {
2689 /* TODO ultimately we should allow --target-image-opts
2690 * to be used even when -n is not given.
2691 * That has to wait for bdrv_create to be improved
2692 * to allow filenames in option syntax
2693 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002694 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002695 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002696 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002697 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002698 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002699 ret = -1;
2700 goto out;
2701 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002702 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002703
Eric Blake15e39ad2020-05-21 14:21:36 -05002704 if (bitmaps && !bdrv_supports_persistent_dirty_bitmap(out_bs)) {
2705 error_report("Format driver '%s' does not support bitmaps",
2706 out_bs->drv->format_name);
2707 ret = -1;
2708 goto out;
2709 }
2710
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002711 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002712 error_report("Compression not supported for this file format");
2713 ret = -1;
2714 goto out;
2715 }
2716
Eric Blake5def6b82016-06-23 16:37:19 -06002717 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002718 * or discard_alignment of the out_bs is greater. Limit to
2719 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2720 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002721 MAX(s.buf_sectors,
2722 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2723 out_bs->bl.pdiscard_alignment >>
2724 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002725
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002726 /* try to align the write requests to the destination to avoid unnecessary
2727 * RMW cycles. */
2728 s.alignment = MAX(pow2floor(s.min_sparse),
2729 DIV_ROUND_UP(out_bs->bl.request_alignment,
2730 BDRV_SECTOR_SIZE));
2731 assert(is_power_of_2(s.alignment));
2732
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002733 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002734 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002735 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002736 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002737 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002738 ret = -1;
2739 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002740 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002741 error_report("output file is smaller than input file");
2742 ret = -1;
2743 goto out;
2744 }
2745 }
2746
Max Reitzc69291e2020-01-21 16:59:14 +01002747 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002748 /* Errors are treated as "backing length unknown" (which means
2749 * s.target_backing_sectors has to be negative, which it will
2750 * be automatically). The backing file length is used only
2751 * for optimizations, so such a case is not fatal. */
Max Reitz4a2061e2019-06-12 19:00:30 +02002752 s.target_backing_sectors =
2753 bdrv_nb_sectors(bdrv_backing_chain_next(out_bs));
Max Reitz351c8ef2018-05-01 18:57:49 +02002754 } else {
2755 s.target_backing_sectors = -1;
2756 }
2757
Peter Lieven24f833c2013-11-27 11:07:07 +01002758 ret = bdrv_get_info(out_bs, &bdi);
2759 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002760 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002761 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002762 goto out;
2763 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002764 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002765 s.compressed = s.compressed || bdi.needs_compressed_writes;
2766 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Peter Lieven24f833c2013-11-27 11:07:07 +01002767 }
2768
Zhengui0c8c4892020-10-20 14:47:44 +00002769 if (rate_limit) {
2770 set_rate_limit(s.target, rate_limit);
2771 }
2772
Peter Lieven9fd77f92017-04-21 11:11:55 +02002773 ret = convert_do_copy(&s);
Eric Blake15e39ad2020-05-21 14:21:36 -05002774
2775 /* Now copy the bitmaps */
2776 if (bitmaps && ret == 0) {
Eric Blake955171e2021-07-21 10:53:48 -05002777 ret = convert_copy_bitmaps(blk_bs(s.src[0]), out_bs, skip_broken);
Eric Blake15e39ad2020-05-21 14:21:36 -05002778 }
2779
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002780out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002781 if (!ret) {
2782 qemu_progress_print(100, 0);
2783 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002784 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002785 qemu_opts_del(opts);
2786 qemu_opts_free(create_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002787 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002788 blk_unref(s.target);
2789 if (s.src) {
2790 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2791 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002792 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002793 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002794 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002795 g_free(s.src_sectors);
Peter Lievenaf8d43d2020-09-01 14:51:29 +02002796 g_free(s.src_alignment);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002797fail_getopt:
Tuguoyi6aec8302020-11-02 09:04:57 +00002798 qemu_opts_del(sn_opts);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002799 g_free(options);
2800
Peter Lieven9fd77f92017-04-21 11:11:55 +02002801 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002802}
2803
bellard57d1a2b2004-08-03 21:15:11 +00002804
bellardfaea38e2006-08-05 21:31:00 +00002805static void dump_snapshots(BlockDriverState *bs)
2806{
2807 QEMUSnapshotInfo *sn_tab, *sn;
2808 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002809
2810 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2811 if (nb_sns <= 0)
2812 return;
2813 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002814 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002815 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002816 for(i = 0; i < nb_sns; i++) {
2817 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002818 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002819 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002820 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002821 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002822}
2823
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002824static void dump_json_block_graph_info_list(BlockGraphInfoList *list)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002825{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002826 GString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002827 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002828 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002829
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002830 visit_type_BlockGraphInfoList(v, NULL, &list, &error_abort);
Eric Blake3b098d52016-06-09 10:48:43 -06002831 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002832 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002833 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002834 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002835 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002836 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002837 g_string_free(str, true);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002838}
2839
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002840static void dump_json_block_graph_info(BlockGraphInfo *info)
Benoît Canetc054b3f2012-09-05 13:09:02 +02002841{
Markus Armbrustereab3a462020-12-11 18:11:37 +01002842 GString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002843 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002844 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002845
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002846 visit_type_BlockGraphInfo(v, NULL, &info, &error_abort);
Eric Blake3b098d52016-06-09 10:48:43 -06002847 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01002848 str = qobject_to_json_pretty(obj, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002849 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002850 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002851 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002852 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01002853 g_string_free(str, true);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002854}
2855
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002856static void dump_human_image_info(BlockGraphInfo *info, int indentation,
2857 const char *path)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002858{
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002859 BlockChildInfoList *children_list;
2860
Hanna Reitzd5701772022-06-20 18:27:04 +02002861 bdrv_node_info_dump(qapi_BlockGraphInfo_base(info), indentation,
2862 info->children == NULL);
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002863
2864 for (children_list = info->children; children_list;
2865 children_list = children_list->next)
2866 {
2867 BlockChildInfo *child = children_list->value;
2868 g_autofree char *child_path = NULL;
2869
2870 printf("%*sChild node '%s%s':\n",
2871 indentation * 4, "", path, child->name);
2872 child_path = g_strdup_printf("%s%s/", path, child->name);
2873 dump_human_image_info(child->info, indentation + 1, child_path);
2874 }
2875}
2876
2877static void dump_human_image_info_list(BlockGraphInfoList *list)
2878{
2879 BlockGraphInfoList *elem;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002880 bool delim = false;
2881
2882 for (elem = list; elem; elem = elem->next) {
2883 if (delim) {
2884 printf("\n");
2885 }
2886 delim = true;
2887
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002888 dump_human_image_info(elem->value, 0, "/");
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002889 }
2890}
2891
2892static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2893{
2894 return strcmp(a, b) == 0;
2895}
2896
2897/**
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002898 * Open an image file chain and return an BlockGraphInfoList
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002899 *
2900 * @filename: topmost image filename
2901 * @fmt: topmost image format (may be NULL to autodetect)
2902 * @chain: true - enumerate entire backing file chain
2903 * false - only topmost image file
2904 *
Hanna Reitzb1f4cd12022-06-20 18:26:57 +02002905 * Returns a list of BlockNodeInfo objects or NULL if there was an error
2906 * opening an image file. If there was an error a message will have been
2907 * printed to stderr.
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002908 */
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002909static BlockGraphInfoList *collect_image_info_list(bool image_opts,
2910 const char *filename,
2911 const char *fmt,
2912 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002913{
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002914 BlockGraphInfoList *head = NULL;
2915 BlockGraphInfoList **tail = &head;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002916 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002917 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002918
2919 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2920
2921 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002922 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002923 BlockDriverState *bs;
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002924 BlockGraphInfo *info;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002925
2926 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2927 error_report("Backing file '%s' creates an infinite loop.",
2928 filename);
2929 goto err;
2930 }
2931 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2932
Max Reitzefaa7c42016-03-16 19:54:38 +01002933 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002934 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2935 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002936 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002937 goto err;
2938 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002939 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002940
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002941 /*
2942 * Note that the returned BlockGraphInfo object will not have
2943 * information about this image's backing node, because we have opened
2944 * it with BDRV_O_NO_BACKING. Printing this object will therefore not
2945 * duplicate the backing chain information that we obtain by walking
2946 * the chain manually here.
2947 */
Kevin Wolf3db0c8b2023-05-10 22:35:57 +02002948 bdrv_graph_rdlock_main_loop();
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002949 bdrv_query_block_graph_info(bs, &info, &err);
Kevin Wolf3db0c8b2023-05-10 22:35:57 +02002950 bdrv_graph_rdunlock_main_loop();
2951
Markus Armbruster84d18f02014-01-30 15:07:28 +01002952 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002953 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002954 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002955 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002956 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002957
Eric Blakec3033fd2021-01-13 16:10:12 -06002958 QAPI_LIST_APPEND(tail, info);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002959
Markus Armbruster26f54e92014-10-07 13:59:04 +02002960 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002961
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002962 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002963 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002964 image_opts = false;
2965
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002966 if (chain) {
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002967 if (info->full_backing_filename) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002968 filename = info->full_backing_filename;
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002969 } else if (info->backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002970 error_report("Could not determine absolute backing filename,"
2971 " but backing filename '%s' present",
2972 info->backing_filename);
2973 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002974 }
Markus Armbruster54fde4f2022-11-04 17:06:52 +01002975 if (info->backing_filename_format) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002976 fmt = info->backing_filename_format;
2977 }
2978 }
2979 }
2980 g_hash_table_destroy(filenames);
2981 return head;
2982
2983err:
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002984 qapi_free_BlockGraphInfoList(head);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002985 g_hash_table_destroy(filenames);
2986 return NULL;
2987}
2988
Benoît Canetc054b3f2012-09-05 13:09:02 +02002989static int img_info(int argc, char **argv)
2990{
2991 int c;
2992 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002993 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002994 const char *filename, *fmt, *output;
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02002995 BlockGraphInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002996 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002997 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002998
bellardea2384d2004-08-01 21:59:26 +00002999 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02003000 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00003001 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02003002 int option_index = 0;
3003 static const struct option long_options[] = {
3004 {"help", no_argument, 0, 'h'},
3005 {"format", required_argument, 0, 'f'},
3006 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003007 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003008 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003009 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003010 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02003011 {0, 0, 0, 0}
3012 };
Fam Zheng335e9932017-05-03 00:35:39 +08003013 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02003014 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003015 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00003016 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003017 }
bellardea2384d2004-08-01 21:59:26 +00003018 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003019 case ':':
3020 missing_argument(argv[optind - 1]);
3021 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003022 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003023 unrecognized_option(argv[optind - 1]);
3024 break;
bellardea2384d2004-08-01 21:59:26 +00003025 case 'h':
3026 help();
3027 break;
3028 case 'f':
3029 fmt = optarg;
3030 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003031 case 'U':
3032 force_share = true;
3033 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02003034 case OPTION_OUTPUT:
3035 output = optarg;
3036 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003037 case OPTION_BACKING_CHAIN:
3038 chain = true;
3039 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003040 case OPTION_OBJECT:
3041 user_creatable_process_cmdline(optarg);
3042 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003043 case OPTION_IMAGE_OPTS:
3044 image_opts = true;
3045 break;
bellardea2384d2004-08-01 21:59:26 +00003046 }
3047 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003048 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003049 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003050 }
bellardea2384d2004-08-01 21:59:26 +00003051 filename = argv[optind++];
3052
Benoît Canetc054b3f2012-09-05 13:09:02 +02003053 if (output && !strcmp(output, "json")) {
3054 output_format = OFORMAT_JSON;
3055 } else if (output && !strcmp(output, "human")) {
3056 output_format = OFORMAT_HUMAN;
3057 } else if (output) {
3058 error_report("--output must be used with human or json as argument.");
3059 return 1;
3060 }
3061
Fam Zheng335e9932017-05-03 00:35:39 +08003062 list = collect_image_info_list(image_opts, filename, fmt, chain,
3063 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003064 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003065 return 1;
3066 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003067
Benoît Canetc054b3f2012-09-05 13:09:02 +02003068 switch (output_format) {
3069 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003070 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02003071 break;
3072 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003073 if (chain) {
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02003074 dump_json_block_graph_info_list(list);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003075 } else {
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02003076 dump_json_block_graph_info(list->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02003077 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003078 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003079 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02003080
Hanna Reitzc04d0ab2022-06-20 18:27:03 +02003081 qapi_free_BlockGraphInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00003082 return 0;
3083}
3084
Eric Blake30065d12019-03-26 13:40:43 -05003085static int dump_map_entry(OutputFormat output_format, MapEntry *e,
3086 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003087{
3088 switch (output_format) {
3089 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08003090 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003091 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05003092 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003093 }
Fam Zheng16b0d552016-01-26 11:59:02 +08003094 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003095 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08003096 e->start, e->length,
3097 e->has_offset ? e->offset : 0,
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003098 e->filename ?: "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003099 }
3100 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
3101 * Modify the flags here to allow more coalescing.
3102 */
Fam Zheng16b0d552016-01-26 11:59:02 +08003103 if (next && (!next->data || next->zero)) {
3104 next->data = false;
3105 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003106 }
3107 break;
3108 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003109 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Eric Blake8417e132021-07-01 14:06:55 -05003110 " \"depth\": %"PRId64", \"present\": %s, \"zero\": %s,"
Andrey Drobyshev via52b10c92023-09-08 00:02:26 +03003111 " \"data\": %s, \"compressed\": %s",
3112 e->start, e->length, e->depth,
Eric Blake8417e132021-07-01 14:06:55 -05003113 e->present ? "true" : "false",
Fam Zheng16b0d552016-01-26 11:59:02 +08003114 e->zero ? "true" : "false",
Andrey Drobyshev via52b10c92023-09-08 00:02:26 +03003115 e->data ? "true" : "false",
3116 e->compressed ? "true" : "false");
Fam Zheng16b0d552016-01-26 11:59:02 +08003117 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02003118 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003119 }
3120 putchar('}');
3121
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003122 if (next) {
3123 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003124 }
3125 break;
3126 }
Eric Blake30065d12019-03-26 13:40:43 -05003127 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003128}
3129
Eric Blake5e344dd2017-10-11 22:47:02 -05003130static int get_block_status(BlockDriverState *bs, int64_t offset,
3131 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003132{
Eric Blake237d78f2017-10-11 22:47:03 -05003133 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003134 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08003135 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05003136 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05003137 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01003138 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003139
3140 /* As an optimization, we could cache the current range of unallocated
3141 * clusters in each file of the chain, and avoid querying the same
3142 * range repeatedly.
3143 */
3144
3145 depth = 0;
3146 for (;;) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003147 bs = bdrv_skip_filters(bs);
Eric Blake237d78f2017-10-11 22:47:03 -05003148 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003149 if (ret < 0) {
3150 return ret;
3151 }
Eric Blake237d78f2017-10-11 22:47:03 -05003152 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003153 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
3154 break;
3155 }
Max Reitz4a2061e2019-06-12 19:00:30 +02003156 bs = bdrv_cow_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003157 if (bs == NULL) {
3158 ret = 0;
3159 break;
3160 }
3161
3162 depth++;
3163 }
3164
John Snow28756452016-02-05 13:12:33 -05003165 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3166
Max Reitzf30c66b2019-02-01 20:29:05 +01003167 if (file && has_offset) {
Kevin Wolfb7cfc7d2023-09-29 16:51:45 +02003168 bdrv_graph_rdlock_main_loop();
Max Reitzf30c66b2019-02-01 20:29:05 +01003169 bdrv_refresh_filename(file);
Kevin Wolfb7cfc7d2023-09-29 16:51:45 +02003170 bdrv_graph_rdunlock_main_loop();
Max Reitzf30c66b2019-02-01 20:29:05 +01003171 filename = file->filename;
3172 }
3173
John Snow28756452016-02-05 13:12:33 -05003174 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003175 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003176 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003177 .data = !!(ret & BDRV_BLOCK_DATA),
3178 .zero = !!(ret & BDRV_BLOCK_ZERO),
Andrey Drobyshev via52b10c92023-09-08 00:02:26 +03003179 .compressed = !!(ret & BDRV_BLOCK_COMPRESSED),
Eric Blake237d78f2017-10-11 22:47:03 -05003180 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003181 .has_offset = has_offset,
3182 .depth = depth,
Eric Blake8417e132021-07-01 14:06:55 -05003183 .present = !!(ret & BDRV_BLOCK_ALLOCATED),
Max Reitzf30c66b2019-02-01 20:29:05 +01003184 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003185 };
3186
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003187 return 0;
3188}
3189
Fam Zheng16b0d552016-01-26 11:59:02 +08003190static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3191{
3192 if (curr->length == 0) {
3193 return false;
3194 }
3195 if (curr->zero != next->zero ||
3196 curr->data != next->data ||
Andrey Drobyshev via52b10c92023-09-08 00:02:26 +03003197 curr->compressed != next->compressed ||
Fam Zheng16b0d552016-01-26 11:59:02 +08003198 curr->depth != next->depth ||
Eric Blake8417e132021-07-01 14:06:55 -05003199 curr->present != next->present ||
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003200 !curr->filename != !next->filename ||
Fam Zheng16b0d552016-01-26 11:59:02 +08003201 curr->has_offset != next->has_offset) {
3202 return false;
3203 }
Markus Armbruster54fde4f2022-11-04 17:06:52 +01003204 if (curr->filename && strcmp(curr->filename, next->filename)) {
Fam Zheng16b0d552016-01-26 11:59:02 +08003205 return false;
3206 }
3207 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3208 return false;
3209 }
3210 return true;
3211}
3212
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003213static int img_map(int argc, char **argv)
3214{
3215 int c;
3216 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003217 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003218 BlockDriverState *bs;
3219 const char *filename, *fmt, *output;
3220 int64_t length;
3221 MapEntry curr = { .length = 0 }, next;
3222 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003223 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003224 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003225 int64_t start_offset = 0;
3226 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003227
3228 fmt = NULL;
3229 output = NULL;
3230 for (;;) {
3231 int option_index = 0;
3232 static const struct option long_options[] = {
3233 {"help", no_argument, 0, 'h'},
3234 {"format", required_argument, 0, 'f'},
3235 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003236 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003237 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003238 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003239 {"start-offset", required_argument, 0, 's'},
3240 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003241 {0, 0, 0, 0}
3242 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003243 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003244 long_options, &option_index);
3245 if (c == -1) {
3246 break;
3247 }
3248 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003249 case ':':
3250 missing_argument(argv[optind - 1]);
3251 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003252 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003253 unrecognized_option(argv[optind - 1]);
3254 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003255 case 'h':
3256 help();
3257 break;
3258 case 'f':
3259 fmt = optarg;
3260 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003261 case 'U':
3262 force_share = true;
3263 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003264 case OPTION_OUTPUT:
3265 output = optarg;
3266 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003267 case 's':
3268 start_offset = cvtnum("start offset", optarg);
3269 if (start_offset < 0) {
3270 return 1;
3271 }
3272 break;
3273 case 'l':
3274 max_length = cvtnum("max length", optarg);
3275 if (max_length < 0) {
3276 return 1;
3277 }
3278 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003279 case OPTION_OBJECT:
3280 user_creatable_process_cmdline(optarg);
3281 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003282 case OPTION_IMAGE_OPTS:
3283 image_opts = true;
3284 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003285 }
3286 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003287 if (optind != argc - 1) {
3288 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003289 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003290 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003291
3292 if (output && !strcmp(output, "json")) {
3293 output_format = OFORMAT_JSON;
3294 } else if (output && !strcmp(output, "human")) {
3295 output_format = OFORMAT_HUMAN;
3296 } else if (output) {
3297 error_report("--output must be used with human or json as argument.");
3298 return 1;
3299 }
3300
Fam Zheng335e9932017-05-03 00:35:39 +08003301 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003302 if (!blk) {
3303 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003304 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003305 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003306
3307 if (output_format == OFORMAT_HUMAN) {
3308 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003309 } else if (output_format == OFORMAT_JSON) {
3310 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003311 }
3312
Max Reitzf1d3cd72015-02-05 13:58:18 -05003313 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003314 if (length < 0) {
3315 error_report("Failed to get size for '%s'", filename);
3316 return 1;
3317 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003318 if (max_length != -1) {
3319 length = MIN(start_offset + max_length, length);
3320 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003321
Eyal Moscovicic0469492020-05-13 16:36:29 +03003322 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003323 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003324 int64_t offset = curr.start + curr.length;
Kevin Wolfd0ceea82020-07-07 16:46:29 +02003325 int64_t n = length - offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003326
Eric Blake5e344dd2017-10-11 22:47:02 -05003327 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003328 if (ret < 0) {
3329 error_report("Could not read file metadata: %s", strerror(-ret));
3330 goto out;
3331 }
3332
Fam Zheng16b0d552016-01-26 11:59:02 +08003333 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003334 curr.length += next.length;
3335 continue;
3336 }
3337
3338 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003339 ret = dump_map_entry(output_format, &curr, &next);
3340 if (ret < 0) {
3341 goto out;
3342 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003343 }
3344 curr = next;
3345 }
3346
Eric Blake30065d12019-03-26 13:40:43 -05003347 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003348 if (output_format == OFORMAT_JSON) {
3349 puts("]");
3350 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003351
3352out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003353 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003354 return ret < 0;
3355}
3356
aliguorif7b4a942009-01-07 17:40:15 +00003357#define SNAPSHOT_LIST 1
3358#define SNAPSHOT_CREATE 2
3359#define SNAPSHOT_APPLY 3
3360#define SNAPSHOT_DELETE 4
3361
Stuart Brady153859b2009-06-07 00:42:17 +01003362static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003363{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003364 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003365 BlockDriverState *bs;
3366 QEMUSnapshotInfo sn;
3367 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003368 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003369 int action = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003370 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003371 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003372 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003373 bool force_share = false;
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003374 int64_t rt;
aliguorif7b4a942009-01-07 17:40:15 +00003375
Kevin Wolfce099542016-03-15 13:01:04 +01003376 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003377 /* Parse commandline parameters */
3378 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003379 static const struct option long_options[] = {
3380 {"help", no_argument, 0, 'h'},
3381 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003382 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003383 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003384 {0, 0, 0, 0}
3385 };
Fam Zheng335e9932017-05-03 00:35:39 +08003386 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003387 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003388 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003389 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003390 }
aliguorif7b4a942009-01-07 17:40:15 +00003391 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003392 case ':':
3393 missing_argument(argv[optind - 1]);
3394 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003395 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003396 unrecognized_option(argv[optind - 1]);
3397 break;
aliguorif7b4a942009-01-07 17:40:15 +00003398 case 'h':
3399 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003400 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003401 case 'l':
3402 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003403 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003404 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003405 }
3406 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003407 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003408 break;
3409 case 'a':
3410 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003411 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003412 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003413 }
3414 action = SNAPSHOT_APPLY;
3415 snapshot_name = optarg;
3416 break;
3417 case 'c':
3418 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003419 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003420 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003421 }
3422 action = SNAPSHOT_CREATE;
3423 snapshot_name = optarg;
3424 break;
3425 case 'd':
3426 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003427 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003428 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003429 }
3430 action = SNAPSHOT_DELETE;
3431 snapshot_name = optarg;
3432 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003433 case 'q':
3434 quiet = true;
3435 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003436 case 'U':
3437 force_share = true;
3438 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003439 case OPTION_OBJECT:
3440 user_creatable_process_cmdline(optarg);
3441 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003442 case OPTION_IMAGE_OPTS:
3443 image_opts = true;
3444 break;
aliguorif7b4a942009-01-07 17:40:15 +00003445 }
3446 }
3447
Kevin Wolffc11eb22013-08-05 10:53:04 +02003448 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003449 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003450 }
aliguorif7b4a942009-01-07 17:40:15 +00003451 filename = argv[optind++];
3452
3453 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003454 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3455 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003456 if (!blk) {
3457 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003458 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003459 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003460
3461 /* Perform the requested action */
3462 switch(action) {
3463 case SNAPSHOT_LIST:
3464 dump_snapshots(bs);
3465 break;
3466
3467 case SNAPSHOT_CREATE:
3468 memset(&sn, 0, sizeof(sn));
3469 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3470
Marc-André Lureauf793dde2022-03-07 11:04:00 +04003471 rt = g_get_real_time();
3472 sn.date_sec = rt / G_USEC_PER_SEC;
3473 sn.date_nsec = (rt % G_USEC_PER_SEC) * 1000;
aliguorif7b4a942009-01-07 17:40:15 +00003474
Kevin Wolfa32e7812023-09-29 16:51:42 +02003475 bdrv_graph_rdlock_main_loop();
aliguorif7b4a942009-01-07 17:40:15 +00003476 ret = bdrv_snapshot_create(bs, &sn);
Kevin Wolfa32e7812023-09-29 16:51:42 +02003477 bdrv_graph_rdunlock_main_loop();
3478
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003479 if (ret) {
Michael Tokarevb0a66202023-08-11 14:09:46 +03003480 error_report("Could not create snapshot '%s': %s",
3481 snapshot_name, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003482 }
aliguorif7b4a942009-01-07 17:40:15 +00003483 break;
3484
3485 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003486 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003487 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003488 error_reportf_err(err, "Could not apply snapshot '%s': ",
3489 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003490 }
aliguorif7b4a942009-01-07 17:40:15 +00003491 break;
3492
3493 case SNAPSHOT_DELETE:
Kevin Wolfa32e7812023-09-29 16:51:42 +02003494 bdrv_graph_rdlock_main_loop();
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003495 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3496 if (ret < 0) {
3497 error_report("Could not delete snapshot '%s': snapshot not "
3498 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003499 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003500 } else {
3501 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3502 if (ret < 0) {
3503 error_reportf_err(err, "Could not delete snapshot '%s': ",
3504 snapshot_name);
3505 ret = 1;
3506 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003507 }
Kevin Wolfa32e7812023-09-29 16:51:42 +02003508 bdrv_graph_rdunlock_main_loop();
aliguorif7b4a942009-01-07 17:40:15 +00003509 break;
3510 }
3511
3512 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003513 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003514 if (ret) {
3515 return 1;
3516 }
Stuart Brady153859b2009-06-07 00:42:17 +01003517 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003518}
3519
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003520static int img_rebase(int argc, char **argv)
3521{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003522 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003523 uint8_t *buf_old = NULL;
3524 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003525 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003526 BlockDriverState *unfiltered_bs;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003527 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003528 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3529 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003530 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003531 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003532 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003533 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003534 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003535 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003536 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003537
3538 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003539 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003540 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003541 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003542 out_baseimg = NULL;
3543 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003544 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003545 static const struct option long_options[] = {
3546 {"help", no_argument, 0, 'h'},
3547 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003548 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003549 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003550 {0, 0, 0, 0}
3551 };
Fam Zheng335e9932017-05-03 00:35:39 +08003552 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003553 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003554 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003555 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003556 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003557 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003558 case ':':
3559 missing_argument(argv[optind - 1]);
3560 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003561 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003562 unrecognized_option(argv[optind - 1]);
3563 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003564 case 'h':
3565 help();
3566 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003567 case 'f':
3568 fmt = optarg;
3569 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003570 case 'F':
3571 out_basefmt = optarg;
3572 break;
3573 case 'b':
3574 out_baseimg = optarg;
3575 break;
3576 case 'u':
3577 unsafe = 1;
3578 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003579 case 'p':
3580 progress = 1;
3581 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003582 case 't':
3583 cache = optarg;
3584 break;
Max Reitz40055952014-07-22 22:58:42 +02003585 case 'T':
3586 src_cache = optarg;
3587 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003588 case 'q':
3589 quiet = true;
3590 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01003591 case OPTION_OBJECT:
3592 user_creatable_process_cmdline(optarg);
3593 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003594 case OPTION_IMAGE_OPTS:
3595 image_opts = true;
3596 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003597 case 'U':
3598 force_share = true;
3599 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003600 }
3601 }
3602
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003603 if (quiet) {
3604 progress = 0;
3605 }
3606
Fam Zhengac1307a2014-04-22 13:36:11 +08003607 if (optind != argc - 1) {
3608 error_exit("Expecting one image file name");
3609 }
3610 if (!unsafe && !out_baseimg) {
3611 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003612 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003613 filename = argv[optind++];
3614
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003615 qemu_progress_init(progress, 2.0);
3616 qemu_progress_print(0, 100);
3617
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003618 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003619 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003620 if (ret < 0) {
3621 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003622 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003623 }
3624
Kevin Wolfce099542016-03-15 13:01:04 +01003625 src_flags = 0;
3626 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003627 if (ret < 0) {
3628 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003629 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003630 }
3631
Kevin Wolfce099542016-03-15 13:01:04 +01003632 /* The source files are opened read-only, don't care about WCE */
3633 assert((src_flags & BDRV_O_RDWR) == 0);
3634 (void) src_writethrough;
3635
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003636 /*
3637 * Open the images.
3638 *
3639 * Ignore the old backing file for unsafe rebase in case we want to correct
3640 * the reference to a renamed or moved backing file.
3641 */
Fam Zheng335e9932017-05-03 00:35:39 +08003642 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3643 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003644 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003645 ret = -1;
3646 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003647 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003648 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003649
Max Reitz4a2061e2019-06-12 19:00:30 +02003650 unfiltered_bs = bdrv_skip_filters(bs);
3651
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003652 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003653 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003654 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003655 ret = -1;
3656 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003657 }
3658 }
3659
3660 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003661 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003662 QDict *options = NULL;
Max Reitz4a2061e2019-06-12 19:00:30 +02003663 BlockDriverState *base_bs = bdrv_cow_bs(unfiltered_bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003664
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003665 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003666 blk_old_backing = blk_new(qemu_get_aio_context(),
3667 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003668 BLK_PERM_ALL);
3669 ret = blk_insert_bs(blk_old_backing, base_bs,
3670 &local_err);
3671 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003672 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003673 "Could not reuse old backing file '%s': ",
3674 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003675 goto out;
3676 }
3677 } else {
3678 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003679 }
Max Reitz644483d2015-02-05 13:58:17 -05003680
Alex Bligha6166732012-10-16 13:46:18 +01003681 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003682 const char *overlay_filename;
3683 char *out_real_path;
3684
Fam Zheng335e9932017-05-03 00:35:39 +08003685 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003686 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003687 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003688 }
3689 if (force_share) {
3690 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003691 }
3692
Kevin Wolfb7cfc7d2023-09-29 16:51:45 +02003693 bdrv_graph_rdlock_main_loop();
Max Reitzf30c66b2019-02-01 20:29:05 +01003694 bdrv_refresh_filename(bs);
Kevin Wolfb7cfc7d2023-09-29 16:51:45 +02003695 bdrv_graph_rdunlock_main_loop();
Max Reitzd16699b2018-05-09 20:20:01 +02003696 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3697 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003698 out_real_path =
3699 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3700 out_baseimg,
3701 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003702 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003703 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003704 error_reportf_err(local_err,
3705 "Could not resolve backing filename: ");
3706 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003707 goto out;
3708 }
3709
Sam Eiderman863cc782019-05-23 19:33:36 +03003710 /*
3711 * Find out whether we rebase an image on top of a previous image
3712 * in its chain.
3713 */
3714 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003715 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003716 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003717 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003718
Kevin Wolfd861ab32019-04-25 14:25:10 +02003719 blk_new_backing = blk_new(qemu_get_aio_context(),
3720 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003721 BLK_PERM_ALL);
3722 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3723 &local_err);
3724 if (ret < 0) {
3725 error_reportf_err(local_err,
3726 "Could not reuse backing file '%s': ",
3727 out_baseimg);
3728 goto out;
3729 }
3730 } else {
3731 blk_new_backing = blk_new_open(out_real_path, NULL,
3732 options, src_flags, &local_err);
3733 g_free(out_real_path);
3734 if (!blk_new_backing) {
3735 error_reportf_err(local_err,
3736 "Could not open new backing file '%s': ",
3737 out_baseimg);
3738 ret = -1;
3739 goto out;
3740 }
Alex Bligha6166732012-10-16 13:46:18 +01003741 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003742 }
3743 }
3744
3745 /*
3746 * Check each unallocated cluster in the COW file. If it is unallocated,
3747 * accesses go to the backing file. We must therefore compare this cluster
3748 * in the old and new backing file, and if they differ we need to copy it
3749 * from the old backing file into the COW file.
3750 *
3751 * If qemu-img crashes during this step, no harm is done. The content of
3752 * the image is the same as the original one at any time.
3753 */
3754 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003755 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003756 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003757 int64_t new_backing_size = 0;
3758 uint64_t offset;
3759 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003760 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003761
Andrey Drobyshevce8b8f92023-09-19 19:57:59 +03003762 if (blk_old_backing && bdrv_opt_mem_align(blk_bs(blk_old_backing)) >
3763 bdrv_opt_mem_align(blk_bs(blk))) {
3764 buf_old = blk_blockalign(blk_old_backing, IO_BUF_SIZE);
3765 } else {
3766 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3767 }
3768 buf_new = blk_blockalign(blk_new_backing, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003769
Eric Blake41536282017-10-11 22:47:15 -05003770 size = blk_getlength(blk);
3771 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003772 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003773 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003774 ret = -1;
3775 goto out;
3776 }
Max Reitz35ddd932019-05-09 19:52:35 +02003777 if (blk_old_backing) {
3778 old_backing_size = blk_getlength(blk_old_backing);
3779 if (old_backing_size < 0) {
3780 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003781
Max Reitz35ddd932019-05-09 19:52:35 +02003782 bdrv_get_backing_filename(bs, backing_name,
3783 sizeof(backing_name));
3784 error_report("Could not get size of '%s': %s",
3785 backing_name, strerror(-old_backing_size));
3786 ret = -1;
3787 goto out;
3788 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003789 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003790 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003791 new_backing_size = blk_getlength(blk_new_backing);
3792 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003793 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003794 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003795 ret = -1;
3796 goto out;
3797 }
Alex Bligha6166732012-10-16 13:46:18 +01003798 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003799
Eric Blake41536282017-10-11 22:47:15 -05003800 if (size != 0) {
3801 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003802 }
3803
Eric Blake41536282017-10-11 22:47:15 -05003804 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003805 bool buf_old_is_zero = false;
3806
Eric Blake41536282017-10-11 22:47:15 -05003807 /* How many bytes can we handle with the next read? */
3808 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003809
3810 /* If the cluster is allocated, we don't need to take action */
Max Reitz4a2061e2019-06-12 19:00:30 +02003811 ret = bdrv_is_allocated(unfiltered_bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003812 if (ret < 0) {
3813 error_report("error while reading image metadata: %s",
3814 strerror(-ret));
3815 goto out;
3816 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003817 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003818 continue;
3819 }
3820
Sam Eiderman863cc782019-05-23 19:33:36 +03003821 if (prefix_chain_bs) {
Andrey Drobyshev8b097fd2023-09-19 19:57:57 +03003822 uint64_t bytes = n;
3823
Sam Eiderman863cc782019-05-23 19:33:36 +03003824 /*
3825 * If cluster wasn't changed since prefix_chain, we don't need
3826 * to take action
3827 */
Max Reitz4a2061e2019-06-12 19:00:30 +02003828 ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
3829 prefix_chain_bs, false,
3830 offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003831 if (ret < 0) {
3832 error_report("error while reading image metadata: %s",
3833 strerror(-ret));
3834 goto out;
3835 }
Andrey Drobyshev8b097fd2023-09-19 19:57:57 +03003836 if (!ret && n) {
Sam Eiderman863cc782019-05-23 19:33:36 +03003837 continue;
3838 }
Andrey Drobyshev8b097fd2023-09-19 19:57:57 +03003839 if (!n) {
3840 /*
3841 * If we've reached EOF of the old backing, it means that
3842 * offsets beyond the old backing size were read as zeroes.
3843 * Now we will need to explicitly zero the cluster in
3844 * order to preserve that state after the rebase.
3845 */
3846 n = bytes;
3847 }
Sam Eiderman863cc782019-05-23 19:33:36 +03003848 }
3849
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003850 /*
3851 * Read old and new backing file and take into consideration that
3852 * backing files may be smaller than the COW image.
3853 */
Eric Blake41536282017-10-11 22:47:15 -05003854 if (offset >= old_backing_size) {
3855 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003856 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003857 } else {
Eric Blake41536282017-10-11 22:47:15 -05003858 if (offset + n > old_backing_size) {
3859 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003860 }
3861
Alberto Fariaa9262f52022-07-05 17:15:11 +01003862 ret = blk_pread(blk_old_backing, offset, n, buf_old, 0);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003863 if (ret < 0) {
3864 error_report("error while reading from old backing file");
3865 goto out;
3866 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003867 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003868
Eric Blake41536282017-10-11 22:47:15 -05003869 if (offset >= new_backing_size || !blk_new_backing) {
3870 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003871 } else {
Eric Blake41536282017-10-11 22:47:15 -05003872 if (offset + n > new_backing_size) {
3873 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003874 }
3875
Alberto Fariaa9262f52022-07-05 17:15:11 +01003876 ret = blk_pread(blk_new_backing, offset, n, buf_new, 0);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003877 if (ret < 0) {
3878 error_report("error while reading from new backing file");
3879 goto out;
3880 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003881 }
3882
3883 /* If they differ, we need to write to the COW file */
3884 uint64_t written = 0;
3885
Eric Blake41536282017-10-11 22:47:15 -05003886 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003887 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003888
Eric Blake41536282017-10-11 22:47:15 -05003889 if (compare_buffers(buf_old + written, buf_new + written,
3890 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003891 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003892 if (buf_old_is_zero) {
3893 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3894 } else {
Alberto Fariaa9262f52022-07-05 17:15:11 +01003895 ret = blk_pwrite(blk, offset + written, pnum,
3896 buf_old + written, 0);
Max Reitz1c6e8772019-05-09 19:52:36 +02003897 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003898 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003899 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003900 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003901 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003902 }
3903 }
3904
3905 written += pnum;
3906 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003907 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003908 }
3909 }
3910
3911 /*
3912 * Change the backing file. All clusters that are different from the old
3913 * backing file are overwritten in the COW file now, so the visible content
3914 * doesn't change when we switch the backing file.
3915 */
Alex Bligha6166732012-10-16 13:46:18 +01003916 if (out_baseimg && *out_baseimg) {
Max Reitz4a2061e2019-06-12 19:00:30 +02003917 ret = bdrv_change_backing_file(unfiltered_bs, out_baseimg, out_basefmt,
3918 true);
Alex Bligha6166732012-10-16 13:46:18 +01003919 } else {
Max Reitz4a2061e2019-06-12 19:00:30 +02003920 ret = bdrv_change_backing_file(unfiltered_bs, NULL, NULL, false);
Alex Bligha6166732012-10-16 13:46:18 +01003921 }
3922
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003923 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003924 error_report("Could not change the backing file to '%s': No "
3925 "space left in the file header", out_baseimg);
Eric Blakea7cd44b2021-07-08 10:52:28 -05003926 } else if (ret == -EINVAL && out_baseimg && !out_basefmt) {
3927 error_report("Could not change the backing file to '%s': backing "
3928 "format must be specified", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003929 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003930 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003931 out_baseimg, strerror(-ret));
3932 }
3933
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003934 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003935 /*
3936 * TODO At this point it is possible to check if any clusters that are
3937 * allocated in the COW file are the same in the backing file. If so, they
3938 * could be dropped from the COW file. Don't do this before switching the
3939 * backing file, in case of a crash this would lead to corruption.
3940 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003941out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003942 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003943 /* Cleanup */
3944 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003945 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003946 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003947 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003948 qemu_vfree(buf_old);
3949 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003950
Markus Armbruster26f54e92014-10-07 13:59:04 +02003951 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003952 if (ret) {
3953 return 1;
3954 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003955 return 0;
3956}
3957
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003958static int img_resize(int argc, char **argv)
3959{
Markus Armbruster6750e792015-02-12 17:43:08 +01003960 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003961 int c, ret, relative;
3962 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003963 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003964 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003965 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003966 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003967 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003968
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003969 static QemuOptsList resize_options = {
3970 .name = "resize_options",
3971 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3972 .desc = {
3973 {
3974 .name = BLOCK_OPT_SIZE,
3975 .type = QEMU_OPT_SIZE,
3976 .help = "Virtual disk size"
3977 }, {
3978 /* end of list */
3979 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003980 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003981 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003982 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003983 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003984
Kevin Wolfe80fec72011-04-29 10:58:12 +02003985 /* Remove size from argv manually so that negative numbers are not treated
3986 * as options by getopt. */
3987 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003988 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003989 return 1;
3990 }
3991
3992 size = argv[--argc];
3993
3994 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003995 fmt = NULL;
3996 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003997 static const struct option long_options[] = {
3998 {"help", no_argument, 0, 'h'},
3999 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004000 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02004001 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004002 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004003 {0, 0, 0, 0}
4004 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004005 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004006 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004007 if (c == -1) {
4008 break;
4009 }
4010 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004011 case ':':
4012 missing_argument(argv[optind - 1]);
4013 break;
Jes Sorensenef873942010-12-06 15:25:40 +01004014 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004015 unrecognized_option(argv[optind - 1]);
4016 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004017 case 'h':
4018 help();
4019 break;
4020 case 'f':
4021 fmt = optarg;
4022 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01004023 case 'q':
4024 quiet = true;
4025 break;
Kevin Wolf99b1e642021-02-17 12:56:45 +01004026 case OPTION_OBJECT:
4027 user_creatable_process_cmdline(optarg);
4028 break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004029 case OPTION_IMAGE_OPTS:
4030 image_opts = true;
4031 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02004032 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02004033 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02004034 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02004035 if (prealloc == PREALLOC_MODE__MAX) {
4036 error_report("Invalid preallocation mode '%s'", optarg);
4037 return 1;
4038 }
4039 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004040 case OPTION_SHRINK:
4041 shrink = true;
4042 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004043 }
4044 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02004045 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01004046 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004047 }
4048 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004049
4050 /* Choose grow, shrink, or absolute resize mode */
4051 switch (size[0]) {
4052 case '+':
4053 relative = 1;
4054 size++;
4055 break;
4056 case '-':
4057 relative = -1;
4058 size++;
4059 break;
4060 default:
4061 relative = 0;
4062 break;
4063 }
4064
4065 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08004066 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004067 if (!qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err)) {
Markus Armbruster6750e792015-02-12 17:43:08 +01004068 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01004069 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004070 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01004071 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004072 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08004073 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
4074 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004075
Max Reitzefaa7c42016-03-16 19:54:38 +01004076 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08004077 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
4078 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004079 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01004080 ret = -1;
4081 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004082 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004083
Max Reitzdc5f6902017-06-13 22:20:55 +02004084 current_size = blk_getlength(blk);
4085 if (current_size < 0) {
4086 error_report("Failed to inquire current image length: %s",
4087 strerror(-current_size));
4088 ret = -1;
4089 goto out;
4090 }
4091
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004092 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02004093 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004094 } else {
4095 total_size = n;
4096 }
4097 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01004098 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004099 ret = -1;
4100 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004101 }
4102
Max Reitzdc5f6902017-06-13 22:20:55 +02004103 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
4104 error_report("Preallocation can only be used for growing images");
4105 ret = -1;
4106 goto out;
4107 }
4108
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004109 if (total_size < current_size && !shrink) {
Kevin Wolf1c404d72020-07-10 14:17:17 +02004110 error_report("Use the --shrink option to perform a shrink operation.");
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004111 warn_report("Shrinking an image will delete all data beyond the "
4112 "shrunken image's end. Before performing such an "
4113 "operation, make sure there is no important data there.");
Kevin Wolf1c404d72020-07-10 14:17:17 +02004114 ret = -1;
4115 goto out;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03004116 }
4117
Max Reitze8d04f92019-09-18 11:51:43 +02004118 /*
4119 * The user expects the image to have the desired size after
4120 * resizing, so pass @exact=true. It is of no use to report
4121 * success when the image has not actually been resized.
4122 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02004123 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02004124 if (!ret) {
4125 qprintf(quiet, "Image resized.\n");
4126 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02004127 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004128 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004129out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004130 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09004131 if (ret) {
4132 return 1;
4133 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01004134 return 0;
4135}
4136
Max Reitz76a3a342014-10-27 11:12:51 +01004137static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02004138 int64_t offset, int64_t total_work_size,
4139 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01004140{
4141 qemu_progress_print(100.f * offset / total_work_size, 0);
4142}
4143
Max Reitz51641352018-05-09 23:00:20 +02004144static int print_amend_option_help(const char *format)
4145{
4146 BlockDriver *drv;
4147
Kevin Wolfbd131d62023-09-29 16:51:48 +02004148 GRAPH_RDLOCK_GUARD_MAINLOOP();
4149
Max Reitz51641352018-05-09 23:00:20 +02004150 /* Find driver and parse its options */
4151 drv = bdrv_find_format(format);
4152 if (!drv) {
4153 error_report("Unknown file format '%s'", format);
4154 return 1;
4155 }
4156
4157 if (!drv->bdrv_amend_options) {
4158 error_report("Format driver '%s' does not support option amendment",
4159 format);
4160 return 1;
4161 }
4162
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004163 /* Every driver supporting amendment must have amend_opts */
4164 assert(drv->amend_opts);
Max Reitz51641352018-05-09 23:00:20 +02004165
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004166 printf("Amend options for '%s':\n", format);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004167 qemu_opts_print_help(drv->amend_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004168 return 0;
4169}
4170
Max Reitz6f176b42013-09-03 10:09:50 +02004171static int img_amend(int argc, char **argv)
4172{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004173 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004174 int c, ret = 0;
4175 char *options = NULL;
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004176 QemuOptsList *amend_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004177 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004178 const char *fmt = NULL, *filename, *cache;
4179 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004180 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004181 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004182 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004183 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004184 bool image_opts = false;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004185 bool force = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004186
Max Reitzbd39e6e2014-07-22 22:58:43 +02004187 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004188 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004189 static const struct option long_options[] = {
4190 {"help", no_argument, 0, 'h'},
4191 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004192 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004193 {"force", no_argument, 0, OPTION_FORCE},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004194 {0, 0, 0, 0}
4195 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004196 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004197 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004198 if (c == -1) {
4199 break;
4200 }
4201
4202 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004203 case ':':
4204 missing_argument(argv[optind - 1]);
4205 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004206 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004207 unrecognized_option(argv[optind - 1]);
4208 break;
4209 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004210 help();
4211 break;
4212 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004213 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004214 ret = -1;
4215 goto out_no_progress;
4216 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004217 break;
4218 case 'f':
4219 fmt = optarg;
4220 break;
4221 case 't':
4222 cache = optarg;
4223 break;
4224 case 'p':
4225 progress = true;
4226 break;
4227 case 'q':
4228 quiet = true;
4229 break;
4230 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004231 user_creatable_process_cmdline(optarg);
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004232 break;
4233 case OPTION_IMAGE_OPTS:
4234 image_opts = true;
4235 break;
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004236 case OPTION_FORCE:
4237 force = true;
4238 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004239 }
4240 }
4241
Max Reitz6f176b42013-09-03 10:09:50 +02004242 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004243 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004244 }
4245
Max Reitz76a3a342014-10-27 11:12:51 +01004246 if (quiet) {
4247 progress = false;
4248 }
4249 qemu_progress_init(progress, 1.0);
4250
Kevin Wolfa283cb62014-02-21 16:24:07 +01004251 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4252 if (fmt && has_help_option(options)) {
4253 /* If a format is explicitly specified (and possibly no filename is
4254 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004255 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004256 goto out;
4257 }
4258
4259 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004260 error_report("Expecting one image file name");
4261 ret = -1;
4262 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004263 }
Max Reitz6f176b42013-09-03 10:09:50 +02004264
Kevin Wolfce099542016-03-15 13:01:04 +01004265 flags = BDRV_O_RDWR;
4266 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004267 if (ret < 0) {
4268 error_report("Invalid cache option: %s", cache);
4269 goto out;
4270 }
4271
Fam Zheng335e9932017-05-03 00:35:39 +08004272 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4273 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004274 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004275 ret = -1;
4276 goto out;
4277 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004278 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004279
4280 fmt = bs->drv->format_name;
4281
Kevin Wolf626f84f2014-02-21 16:24:06 +01004282 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004283 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004284 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004285 goto out;
4286 }
4287
Kevin Wolfbd131d62023-09-29 16:51:48 +02004288 bdrv_graph_rdlock_main_loop();
Max Reitz1f996682018-05-09 23:00:17 +02004289 if (!bs->drv->bdrv_amend_options) {
4290 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004291 fmt);
Kevin Wolfbd131d62023-09-29 16:51:48 +02004292 bdrv_graph_rdunlock_main_loop();
Max Reitzb2439d22014-12-02 18:32:47 +01004293 ret = -1;
4294 goto out;
4295 }
4296
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004297 /* Every driver supporting amendment must have amend_opts */
4298 assert(bs->drv->amend_opts);
Max Reitz1f996682018-05-09 23:00:17 +02004299
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004300 amend_opts = qemu_opts_append(amend_opts, bs->drv->amend_opts);
4301 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster235e59c2020-07-07 18:05:42 +02004302 if (!qemu_opts_do_parse(opts, options, NULL, &err)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004303 /* Try to parse options using the create options */
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004304 amend_opts = qemu_opts_append(amend_opts, bs->drv->create_opts);
4305 qemu_opts_del(opts);
4306 opts = qemu_opts_create(amend_opts, NULL, 0, &error_abort);
Markus Armbruster9e194e02020-07-07 18:06:11 +02004307 if (qemu_opts_do_parse(opts, options, NULL, NULL)) {
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004308 error_append_hint(&err,
4309 "This option is only supported for image creation\n");
Maxim Levitsky0b6786a2020-06-25 14:55:40 +02004310 }
4311
Kevin Wolfbd131d62023-09-29 16:51:48 +02004312 bdrv_graph_rdunlock_main_loop();
Paolo Bonziniece90862017-01-04 15:56:24 +01004313 error_report_err(err);
4314 ret = -1;
4315 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004316 }
4317
Max Reitz76a3a342014-10-27 11:12:51 +01004318 /* In case the driver does not call amend_status_cb() */
4319 qemu_progress_print(0.f, 0);
Maxim Levitskya3579bf2020-06-25 14:55:38 +02004320 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, force, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004321 qemu_progress_print(100.f, 0);
Kevin Wolfbd131d62023-09-29 16:51:48 +02004322 bdrv_graph_rdunlock_main_loop();
4323
Max Reitz6f176b42013-09-03 10:09:50 +02004324 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004325 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004326 goto out;
4327 }
4328
4329out:
Max Reitz76a3a342014-10-27 11:12:51 +01004330 qemu_progress_end();
4331
Max Reitze814dff2015-08-20 16:00:38 -07004332out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004333 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004334 qemu_opts_del(opts);
Maxim Levitskydf373fb2020-06-25 14:55:39 +02004335 qemu_opts_free(amend_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004336 g_free(options);
4337
Max Reitz6f176b42013-09-03 10:09:50 +02004338 if (ret) {
4339 return 1;
4340 }
4341 return 0;
4342}
4343
Kevin Wolfb6133b82014-08-05 14:17:13 +02004344typedef struct BenchData {
4345 BlockBackend *blk;
4346 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004347 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004348 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004349 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004350 int nrreq;
4351 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004352 int flush_interval;
4353 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004354 uint8_t *buf;
4355 QEMUIOVector *qiov;
4356
4357 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004358 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004359 uint64_t offset;
4360} BenchData;
4361
Kevin Wolf55d539c2016-06-03 13:59:41 +02004362static void bench_undrained_flush_cb(void *opaque, int ret)
4363{
4364 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004365 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004366 exit(EXIT_FAILURE);
4367 }
4368}
4369
Kevin Wolfb6133b82014-08-05 14:17:13 +02004370static void bench_cb(void *opaque, int ret)
4371{
4372 BenchData *b = opaque;
4373 BlockAIOCB *acb;
4374
4375 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004376 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004377 exit(EXIT_FAILURE);
4378 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004379
4380 if (b->in_flush) {
4381 /* Just finished a flush with drained queue: Start next requests */
4382 assert(b->in_flight == 0);
4383 b->in_flush = false;
4384 } else if (b->in_flight > 0) {
4385 int remaining = b->n - b->in_flight;
4386
Kevin Wolfb6133b82014-08-05 14:17:13 +02004387 b->n--;
4388 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004389
4390 /* Time for flush? Drain queue if requested, then flush */
4391 if (b->flush_interval && remaining % b->flush_interval == 0) {
4392 if (!b->in_flight || !b->drain_on_flush) {
4393 BlockCompletionFunc *cb;
4394
4395 if (b->drain_on_flush) {
4396 b->in_flush = true;
4397 cb = bench_cb;
4398 } else {
4399 cb = bench_undrained_flush_cb;
4400 }
4401
4402 acb = blk_aio_flush(b->blk, cb, b);
4403 if (!acb) {
4404 error_report("Failed to issue flush request");
4405 exit(EXIT_FAILURE);
4406 }
4407 }
4408 if (b->drain_on_flush) {
4409 return;
4410 }
4411 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004412 }
4413
4414 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004415 int64_t offset = b->offset;
4416 /* blk_aio_* might look for completed I/Os and kick bench_cb
4417 * again, so make sure this operation is counted by in_flight
4418 * and b->offset is ready for the next submission.
4419 */
4420 b->in_flight++;
4421 b->offset += b->step;
4422 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004423 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004424 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004425 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004426 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004427 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004428 if (!acb) {
4429 error_report("Failed to issue request");
4430 exit(EXIT_FAILURE);
4431 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004432 }
4433}
4434
4435static int img_bench(int argc, char **argv)
4436{
4437 int c, ret = 0;
4438 const char *fmt = NULL, *filename;
4439 bool quiet = false;
4440 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004441 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004442 int count = 75000;
4443 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004444 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004445 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004446 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004447 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004448 int flush_interval = 0;
4449 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004450 int64_t image_size;
4451 BlockBackend *blk = NULL;
4452 BenchData data = {};
4453 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004454 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004455 struct timeval t1, t2;
4456 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004457 bool force_share = false;
Stefan Hajnoczi4f384012022-10-13 14:58:59 -04004458 size_t buf_size = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004459
4460 for (;;) {
4461 static const struct option long_options[] = {
4462 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004463 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004464 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004465 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004466 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004467 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004468 {0, 0, 0, 0}
4469 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004470 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4471 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004472 if (c == -1) {
4473 break;
4474 }
4475
4476 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004477 case ':':
4478 missing_argument(argv[optind - 1]);
4479 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004480 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004481 unrecognized_option(argv[optind - 1]);
4482 break;
4483 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004484 help();
4485 break;
4486 case 'c':
4487 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004488 unsigned long res;
4489
4490 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004491 error_report("Invalid request count specified");
4492 return 1;
4493 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004494 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004495 break;
4496 }
4497 case 'd':
4498 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004499 unsigned long res;
4500
4501 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004502 error_report("Invalid queue depth specified");
4503 return 1;
4504 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004505 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004506 break;
4507 }
4508 case 'f':
4509 fmt = optarg;
4510 break;
4511 case 'n':
4512 flags |= BDRV_O_NATIVE_AIO;
4513 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004514 case 'i':
4515 ret = bdrv_parse_aio(optarg, &flags);
4516 if (ret < 0) {
4517 error_report("Invalid aio option: %s", optarg);
4518 ret = -1;
4519 goto out;
4520 }
4521 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004522 case 'o':
4523 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004524 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004525 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004526 return 1;
4527 }
4528 break;
4529 }
4530 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004531 case 'q':
4532 quiet = true;
4533 break;
4534 case 's':
4535 {
4536 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004537
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004538 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4539 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004540 return 1;
4541 }
4542
4543 bufsize = sval;
4544 break;
4545 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004546 case 'S':
4547 {
4548 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004549
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004550 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4551 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004552 return 1;
4553 }
4554
4555 step = sval;
4556 break;
4557 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004558 case 't':
4559 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4560 if (ret < 0) {
4561 error_report("Invalid cache mode");
4562 ret = -1;
4563 goto out;
4564 }
4565 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004566 case 'w':
4567 flags |= BDRV_O_RDWR;
4568 is_write = true;
4569 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004570 case 'U':
4571 force_share = true;
4572 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004573 case OPTION_PATTERN:
4574 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004575 unsigned long res;
4576
4577 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004578 error_report("Invalid pattern byte specified");
4579 return 1;
4580 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004581 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004582 break;
4583 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004584 case OPTION_FLUSH_INTERVAL:
4585 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004586 unsigned long res;
4587
4588 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004589 error_report("Invalid flush interval specified");
4590 return 1;
4591 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004592 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004593 break;
4594 }
4595 case OPTION_NO_DRAIN:
4596 drain_on_flush = false;
4597 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004598 case OPTION_IMAGE_OPTS:
4599 image_opts = true;
4600 break;
4601 }
4602 }
4603
4604 if (optind != argc - 1) {
4605 error_exit("Expecting one image file name");
4606 }
4607 filename = argv[argc - 1];
4608
Kevin Wolf55d539c2016-06-03 13:59:41 +02004609 if (!is_write && flush_interval) {
4610 error_report("--flush-interval is only available in write tests");
4611 ret = -1;
4612 goto out;
4613 }
4614 if (flush_interval && flush_interval < depth) {
4615 error_report("Flush interval can't be smaller than depth");
4616 ret = -1;
4617 goto out;
4618 }
4619
Fam Zheng335e9932017-05-03 00:35:39 +08004620 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4621 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004622 if (!blk) {
4623 ret = -1;
4624 goto out;
4625 }
4626
4627 image_size = blk_getlength(blk);
4628 if (image_size < 0) {
4629 ret = image_size;
4630 goto out;
4631 }
4632
4633 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004634 .blk = blk,
4635 .image_size = image_size,
4636 .bufsize = bufsize,
4637 .step = step ?: bufsize,
4638 .nrreq = depth,
4639 .n = count,
4640 .offset = offset,
4641 .write = is_write,
4642 .flush_interval = flush_interval,
4643 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004644 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004645 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004646 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004647 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004648 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004649 if (flush_interval) {
4650 printf("Sending flush every %d requests\n", flush_interval);
4651 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004652
Fam Zheng79d46582018-01-16 14:08:58 +08004653 buf_size = data.nrreq * data.bufsize;
4654 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004655 memset(data.buf, pattern, data.nrreq * data.bufsize);
4656
Stefan Hajnoczif4ec04b2022-10-13 14:59:02 -04004657 blk_register_buf(blk, data.buf, buf_size, &error_fatal);
Fam Zheng79d46582018-01-16 14:08:58 +08004658
Kevin Wolfb6133b82014-08-05 14:17:13 +02004659 data.qiov = g_new(QEMUIOVector, data.nrreq);
4660 for (i = 0; i < data.nrreq; i++) {
4661 qemu_iovec_init(&data.qiov[i], 1);
4662 qemu_iovec_add(&data.qiov[i],
4663 data.buf + i * data.bufsize, data.bufsize);
4664 }
4665
4666 gettimeofday(&t1, NULL);
4667 bench_cb(&data, 0);
4668
4669 while (data.n > 0) {
4670 main_loop_wait(false);
4671 }
4672 gettimeofday(&t2, NULL);
4673
4674 printf("Run completed in %3.3f seconds.\n",
4675 (t2.tv_sec - t1.tv_sec)
4676 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4677
4678out:
Fam Zheng79d46582018-01-16 14:08:58 +08004679 if (data.buf) {
Stefan Hajnoczi4f384012022-10-13 14:58:59 -04004680 blk_unregister_buf(blk, data.buf, buf_size);
Fam Zheng79d46582018-01-16 14:08:58 +08004681 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004682 qemu_vfree(data.buf);
4683 blk_unref(blk);
4684
4685 if (ret) {
4686 return 1;
4687 }
4688 return 0;
4689}
4690
Eric Blake3b51ab42020-05-12 20:16:45 -05004691enum ImgBitmapAct {
4692 BITMAP_ADD,
4693 BITMAP_REMOVE,
4694 BITMAP_CLEAR,
4695 BITMAP_ENABLE,
4696 BITMAP_DISABLE,
4697 BITMAP_MERGE,
4698};
4699typedef struct ImgBitmapAction {
4700 enum ImgBitmapAct act;
4701 const char *src; /* only used for merge */
4702 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4703} ImgBitmapAction;
4704
4705static int img_bitmap(int argc, char **argv)
4706{
4707 Error *err = NULL;
4708 int c, ret = 1;
4709 QemuOpts *opts = NULL;
4710 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4711 const char *filename, *bitmap;
4712 BlockBackend *blk = NULL, *src = NULL;
4713 BlockDriverState *bs = NULL, *src_bs = NULL;
4714 bool image_opts = false;
4715 int64_t granularity = 0;
4716 bool add = false, merge = false;
4717 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4718 ImgBitmapAction *act, *act_next;
4719 const char *op;
Kevin Wolfc5e47712023-01-12 20:14:53 +01004720 int inactivate_ret;
Eric Blake3b51ab42020-05-12 20:16:45 -05004721
4722 QSIMPLEQ_INIT(&actions);
4723
4724 for (;;) {
4725 static const struct option long_options[] = {
4726 {"help", no_argument, 0, 'h'},
4727 {"object", required_argument, 0, OPTION_OBJECT},
4728 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4729 {"add", no_argument, 0, OPTION_ADD},
4730 {"remove", no_argument, 0, OPTION_REMOVE},
4731 {"clear", no_argument, 0, OPTION_CLEAR},
4732 {"enable", no_argument, 0, OPTION_ENABLE},
4733 {"disable", no_argument, 0, OPTION_DISABLE},
4734 {"merge", required_argument, 0, OPTION_MERGE},
4735 {"granularity", required_argument, 0, 'g'},
4736 {"source-file", required_argument, 0, 'b'},
4737 {"source-format", required_argument, 0, 'F'},
4738 {0, 0, 0, 0}
4739 };
4740 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4741 if (c == -1) {
4742 break;
4743 }
4744
4745 switch (c) {
4746 case ':':
4747 missing_argument(argv[optind - 1]);
4748 break;
4749 case '?':
4750 unrecognized_option(argv[optind - 1]);
4751 break;
4752 case 'h':
4753 help();
4754 break;
4755 case 'b':
4756 src_filename = optarg;
4757 break;
4758 case 'f':
4759 fmt = optarg;
4760 break;
4761 case 'F':
4762 src_fmt = optarg;
4763 break;
4764 case 'g':
4765 granularity = cvtnum("granularity", optarg);
4766 if (granularity < 0) {
4767 return 1;
4768 }
4769 break;
4770 case OPTION_ADD:
4771 act = g_new0(ImgBitmapAction, 1);
4772 act->act = BITMAP_ADD;
4773 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4774 add = true;
4775 break;
4776 case OPTION_REMOVE:
4777 act = g_new0(ImgBitmapAction, 1);
4778 act->act = BITMAP_REMOVE;
4779 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4780 break;
4781 case OPTION_CLEAR:
4782 act = g_new0(ImgBitmapAction, 1);
4783 act->act = BITMAP_CLEAR;
4784 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4785 break;
4786 case OPTION_ENABLE:
4787 act = g_new0(ImgBitmapAction, 1);
4788 act->act = BITMAP_ENABLE;
4789 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4790 break;
4791 case OPTION_DISABLE:
4792 act = g_new0(ImgBitmapAction, 1);
4793 act->act = BITMAP_DISABLE;
4794 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4795 break;
4796 case OPTION_MERGE:
4797 act = g_new0(ImgBitmapAction, 1);
4798 act->act = BITMAP_MERGE;
4799 act->src = optarg;
4800 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4801 merge = true;
4802 break;
4803 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01004804 user_creatable_process_cmdline(optarg);
Eric Blake3b51ab42020-05-12 20:16:45 -05004805 break;
4806 case OPTION_IMAGE_OPTS:
4807 image_opts = true;
4808 break;
4809 }
4810 }
4811
Eric Blake3b51ab42020-05-12 20:16:45 -05004812 if (QSIMPLEQ_EMPTY(&actions)) {
4813 error_report("Need at least one of --add, --remove, --clear, "
4814 "--enable, --disable, or --merge");
4815 goto out;
4816 }
4817
4818 if (granularity && !add) {
4819 error_report("granularity only supported with --add");
4820 goto out;
4821 }
4822 if (src_fmt && !src_filename) {
4823 error_report("-F only supported with -b");
4824 goto out;
4825 }
4826 if (src_filename && !merge) {
4827 error_report("Merge bitmap source file only supported with "
4828 "--merge");
4829 goto out;
4830 }
4831
4832 if (optind != argc - 2) {
4833 error_report("Expecting filename and bitmap name");
4834 goto out;
4835 }
4836
4837 filename = argv[optind];
4838 bitmap = argv[optind + 1];
4839
Eric Blake14f16bf2020-09-14 14:10:09 -05004840 /*
4841 * No need to open backing chains; we will be manipulating bitmaps
4842 * directly in this image without reference to image contents.
4843 */
4844 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_NO_BACKING,
4845 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004846 if (!blk) {
4847 goto out;
4848 }
4849 bs = blk_bs(blk);
4850 if (src_filename) {
Eric Blake14f16bf2020-09-14 14:10:09 -05004851 src = img_open(false, src_filename, src_fmt, BDRV_O_NO_BACKING,
4852 false, false, false);
Eric Blake3b51ab42020-05-12 20:16:45 -05004853 if (!src) {
4854 goto out;
4855 }
4856 src_bs = blk_bs(src);
4857 } else {
4858 src_bs = bs;
4859 }
4860
4861 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4862 switch (act->act) {
4863 case BITMAP_ADD:
4864 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4865 !!granularity, granularity, true, true,
4866 false, false, &err);
4867 op = "add";
4868 break;
4869 case BITMAP_REMOVE:
4870 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4871 op = "remove";
4872 break;
4873 case BITMAP_CLEAR:
4874 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4875 op = "clear";
4876 break;
4877 case BITMAP_ENABLE:
4878 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4879 op = "enable";
4880 break;
4881 case BITMAP_DISABLE:
4882 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4883 op = "disable";
4884 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004885 case BITMAP_MERGE:
4886 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4887 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004888 op = "merge";
4889 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004890 default:
4891 g_assert_not_reached();
4892 }
4893
4894 if (err) {
4895 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4896 op, bitmap);
4897 goto out;
4898 }
4899 g_free(act);
4900 }
4901
4902 ret = 0;
4903
4904 out:
Kevin Wolfc5e47712023-01-12 20:14:53 +01004905 /*
4906 * Manually inactivate the images first because this way we can know whether
4907 * an error occurred. blk_unref() doesn't tell us about failures.
4908 */
4909 inactivate_ret = bdrv_inactivate_all();
4910 if (inactivate_ret < 0) {
4911 error_report("Error while closing the image: %s", strerror(-inactivate_ret));
4912 ret = 1;
4913 }
4914
Eric Blake3b51ab42020-05-12 20:16:45 -05004915 blk_unref(src);
4916 blk_unref(blk);
4917 qemu_opts_del(opts);
4918 return ret;
4919}
4920
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004921#define C_BS 01
4922#define C_COUNT 02
4923#define C_IF 04
4924#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004925#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004926
4927struct DdInfo {
4928 unsigned int flags;
4929 int64_t count;
4930};
4931
4932struct DdIo {
4933 int bsz; /* Block size */
4934 char *filename;
4935 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004936 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004937};
4938
4939struct DdOpts {
4940 const char *name;
4941 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4942 unsigned int flag;
4943};
4944
4945static int img_dd_bs(const char *arg,
4946 struct DdIo *in, struct DdIo *out,
4947 struct DdInfo *dd)
4948{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004949 int64_t res;
4950
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004951 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004952
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004953 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004954 return 1;
4955 }
4956 in->bsz = out->bsz = res;
4957
4958 return 0;
4959}
4960
4961static int img_dd_count(const char *arg,
4962 struct DdIo *in, struct DdIo *out,
4963 struct DdInfo *dd)
4964{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004965 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004966
Markus Armbruster606caa02017-02-21 21:14:04 +01004967 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004968 return 1;
4969 }
4970
4971 return 0;
4972}
4973
4974static int img_dd_if(const char *arg,
4975 struct DdIo *in, struct DdIo *out,
4976 struct DdInfo *dd)
4977{
4978 in->filename = g_strdup(arg);
4979
4980 return 0;
4981}
4982
4983static int img_dd_of(const char *arg,
4984 struct DdIo *in, struct DdIo *out,
4985 struct DdInfo *dd)
4986{
4987 out->filename = g_strdup(arg);
4988
4989 return 0;
4990}
4991
Reda Sallahif7c15532016-08-10 16:16:09 +02004992static int img_dd_skip(const char *arg,
4993 struct DdIo *in, struct DdIo *out,
4994 struct DdInfo *dd)
4995{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004996 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004997
Markus Armbruster606caa02017-02-21 21:14:04 +01004998 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004999 return 1;
5000 }
5001
5002 return 0;
5003}
5004
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005005static int img_dd(int argc, char **argv)
5006{
5007 int ret = 0;
5008 char *arg = NULL;
5009 char *tmp;
5010 BlockDriver *drv = NULL, *proto_drv = NULL;
5011 BlockBackend *blk1 = NULL, *blk2 = NULL;
5012 QemuOpts *opts = NULL;
5013 QemuOptsList *create_opts = NULL;
5014 Error *local_err = NULL;
5015 bool image_opts = false;
5016 int c, i;
5017 const char *out_fmt = "raw";
5018 const char *fmt = NULL;
5019 int64_t size = 0;
Miroslav Rezanina0f48c472022-11-09 10:57:13 -05005020 int64_t out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08005021 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005022 struct DdInfo dd = {
5023 .flags = 0,
5024 .count = 0,
5025 };
5026 struct DdIo in = {
5027 .bsz = 512, /* Block size is by default 512 bytes */
5028 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02005029 .buf = NULL,
5030 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005031 };
5032 struct DdIo out = {
5033 .bsz = 512,
5034 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02005035 .buf = NULL,
5036 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005037 };
5038
5039 const struct DdOpts options[] = {
5040 { "bs", img_dd_bs, C_BS },
5041 { "count", img_dd_count, C_COUNT },
5042 { "if", img_dd_if, C_IF },
5043 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02005044 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005045 { NULL, NULL, 0 }
5046 };
5047 const struct option long_options[] = {
5048 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005049 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005050 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08005051 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005052 { 0, 0, 0, 0 }
5053 };
5054
Fam Zheng335e9932017-05-03 00:35:39 +08005055 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005056 if (c == EOF) {
5057 break;
5058 }
5059 switch (c) {
5060 case 'O':
5061 out_fmt = optarg;
5062 break;
5063 case 'f':
5064 fmt = optarg;
5065 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005066 case ':':
5067 missing_argument(argv[optind - 1]);
5068 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005069 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005070 unrecognized_option(argv[optind - 1]);
5071 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005072 case 'h':
5073 help();
5074 break;
Fam Zheng335e9932017-05-03 00:35:39 +08005075 case 'U':
5076 force_share = true;
5077 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005078 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005079 user_creatable_process_cmdline(optarg);
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01005080 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005081 case OPTION_IMAGE_OPTS:
5082 image_opts = true;
5083 break;
5084 }
5085 }
5086
5087 for (i = optind; i < argc; i++) {
5088 int j;
5089 arg = g_strdup(argv[i]);
5090
5091 tmp = strchr(arg, '=');
5092 if (tmp == NULL) {
5093 error_report("unrecognized operand %s", arg);
5094 ret = -1;
5095 goto out;
5096 }
5097
5098 *tmp++ = '\0';
5099
5100 for (j = 0; options[j].name != NULL; j++) {
5101 if (!strcmp(arg, options[j].name)) {
5102 break;
5103 }
5104 }
5105 if (options[j].name == NULL) {
5106 error_report("unrecognized operand %s", arg);
5107 ret = -1;
5108 goto out;
5109 }
5110
5111 if (options[j].f(tmp, &in, &out, &dd) != 0) {
5112 ret = -1;
5113 goto out;
5114 }
5115 dd.flags |= options[j].flag;
5116 g_free(arg);
5117 arg = NULL;
5118 }
5119
5120 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
5121 error_report("Must specify both input and output files");
5122 ret = -1;
5123 goto out;
5124 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01005125
Fam Zheng335e9932017-05-03 00:35:39 +08005126 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
5127 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005128
5129 if (!blk1) {
5130 ret = -1;
5131 goto out;
5132 }
5133
5134 drv = bdrv_find_format(out_fmt);
5135 if (!drv) {
5136 error_report("Unknown file format");
5137 ret = -1;
5138 goto out;
5139 }
5140 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
5141
5142 if (!proto_drv) {
5143 error_report_err(local_err);
5144 ret = -1;
5145 goto out;
5146 }
5147 if (!drv->create_opts) {
5148 error_report("Format driver '%s' does not support image creation",
5149 drv->format_name);
5150 ret = -1;
5151 goto out;
5152 }
5153 if (!proto_drv->create_opts) {
5154 error_report("Protocol driver '%s' does not support image creation",
5155 proto_drv->format_name);
5156 ret = -1;
5157 goto out;
5158 }
5159 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5160 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5161
5162 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5163
5164 size = blk_getlength(blk1);
5165 if (size < 0) {
5166 error_report("Failed to get size for '%s'", in.filename);
5167 ret = -1;
5168 goto out;
5169 }
5170
5171 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5172 dd.count * in.bsz < size) {
5173 size = dd.count * in.bsz;
5174 }
5175
Reda Sallahif7c15532016-08-10 16:16:09 +02005176 /* Overflow means the specified offset is beyond input image's size */
5177 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5178 size < in.bsz * in.offset)) {
5179 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5180 } else {
5181 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5182 size - in.bsz * in.offset, &error_abort);
5183 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005184
5185 ret = bdrv_create(drv, out.filename, opts, &local_err);
5186 if (ret < 0) {
5187 error_reportf_err(local_err,
5188 "%s: error while creating output image: ",
5189 out.filename);
5190 ret = -1;
5191 goto out;
5192 }
5193
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005194 /* TODO, we can't honour --image-opts for the target,
5195 * since it needs to be given in a format compatible
5196 * with the bdrv_create() call above which does not
5197 * support image-opts style.
5198 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005199 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005200 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005201
5202 if (!blk2) {
5203 ret = -1;
5204 goto out;
5205 }
5206
Reda Sallahif7c15532016-08-10 16:16:09 +02005207 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5208 size < in.offset * in.bsz)) {
5209 /* We give a warning if the skip option is bigger than the input
5210 * size and create an empty output disk image (i.e. like dd(1)).
5211 */
5212 error_report("%s: cannot skip to specified offset", in.filename);
5213 in_pos = size;
5214 } else {
5215 in_pos = in.offset * in.bsz;
5216 }
5217
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005218 in.buf = g_new(uint8_t, in.bsz);
5219
Miroslav Rezanina0f48c472022-11-09 10:57:13 -05005220 for (out_pos = 0; in_pos < size; ) {
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005221 int bytes = (in_pos + in.bsz > size) ? size - in_pos : in.bsz;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005222
Alberto Fariaa9262f52022-07-05 17:15:11 +01005223 ret = blk_pread(blk1, in_pos, bytes, in.buf, 0);
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005224 if (ret < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005225 error_report("error while reading from input image file: %s",
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005226 strerror(-ret));
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005227 goto out;
5228 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005229 in_pos += bytes;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005230
Alberto Fariaa9262f52022-07-05 17:15:11 +01005231 ret = blk_pwrite(blk2, out_pos, bytes, in.buf, 0);
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005232 if (ret < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005233 error_report("error while writing to output image file: %s",
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005234 strerror(-ret));
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005235 goto out;
5236 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01005237 out_pos += bytes;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005238 }
5239
5240out:
5241 g_free(arg);
5242 qemu_opts_del(opts);
5243 qemu_opts_free(create_opts);
5244 blk_unref(blk1);
5245 blk_unref(blk2);
5246 g_free(in.filename);
5247 g_free(out.filename);
5248 g_free(in.buf);
5249 g_free(out.buf);
5250
5251 if (ret) {
5252 return 1;
5253 }
5254 return 0;
5255}
5256
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005257static void dump_json_block_measure_info(BlockMeasureInfo *info)
5258{
Markus Armbrustereab3a462020-12-11 18:11:37 +01005259 GString *str;
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005260 QObject *obj;
5261 Visitor *v = qobject_output_visitor_new(&obj);
5262
5263 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5264 visit_complete(v, &obj);
Markus Armbruster6589f452020-12-11 18:11:35 +01005265 str = qobject_to_json_pretty(obj, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005266 assert(str != NULL);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005267 printf("%s\n", str->str);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005268 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005269 visit_free(v);
Markus Armbrustereab3a462020-12-11 18:11:37 +01005270 g_string_free(str, true);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005271}
5272
5273static int img_measure(int argc, char **argv)
5274{
5275 static const struct option long_options[] = {
5276 {"help", no_argument, 0, 'h'},
5277 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5278 {"object", required_argument, 0, OPTION_OBJECT},
5279 {"output", required_argument, 0, OPTION_OUTPUT},
5280 {"size", required_argument, 0, OPTION_SIZE},
5281 {"force-share", no_argument, 0, 'U'},
5282 {0, 0, 0, 0}
5283 };
5284 OutputFormat output_format = OFORMAT_HUMAN;
5285 BlockBackend *in_blk = NULL;
5286 BlockDriver *drv;
5287 const char *filename = NULL;
5288 const char *fmt = NULL;
5289 const char *out_fmt = "raw";
5290 char *options = NULL;
5291 char *snapshot_name = NULL;
5292 bool force_share = false;
5293 QemuOpts *opts = NULL;
5294 QemuOpts *object_opts = NULL;
5295 QemuOpts *sn_opts = NULL;
5296 QemuOptsList *create_opts = NULL;
5297 bool image_opts = false;
5298 uint64_t img_size = UINT64_MAX;
5299 BlockMeasureInfo *info = NULL;
5300 Error *local_err = NULL;
5301 int ret = 1;
5302 int c;
5303
5304 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5305 long_options, NULL)) != -1) {
5306 switch (c) {
5307 case '?':
5308 case 'h':
5309 help();
5310 break;
5311 case 'f':
5312 fmt = optarg;
5313 break;
5314 case 'O':
5315 out_fmt = optarg;
5316 break;
5317 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005318 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005319 goto out;
5320 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005321 break;
5322 case 'l':
5323 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5324 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5325 optarg, false);
5326 if (!sn_opts) {
5327 error_report("Failed in parsing snapshot param '%s'",
5328 optarg);
5329 goto out;
5330 }
5331 } else {
5332 snapshot_name = optarg;
5333 }
5334 break;
5335 case 'U':
5336 force_share = true;
5337 break;
5338 case OPTION_OBJECT:
Kevin Wolf99b1e642021-02-17 12:56:45 +01005339 user_creatable_process_cmdline(optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005340 break;
5341 case OPTION_IMAGE_OPTS:
5342 image_opts = true;
5343 break;
5344 case OPTION_OUTPUT:
5345 if (!strcmp(optarg, "json")) {
5346 output_format = OFORMAT_JSON;
5347 } else if (!strcmp(optarg, "human")) {
5348 output_format = OFORMAT_HUMAN;
5349 } else {
5350 error_report("--output must be used with human or json "
5351 "as argument.");
5352 goto out;
5353 }
5354 break;
5355 case OPTION_SIZE:
5356 {
5357 int64_t sval;
5358
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005359 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005360 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005361 goto out;
5362 }
5363 img_size = (uint64_t)sval;
5364 }
5365 break;
5366 }
5367 }
5368
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005369 if (argc - optind > 1) {
5370 error_report("At most one filename argument is allowed.");
5371 goto out;
5372 } else if (argc - optind == 1) {
5373 filename = argv[optind];
5374 }
5375
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005376 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5377 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005378 goto out;
5379 }
5380 if (filename && img_size != UINT64_MAX) {
5381 error_report("--size N cannot be used together with a filename.");
5382 goto out;
5383 }
5384 if (!filename && img_size == UINT64_MAX) {
5385 error_report("Either --size N or one filename must be specified.");
5386 goto out;
5387 }
5388
5389 if (filename) {
5390 in_blk = img_open(image_opts, filename, fmt, 0,
5391 false, false, force_share);
5392 if (!in_blk) {
5393 goto out;
5394 }
5395
5396 if (sn_opts) {
5397 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5398 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5399 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5400 &local_err);
5401 } else if (snapshot_name != NULL) {
5402 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5403 snapshot_name, &local_err);
5404 }
5405 if (local_err) {
5406 error_reportf_err(local_err, "Failed to load snapshot: ");
5407 goto out;
5408 }
5409 }
5410
5411 drv = bdrv_find_format(out_fmt);
5412 if (!drv) {
5413 error_report("Unknown file format '%s'", out_fmt);
5414 goto out;
5415 }
5416 if (!drv->create_opts) {
5417 error_report("Format driver '%s' does not support image creation",
5418 drv->format_name);
5419 goto out;
5420 }
5421
5422 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5423 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5424 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5425 if (options) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02005426 if (!qemu_opts_do_parse(opts, options, NULL, &local_err)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005427 error_report_err(local_err);
5428 error_report("Invalid options for file format '%s'", out_fmt);
5429 goto out;
5430 }
5431 }
5432 if (img_size != UINT64_MAX) {
5433 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5434 }
5435
5436 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5437 if (local_err) {
5438 error_report_err(local_err);
5439 goto out;
5440 }
5441
5442 if (output_format == OFORMAT_HUMAN) {
5443 printf("required size: %" PRIu64 "\n", info->required);
5444 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005445 if (info->has_bitmaps) {
5446 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5447 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005448 } else {
5449 dump_json_block_measure_info(info);
5450 }
5451
5452 ret = 0;
5453
5454out:
5455 qapi_free_BlockMeasureInfo(info);
5456 qemu_opts_del(object_opts);
5457 qemu_opts_del(opts);
5458 qemu_opts_del(sn_opts);
5459 qemu_opts_free(create_opts);
5460 g_free(options);
5461 blk_unref(in_blk);
5462 return ret;
5463}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005464
Anthony Liguoric227f092009-10-01 16:12:16 -05005465static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005466#define DEF(option, callback, arg_string) \
5467 { option, callback },
5468#include "qemu-img-cmds.h"
5469#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005470 { NULL, NULL, },
5471};
5472
bellardea2384d2004-08-01 21:59:26 +00005473int main(int argc, char **argv)
5474{
Anthony Liguoric227f092009-10-01 16:12:16 -05005475 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005476 const char *cmdname;
Jeff Cody7db16892014-04-25 17:02:32 -04005477 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005478 static const struct option long_options[] = {
5479 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005480 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005481 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005482 {0, 0, 0, 0}
5483 };
bellardea2384d2004-08-01 21:59:26 +00005484
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005485#ifdef CONFIG_POSIX
5486 signal(SIGPIPE, SIG_IGN);
5487#endif
5488
Daniel P. Berrangé98c5d2e2020-08-25 11:38:48 +01005489 socket_init();
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005490 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005491 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005492 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005493
Markus Armbrusterf9734d52021-07-20 14:53:53 +02005494 qemu_init_main_loop(&error_fatal);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005495
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005496 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005497
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005498 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005499 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005500 if (argc < 2) {
5501 error_exit("Not enough arguments");
5502 }
Stuart Brady153859b2009-06-07 00:42:17 +01005503
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005504 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005505 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005506
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005507 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005508 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005509 case ':':
5510 missing_argument(argv[optind - 1]);
5511 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005512 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005513 unrecognized_option(argv[optind - 1]);
5514 return 0;
5515 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005516 help();
5517 return 0;
5518 case 'V':
5519 printf(QEMU_IMG_VERSION);
5520 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005521 case 'T':
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005522 trace_opt_parse(optarg);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005523 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005524 }
bellardea2384d2004-08-01 21:59:26 +00005525 }
Stuart Brady153859b2009-06-07 00:42:17 +01005526
Denis V. Lunev10985132016-06-17 17:44:13 +03005527 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005528
Denis V. Lunev10985132016-06-17 17:44:13 +03005529 /* reset getopt_long scanning */
5530 argc -= optind;
5531 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005532 return 0;
5533 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005534 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005535 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005536
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005537 if (!trace_init_backends()) {
5538 exit(1);
5539 }
Paolo Bonzini92eecff2020-11-02 06:58:41 -05005540 trace_init_file();
Richard Hendersonc5955f42022-04-17 11:29:44 -07005541 qemu_set_log(LOG_TRACE, &error_fatal);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005542
Denis V. Lunev10985132016-06-17 17:44:13 +03005543 /* find the command */
5544 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5545 if (!strcmp(cmdname, cmd->name)) {
5546 return cmd->handler(argc, argv);
5547 }
5548 }
Jeff Cody7db16892014-04-25 17:02:32 -04005549
Stuart Brady153859b2009-06-07 00:42:17 +01005550 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005551 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005552}