blob: 0778d8f56614058779453cb9d3a658aeaf4cf297 [file] [log] [blame]
bellardea2384d2004-08-01 21:59:26 +00001/*
bellardfb43f4d2006-08-07 21:34:46 +00002 * QEMU disk image utility
ths5fafdf22007-09-16 21:08:06 +00003 *
bellard68d0f702008-01-06 17:21:48 +00004 * Copyright (c) 2003-2008 Fabrice Bellard
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardea2384d2004-08-01 21:59:26 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbruster452fcdb2018-02-01 12:18:39 +010024
Peter Maydell80c71a22016-01-18 18:01:42 +000025#include "qemu/osdep.h"
Eric Blakec2a3d7d2017-07-21 08:50:47 -050026#include <getopt.h>
27
Markus Armbrustera8d25322019-05-23 16:35:08 +020028#include "qemu-common.h"
Fam Zheng67a1de02016-06-01 17:44:21 +080029#include "qemu-version.h"
Markus Armbrusterda34e652016-03-14 09:01:28 +010030#include "qapi/error.h"
Eric Blake3b51ab42020-05-12 20:16:45 -050031#include "qapi/qapi-commands-block-core.h"
Markus Armbruster9af23982018-02-11 10:36:01 +010032#include "qapi/qapi-visit-block-core.h"
Daniel P. Berrangeb3db2112016-09-30 15:45:27 +010033#include "qapi/qobject-output-visitor.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010035#include "qapi/qmp/qdict.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010036#include "qapi/qmp/qstring.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020037#include "qemu/cutils.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000038#include "qemu/config-file.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010039#include "qemu/option.h"
40#include "qemu/error-report.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030041#include "qemu/log.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
Stefano Garzarella97ede572019-05-08 12:43:24 +020044#include "qemu/units.h"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000045#include "qom/object_interfaces.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020046#include "sysemu/block-backend.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010047#include "block/block_int.h"
Max Reitzd4a32382014-10-24 15:57:37 +020048#include "block/blockjob.h"
Wenchao Xiaf364ec62013-05-25 11:09:44 +080049#include "block/qapi.h"
Daniel P. Berrangec2297082016-04-06 12:12:06 +010050#include "crypto/init.h"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +030051#include "trace/control.h"
bellarde8445332006-06-14 15:32:10 +000052
Thomas Huth7e563bf2018-02-15 12:06:47 +010053#define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
Thomas Huth0781dd62016-10-05 11:54:44 +020054 "\n" QEMU_COPYRIGHT "\n"
Jeff Cody5f6979c2014-04-28 14:37:18 -040055
Anthony Liguoric227f092009-10-01 16:12:16 -050056typedef struct img_cmd_t {
Stuart Brady153859b2009-06-07 00:42:17 +010057 const char *name;
58 int (*handler)(int argc, char **argv);
Anthony Liguoric227f092009-10-01 16:12:16 -050059} img_cmd_t;
Stuart Brady153859b2009-06-07 00:42:17 +010060
Federico Simoncelli8599ea42013-01-28 06:59:47 -050061enum {
62 OPTION_OUTPUT = 256,
63 OPTION_BACKING_CHAIN = 257,
Daniel P. Berrange3babeb12016-02-17 10:10:17 +000064 OPTION_OBJECT = 258,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +000065 OPTION_IMAGE_OPTS = 259,
Kevin Wolfb6495fa2015-07-10 18:09:18 +020066 OPTION_PATTERN = 260,
Kevin Wolf55d539c2016-06-03 13:59:41 +020067 OPTION_FLUSH_INTERVAL = 261,
68 OPTION_NO_DRAIN = 262,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +010069 OPTION_TARGET_IMAGE_OPTS = 263,
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +010070 OPTION_SIZE = 264,
Max Reitzdc5f6902017-06-13 22:20:55 +020071 OPTION_PREALLOCATION = 265,
Pavel Butsykin4ffca892017-09-18 15:42:27 +030072 OPTION_SHRINK = 266,
Max Reitz8eaac022019-05-07 22:35:03 +020073 OPTION_SALVAGE = 267,
David Edmondson168468f2020-02-05 11:02:48 +000074 OPTION_TARGET_IS_ZERO = 268,
Eric Blake3b51ab42020-05-12 20:16:45 -050075 OPTION_ADD = 269,
76 OPTION_REMOVE = 270,
77 OPTION_CLEAR = 271,
78 OPTION_ENABLE = 272,
79 OPTION_DISABLE = 273,
80 OPTION_MERGE = 274,
Federico Simoncelli8599ea42013-01-28 06:59:47 -050081};
82
83typedef enum OutputFormat {
84 OFORMAT_JSON,
85 OFORMAT_HUMAN,
86} OutputFormat;
87
Kevin Wolfe6996142016-03-15 13:03:11 +010088/* Default to cache=writeback as data integrity is not important for qemu-img */
Federico Simoncelli661a0f72011-06-20 12:48:19 -040089#define BDRV_DEFAULT_CACHE "writeback"
aurel32137519c2008-11-30 19:12:49 +000090
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010091static void format_print(void *opaque, const char *name)
bellardea2384d2004-08-01 21:59:26 +000092{
Stefan Hajnoczi00c6d402014-08-27 12:08:56 +010093 printf(" %s", name);
bellardea2384d2004-08-01 21:59:26 +000094}
95
Fam Zhengac1307a2014-04-22 13:36:11 +080096static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
97{
98 va_list ap;
99
Fam Zhengac1307a2014-04-22 13:36:11 +0800100 va_start(ap, fmt);
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200101 error_vreport(fmt, ap);
Fam Zhengac1307a2014-04-22 13:36:11 +0800102 va_end(ap);
103
Markus Armbrustere9e1d922019-04-17 21:06:27 +0200104 error_printf("Try 'qemu-img --help' for more information\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800105 exit(EXIT_FAILURE);
106}
107
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800108static void QEMU_NORETURN missing_argument(const char *option)
109{
110 error_exit("missing argument for option '%s'", option);
111}
112
113static void QEMU_NORETURN unrecognized_option(const char *option)
114{
115 error_exit("unrecognized option '%s'", option);
116}
117
Eric Blake0562adf2020-05-12 20:16:41 -0500118/* Please keep in synch with docs/tools/qemu-img.rst */
Fam Zhengac1307a2014-04-22 13:36:11 +0800119static void QEMU_NORETURN help(void)
bellardea2384d2004-08-01 21:59:26 +0000120{
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100121 const char *help_msg =
Jeff Cody5f6979c2014-04-28 14:37:18 -0400122 QEMU_IMG_VERSION
Denis V. Lunev10985132016-06-17 17:44:13 +0300123 "usage: qemu-img [standard options] command [command options]\n"
malc3f020d72010-02-08 12:04:56 +0300124 "QEMU disk image utility\n"
125 "\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300126 " '-h', '--help' display this help and exit\n"
127 " '-V', '--version' output version information and exit\n"
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +0300128 " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
129 " specify tracing options\n"
Denis V. Lunev10985132016-06-17 17:44:13 +0300130 "\n"
malc3f020d72010-02-08 12:04:56 +0300131 "Command syntax:\n"
Stuart Brady153859b2009-06-07 00:42:17 +0100132#define DEF(option, callback, arg_string) \
133 " " arg_string "\n"
134#include "qemu-img-cmds.h"
135#undef DEF
malc3f020d72010-02-08 12:04:56 +0300136 "\n"
137 "Command parameters:\n"
138 " 'filename' is a disk image filename\n"
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000139 " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
140 " manual page for a description of the object properties. The most common\n"
141 " object type is a 'secret', which is used to supply passwords and/or\n"
142 " encryption keys.\n"
malc3f020d72010-02-08 12:04:56 +0300143 " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400144 " 'cache' is the cache mode used to write the output disk image, the valid\n"
Liu Yuan80ccf932012-04-20 17:10:56 +0800145 " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
146 " 'directsync' and 'unsafe' (default for convert)\n"
Stefan Hajnoczibb87fdf2014-09-02 11:01:02 +0100147 " 'src_cache' is the cache mode used to read input disk images, the valid\n"
148 " options are the same as for the 'cache' option\n"
malc3f020d72010-02-08 12:04:56 +0300149 " 'size' is the disk image size in bytes. Optional suffixes\n"
Kevin Wolf5e009842013-06-05 14:19:27 +0200150 " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
151 " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
152 " supported. 'b' is ignored.\n"
malc3f020d72010-02-08 12:04:56 +0300153 " 'output_filename' is the destination disk image filename\n"
154 " 'output_fmt' is the destination format\n"
155 " 'options' is a comma separated list of format specific options in a\n"
156 " name=value format. Use -o ? for an overview of the options supported by the\n"
157 " used format\n"
Wenchao Xiaef806542013-12-04 17:10:57 +0800158 " 'snapshot_param' is param used for internal snapshot, format\n"
159 " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
160 " '[ID_OR_NAME]'\n"
malc3f020d72010-02-08 12:04:56 +0300161 " '-c' indicates that target image must be compressed (qcow format only)\n"
John Snow6e6e55f2017-07-17 20:34:22 -0400162 " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
163 " new backing file match exactly. The image doesn't need a working\n"
164 " backing file before rebasing in this case (useful for renaming the\n"
165 " backing file). For image creation, allow creating without attempting\n"
166 " to open the backing file.\n"
malc3f020d72010-02-08 12:04:56 +0300167 " '-h' with or without a command shows this help and lists the supported formats\n"
Jes Sorensen6b837bc2011-03-30 14:16:25 +0200168 " '-p' show progress of command (only certain commands)\n"
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100169 " '-q' use Quiet mode - do not print any output (except errors)\n"
Peter Lieven11b66992013-10-24 12:07:05 +0200170 " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
171 " contain only zeros for qemu-img to create a sparse image during\n"
172 " conversion. If the number of bytes is 0, the source will not be scanned for\n"
173 " unallocated or zero sectors, and the destination image will always be\n"
174 " fully allocated\n"
Benoît Canetc054b3f2012-09-05 13:09:02 +0200175 " '--output' takes the format in which the output must be done (human or json)\n"
Alexandre Derumierb2e10492013-09-02 19:07:24 +0100176 " '-n' skips the target volume creation (useful if the volume is created\n"
177 " prior to running qemu-img)\n"
malc3f020d72010-02-08 12:04:56 +0300178 "\n"
Eric Blake3b51ab42020-05-12 20:16:45 -0500179 "Parameters to bitmap subcommand:\n"
180 " 'bitmap' is the name of the bitmap to manipulate, through one or more\n"
181 " actions from '--add', '--remove', '--clear', '--enable', '--disable',\n"
182 " or '--merge source'\n"
183 " '-g granularity' sets the granularity for '--add' actions\n"
184 " '-b source' and '-F src_fmt' tell '--merge' actions to find the source\n"
185 " bitmaps from an alternative file\n"
186 "\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200187 "Parameters to check subcommand:\n"
188 " '-r' tries to repair any inconsistencies that are found during the check.\n"
189 " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
190 " kinds of errors, with a higher risk of choosing the wrong fix or\n"
Stefan Weil0546b8c2012-08-10 22:03:25 +0200191 " hiding corruption that has already occurred.\n"
Kevin Wolf4534ff52012-05-11 16:07:02 +0200192 "\n"
Peter Lieven2d9187b2017-02-28 13:40:07 +0100193 "Parameters to convert subcommand:\n"
194 " '-m' specifies how many coroutines work in parallel during the convert\n"
195 " process (defaults to 8)\n"
196 " '-W' allow to write to the target out of order rather than sequential\n"
197 "\n"
malc3f020d72010-02-08 12:04:56 +0300198 "Parameters to snapshot subcommand:\n"
199 " 'snapshot' is the name of the snapshot to create, apply or delete\n"
200 " '-a' applies a snapshot (revert disk to saved state)\n"
201 " '-c' creates a snapshot\n"
202 " '-d' deletes a snapshot\n"
Miroslav Rezaninad14ed182013-02-13 09:09:41 +0100203 " '-l' lists all snapshots in the given image\n"
204 "\n"
205 "Parameters to compare subcommand:\n"
206 " '-f' first image format\n"
207 " '-F' second image format\n"
Reda Sallahi86ce1f62016-08-10 04:43:12 +0200208 " '-s' run in Strict mode - fail on different image size or sector allocation\n"
209 "\n"
210 "Parameters to dd subcommand:\n"
211 " 'bs=BYTES' read and write up to BYTES bytes at a time "
212 "(default: 512)\n"
213 " 'count=N' copy only N input blocks\n"
214 " 'if=FILE' read from FILE\n"
Reda Sallahif7c15532016-08-10 16:16:09 +0200215 " 'of=FILE' write to FILE\n"
216 " 'skip=N' skip N bs-sized blocks at the start of input\n";
Paolo Bonzinie00291c2010-02-04 16:49:56 +0100217
218 printf("%s\nSupported formats:", help_msg);
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300219 bdrv_iterate_format(format_print, NULL, false);
Eric Blakef5048cb2017-08-03 11:33:53 -0500220 printf("\n\n" QEMU_HELP_BOTTOM "\n");
Fam Zhengac1307a2014-04-22 13:36:11 +0800221 exit(EXIT_SUCCESS);
bellardea2384d2004-08-01 21:59:26 +0000222}
223
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000224static QemuOptsList qemu_object_opts = {
225 .name = "object",
226 .implied_opt_name = "qom-type",
227 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
228 .desc = {
229 { }
230 },
231};
232
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200233static bool qemu_img_object_print_help(const char *type, QemuOpts *opts)
234{
235 if (user_creatable_print_help(type, opts)) {
236 exit(0);
237 }
238 return true;
239}
240
Markus Armbruster80c710c2020-04-15 09:49:26 +0200241/*
242 * Is @optarg safe for accumulate_options()?
243 * It is when multiple of them can be joined together separated by ','.
244 * To make that work, @optarg must not start with ',' (or else a
245 * separating ',' preceding it gets escaped), and it must not end with
246 * an odd number of ',' (or else a separating ',' following it gets
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200247 * escaped), or be empty (or else a separating ',' preceding it can
248 * escape a separating ',' following it).
249 *
Markus Armbruster80c710c2020-04-15 09:49:26 +0200250 */
251static bool is_valid_option_list(const char *optarg)
252{
253 size_t len = strlen(optarg);
254 size_t i;
255
Markus Armbrusterf62514b2020-04-15 09:49:27 +0200256 if (!optarg[0] || optarg[0] == ',') {
Markus Armbruster80c710c2020-04-15 09:49:26 +0200257 return false;
258 }
259
260 for (i = len; i > 0 && optarg[i - 1] == ','; i--) {
261 }
262 if ((len - i) % 2) {
263 return false;
264 }
265
266 return true;
267}
268
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200269static int accumulate_options(char **options, char *optarg)
270{
271 char *new_options;
272
273 if (!is_valid_option_list(optarg)) {
274 error_report("Invalid option list: %s", optarg);
275 return -1;
276 }
277
278 if (!*options) {
279 *options = g_strdup(optarg);
280 } else {
281 new_options = g_strdup_printf("%s,%s", *options, optarg);
282 g_free(*options);
283 *options = new_options;
284 }
285 return 0;
286}
287
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000288static QemuOptsList qemu_source_opts = {
289 .name = "source",
290 .implied_opt_name = "file",
291 .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
292 .desc = {
293 { }
294 },
295};
296
Stefan Weil7c30f652013-06-16 17:01:05 +0200297static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100298{
299 int ret = 0;
300 if (!quiet) {
301 va_list args;
302 va_start(args, fmt);
303 ret = vprintf(fmt, args);
304 va_end(args);
305 }
306 return ret;
307}
308
bellardea2384d2004-08-01 21:59:26 +0000309
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100310static int print_block_option_help(const char *filename, const char *fmt)
311{
312 BlockDriver *drv, *proto_drv;
Chunyan Liu83d05212014-06-05 17:20:51 +0800313 QemuOptsList *create_opts = NULL;
Max Reitzb65a5e12015-02-05 13:58:12 -0500314 Error *local_err = NULL;
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100315
316 /* Find driver and parse its options */
317 drv = bdrv_find_format(fmt);
318 if (!drv) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100319 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100320 return 1;
321 }
322
Max Reitzd402b6a2018-05-09 23:00:21 +0200323 if (!drv->create_opts) {
324 error_report("Format driver '%s' does not support image creation", fmt);
325 return 1;
326 }
327
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800328 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100329 if (filename) {
Max Reitzb65a5e12015-02-05 13:58:12 -0500330 proto_drv = bdrv_find_protocol(filename, true, &local_err);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100331 if (!proto_drv) {
Markus Armbruster2867ce42015-03-12 16:08:02 +0100332 error_report_err(local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +0800333 qemu_opts_free(create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100334 return 1;
335 }
Max Reitzd402b6a2018-05-09 23:00:21 +0200336 if (!proto_drv->create_opts) {
Max Reitzf0998872018-11-19 11:19:20 +0100337 error_report("Protocol driver '%s' does not support image creation",
Max Reitzd402b6a2018-05-09 23:00:21 +0200338 proto_drv->format_name);
Max Reitz3ecd5a42018-11-19 11:19:21 +0100339 qemu_opts_free(create_opts);
Max Reitzd402b6a2018-05-09 23:00:21 +0200340 return 1;
341 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800342 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfa283cb62014-02-21 16:24:07 +0100343 }
344
Max Reitzf4619af2019-04-13 17:20:37 +0200345 if (filename) {
346 printf("Supported options:\n");
347 } else {
348 printf("Supported %s options:\n", fmt);
349 }
Max Reitz63898712018-10-19 18:49:25 +0200350 qemu_opts_print_help(create_opts, false);
Chunyan Liu83d05212014-06-05 17:20:51 +0800351 qemu_opts_free(create_opts);
Max Reitzf4619af2019-04-13 17:20:37 +0200352
353 if (!filename) {
354 printf("\n"
355 "The protocol level may support further options.\n"
356 "Specify the target filename to include those options.\n");
357 }
358
Jes Sorensen4ac8aac2010-12-06 15:25:38 +0100359 return 0;
360}
361
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000362
Max Reitzefaa7c42016-03-16 19:54:38 +0100363static BlockBackend *img_open_opts(const char *optstr,
Kevin Wolfce099542016-03-15 13:01:04 +0100364 QemuOpts *opts, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800365 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000366{
367 QDict *options;
368 Error *local_err = NULL;
369 BlockBackend *blk;
370 options = qemu_opts_to_qdict(opts, NULL);
Fam Zheng335e9932017-05-03 00:35:39 +0800371 if (force_share) {
372 if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
Max Reitz4615f872018-05-02 22:20:50 +0200373 && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
Fam Zheng335e9932017-05-03 00:35:39 +0800374 error_report("--force-share/-U conflicts with image options");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200375 qobject_unref(options);
Fam Zheng335e9932017-05-03 00:35:39 +0800376 return NULL;
377 }
Max Reitz4615f872018-05-02 22:20:50 +0200378 qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
Fam Zheng335e9932017-05-03 00:35:39 +0800379 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100380 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000381 if (!blk) {
Daniel P. Berrange143605a2016-04-06 10:16:18 +0100382 error_reportf_err(local_err, "Could not open '%s': ", optstr);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000383 return NULL;
384 }
Kevin Wolfce099542016-03-15 13:01:04 +0100385 blk_set_enable_write_cache(blk, !writethrough);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000386
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000387 return blk;
388}
389
Max Reitzefaa7c42016-03-16 19:54:38 +0100390static BlockBackend *img_open_file(const char *filename,
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100391 QDict *options,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000392 const char *fmt, int flags,
Fam Zheng335e9932017-05-03 00:35:39 +0800393 bool writethrough, bool quiet,
394 bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000395{
396 BlockBackend *blk;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200397 Error *local_err = NULL;
Kevin Wolfad717132010-12-16 15:37:41 +0100398
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100399 if (!options) {
400 options = qdict_new();
401 }
bellard75c23802004-08-27 21:28:58 +0000402 if (fmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -0500403 qdict_put_str(options, "driver", fmt);
bellard75c23802004-08-27 21:28:58 +0000404 }
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100405
Fam Zheng335e9932017-05-03 00:35:39 +0800406 if (force_share) {
Eric Blake579cf1d2017-05-15 14:54:39 -0500407 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Fam Zheng335e9932017-05-03 00:35:39 +0800408 }
Max Reitzefaa7c42016-03-16 19:54:38 +0100409 blk = blk_new_open(filename, NULL, options, flags, &local_err);
Max Reitz5bd31322015-02-05 13:58:16 -0500410 if (!blk) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100411 error_reportf_err(local_err, "Could not open '%s': ", filename);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000412 return NULL;
bellard75c23802004-08-27 21:28:58 +0000413 }
Kevin Wolfce099542016-03-15 13:01:04 +0100414 blk_set_enable_write_cache(blk, !writethrough);
Kevin Wolfb9eaf9e2011-02-09 11:25:53 +0100415
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200416 return blk;
bellard75c23802004-08-27 21:28:58 +0000417}
418
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000419
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100420static int img_add_key_secrets(void *opaque,
421 const char *name, const char *value,
422 Error **errp)
423{
424 QDict *options = opaque;
425
426 if (g_str_has_suffix(name, "key-secret")) {
Eric Blake187f47e2017-06-24 12:10:07 -0600427 qdict_put_str(options, name, value);
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100428 }
429
430 return 0;
431}
432
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100433
Max Reitzefaa7c42016-03-16 19:54:38 +0100434static BlockBackend *img_open(bool image_opts,
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000435 const char *filename,
Kevin Wolfce099542016-03-15 13:01:04 +0100436 const char *fmt, int flags, bool writethrough,
Fam Zheng335e9932017-05-03 00:35:39 +0800437 bool quiet, bool force_share)
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000438{
439 BlockBackend *blk;
440 if (image_opts) {
441 QemuOpts *opts;
442 if (fmt) {
443 error_report("--image-opts and --format are mutually exclusive");
444 return NULL;
445 }
446 opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
447 filename, true);
448 if (!opts) {
449 return NULL;
450 }
Fam Zheng335e9932017-05-03 00:35:39 +0800451 blk = img_open_opts(filename, opts, flags, writethrough, quiet,
452 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000453 } else {
Daniel P. Berrange29cf9332017-05-15 17:47:12 +0100454 blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
Fam Zheng335e9932017-05-03 00:35:39 +0800455 force_share);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000456 }
457 return blk;
458}
459
460
Chunyan Liu83d05212014-06-05 17:20:51 +0800461static int add_old_style_options(const char *fmt, QemuOpts *opts,
Jes Sorenseneec77d92010-12-07 17:44:34 +0100462 const char *base_filename,
463 const char *base_fmt)
Kevin Wolfefa84d42009-05-18 16:42:12 +0200464{
Markus Armbruster6750e792015-02-12 17:43:08 +0100465 Error *err = NULL;
466
Kevin Wolfefa84d42009-05-18 16:42:12 +0200467 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100468 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100469 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100470 error_report("Backing file not supported for file format '%s'",
471 fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100472 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900473 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200474 }
475 }
476 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +0100477 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +0100478 if (err) {
Jes Sorensen15654a62010-12-16 14:31:53 +0100479 error_report("Backing file format not supported for file "
480 "format '%s'", fmt);
Markus Armbruster6750e792015-02-12 17:43:08 +0100481 error_free(err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900482 return -1;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200483 }
484 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900485 return 0;
Kevin Wolfefa84d42009-05-18 16:42:12 +0200486}
487
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300488static int64_t cvtnum_full(const char *name, const char *value, int64_t min,
489 int64_t max)
Markus Armbruster606caa02017-02-21 21:14:04 +0100490{
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100491 int err;
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300492 uint64_t res;
Markus Armbruster606caa02017-02-21 21:14:04 +0100493
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300494 err = qemu_strtosz(value, NULL, &res);
495 if (err < 0 && err != -ERANGE) {
496 error_report("Invalid %s specified. You may use "
497 "k, M, G, T, P or E suffixes for", name);
498 error_report("kilobytes, megabytes, gigabytes, terabytes, "
499 "petabytes and exabytes.");
Markus Armbrusterf17fd4f2017-02-21 21:14:06 +0100500 return err;
501 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300502 if (err == -ERANGE || res > max || res < min) {
503 error_report("Invalid %s specified. Must be between %" PRId64
504 " and %" PRId64 ".", name, min, max);
Markus Armbrusterf46bfdb2017-02-21 21:14:07 +0100505 return -ERANGE;
506 }
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300507 return res;
508}
509
510static int64_t cvtnum(const char *name, const char *value)
511{
512 return cvtnum_full(name, value, 0, INT64_MAX);
Markus Armbruster606caa02017-02-21 21:14:04 +0100513}
514
bellardea2384d2004-08-01 21:59:26 +0000515static int img_create(int argc, char **argv)
516{
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200517 int c;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100518 uint64_t img_size = -1;
bellardea2384d2004-08-01 21:59:26 +0000519 const char *fmt = "raw";
aliguori9230eaf2009-03-28 17:55:19 +0000520 const char *base_fmt = NULL;
bellardea2384d2004-08-01 21:59:26 +0000521 const char *filename;
522 const char *base_filename = NULL;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200523 char *options = NULL;
Luiz Capitulino9b375252012-11-30 10:52:05 -0200524 Error *local_err = NULL;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100525 bool quiet = false;
John Snow6e6e55f2017-07-17 20:34:22 -0400526 int flags = 0;
ths3b46e622007-09-17 08:09:54 +0000527
bellardea2384d2004-08-01 21:59:26 +0000528 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000529 static const struct option long_options[] = {
530 {"help", no_argument, 0, 'h'},
531 {"object", required_argument, 0, OPTION_OBJECT},
532 {0, 0, 0, 0}
533 };
John Snow6e6e55f2017-07-17 20:34:22 -0400534 c = getopt_long(argc, argv, ":F:b:f:ho:qu",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000535 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100536 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000537 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100538 }
bellardea2384d2004-08-01 21:59:26 +0000539 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800540 case ':':
541 missing_argument(argv[optind - 1]);
542 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100543 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800544 unrecognized_option(argv[optind - 1]);
545 break;
bellardea2384d2004-08-01 21:59:26 +0000546 case 'h':
547 help();
548 break;
aliguori9230eaf2009-03-28 17:55:19 +0000549 case 'F':
550 base_fmt = optarg;
551 break;
bellardea2384d2004-08-01 21:59:26 +0000552 case 'b':
553 base_filename = optarg;
554 break;
555 case 'f':
556 fmt = optarg;
557 break;
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200558 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +0200559 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100560 goto fail;
561 }
Kevin Wolf9ea2ea72009-05-18 16:42:11 +0200562 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100563 case 'q':
564 quiet = true;
565 break;
John Snow6e6e55f2017-07-17 20:34:22 -0400566 case 'u':
567 flags |= BDRV_O_NO_BACKING;
568 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000569 case OPTION_OBJECT: {
570 QemuOpts *opts;
571 opts = qemu_opts_parse_noisily(&qemu_object_opts,
572 optarg, true);
573 if (!opts) {
574 goto fail;
575 }
576 } break;
bellardea2384d2004-08-01 21:59:26 +0000577 }
578 }
aliguori9230eaf2009-03-28 17:55:19 +0000579
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900580 /* Get the filename */
Kevin Wolfa283cb62014-02-21 16:24:07 +0100581 filename = (optind < argc) ? argv[optind] : NULL;
582 if (options && has_help_option(options)) {
583 g_free(options);
584 return print_block_option_help(filename, fmt);
585 }
586
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100587 if (optind >= argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800588 error_exit("Expecting image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100589 }
Kevin Wolfa283cb62014-02-21 16:24:07 +0100590 optind++;
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900591
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000592 if (qemu_opts_foreach(&qemu_object_opts,
593 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200594 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000595 goto fail;
596 }
597
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100598 /* Get image size, if specified */
599 if (optind < argc) {
Jes Sorensen70b4f4b2011-01-05 11:41:02 +0100600 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +0100601
Eyal Moscovici43d589b2020-05-13 16:36:26 +0300602 sval = cvtnum("image size", argv[optind++]);
Markus Armbruster606caa02017-02-21 21:14:04 +0100603 if (sval < 0) {
Kevin Wolf77386bf2014-02-21 16:24:04 +0100604 goto fail;
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100605 }
606 img_size = (uint64_t)sval;
607 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200608 if (optind != argc) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800609 error_exit("Unexpected argument: %s", argv[optind]);
Kevin Wolffc11eb22013-08-05 10:53:04 +0200610 }
Jes Sorensen1da7cfb2010-12-09 14:17:25 +0100611
Luiz Capitulino9b375252012-11-30 10:52:05 -0200612 bdrv_img_create(filename, fmt, base_filename, base_fmt,
John Snow6e6e55f2017-07-17 20:34:22 -0400613 options, img_size, flags, quiet, &local_err);
Markus Armbruster84d18f02014-01-30 15:07:28 +0100614 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +0100615 error_reportf_err(local_err, "%s: ", filename);
Kevin Wolf77386bf2014-02-21 16:24:04 +0100616 goto fail;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900617 }
Luiz Capitulinoa9300912012-11-30 10:52:06 -0200618
Kevin Wolf77386bf2014-02-21 16:24:04 +0100619 g_free(options);
bellardea2384d2004-08-01 21:59:26 +0000620 return 0;
Kevin Wolf77386bf2014-02-21 16:24:04 +0100621
622fail:
623 g_free(options);
624 return 1;
bellardea2384d2004-08-01 21:59:26 +0000625}
626
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100627static void dump_json_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500628{
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500629 QString *str;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500630 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +0100631 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600632
633 visit_type_ImageCheck(v, NULL, &check, &error_abort);
634 visit_complete(v, &obj);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500635 str = qobject_to_json_pretty(obj);
636 assert(str != NULL);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100637 qprintf(quiet, "%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200638 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -0600639 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +0200640 qobject_unref(str);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500641}
642
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100643static void dump_human_image_check(ImageCheck *check, bool quiet)
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500644{
645 if (!(check->corruptions || check->leaks || check->check_errors)) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100646 qprintf(quiet, "No errors were found on the image.\n");
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500647 } else {
648 if (check->corruptions) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100649 qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
650 "Data may be corrupted, or further writes to the image "
651 "may corrupt it.\n",
652 check->corruptions);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500653 }
654
655 if (check->leaks) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100656 qprintf(quiet,
657 "\n%" PRId64 " leaked clusters were found on the image.\n"
658 "This means waste of disk space, but no harm to data.\n",
659 check->leaks);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500660 }
661
662 if (check->check_errors) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100663 qprintf(quiet,
664 "\n%" PRId64
665 " internal errors have occurred during the check.\n",
666 check->check_errors);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500667 }
668 }
669
670 if (check->total_clusters != 0 && check->allocated_clusters != 0) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100671 qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
672 "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
673 check->allocated_clusters, check->total_clusters,
674 check->allocated_clusters * 100.0 / check->total_clusters,
675 check->fragmented_clusters * 100.0 / check->allocated_clusters,
676 check->compressed_clusters * 100.0 /
677 check->allocated_clusters);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500678 }
679
680 if (check->image_end_offset) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100681 qprintf(quiet,
682 "Image end offset: %" PRId64 "\n", check->image_end_offset);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500683 }
684}
685
686static int collect_image_check(BlockDriverState *bs,
687 ImageCheck *check,
688 const char *filename,
689 const char *fmt,
690 int fix)
691{
692 int ret;
693 BdrvCheckResult result;
694
695 ret = bdrv_check(bs, &result, fix);
696 if (ret < 0) {
697 return ret;
698 }
699
700 check->filename = g_strdup(filename);
701 check->format = g_strdup(bdrv_get_format_name(bs));
702 check->check_errors = result.check_errors;
703 check->corruptions = result.corruptions;
704 check->has_corruptions = result.corruptions != 0;
705 check->leaks = result.leaks;
706 check->has_leaks = result.leaks != 0;
707 check->corruptions_fixed = result.corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100708 check->has_corruptions_fixed = result.corruptions_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500709 check->leaks_fixed = result.leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100710 check->has_leaks_fixed = result.leaks_fixed != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500711 check->image_end_offset = result.image_end_offset;
712 check->has_image_end_offset = result.image_end_offset != 0;
713 check->total_clusters = result.bfi.total_clusters;
714 check->has_total_clusters = result.bfi.total_clusters != 0;
715 check->allocated_clusters = result.bfi.allocated_clusters;
716 check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
717 check->fragmented_clusters = result.bfi.fragmented_clusters;
718 check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
Stefan Hajnoczie6439d72013-02-07 17:15:04 +0100719 check->compressed_clusters = result.bfi.compressed_clusters;
720 check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500721
722 return 0;
723}
724
Kevin Wolfe076f332010-06-29 11:43:13 +0200725/*
726 * Checks an image for consistency. Exit codes:
727 *
Max Reitzd6635c42014-06-02 22:15:21 +0200728 * 0 - Check completed, image is good
729 * 1 - Check not completed because of internal errors
730 * 2 - Check completed, image is corrupted
731 * 3 - Check completed, image has leaked clusters, but is good otherwise
732 * 63 - Checks are not supported by the image format
Kevin Wolfe076f332010-06-29 11:43:13 +0200733 */
aliguori15859692009-04-21 23:11:53 +0000734static int img_check(int argc, char **argv)
735{
736 int c, ret;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500737 OutputFormat output_format = OFORMAT_HUMAN;
Max Reitz40055952014-07-22 22:58:42 +0200738 const char *filename, *fmt, *output, *cache;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200739 BlockBackend *blk;
aliguori15859692009-04-21 23:11:53 +0000740 BlockDriverState *bs;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200741 int fix = 0;
Kevin Wolfce099542016-03-15 13:01:04 +0100742 int flags = BDRV_O_CHECK;
743 bool writethrough;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200744 ImageCheck *check;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100745 bool quiet = false;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000746 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +0800747 bool force_share = false;
aliguori15859692009-04-21 23:11:53 +0000748
749 fmt = NULL;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500750 output = NULL;
Max Reitz40055952014-07-22 22:58:42 +0200751 cache = BDRV_DEFAULT_CACHE;
Kevin Wolfce099542016-03-15 13:01:04 +0100752
aliguori15859692009-04-21 23:11:53 +0000753 for(;;) {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500754 int option_index = 0;
755 static const struct option long_options[] = {
756 {"help", no_argument, 0, 'h'},
757 {"format", required_argument, 0, 'f'},
Prasad Joshi4fd6a982014-03-25 00:08:54 +0530758 {"repair", required_argument, 0, 'r'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500759 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000760 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000761 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +0800762 {"force-share", no_argument, 0, 'U'},
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500763 {0, 0, 0, 0}
764 };
Fam Zheng335e9932017-05-03 00:35:39 +0800765 c = getopt_long(argc, argv, ":hf:r:T:qU",
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500766 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100767 if (c == -1) {
aliguori15859692009-04-21 23:11:53 +0000768 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100769 }
aliguori15859692009-04-21 23:11:53 +0000770 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800771 case ':':
772 missing_argument(argv[optind - 1]);
773 break;
Jes Sorensenef873942010-12-06 15:25:40 +0100774 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800775 unrecognized_option(argv[optind - 1]);
776 break;
aliguori15859692009-04-21 23:11:53 +0000777 case 'h':
778 help();
779 break;
780 case 'f':
781 fmt = optarg;
782 break;
Kevin Wolf4534ff52012-05-11 16:07:02 +0200783 case 'r':
784 flags |= BDRV_O_RDWR;
785
786 if (!strcmp(optarg, "leaks")) {
787 fix = BDRV_FIX_LEAKS;
788 } else if (!strcmp(optarg, "all")) {
789 fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
790 } else {
Fam Zhengac1307a2014-04-22 13:36:11 +0800791 error_exit("Unknown option value for -r "
792 "(expecting 'leaks' or 'all'): %s", optarg);
Kevin Wolf4534ff52012-05-11 16:07:02 +0200793 }
794 break;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500795 case OPTION_OUTPUT:
796 output = optarg;
797 break;
Max Reitz40055952014-07-22 22:58:42 +0200798 case 'T':
799 cache = optarg;
800 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100801 case 'q':
802 quiet = true;
803 break;
Fam Zheng335e9932017-05-03 00:35:39 +0800804 case 'U':
805 force_share = true;
806 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000807 case OPTION_OBJECT: {
808 QemuOpts *opts;
809 opts = qemu_opts_parse_noisily(&qemu_object_opts,
810 optarg, true);
811 if (!opts) {
812 return 1;
813 }
814 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000815 case OPTION_IMAGE_OPTS:
816 image_opts = true;
817 break;
aliguori15859692009-04-21 23:11:53 +0000818 }
819 }
Kevin Wolffc11eb22013-08-05 10:53:04 +0200820 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +0800821 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100822 }
aliguori15859692009-04-21 23:11:53 +0000823 filename = argv[optind++];
824
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500825 if (output && !strcmp(output, "json")) {
826 output_format = OFORMAT_JSON;
827 } else if (output && !strcmp(output, "human")) {
828 output_format = OFORMAT_HUMAN;
829 } else if (output) {
830 error_report("--output must be used with human or json as argument.");
831 return 1;
832 }
833
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000834 if (qemu_opts_foreach(&qemu_object_opts,
835 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +0200836 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000837 return 1;
838 }
839
Kevin Wolfce099542016-03-15 13:01:04 +0100840 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +0200841 if (ret < 0) {
842 error_report("Invalid source cache option: %s", cache);
843 return 1;
844 }
845
Fam Zheng335e9932017-05-03 00:35:39 +0800846 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
847 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200848 if (!blk) {
849 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +0900850 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200851 bs = blk_bs(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500852
853 check = g_new0(ImageCheck, 1);
854 ret = collect_image_check(bs, check, filename, fmt, fix);
Kevin Wolfe076f332010-06-29 11:43:13 +0200855
856 if (ret == -ENOTSUP) {
Max Reitz55d492d2014-05-31 21:33:30 +0200857 error_report("This image format does not support checks");
Peter Lievenfefddf92013-10-24 08:53:34 +0200858 ret = 63;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500859 goto fail;
Kevin Wolfe076f332010-06-29 11:43:13 +0200860 }
861
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500862 if (check->corruptions_fixed || check->leaks_fixed) {
863 int corruptions_fixed, leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100864 bool has_leaks_fixed, has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500865
866 leaks_fixed = check->leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100867 has_leaks_fixed = check->has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500868 corruptions_fixed = check->corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100869 has_corruptions_fixed = check->has_corruptions_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500870
871 if (output_format == OFORMAT_HUMAN) {
Miroslav Rezaninaf382d432013-02-13 09:09:40 +0100872 qprintf(quiet,
873 "The following inconsistencies were found and repaired:\n\n"
874 " %" PRId64 " leaked clusters\n"
875 " %" PRId64 " corruptions\n\n"
876 "Double checking the fixed image now...\n",
877 check->leaks_fixed,
878 check->corruptions_fixed);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500879 }
880
Pan Nengyuanfc124ea2020-02-27 09:29:50 +0800881 qapi_free_ImageCheck(check);
882 check = g_new0(ImageCheck, 1);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500883 ret = collect_image_check(bs, check, filename, fmt, 0);
884
885 check->leaks_fixed = leaks_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100886 check->has_leaks_fixed = has_leaks_fixed;
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500887 check->corruptions_fixed = corruptions_fixed;
Max Reitz16563242020-03-24 18:27:55 +0100888 check->has_corruptions_fixed = has_corruptions_fixed;
Kevin Wolfccf34712012-05-11 18:16:54 +0200889 }
890
Max Reitz832390a2014-10-23 15:29:12 +0200891 if (!ret) {
892 switch (output_format) {
893 case OFORMAT_HUMAN:
894 dump_human_image_check(check, quiet);
895 break;
896 case OFORMAT_JSON:
897 dump_json_image_check(check, quiet);
898 break;
899 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500900 }
901
902 if (ret || check->check_errors) {
Max Reitz832390a2014-10-23 15:29:12 +0200903 if (ret) {
904 error_report("Check failed: %s", strerror(-ret));
905 } else {
906 error_report("Check failed");
907 }
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500908 ret = 1;
909 goto fail;
910 }
911
912 if (check->corruptions) {
913 ret = 2;
914 } else if (check->leaks) {
915 ret = 3;
Kevin Wolfe076f332010-06-29 11:43:13 +0200916 } else {
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500917 ret = 0;
aliguori15859692009-04-21 23:11:53 +0000918 }
919
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500920fail:
921 qapi_free_ImageCheck(check);
Markus Armbruster26f54e92014-10-07 13:59:04 +0200922 blk_unref(blk);
Federico Simoncelli8599ea42013-01-28 06:59:47 -0500923 return ret;
aliguori15859692009-04-21 23:11:53 +0000924}
925
Max Reitzd4a32382014-10-24 15:57:37 +0200926typedef struct CommonBlockJobCBInfo {
927 BlockDriverState *bs;
928 Error **errp;
929} CommonBlockJobCBInfo;
930
931static void common_block_job_cb(void *opaque, int ret)
932{
933 CommonBlockJobCBInfo *cbi = opaque;
934
935 if (ret < 0) {
936 error_setg_errno(cbi->errp, -ret, "Block job failed");
937 }
Max Reitzd4a32382014-10-24 15:57:37 +0200938}
939
940static void run_block_job(BlockJob *job, Error **errp)
941{
Kevin Wolfb75536c2016-04-18 17:30:17 +0200942 AioContext *aio_context = blk_get_aio_context(job->blk);
sochin.jiang4172a002017-06-15 14:47:33 +0800943 int ret = 0;
Max Reitzd4a32382014-10-24 15:57:37 +0200944
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200945 aio_context_acquire(aio_context);
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200946 job_ref(&job->job);
Max Reitzd4a32382014-10-24 15:57:37 +0200947 do {
Kevin Wolf30a5c882018-05-04 12:17:20 +0200948 float progress = 0.0f;
Max Reitzd4a32382014-10-24 15:57:37 +0200949 aio_poll(aio_context, true);
Vladimir Sementsov-Ogievskiy01fe1ca2020-03-11 13:29:56 +0300950 if (job->job.progress.total) {
951 progress = (float)job->job.progress.current /
952 job->job.progress.total * 100.f;
Kevin Wolf30a5c882018-05-04 12:17:20 +0200953 }
954 qemu_progress_print(progress, 0);
Kevin Wolfdf956ae2018-04-25 15:09:58 +0200955 } while (!job_is_ready(&job->job) && !job_is_completed(&job->job));
Max Reitzd4a32382014-10-24 15:57:37 +0200956
Kevin Wolfdbe5e6c2018-04-19 13:04:01 +0200957 if (!job_is_completed(&job->job)) {
Kevin Wolf3d70ff52018-04-24 16:13:52 +0200958 ret = job_complete_sync(&job->job, errp);
sochin.jiang4172a002017-06-15 14:47:33 +0800959 } else {
Kevin Wolf4ad35182018-04-19 17:30:16 +0200960 ret = job->job.ret;
sochin.jiang4172a002017-06-15 14:47:33 +0800961 }
Kevin Wolf80fa2c72018-04-13 18:50:05 +0200962 job_unref(&job->job);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200963 aio_context_release(aio_context);
Max Reitz687fa1d2014-10-24 15:57:39 +0200964
sochin.jiang4172a002017-06-15 14:47:33 +0800965 /* publish completion progress only when success */
966 if (!ret) {
967 qemu_progress_print(100.f, 0);
968 }
Max Reitzd4a32382014-10-24 15:57:37 +0200969}
970
bellardea2384d2004-08-01 21:59:26 +0000971static int img_commit(int argc, char **argv)
972{
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400973 int c, ret, flags;
Max Reitz1b22bff2014-10-24 15:57:40 +0200974 const char *filename, *fmt, *cache, *base;
Markus Armbruster26f54e92014-10-07 13:59:04 +0200975 BlockBackend *blk;
Max Reitzd4a32382014-10-24 15:57:37 +0200976 BlockDriverState *bs, *base_bs;
Kevin Wolf4ef85a92017-01-25 19:16:34 +0100977 BlockJob *job;
Max Reitz687fa1d2014-10-24 15:57:39 +0200978 bool progress = false, quiet = false, drop = false;
Kevin Wolfce099542016-03-15 13:01:04 +0100979 bool writethrough;
Max Reitzd4a32382014-10-24 15:57:37 +0200980 Error *local_err = NULL;
981 CommonBlockJobCBInfo cbi;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000982 bool image_opts = false;
Paolo Bonzini9e944cb2016-10-27 12:49:04 +0200983 AioContext *aio_context;
bellardea2384d2004-08-01 21:59:26 +0000984
985 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -0400986 cache = BDRV_DEFAULT_CACHE;
Max Reitz1b22bff2014-10-24 15:57:40 +0200987 base = NULL;
bellardea2384d2004-08-01 21:59:26 +0000988 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000989 static const struct option long_options[] = {
990 {"help", no_argument, 0, 'h'},
991 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +0000992 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000993 {0, 0, 0, 0}
994 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +0800995 c = getopt_long(argc, argv, ":f:ht:b:dpq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +0000996 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100997 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +0000998 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +0100999 }
bellardea2384d2004-08-01 21:59:26 +00001000 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001001 case ':':
1002 missing_argument(argv[optind - 1]);
1003 break;
Jes Sorensenef873942010-12-06 15:25:40 +01001004 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001005 unrecognized_option(argv[optind - 1]);
1006 break;
bellardea2384d2004-08-01 21:59:26 +00001007 case 'h':
1008 help();
1009 break;
1010 case 'f':
1011 fmt = optarg;
1012 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001013 case 't':
1014 cache = optarg;
1015 break;
Max Reitz1b22bff2014-10-24 15:57:40 +02001016 case 'b':
1017 base = optarg;
1018 /* -b implies -d */
1019 drop = true;
1020 break;
Max Reitz9a86fe42014-10-24 15:57:38 +02001021 case 'd':
1022 drop = true;
1023 break;
Max Reitz687fa1d2014-10-24 15:57:39 +02001024 case 'p':
1025 progress = true;
1026 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01001027 case 'q':
1028 quiet = true;
1029 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001030 case OPTION_OBJECT: {
1031 QemuOpts *opts;
1032 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1033 optarg, true);
1034 if (!opts) {
1035 return 1;
1036 }
1037 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001038 case OPTION_IMAGE_OPTS:
1039 image_opts = true;
1040 break;
bellardea2384d2004-08-01 21:59:26 +00001041 }
1042 }
Max Reitz687fa1d2014-10-24 15:57:39 +02001043
1044 /* Progress is not shown in Quiet mode */
1045 if (quiet) {
1046 progress = false;
1047 }
1048
Kevin Wolffc11eb22013-08-05 10:53:04 +02001049 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001050 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01001051 }
bellardea2384d2004-08-01 21:59:26 +00001052 filename = argv[optind++];
1053
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001054 if (qemu_opts_foreach(&qemu_object_opts,
1055 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001056 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001057 return 1;
1058 }
1059
Max Reitz9a86fe42014-10-24 15:57:38 +02001060 flags = BDRV_O_RDWR | BDRV_O_UNMAP;
Kevin Wolfce099542016-03-15 13:01:04 +01001061 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001062 if (ret < 0) {
1063 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczia3981eb2014-08-26 19:17:54 +01001064 return 1;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04001065 }
1066
Fam Zheng335e9932017-05-03 00:35:39 +08001067 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
1068 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001069 if (!blk) {
1070 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001071 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001072 bs = blk_bs(blk);
1073
Max Reitz687fa1d2014-10-24 15:57:39 +02001074 qemu_progress_init(progress, 1.f);
1075 qemu_progress_print(0.f, 100);
1076
Max Reitz1b22bff2014-10-24 15:57:40 +02001077 if (base) {
1078 base_bs = bdrv_find_backing_image(bs, base);
1079 if (!base_bs) {
Max Reitz6b33f3a2016-12-01 03:05:08 +01001080 error_setg(&local_err,
1081 "Did not find '%s' in the backing chain of '%s'",
1082 base, filename);
Max Reitz1b22bff2014-10-24 15:57:40 +02001083 goto done;
1084 }
1085 } else {
1086 /* This is different from QMP, which by default uses the deepest file in
1087 * the backing chain (i.e., the very base); however, the traditional
1088 * behavior of qemu-img commit is using the immediate backing file. */
Kevin Wolf760e0062015-06-17 14:55:21 +02001089 base_bs = backing_bs(bs);
Max Reitz1b22bff2014-10-24 15:57:40 +02001090 if (!base_bs) {
1091 error_setg(&local_err, "Image does not have a backing file");
1092 goto done;
1093 }
bellardea2384d2004-08-01 21:59:26 +00001094 }
1095
Max Reitzd4a32382014-10-24 15:57:37 +02001096 cbi = (CommonBlockJobCBInfo){
1097 .errp = &local_err,
1098 .bs = bs,
1099 };
1100
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001101 aio_context = bdrv_get_aio_context(bs);
1102 aio_context_acquire(aio_context);
Kevin Wolfbb02b652018-04-19 17:54:56 +02001103 commit_active_start("commit", bs, base_bs, JOB_DEFAULT, 0,
Kevin Wolf0db832f2017-02-20 18:10:05 +01001104 BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
Fam Zheng78bbd912017-04-21 20:27:04 +08001105 &cbi, false, &local_err);
Paolo Bonzini9e944cb2016-10-27 12:49:04 +02001106 aio_context_release(aio_context);
Max Reitzd4a32382014-10-24 15:57:37 +02001107 if (local_err) {
1108 goto done;
1109 }
1110
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001111 /* When the block job completes, the BlockBackend reference will point to
1112 * the old backing file. In order to avoid that the top image is already
1113 * deleted, so we can still empty it afterwards, increment the reference
1114 * counter here preemptively. */
Max Reitz9a86fe42014-10-24 15:57:38 +02001115 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001116 bdrv_ref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001117 }
1118
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001119 job = block_job_get("commit");
Liam Merwick2e2db262018-11-05 21:38:37 +00001120 assert(job);
Kevin Wolf4ef85a92017-01-25 19:16:34 +01001121 run_block_job(job, &local_err);
Max Reitz9a86fe42014-10-24 15:57:38 +02001122 if (local_err) {
1123 goto unref_backing;
1124 }
1125
Max Reitz2d97fde2020-04-29 16:11:26 +02001126 if (!drop) {
1127 BlockBackend *old_backing_blk;
1128
1129 old_backing_blk = blk_new_with_bs(bs, BLK_PERM_WRITE, BLK_PERM_ALL,
1130 &local_err);
1131 if (!old_backing_blk) {
1132 goto unref_backing;
1133 }
1134 ret = blk_make_empty(old_backing_blk, &local_err);
1135 blk_unref(old_backing_blk);
1136 if (ret == -ENOTSUP) {
1137 error_free(local_err);
1138 local_err = NULL;
1139 } else if (ret < 0) {
Max Reitz9a86fe42014-10-24 15:57:38 +02001140 goto unref_backing;
1141 }
1142 }
1143
1144unref_backing:
1145 if (!drop) {
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001146 bdrv_unref(bs);
Max Reitz9a86fe42014-10-24 15:57:38 +02001147 }
Max Reitzd4a32382014-10-24 15:57:37 +02001148
1149done:
Max Reitz687fa1d2014-10-24 15:57:39 +02001150 qemu_progress_end();
1151
Markus Armbruster26f54e92014-10-07 13:59:04 +02001152 blk_unref(blk);
Max Reitzd4a32382014-10-24 15:57:37 +02001153
1154 if (local_err) {
Markus Armbruster6936f292015-02-10 15:14:02 +01001155 error_report_err(local_err);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09001156 return 1;
1157 }
Max Reitzd4a32382014-10-24 15:57:37 +02001158
1159 qprintf(quiet, "Image committed.\n");
bellardea2384d2004-08-01 21:59:26 +00001160 return 0;
1161}
1162
Dmitry Konishchevf6a00aa2011-05-18 15:03:59 +04001163/*
Eric Blakedebb38a2017-10-11 22:47:11 -05001164 * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
1165 * of the first sector boundary within buf where the sector contains a
1166 * non-zero byte. This function is robust to a buffer that is not
1167 * sector-aligned.
1168 */
1169static int64_t find_nonzero(const uint8_t *buf, int64_t n)
1170{
1171 int64_t i;
1172 int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
1173
1174 for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
1175 if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
1176 return i;
1177 }
1178 }
1179 if (i < n && !buffer_is_zero(buf + i, n - end)) {
1180 return i;
1181 }
1182 return -1;
1183}
1184
1185/*
thsf58c7b32008-06-05 21:53:49 +00001186 * Returns true iff the first sector pointed to by 'buf' contains at least
1187 * a non-NUL byte.
1188 *
1189 * 'pnum' is set to the number of sectors (including and immediately following
1190 * the first one) that are known to be in the same allocated/unallocated state.
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001191 * The function will try to align the end offset to alignment boundaries so
1192 * that the request will at least end aligned and consequtive requests will
1193 * also start at an aligned offset.
thsf58c7b32008-06-05 21:53:49 +00001194 */
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001195static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum,
1196 int64_t sector_num, int alignment)
bellardea2384d2004-08-01 21:59:26 +00001197{
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001198 bool is_zero;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001199 int i, tail;
bellardea2384d2004-08-01 21:59:26 +00001200
1201 if (n <= 0) {
1202 *pnum = 0;
1203 return 0;
1204 }
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001205 is_zero = buffer_is_zero(buf, 512);
bellardea2384d2004-08-01 21:59:26 +00001206 for(i = 1; i < n; i++) {
1207 buf += 512;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001208 if (is_zero != buffer_is_zero(buf, 512)) {
bellardea2384d2004-08-01 21:59:26 +00001209 break;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001210 }
bellardea2384d2004-08-01 21:59:26 +00001211 }
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001212
1213 tail = (sector_num + i) & (alignment - 1);
1214 if (tail) {
1215 if (is_zero && i <= tail) {
1216 /* treat unallocated areas which only consist
1217 * of a small tail as allocated. */
1218 is_zero = false;
1219 }
1220 if (!is_zero) {
1221 /* align up end offset of allocated areas. */
1222 i += alignment - tail;
1223 i = MIN(i, n);
1224 } else {
1225 /* align down end offset of zero areas. */
1226 i -= tail;
1227 }
1228 }
bellardea2384d2004-08-01 21:59:26 +00001229 *pnum = i;
Stefan Hajnoczi1a6d39f2012-02-07 13:27:24 +00001230 return !is_zero;
bellardea2384d2004-08-01 21:59:26 +00001231}
1232
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001233/*
Kevin Wolfa22f1232011-08-26 15:27:13 +02001234 * Like is_allocated_sectors, but if the buffer starts with a used sector,
1235 * up to 'min' consecutive sectors containing zeros are ignored. This avoids
1236 * breaking up write requests for only small sparse areas.
1237 */
1238static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001239 int min, int64_t sector_num, int alignment)
Kevin Wolfa22f1232011-08-26 15:27:13 +02001240{
1241 int ret;
1242 int num_checked, num_used;
1243
1244 if (n < min) {
1245 min = n;
1246 }
1247
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001248 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001249 if (!ret) {
1250 return ret;
1251 }
1252
1253 num_used = *pnum;
1254 buf += BDRV_SECTOR_SIZE * *pnum;
1255 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001256 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001257 num_checked = num_used;
1258
1259 while (n > 0) {
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001260 ret = is_allocated_sectors(buf, n, pnum, sector_num, alignment);
Kevin Wolfa22f1232011-08-26 15:27:13 +02001261
1262 buf += BDRV_SECTOR_SIZE * *pnum;
1263 n -= *pnum;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001264 sector_num += *pnum;
Kevin Wolfa22f1232011-08-26 15:27:13 +02001265 num_checked += *pnum;
1266 if (ret) {
1267 num_used = num_checked;
1268 } else if (*pnum >= min) {
1269 break;
1270 }
1271 }
1272
1273 *pnum = num_used;
1274 return 1;
1275}
1276
1277/*
Eric Blakedc61cd32017-10-11 22:47:14 -05001278 * Compares two buffers sector by sector. Returns 0 if the first
1279 * sector of each buffer matches, non-zero otherwise.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001280 *
Eric Blakedc61cd32017-10-11 22:47:14 -05001281 * pnum is set to the sector-aligned size of the buffer prefix that
1282 * has the same matching status as the first sector.
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001283 */
Eric Blakedc61cd32017-10-11 22:47:14 -05001284static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
1285 int64_t bytes, int64_t *pnum)
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001286{
Radim Krčmář8c1ac472015-02-20 17:06:15 +01001287 bool res;
Eric Blakedc61cd32017-10-11 22:47:14 -05001288 int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001289
Eric Blakedc61cd32017-10-11 22:47:14 -05001290 assert(bytes > 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001291
Eric Blakedc61cd32017-10-11 22:47:14 -05001292 res = !!memcmp(buf1, buf2, i);
1293 while (i < bytes) {
1294 int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001295
Eric Blakedc61cd32017-10-11 22:47:14 -05001296 if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001297 break;
1298 }
Eric Blakedc61cd32017-10-11 22:47:14 -05001299 i += len;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01001300 }
1301
1302 *pnum = i;
1303 return res;
1304}
1305
Stefano Garzarella97ede572019-05-08 12:43:24 +02001306#define IO_BUF_SIZE (2 * MiB)
bellardea2384d2004-08-01 21:59:26 +00001307
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001308/*
1309 * Check if passed sectors are empty (not allocated or contain only 0 bytes)
1310 *
Eric Blake0608e402017-10-11 22:47:12 -05001311 * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
1312 * filled with 0, 1 if sectors contain non-zero data (this is a comparison
1313 * failure), and 4 on error (the exit status for read errors), after emitting
1314 * an error message.
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001315 *
Max Reitzf1d3cd72015-02-05 13:58:18 -05001316 * @param blk: BlockBackend for the image
Eric Blakec41508e2017-10-11 22:47:13 -05001317 * @param offset: Starting offset to check
1318 * @param bytes: Number of bytes to check
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001319 * @param filename: Name of disk file we are checking (logging purpose)
1320 * @param buffer: Allocated buffer for storing read data
1321 * @param quiet: Flag for quiet mode
1322 */
Eric Blakec41508e2017-10-11 22:47:13 -05001323static int check_empty_sectors(BlockBackend *blk, int64_t offset,
1324 int64_t bytes, const char *filename,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001325 uint8_t *buffer, bool quiet)
1326{
Eric Blakedebb38a2017-10-11 22:47:11 -05001327 int ret = 0;
1328 int64_t idx;
1329
Eric Blakec41508e2017-10-11 22:47:13 -05001330 ret = blk_pread(blk, offset, buffer, bytes);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001331 if (ret < 0) {
1332 error_report("Error while reading offset %" PRId64 " of %s: %s",
Eric Blakec41508e2017-10-11 22:47:13 -05001333 offset, filename, strerror(-ret));
Eric Blake0608e402017-10-11 22:47:12 -05001334 return 4;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001335 }
Eric Blakec41508e2017-10-11 22:47:13 -05001336 idx = find_nonzero(buffer, bytes);
Eric Blakedebb38a2017-10-11 22:47:11 -05001337 if (idx >= 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001338 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blakec41508e2017-10-11 22:47:13 -05001339 offset + idx);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001340 return 1;
1341 }
1342
1343 return 0;
1344}
1345
1346/*
1347 * Compares two images. Exit codes:
1348 *
1349 * 0 - Images are identical
1350 * 1 - Images differ
1351 * >1 - Error occurred
1352 */
1353static int img_compare(int argc, char **argv)
1354{
Max Reitz40055952014-07-22 22:58:42 +02001355 const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001356 BlockBackend *blk1, *blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001357 BlockDriverState *bs1, *bs2;
Eric Blake033d9fc2017-10-11 22:47:16 -05001358 int64_t total_size1, total_size2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001359 uint8_t *buf1 = NULL, *buf2 = NULL;
Eric Blake31826642017-10-11 22:47:08 -05001360 int64_t pnum1, pnum2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001361 int allocated1, allocated2;
1362 int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
1363 bool progress = false, quiet = false, strict = false;
Max Reitz40055952014-07-22 22:58:42 +02001364 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01001365 bool writethrough;
Eric Blake033d9fc2017-10-11 22:47:16 -05001366 int64_t total_size;
1367 int64_t offset = 0;
1368 int64_t chunk;
Eric Blakedc61cd32017-10-11 22:47:14 -05001369 int c;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001370 uint64_t progress_base;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001371 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08001372 bool force_share = false;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001373
Max Reitz40055952014-07-22 22:58:42 +02001374 cache = BDRV_DEFAULT_CACHE;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001375 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001376 static const struct option long_options[] = {
1377 {"help", no_argument, 0, 'h'},
1378 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001379 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08001380 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001381 {0, 0, 0, 0}
1382 };
Fam Zheng335e9932017-05-03 00:35:39 +08001383 c = getopt_long(argc, argv, ":hf:F:T:pqsU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001384 long_options, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001385 if (c == -1) {
1386 break;
1387 }
1388 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001389 case ':':
1390 missing_argument(argv[optind - 1]);
1391 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001392 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08001393 unrecognized_option(argv[optind - 1]);
1394 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001395 case 'h':
1396 help();
1397 break;
1398 case 'f':
1399 fmt1 = optarg;
1400 break;
1401 case 'F':
1402 fmt2 = optarg;
1403 break;
Max Reitz40055952014-07-22 22:58:42 +02001404 case 'T':
1405 cache = optarg;
1406 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001407 case 'p':
1408 progress = true;
1409 break;
1410 case 'q':
1411 quiet = true;
1412 break;
1413 case 's':
1414 strict = true;
1415 break;
Fam Zheng335e9932017-05-03 00:35:39 +08001416 case 'U':
1417 force_share = true;
1418 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001419 case OPTION_OBJECT: {
1420 QemuOpts *opts;
1421 opts = qemu_opts_parse_noisily(&qemu_object_opts,
1422 optarg, true);
1423 if (!opts) {
1424 ret = 2;
1425 goto out4;
1426 }
1427 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001428 case OPTION_IMAGE_OPTS:
1429 image_opts = true;
1430 break;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001431 }
1432 }
1433
1434 /* Progress is not shown in Quiet mode */
1435 if (quiet) {
1436 progress = false;
1437 }
1438
1439
Kevin Wolffc11eb22013-08-05 10:53:04 +02001440 if (optind != argc - 2) {
Fam Zhengac1307a2014-04-22 13:36:11 +08001441 error_exit("Expecting two image file names");
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001442 }
1443 filename1 = argv[optind++];
1444 filename2 = argv[optind++];
1445
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001446 if (qemu_opts_foreach(&qemu_object_opts,
1447 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02001448 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001449 ret = 2;
1450 goto out4;
1451 }
1452
Stefan Hajnoczicbda0162014-08-26 19:17:55 +01001453 /* Initialize before goto out */
1454 qemu_progress_init(progress, 2.0);
1455
Kevin Wolfce099542016-03-15 13:01:04 +01001456 flags = 0;
1457 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitz40055952014-07-22 22:58:42 +02001458 if (ret < 0) {
1459 error_report("Invalid source cache option: %s", cache);
1460 ret = 2;
1461 goto out3;
1462 }
1463
Fam Zheng335e9932017-05-03 00:35:39 +08001464 blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
1465 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001466 if (!blk1) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001467 ret = 2;
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001468 goto out3;
1469 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001470
Fam Zheng335e9932017-05-03 00:35:39 +08001471 blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
1472 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001473 if (!blk2) {
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001474 ret = 2;
Markus Armbruster26f54e92014-10-07 13:59:04 +02001475 goto out2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001476 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00001477 bs1 = blk_bs(blk1);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02001478 bs2 = blk_bs(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001479
Max Reitzf1d3cd72015-02-05 13:58:18 -05001480 buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
1481 buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
Eric Blake033d9fc2017-10-11 22:47:16 -05001482 total_size1 = blk_getlength(blk1);
1483 if (total_size1 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001484 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001485 filename1, strerror(-total_size1));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001486 ret = 4;
1487 goto out;
1488 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001489 total_size2 = blk_getlength(blk2);
1490 if (total_size2 < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001491 error_report("Can't get size of %s: %s",
Eric Blake033d9fc2017-10-11 22:47:16 -05001492 filename2, strerror(-total_size2));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02001493 ret = 4;
1494 goto out;
1495 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001496 total_size = MIN(total_size1, total_size2);
1497 progress_base = MAX(total_size1, total_size2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001498
1499 qemu_progress_print(0, 100);
1500
Eric Blake033d9fc2017-10-11 22:47:16 -05001501 if (strict && total_size1 != total_size2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001502 ret = 1;
1503 qprintf(quiet, "Strict mode: Image size mismatch!\n");
1504 goto out;
1505 }
1506
Eric Blake033d9fc2017-10-11 22:47:16 -05001507 while (offset < total_size) {
Eric Blake31826642017-10-11 22:47:08 -05001508 int status1, status2;
Fam Zheng67a0fd22016-01-26 11:58:48 +08001509
Eric Blake033d9fc2017-10-11 22:47:16 -05001510 status1 = bdrv_block_status_above(bs1, NULL, offset,
1511 total_size1 - offset, &pnum1, NULL,
1512 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001513 if (status1 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001514 ret = 3;
1515 error_report("Sector allocation test failed for %s", filename1);
1516 goto out;
1517 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001518 allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001519
Eric Blake033d9fc2017-10-11 22:47:16 -05001520 status2 = bdrv_block_status_above(bs2, NULL, offset,
1521 total_size2 - offset, &pnum2, NULL,
1522 NULL);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001523 if (status2 < 0) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001524 ret = 3;
1525 error_report("Sector allocation test failed for %s", filename2);
1526 goto out;
1527 }
Fam Zheng25ad8e62016-01-13 16:37:41 +08001528 allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
Eric Blake7daddc62017-10-11 22:47:09 -05001529
1530 assert(pnum1 && pnum2);
Eric Blake033d9fc2017-10-11 22:47:16 -05001531 chunk = MIN(pnum1, pnum2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001532
Fam Zheng25ad8e62016-01-13 16:37:41 +08001533 if (strict) {
Eric Blake31826642017-10-11 22:47:08 -05001534 if (status1 != status2) {
Fam Zheng25ad8e62016-01-13 16:37:41 +08001535 ret = 1;
1536 qprintf(quiet, "Strict mode: Offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001537 " block status mismatch!\n", offset);
Fam Zheng25ad8e62016-01-13 16:37:41 +08001538 goto out;
1539 }
1540 }
1541 if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
Eric Blake7daddc62017-10-11 22:47:09 -05001542 /* nothing to do */
Fam Zheng25ad8e62016-01-13 16:37:41 +08001543 } else if (allocated1 == allocated2) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001544 if (allocated1) {
Eric Blakedc61cd32017-10-11 22:47:14 -05001545 int64_t pnum;
1546
Eric Blake033d9fc2017-10-11 22:47:16 -05001547 chunk = MIN(chunk, IO_BUF_SIZE);
1548 ret = blk_pread(blk1, offset, buf1, chunk);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001549 if (ret < 0) {
1550 error_report("Error while reading offset %" PRId64
Eric Blake033d9fc2017-10-11 22:47:16 -05001551 " of %s: %s",
1552 offset, filename1, strerror(-ret));
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001553 ret = 4;
1554 goto out;
1555 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001556 ret = blk_pread(blk2, offset, buf2, chunk);
1557 if (ret < 0) {
1558 error_report("Error while reading offset %" PRId64
1559 " of %s: %s",
1560 offset, filename2, strerror(-ret));
1561 ret = 4;
1562 goto out;
1563 }
1564 ret = compare_buffers(buf1, buf2, chunk, &pnum);
1565 if (ret || pnum != chunk) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001566 qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
Eric Blake033d9fc2017-10-11 22:47:16 -05001567 offset + (ret ? 0 : pnum));
Fam Zheng36452f12013-11-13 20:26:49 +08001568 ret = 1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001569 goto out;
1570 }
1571 }
1572 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001573 chunk = MIN(chunk, IO_BUF_SIZE);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001574 if (allocated1) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001575 ret = check_empty_sectors(blk1, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001576 filename1, buf1, quiet);
1577 } else {
Eric Blake033d9fc2017-10-11 22:47:16 -05001578 ret = check_empty_sectors(blk2, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001579 filename2, buf1, quiet);
1580 }
1581 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001582 goto out;
1583 }
1584 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001585 offset += chunk;
1586 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001587 }
1588
Eric Blake033d9fc2017-10-11 22:47:16 -05001589 if (total_size1 != total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001590 BlockBackend *blk_over;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001591 const char *filename_over;
1592
1593 qprintf(quiet, "Warning: Image size mismatch!\n");
Eric Blake033d9fc2017-10-11 22:47:16 -05001594 if (total_size1 > total_size2) {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001595 blk_over = blk1;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001596 filename_over = filename1;
1597 } else {
Max Reitzf1d3cd72015-02-05 13:58:18 -05001598 blk_over = blk2;
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001599 filename_over = filename2;
1600 }
1601
Eric Blake033d9fc2017-10-11 22:47:16 -05001602 while (offset < progress_base) {
1603 ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
1604 progress_base - offset, &chunk,
1605 NULL, NULL);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001606 if (ret < 0) {
1607 ret = 3;
1608 error_report("Sector allocation test failed for %s",
1609 filename_over);
1610 goto out;
1611
1612 }
Eric Blake391cb1a2017-10-11 22:47:10 -05001613 if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
Eric Blake033d9fc2017-10-11 22:47:16 -05001614 chunk = MIN(chunk, IO_BUF_SIZE);
1615 ret = check_empty_sectors(blk_over, offset, chunk,
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001616 filename_over, buf1, quiet);
1617 if (ret) {
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001618 goto out;
1619 }
1620 }
Eric Blake033d9fc2017-10-11 22:47:16 -05001621 offset += chunk;
1622 qemu_progress_print(((float) chunk / progress_base) * 100, 100);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001623 }
1624 }
1625
1626 qprintf(quiet, "Images are identical.\n");
1627 ret = 0;
1628
1629out:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001630 qemu_vfree(buf1);
1631 qemu_vfree(buf2);
Markus Armbruster26f54e92014-10-07 13:59:04 +02001632 blk_unref(blk2);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001633out2:
Markus Armbruster26f54e92014-10-07 13:59:04 +02001634 blk_unref(blk1);
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001635out3:
1636 qemu_progress_end();
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00001637out4:
Miroslav Rezaninad14ed182013-02-13 09:09:41 +01001638 return ret;
1639}
1640
Eric Blake6c729dd2020-05-21 14:21:35 -05001641/* Convenience wrapper around qmp_block_dirty_bitmap_merge */
1642static void do_dirty_bitmap_merge(const char *dst_node, const char *dst_name,
1643 const char *src_node, const char *src_name,
1644 Error **errp)
1645{
1646 BlockDirtyBitmapMergeSource *merge_src;
1647 BlockDirtyBitmapMergeSourceList *list;
1648
1649 merge_src = g_new0(BlockDirtyBitmapMergeSource, 1);
1650 merge_src->type = QTYPE_QDICT;
1651 merge_src->u.external.node = g_strdup(src_node);
1652 merge_src->u.external.name = g_strdup(src_name);
1653 list = g_new0(BlockDirtyBitmapMergeSourceList, 1);
1654 list->value = merge_src;
1655 qmp_block_dirty_bitmap_merge(dst_node, dst_name, list, errp);
1656 qapi_free_BlockDirtyBitmapMergeSourceList(list);
1657}
1658
Kevin Wolf690c7302015-03-19 13:33:32 +01001659enum ImgConvertBlockStatus {
1660 BLK_DATA,
1661 BLK_ZERO,
1662 BLK_BACKING_FILE,
1663};
1664
Peter Lieven2d9187b2017-02-28 13:40:07 +01001665#define MAX_COROUTINES 16
1666
Kevin Wolf690c7302015-03-19 13:33:32 +01001667typedef struct ImgConvertState {
1668 BlockBackend **src;
1669 int64_t *src_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001670 int src_num;
Kevin Wolf690c7302015-03-19 13:33:32 +01001671 int64_t total_sectors;
1672 int64_t allocated_sectors;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001673 int64_t allocated_done;
1674 int64_t sector_num;
1675 int64_t wr_offs;
Kevin Wolf690c7302015-03-19 13:33:32 +01001676 enum ImgConvertBlockStatus status;
1677 int64_t sector_next_status;
1678 BlockBackend *target;
1679 bool has_zero_init;
1680 bool compressed;
Max Reitz351c8ef2018-05-01 18:57:49 +02001681 bool unallocated_blocks_are_zero;
Max Reitz4d7c4872019-07-24 19:12:29 +02001682 bool target_is_new;
Kevin Wolf690c7302015-03-19 13:33:32 +01001683 bool target_has_backing;
Max Reitz351c8ef2018-05-01 18:57:49 +02001684 int64_t target_backing_sectors; /* negative if unknown */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001685 bool wr_in_order;
Fam Zhengee5306d2018-06-01 17:26:48 +08001686 bool copy_range;
Max Reitz8eaac022019-05-07 22:35:03 +02001687 bool salvage;
Max Reitz3d96cb92019-05-07 22:35:02 +02001688 bool quiet;
Kevin Wolf690c7302015-03-19 13:33:32 +01001689 int min_sparse;
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001690 int alignment;
Kevin Wolf690c7302015-03-19 13:33:32 +01001691 size_t cluster_sectors;
1692 size_t buf_sectors;
Peter Lieven9fd77f92017-04-21 11:11:55 +02001693 long num_coroutines;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001694 int running_coroutines;
1695 Coroutine *co[MAX_COROUTINES];
1696 int64_t wait_sector_num[MAX_COROUTINES];
1697 CoMutex lock;
1698 int ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001699} ImgConvertState;
1700
Peter Lieven2d9187b2017-02-28 13:40:07 +01001701static void convert_select_part(ImgConvertState *s, int64_t sector_num,
1702 int *src_cur, int64_t *src_cur_offset)
Kevin Wolf690c7302015-03-19 13:33:32 +01001703{
Peter Lieven2d9187b2017-02-28 13:40:07 +01001704 *src_cur = 0;
1705 *src_cur_offset = 0;
1706 while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
1707 *src_cur_offset += s->src_sectors[*src_cur];
1708 (*src_cur)++;
1709 assert(*src_cur < s->src_num);
Kevin Wolf690c7302015-03-19 13:33:32 +01001710 }
1711}
1712
1713static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
1714{
Eric Blake31826642017-10-11 22:47:08 -05001715 int64_t src_cur_offset;
1716 int ret, n, src_cur;
Max Reitz351c8ef2018-05-01 18:57:49 +02001717 bool post_backing_zero = false;
Kevin Wolf690c7302015-03-19 13:33:32 +01001718
Peter Lieven2d9187b2017-02-28 13:40:07 +01001719 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
Kevin Wolf690c7302015-03-19 13:33:32 +01001720
1721 assert(s->total_sectors > sector_num);
1722 n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
1723
Max Reitz351c8ef2018-05-01 18:57:49 +02001724 if (s->target_backing_sectors >= 0) {
1725 if (sector_num >= s->target_backing_sectors) {
1726 post_backing_zero = s->unallocated_blocks_are_zero;
1727 } else if (sector_num + n > s->target_backing_sectors) {
1728 /* Split requests around target_backing_sectors (because
1729 * starting from there, zeros are handled differently) */
1730 n = s->target_backing_sectors - sector_num;
1731 }
1732 }
1733
Kevin Wolf690c7302015-03-19 13:33:32 +01001734 if (s->sector_next_status <= sector_num) {
Max Reitz8eaac022019-05-07 22:35:03 +02001735 uint64_t offset = (sector_num - src_cur_offset) * BDRV_SECTOR_SIZE;
1736 int64_t count;
Eric Blake31826642017-10-11 22:47:08 -05001737
Max Reitz8eaac022019-05-07 22:35:03 +02001738 do {
1739 count = n * BDRV_SECTOR_SIZE;
Eric Blake237d78f2017-10-11 22:47:03 -05001740
Max Reitz8eaac022019-05-07 22:35:03 +02001741 if (s->target_has_backing) {
1742 ret = bdrv_block_status(blk_bs(s->src[src_cur]), offset,
1743 count, &count, NULL, NULL);
1744 } else {
1745 ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
1746 offset, count, &count, NULL,
1747 NULL);
1748 }
1749
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
1775 if (ret & BDRV_BLOCK_ZERO) {
Max Reitz351c8ef2018-05-01 18:57:49 +02001776 s->status = post_backing_zero ? BLK_BACKING_FILE : BLK_ZERO;
Kevin Wolf690c7302015-03-19 13:33:32 +01001777 } else if (ret & BDRV_BLOCK_DATA) {
1778 s->status = BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001779 } else {
Vladimir Sementsov-Ogievskiy9f1b92a2017-04-07 14:34:04 +03001780 s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
Kevin Wolf690c7302015-03-19 13:33:32 +01001781 }
1782
1783 s->sector_next_status = sector_num + n;
1784 }
1785
1786 n = MIN(n, s->sector_next_status - sector_num);
1787 if (s->status == BLK_DATA) {
1788 n = MIN(n, s->buf_sectors);
1789 }
1790
1791 /* We need to write complete clusters for compressed images, so if an
1792 * unallocated area is shorter than that, we must consider the whole
1793 * cluster allocated. */
1794 if (s->compressed) {
1795 if (n < s->cluster_sectors) {
1796 n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
1797 s->status = BLK_DATA;
1798 } else {
1799 n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
1800 }
1801 }
1802
1803 return n;
1804}
1805
Peter Lieven2d9187b2017-02-28 13:40:07 +01001806static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
1807 int nb_sectors, uint8_t *buf)
Kevin Wolf690c7302015-03-19 13:33:32 +01001808{
Max Reitz8eaac022019-05-07 22:35:03 +02001809 uint64_t single_read_until = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001810 int n, ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01001811
Kevin Wolf690c7302015-03-19 13:33:32 +01001812 assert(nb_sectors <= s->buf_sectors);
1813 while (nb_sectors > 0) {
1814 BlockBackend *blk;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001815 int src_cur;
1816 int64_t bs_sectors, src_cur_offset;
Max Reitz8eaac022019-05-07 22:35:03 +02001817 uint64_t offset;
Kevin Wolf690c7302015-03-19 13:33:32 +01001818
1819 /* In the case of compression with multiple source files, we can get a
1820 * nb_sectors that spreads into the next part. So we must be able to
1821 * read across multiple BDSes for one convert_read() call. */
Peter Lieven2d9187b2017-02-28 13:40:07 +01001822 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1823 blk = s->src[src_cur];
1824 bs_sectors = s->src_sectors[src_cur];
Kevin Wolf690c7302015-03-19 13:33:32 +01001825
Max Reitz8eaac022019-05-07 22:35:03 +02001826 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001827
Max Reitz8eaac022019-05-07 22:35:03 +02001828 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1829 if (single_read_until > offset) {
1830 n = 1;
1831 }
1832
1833 ret = blk_co_pread(blk, offset, n << BDRV_SECTOR_BITS, buf, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01001834 if (ret < 0) {
Max Reitz8eaac022019-05-07 22:35:03 +02001835 if (s->salvage) {
1836 if (n > 1) {
1837 single_read_until = offset + (n << BDRV_SECTOR_BITS);
1838 continue;
1839 } else {
1840 if (!s->quiet) {
1841 warn_report("error while reading offset %" PRIu64
1842 ": %s", offset, strerror(-ret));
1843 }
1844 memset(buf, 0, BDRV_SECTOR_SIZE);
1845 }
1846 } else {
1847 return ret;
1848 }
Kevin Wolf690c7302015-03-19 13:33:32 +01001849 }
1850
1851 sector_num += n;
1852 nb_sectors -= n;
1853 buf += n * BDRV_SECTOR_SIZE;
1854 }
1855
1856 return 0;
1857}
1858
Peter Lieven2d9187b2017-02-28 13:40:07 +01001859
1860static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
1861 int nb_sectors, uint8_t *buf,
1862 enum ImgConvertBlockStatus status)
Kevin Wolf690c7302015-03-19 13:33:32 +01001863{
1864 int ret;
1865
1866 while (nb_sectors > 0) {
1867 int n = nb_sectors;
Lidong Chendb933fb2017-04-27 10:58:27 +08001868 BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
1869
Peter Lieven2d9187b2017-02-28 13:40:07 +01001870 switch (status) {
Kevin Wolf690c7302015-03-19 13:33:32 +01001871 case BLK_BACKING_FILE:
1872 /* If we have a backing file, leave clusters unallocated that are
1873 * unallocated in the source image, so that the backing file is
1874 * visible at the respective offset. */
1875 assert(s->target_has_backing);
1876 break;
1877
1878 case BLK_DATA:
Lidong Chendb933fb2017-04-27 10:58:27 +08001879 /* If we're told to keep the target fully allocated (-S 0) or there
1880 * is real non-zero data, we must write it. Otherwise we can treat
1881 * it as zero sectors.
1882 * Compressed clusters need to be written as a whole, so in that
1883 * case we can only save the write if the buffer is completely
1884 * zeroed. */
Kevin Wolf690c7302015-03-19 13:33:32 +01001885 if (!s->min_sparse ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001886 (!s->compressed &&
Peter Lieven8dcd3c92018-07-12 15:00:10 +02001887 is_allocated_sectors_min(buf, n, &n, s->min_sparse,
1888 sector_num, s->alignment)) ||
Lidong Chendb933fb2017-04-27 10:58:27 +08001889 (s->compressed &&
1890 !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
Kevin Wolf690c7302015-03-19 13:33:32 +01001891 {
Vladimir Sementsov-Ogievskiy265a7e52019-04-22 17:58:38 +03001892 ret = blk_co_pwrite(s->target, sector_num << BDRV_SECTOR_BITS,
1893 n << BDRV_SECTOR_BITS, buf, flags);
Kevin Wolf690c7302015-03-19 13:33:32 +01001894 if (ret < 0) {
1895 return ret;
1896 }
1897 break;
1898 }
1899 /* fall-through */
1900
1901 case BLK_ZERO:
1902 if (s->has_zero_init) {
Lidong Chendb933fb2017-04-27 10:58:27 +08001903 assert(!s->target_has_backing);
Kevin Wolf690c7302015-03-19 13:33:32 +01001904 break;
1905 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01001906 ret = blk_co_pwrite_zeroes(s->target,
1907 sector_num << BDRV_SECTOR_BITS,
Nir Soffera3d6ae22019-03-24 02:20:12 +02001908 n << BDRV_SECTOR_BITS,
1909 BDRV_REQ_MAY_UNMAP);
Kevin Wolf690c7302015-03-19 13:33:32 +01001910 if (ret < 0) {
1911 return ret;
1912 }
1913 break;
1914 }
1915
1916 sector_num += n;
1917 nb_sectors -= n;
1918 buf += n * BDRV_SECTOR_SIZE;
1919 }
1920
1921 return 0;
1922}
1923
Fam Zhengee5306d2018-06-01 17:26:48 +08001924static int coroutine_fn convert_co_copy_range(ImgConvertState *s, int64_t sector_num,
1925 int nb_sectors)
1926{
1927 int n, ret;
1928
1929 while (nb_sectors > 0) {
1930 BlockBackend *blk;
1931 int src_cur;
1932 int64_t bs_sectors, src_cur_offset;
1933 int64_t offset;
1934
1935 convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
1936 offset = (sector_num - src_cur_offset) << BDRV_SECTOR_BITS;
1937 blk = s->src[src_cur];
1938 bs_sectors = s->src_sectors[src_cur];
1939
1940 n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
1941
1942 ret = blk_co_copy_range(blk, offset, s->target,
1943 sector_num << BDRV_SECTOR_BITS,
Vladimir Sementsov-Ogievskiy67b51fb2018-07-09 19:37:17 +03001944 n << BDRV_SECTOR_BITS, 0, 0);
Fam Zhengee5306d2018-06-01 17:26:48 +08001945 if (ret < 0) {
1946 return ret;
1947 }
1948
1949 sector_num += n;
1950 nb_sectors -= n;
1951 }
1952 return 0;
1953}
1954
Peter Lieven2d9187b2017-02-28 13:40:07 +01001955static void coroutine_fn convert_co_do_copy(void *opaque)
1956{
1957 ImgConvertState *s = opaque;
1958 uint8_t *buf = NULL;
1959 int ret, i;
1960 int index = -1;
1961
1962 for (i = 0; i < s->num_coroutines; i++) {
1963 if (s->co[i] == qemu_coroutine_self()) {
1964 index = i;
1965 break;
1966 }
1967 }
1968 assert(index >= 0);
1969
1970 s->running_coroutines++;
1971 buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
1972
1973 while (1) {
1974 int n;
1975 int64_t sector_num;
1976 enum ImgConvertBlockStatus status;
Fam Zhengee5306d2018-06-01 17:26:48 +08001977 bool copy_range;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001978
1979 qemu_co_mutex_lock(&s->lock);
1980 if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
1981 qemu_co_mutex_unlock(&s->lock);
Anton Nefedovb91127e2017-04-26 11:33:15 +03001982 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001983 }
1984 n = convert_iteration_sectors(s, s->sector_num);
1985 if (n < 0) {
1986 qemu_co_mutex_unlock(&s->lock);
1987 s->ret = n;
Anton Nefedovb91127e2017-04-26 11:33:15 +03001988 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01001989 }
1990 /* save current sector and allocation status to local variables */
1991 sector_num = s->sector_num;
1992 status = s->status;
1993 if (!s->min_sparse && s->status == BLK_ZERO) {
1994 n = MIN(n, s->buf_sectors);
1995 }
1996 /* increment global sector counter so that other coroutines can
1997 * already continue reading beyond this request */
1998 s->sector_num += n;
1999 qemu_co_mutex_unlock(&s->lock);
2000
2001 if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
2002 s->allocated_done += n;
2003 qemu_progress_print(100.0 * s->allocated_done /
2004 s->allocated_sectors, 0);
2005 }
2006
Fam Zhengee5306d2018-06-01 17:26:48 +08002007retry:
2008 copy_range = s->copy_range && s->status == BLK_DATA;
2009 if (status == BLK_DATA && !copy_range) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002010 ret = convert_co_read(s, sector_num, n, buf);
2011 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002012 error_report("error while reading at byte %lld: %s",
2013 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Peter Lieven2d9187b2017-02-28 13:40:07 +01002014 s->ret = ret;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002015 }
2016 } else if (!s->min_sparse && status == BLK_ZERO) {
2017 status = BLK_DATA;
2018 memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
2019 }
2020
2021 if (s->wr_in_order) {
2022 /* keep writes in order */
Anton Nefedovb91127e2017-04-26 11:33:15 +03002023 while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002024 s->wait_sector_num[index] = sector_num;
2025 qemu_coroutine_yield();
2026 }
2027 s->wait_sector_num[index] = -1;
2028 }
2029
Anton Nefedovb91127e2017-04-26 11:33:15 +03002030 if (s->ret == -EINPROGRESS) {
Fam Zhengee5306d2018-06-01 17:26:48 +08002031 if (copy_range) {
2032 ret = convert_co_copy_range(s, sector_num, n);
2033 if (ret) {
2034 s->copy_range = false;
2035 goto retry;
2036 }
2037 } else {
2038 ret = convert_co_write(s, sector_num, n, buf, status);
2039 }
Anton Nefedovb91127e2017-04-26 11:33:15 +03002040 if (ret < 0) {
Eric Blake39f77cb2020-04-02 08:57:17 -05002041 error_report("error while writing at byte %lld: %s",
2042 sector_num * BDRV_SECTOR_SIZE, strerror(-ret));
Anton Nefedovb91127e2017-04-26 11:33:15 +03002043 s->ret = ret;
2044 }
Peter Lieven2d9187b2017-02-28 13:40:07 +01002045 }
2046
2047 if (s->wr_in_order) {
2048 /* reenter the coroutine that might have waited
2049 * for this write to complete */
2050 s->wr_offs = sector_num + n;
2051 for (i = 0; i < s->num_coroutines; i++) {
2052 if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
2053 /*
2054 * A -> B -> A cannot occur because A has
2055 * s->wait_sector_num[i] == -1 during A -> B. Therefore
2056 * B will never enter A during this time window.
2057 */
2058 qemu_coroutine_enter(s->co[i]);
2059 break;
2060 }
2061 }
2062 }
2063 }
2064
Peter Lieven2d9187b2017-02-28 13:40:07 +01002065 qemu_vfree(buf);
2066 s->co[index] = NULL;
2067 s->running_coroutines--;
2068 if (!s->running_coroutines && s->ret == -EINPROGRESS) {
2069 /* the convert job finished successfully */
2070 s->ret = 0;
2071 }
2072}
2073
Kevin Wolf690c7302015-03-19 13:33:32 +01002074static int convert_do_copy(ImgConvertState *s)
2075{
Peter Lieven2d9187b2017-02-28 13:40:07 +01002076 int ret, i, n;
2077 int64_t sector_num = 0;
Kevin Wolf690c7302015-03-19 13:33:32 +01002078
2079 /* Check whether we have zero initialisation or can get it efficiently */
David Edmondson168468f2020-02-05 11:02:48 +00002080 if (!s->has_zero_init && s->target_is_new && s->min_sparse &&
2081 !s->target_has_backing) {
Max Reitz4d7c4872019-07-24 19:12:29 +02002082 s->has_zero_init = bdrv_has_zero_init(blk_bs(s->target));
Max Reitz4d7c4872019-07-24 19:12:29 +02002083 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002084
2085 if (!s->has_zero_init && !s->target_has_backing &&
2086 bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
2087 {
Kevin Wolfc9fdcf22019-03-22 13:49:28 +01002088 ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK);
Kevin Wolf690c7302015-03-19 13:33:32 +01002089 if (ret == 0) {
2090 s->has_zero_init = true;
2091 }
2092 }
2093
2094 /* Allocate buffer for copied data. For compressed images, only one cluster
2095 * can be copied at a time. */
2096 if (s->compressed) {
2097 if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
2098 error_report("invalid cluster size");
Peter Lieven2d9187b2017-02-28 13:40:07 +01002099 return -EINVAL;
Kevin Wolf690c7302015-03-19 13:33:32 +01002100 }
2101 s->buf_sectors = s->cluster_sectors;
2102 }
Kevin Wolf690c7302015-03-19 13:33:32 +01002103
Kevin Wolf690c7302015-03-19 13:33:32 +01002104 while (sector_num < s->total_sectors) {
2105 n = convert_iteration_sectors(s, sector_num);
2106 if (n < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002107 return n;
Kevin Wolf690c7302015-03-19 13:33:32 +01002108 }
Max Reitzaad15de2016-03-24 23:33:57 +01002109 if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
2110 {
Kevin Wolf690c7302015-03-19 13:33:32 +01002111 s->allocated_sectors += n;
2112 }
2113 sector_num += n;
2114 }
2115
2116 /* Do the copy */
Kevin Wolf690c7302015-03-19 13:33:32 +01002117 s->sector_next_status = 0;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002118 s->ret = -EINPROGRESS;
Kevin Wolf690c7302015-03-19 13:33:32 +01002119
Peter Lieven2d9187b2017-02-28 13:40:07 +01002120 qemu_co_mutex_init(&s->lock);
2121 for (i = 0; i < s->num_coroutines; i++) {
2122 s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
2123 s->wait_sector_num[i] = -1;
2124 qemu_coroutine_enter(s->co[i]);
Kevin Wolf690c7302015-03-19 13:33:32 +01002125 }
2126
Anton Nefedovb91127e2017-04-26 11:33:15 +03002127 while (s->running_coroutines) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002128 main_loop_wait(false);
2129 }
2130
2131 if (s->compressed && !s->ret) {
Kevin Wolf690c7302015-03-19 13:33:32 +01002132 /* signal EOF to align */
Pavel Butsykinfe5c1352016-07-22 11:17:40 +03002133 ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
Kevin Wolf690c7302015-03-19 13:33:32 +01002134 if (ret < 0) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002135 return ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002136 }
2137 }
2138
Peter Lieven2d9187b2017-02-28 13:40:07 +01002139 return s->ret;
Kevin Wolf690c7302015-03-19 13:33:32 +01002140}
2141
Peter Lieven6360ab22018-07-13 09:15:39 +02002142#define MAX_BUF_SECTORS 32768
2143
bellardea2384d2004-08-01 21:59:26 +00002144static int img_convert(int argc, char **argv)
2145{
Peter Lieven9fd77f92017-04-21 11:11:55 +02002146 int c, bs_i, flags, src_flags = 0;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002147 const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002148 *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
2149 *out_filename, *out_baseimg_param, *snapshot_name = NULL;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002150 BlockDriver *drv = NULL, *proto_drv = NULL;
bellardfaea38e2006-08-05 21:31:00 +00002151 BlockDriverInfo bdi;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002152 BlockDriverState *out_bs;
2153 QemuOpts *opts = NULL, *sn_opts = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08002154 QemuOptsList *create_opts = NULL;
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002155 QDict *open_opts = NULL;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002156 char *options = NULL;
Max Reitzcc84d902013-09-06 17:14:26 +02002157 Error *local_err = NULL;
Max Reitz3d96cb92019-05-07 22:35:02 +02002158 bool writethrough, src_writethrough, image_opts = false,
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002159 skip_create = false, progress = false, tgt_image_opts = false;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002160 int64_t ret = -EINVAL;
Fam Zheng335e9932017-05-03 00:35:39 +08002161 bool force_share = false;
Fam Zhenge11ce122018-07-27 11:34:01 +08002162 bool explict_min_sparse = false;
bellardea2384d2004-08-01 21:59:26 +00002163
Peter Lieven9fd77f92017-04-21 11:11:55 +02002164 ImgConvertState s = (ImgConvertState) {
2165 /* Need at least 4k of zeros for sparse detection */
2166 .min_sparse = 8,
Fam Zhenge11ce122018-07-27 11:34:01 +08002167 .copy_range = false,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002168 .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
2169 .wr_in_order = true,
2170 .num_coroutines = 8,
2171 };
2172
bellardea2384d2004-08-01 21:59:26 +00002173 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002174 static const struct option long_options[] = {
2175 {"help", no_argument, 0, 'h'},
2176 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002177 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002178 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002179 {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
Max Reitz8eaac022019-05-07 22:35:03 +02002180 {"salvage", no_argument, 0, OPTION_SALVAGE},
David Edmondson168468f2020-02-05 11:02:48 +00002181 {"target-is-zero", no_argument, 0, OPTION_TARGET_IS_ZERO},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002182 {0, 0, 0, 0}
2183 };
Fam Zhenge11ce122018-07-27 11:34:01 +08002184 c = getopt_long(argc, argv, ":hf:O:B:Cco:l:S:pt:T:qnm:WU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002185 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002186 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002187 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002188 }
bellardea2384d2004-08-01 21:59:26 +00002189 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002190 case ':':
2191 missing_argument(argv[optind - 1]);
2192 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002193 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002194 unrecognized_option(argv[optind - 1]);
2195 break;
bellardea2384d2004-08-01 21:59:26 +00002196 case 'h':
2197 help();
2198 break;
2199 case 'f':
2200 fmt = optarg;
2201 break;
2202 case 'O':
2203 out_fmt = optarg;
2204 break;
thsf58c7b32008-06-05 21:53:49 +00002205 case 'B':
2206 out_baseimg = optarg;
2207 break;
Fam Zhenge11ce122018-07-27 11:34:01 +08002208 case 'C':
2209 s.copy_range = true;
2210 break;
bellardea2384d2004-08-01 21:59:26 +00002211 case 'c':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002212 s.compressed = true;
bellardea2384d2004-08-01 21:59:26 +00002213 break;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002214 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02002215 if (accumulate_options(&options, optarg) < 0) {
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002216 goto fail_getopt;
Kevin Wolf2dc83282014-02-21 16:24:05 +01002217 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002218 break;
Wenchao Xiaef806542013-12-04 17:10:57 +08002219 case 'l':
2220 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +01002221 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
2222 optarg, false);
Wenchao Xiaef806542013-12-04 17:10:57 +08002223 if (!sn_opts) {
2224 error_report("Failed in parsing snapshot param '%s'",
2225 optarg);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002226 goto fail_getopt;
Wenchao Xiaef806542013-12-04 17:10:57 +08002227 }
2228 } else {
2229 snapshot_name = optarg;
2230 }
2231 break;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002232 case 'S':
2233 {
2234 int64_t sval;
Markus Armbruster606caa02017-02-21 21:14:04 +01002235
Eyal Moscovici43d589b2020-05-13 16:36:26 +03002236 sval = cvtnum("buffer size for sparse output", optarg);
2237 if (sval < 0) {
2238 goto fail_getopt;
2239 } else if (!QEMU_IS_ALIGNED(sval, BDRV_SECTOR_SIZE) ||
Peter Lieven6360ab22018-07-13 09:15:39 +02002240 sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
2241 error_report("Invalid buffer size for sparse output specified. "
2242 "Valid sizes are multiples of %llu up to %llu. Select "
2243 "0 to disable sparse detection (fully allocates output).",
2244 BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002245 goto fail_getopt;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002246 }
2247
Peter Lieven9fd77f92017-04-21 11:11:55 +02002248 s.min_sparse = sval / BDRV_SECTOR_SIZE;
Fam Zhenge11ce122018-07-27 11:34:01 +08002249 explict_min_sparse = true;
Kevin Wolfa22f1232011-08-26 15:27:13 +02002250 break;
2251 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002252 case 'p':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002253 progress = true;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002254 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002255 case 't':
2256 cache = optarg;
2257 break;
Max Reitz40055952014-07-22 22:58:42 +02002258 case 'T':
2259 src_cache = optarg;
2260 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002261 case 'q':
Max Reitz3d96cb92019-05-07 22:35:02 +02002262 s.quiet = true;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002263 break;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002264 case 'n':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002265 skip_create = true;
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002266 break;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002267 case 'm':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002268 if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
2269 s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
Peter Lieven2d9187b2017-02-28 13:40:07 +01002270 error_report("Invalid number of coroutines. Allowed number of"
2271 " coroutines is between 1 and %d", MAX_COROUTINES);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002272 goto fail_getopt;
2273 }
2274 break;
2275 case 'W':
Peter Lieven9fd77f92017-04-21 11:11:55 +02002276 s.wr_in_order = false;
Peter Lieven2d9187b2017-02-28 13:40:07 +01002277 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002278 case 'U':
2279 force_share = true;
2280 break;
Max Reitz3258b912017-04-26 15:46:47 +02002281 case OPTION_OBJECT: {
2282 QemuOpts *object_opts;
2283 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
2284 optarg, true);
2285 if (!object_opts) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002286 goto fail_getopt;
2287 }
2288 break;
Max Reitz3258b912017-04-26 15:46:47 +02002289 }
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002290 case OPTION_IMAGE_OPTS:
2291 image_opts = true;
2292 break;
Max Reitz8eaac022019-05-07 22:35:03 +02002293 case OPTION_SALVAGE:
2294 s.salvage = true;
2295 break;
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002296 case OPTION_TARGET_IMAGE_OPTS:
2297 tgt_image_opts = true;
2298 break;
David Edmondson168468f2020-02-05 11:02:48 +00002299 case OPTION_TARGET_IS_ZERO:
2300 /*
2301 * The user asserting that the target is blank has the
2302 * same effect as the target driver supporting zero
2303 * initialisation.
2304 */
2305 s.has_zero_init = true;
2306 break;
bellardea2384d2004-08-01 21:59:26 +00002307 }
2308 }
ths3b46e622007-09-17 08:09:54 +00002309
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002310 if (!out_fmt && !tgt_image_opts) {
2311 out_fmt = "raw";
2312 }
2313
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002314 if (qemu_opts_foreach(&qemu_object_opts,
2315 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002316 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002317 goto fail_getopt;
2318 }
2319
Fam Zhenge11ce122018-07-27 11:34:01 +08002320 if (s.compressed && s.copy_range) {
2321 error_report("Cannot enable copy offloading when -c is used");
2322 goto fail_getopt;
2323 }
2324
2325 if (explict_min_sparse && s.copy_range) {
2326 error_report("Cannot enable copy offloading when -S is used");
2327 goto fail_getopt;
2328 }
2329
Max Reitz8eaac022019-05-07 22:35:03 +02002330 if (s.copy_range && s.salvage) {
2331 error_report("Cannot use copy offloading in salvaging mode");
2332 goto fail_getopt;
2333 }
2334
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002335 if (tgt_image_opts && !skip_create) {
2336 error_report("--target-image-opts requires use of -n flag");
2337 goto fail_getopt;
2338 }
2339
Kevin Wolfffd8e8f2019-08-09 11:09:21 +02002340 if (skip_create && options) {
2341 warn_report("-o has no effect when skipping image creation");
2342 warn_report("This will become an error in future QEMU versions.");
2343 }
2344
David Edmondson168468f2020-02-05 11:02:48 +00002345 if (s.has_zero_init && !skip_create) {
2346 error_report("--target-is-zero requires use of -n flag");
2347 goto fail_getopt;
2348 }
2349
Peter Lieven9fd77f92017-04-21 11:11:55 +02002350 s.src_num = argc - optind - 1;
2351 out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
2352
2353 if (options && has_help_option(options)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002354 if (out_fmt) {
2355 ret = print_block_option_help(out_filename, out_fmt);
2356 goto fail_getopt;
2357 } else {
2358 error_report("Option help requires a format be specified");
2359 goto fail_getopt;
2360 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002361 }
2362
2363 if (s.src_num < 1) {
2364 error_report("Must specify image file name");
2365 goto fail_getopt;
2366 }
2367
2368
Peter Lieven9fd77f92017-04-21 11:11:55 +02002369 /* ret is still -EINVAL until here */
2370 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
2371 if (ret < 0) {
2372 error_report("Invalid source cache option: %s", src_cache);
Peter Lieven2d9187b2017-02-28 13:40:07 +01002373 goto fail_getopt;
2374 }
2375
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002376 /* Initialize before goto out */
Max Reitz3d96cb92019-05-07 22:35:02 +02002377 if (s.quiet) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002378 progress = false;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01002379 }
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002380 qemu_progress_init(progress, 1.0);
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002381 qemu_progress_print(0, 100);
2382
Peter Lieven9fd77f92017-04-21 11:11:55 +02002383 s.src = g_new0(BlockBackend *, s.src_num);
2384 s.src_sectors = g_new(int64_t, s.src_num);
balrog926c2d22007-10-31 01:11:44 +00002385
Peter Lieven9fd77f92017-04-21 11:11:55 +02002386 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2387 s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
Max Reitz3d96cb92019-05-07 22:35:02 +02002388 fmt, src_flags, src_writethrough, s.quiet,
Fam Zheng335e9932017-05-03 00:35:39 +08002389 force_share);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002390 if (!s.src[bs_i]) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002391 ret = -1;
2392 goto out;
2393 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002394 s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
2395 if (s.src_sectors[bs_i] < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002396 error_report("Could not get size of %s: %s",
Peter Lieven9fd77f92017-04-21 11:11:55 +02002397 argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02002398 ret = -1;
2399 goto out;
2400 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002401 s.total_sectors += s.src_sectors[bs_i];
balrog926c2d22007-10-31 01:11:44 +00002402 }
bellardea2384d2004-08-01 21:59:26 +00002403
Wenchao Xiaef806542013-12-04 17:10:57 +08002404 if (sn_opts) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002405 bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
Peter Maydell10d6eda2017-02-10 16:28:24 +00002406 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
2407 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
2408 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002409 } else if (snapshot_name != NULL) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002410 if (s.src_num > 1) {
Markus Armbruster6daf1942011-06-22 14:03:54 +02002411 error_report("No support for concatenating multiple snapshot");
edison51ef6722010-09-21 19:58:41 -07002412 ret = -1;
2413 goto out;
2414 }
Wenchao Xia7b4c4782013-12-04 17:10:54 +08002415
Peter Lieven9fd77f92017-04-21 11:11:55 +02002416 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
2417 &local_err);
Wenchao Xiaef806542013-12-04 17:10:57 +08002418 }
Markus Armbruster84d18f02014-01-30 15:07:28 +01002419 if (local_err) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002420 error_reportf_err(local_err, "Failed to load snapshot: ");
Wenchao Xiaef806542013-12-04 17:10:57 +08002421 ret = -1;
2422 goto out;
edison51ef6722010-09-21 19:58:41 -07002423 }
2424
Max Reitz2e024cd2015-02-11 09:58:46 -05002425 if (!skip_create) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002426 /* Find driver and parse its options */
2427 drv = bdrv_find_format(out_fmt);
2428 if (!drv) {
2429 error_report("Unknown file format '%s'", out_fmt);
2430 ret = -1;
2431 goto out;
2432 }
2433
2434 proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
2435 if (!proto_drv) {
2436 error_report_err(local_err);
2437 ret = -1;
2438 goto out;
2439 }
2440
Max Reitz2e024cd2015-02-11 09:58:46 -05002441 if (!drv->create_opts) {
2442 error_report("Format driver '%s' does not support image creation",
2443 drv->format_name);
2444 ret = -1;
2445 goto out;
2446 }
Max Reitzf75613c2014-12-02 18:32:46 +01002447
Max Reitz2e024cd2015-02-11 09:58:46 -05002448 if (!proto_drv->create_opts) {
2449 error_report("Protocol driver '%s' does not support image creation",
2450 proto_drv->format_name);
2451 ret = -1;
2452 goto out;
2453 }
Max Reitzf75613c2014-12-02 18:32:46 +01002454
Max Reitz2e024cd2015-02-11 09:58:46 -05002455 create_opts = qemu_opts_append(create_opts, drv->create_opts);
2456 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Kevin Wolfdb08adf2009-06-04 15:39:38 +02002457
Max Reitz2e024cd2015-02-11 09:58:46 -05002458 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002459 if (options) {
2460 qemu_opts_do_parse(opts, options, NULL, &local_err);
2461 if (local_err) {
Markus Armbruster97a2ca72015-03-14 10:23:15 +01002462 error_report_err(local_err);
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01002463 ret = -1;
2464 goto out;
2465 }
Max Reitz2e024cd2015-02-11 09:58:46 -05002466 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002467
Peter Lieven9fd77f92017-04-21 11:11:55 +02002468 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
Markus Armbruster39101f22015-02-12 16:46:36 +01002469 &error_abort);
Max Reitz2e024cd2015-02-11 09:58:46 -05002470 ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
2471 if (ret < 0) {
2472 goto out;
2473 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002474 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002475
Kevin Wolfa18953f2010-10-14 15:46:04 +02002476 /* Get backing file name if -o backing_file was used */
Chunyan Liu83d05212014-06-05 17:20:51 +08002477 out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
Kevin Wolfa18953f2010-10-14 15:46:04 +02002478 if (out_baseimg_param) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002479 out_baseimg = out_baseimg_param;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002480 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002481 s.target_has_backing = (bool) out_baseimg;
Kevin Wolfa18953f2010-10-14 15:46:04 +02002482
David Edmondson168468f2020-02-05 11:02:48 +00002483 if (s.has_zero_init && s.target_has_backing) {
2484 error_report("Cannot use --target-is-zero when the destination "
2485 "image has a backing file");
2486 goto out;
2487 }
2488
Max Reitz48758a82017-04-26 15:46:48 +02002489 if (s.src_num > 1 && out_baseimg) {
2490 error_report("Having a backing file for the target makes no sense when "
2491 "concatenating multiple input images");
2492 ret = -1;
2493 goto out;
2494 }
2495
Kevin Wolfefa84d42009-05-18 16:42:12 +02002496 /* Check if compression is supported */
Peter Lieven9fd77f92017-04-21 11:11:55 +02002497 if (s.compressed) {
Chunyan Liu83d05212014-06-05 17:20:51 +08002498 bool encryption =
2499 qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002500 const char *encryptfmt =
2501 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
Chunyan Liu83d05212014-06-05 17:20:51 +08002502 const char *preallocation =
2503 qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
Kevin Wolfefa84d42009-05-18 16:42:12 +02002504
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002505 if (drv && !block_driver_can_compress(drv)) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002506 error_report("Compression not supported for this file format");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002507 ret = -1;
2508 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002509 }
2510
Daniel P. Berrange0cb8d472017-06-23 17:24:06 +01002511 if (encryption || encryptfmt) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002512 error_report("Compression and encryption not supported at "
2513 "the same time");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002514 ret = -1;
2515 goto out;
Kevin Wolfefa84d42009-05-18 16:42:12 +02002516 }
Kevin Wolf41521fa2011-10-18 16:19:42 +02002517
Chunyan Liu83d05212014-06-05 17:20:51 +08002518 if (preallocation
2519 && strcmp(preallocation, "off"))
Kevin Wolf41521fa2011-10-18 16:19:42 +02002520 {
2521 error_report("Compression and preallocation not supported at "
2522 "the same time");
2523 ret = -1;
2524 goto out;
2525 }
Kevin Wolfefa84d42009-05-18 16:42:12 +02002526 }
2527
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002528 /*
2529 * The later open call will need any decryption secrets, and
2530 * bdrv_create() will purge "opts", so extract them now before
2531 * they are lost.
2532 */
2533 if (!skip_create) {
2534 open_opts = qdict_new();
2535 qemu_opt_foreach(opts, img_add_key_secrets, open_opts, &error_abort);
2536 }
2537
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002538 if (!skip_create) {
2539 /* Create the new image */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002540 ret = bdrv_create(drv, out_filename, opts, &local_err);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002541 if (ret < 0) {
Markus Armbrusterc29b77f2015-12-18 16:35:14 +01002542 error_reportf_err(local_err, "%s: error while converting %s: ",
2543 out_filename, out_fmt);
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002544 goto out;
bellardea2384d2004-08-01 21:59:26 +00002545 }
2546 }
ths3b46e622007-09-17 08:09:54 +00002547
Max Reitz4d7c4872019-07-24 19:12:29 +02002548 s.target_is_new = !skip_create;
2549
Peter Lieven9fd77f92017-04-21 11:11:55 +02002550 flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
Kevin Wolfce099542016-03-15 13:01:04 +01002551 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002552 if (ret < 0) {
2553 error_report("Invalid cache option: %s", cache);
Markus Armbrusterbb9cd2e2014-05-28 11:17:07 +02002554 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04002555 }
2556
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002557 if (skip_create) {
2558 s.target = img_open(tgt_image_opts, out_filename, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002559 flags, writethrough, s.quiet, false);
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002560 } else {
2561 /* TODO ultimately we should allow --target-image-opts
2562 * to be used even when -n is not given.
2563 * That has to wait for bdrv_create to be improved
2564 * to allow filenames in option syntax
2565 */
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002566 s.target = img_open_file(out_filename, open_opts, out_fmt,
Max Reitz3d96cb92019-05-07 22:35:02 +02002567 flags, writethrough, s.quiet, false);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002568 open_opts = NULL; /* blk_new_open will have freed it */
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002569 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002570 if (!s.target) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002571 ret = -1;
2572 goto out;
2573 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002574 out_bs = blk_bs(s.target);
bellardea2384d2004-08-01 21:59:26 +00002575
Vladimir Sementsov-Ogievskiyac850bf2019-06-04 19:15:06 +03002576 if (s.compressed && !block_driver_can_compress(out_bs->drv)) {
Daniel P. Berrange305b4c62017-05-15 17:47:11 +01002577 error_report("Compression not supported for this file format");
2578 ret = -1;
2579 goto out;
2580 }
2581
Eric Blake5def6b82016-06-23 16:37:19 -06002582 /* increase bufsectors from the default 4096 (2M) if opt_transfer
Peter Lieven6360ab22018-07-13 09:15:39 +02002583 * or discard_alignment of the out_bs is greater. Limit to
2584 * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
2585 s.buf_sectors = MIN(MAX_BUF_SECTORS,
Peter Lieven9fd77f92017-04-21 11:11:55 +02002586 MAX(s.buf_sectors,
2587 MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
2588 out_bs->bl.pdiscard_alignment >>
2589 BDRV_SECTOR_BITS)));
Peter Lievenf2521c92013-11-27 11:07:06 +01002590
Peter Lieven8dcd3c92018-07-12 15:00:10 +02002591 /* try to align the write requests to the destination to avoid unnecessary
2592 * RMW cycles. */
2593 s.alignment = MAX(pow2floor(s.min_sparse),
2594 DIV_ROUND_UP(out_bs->bl.request_alignment,
2595 BDRV_SECTOR_SIZE));
2596 assert(is_power_of_2(s.alignment));
2597
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002598 if (skip_create) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002599 int64_t output_sectors = blk_nb_sectors(s.target);
Markus Armbruster43716fa2014-06-26 13:23:21 +02002600 if (output_sectors < 0) {
Gongleieec5eb42015-02-25 12:22:27 +08002601 error_report("unable to get output image length: %s",
Markus Armbruster43716fa2014-06-26 13:23:21 +02002602 strerror(-output_sectors));
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002603 ret = -1;
2604 goto out;
Peter Lieven9fd77f92017-04-21 11:11:55 +02002605 } else if (output_sectors < s.total_sectors) {
Alexandre Derumierb2e10492013-09-02 19:07:24 +01002606 error_report("output file is smaller than input file");
2607 ret = -1;
2608 goto out;
2609 }
2610 }
2611
Max Reitzc69291e2020-01-21 16:59:14 +01002612 if (s.target_has_backing && s.target_is_new) {
Max Reitz351c8ef2018-05-01 18:57:49 +02002613 /* Errors are treated as "backing length unknown" (which means
2614 * s.target_backing_sectors has to be negative, which it will
2615 * be automatically). The backing file length is used only
2616 * for optimizations, so such a case is not fatal. */
2617 s.target_backing_sectors = bdrv_nb_sectors(out_bs->backing->bs);
2618 } else {
2619 s.target_backing_sectors = -1;
2620 }
2621
Peter Lieven24f833c2013-11-27 11:07:07 +01002622 ret = bdrv_get_info(out_bs, &bdi);
2623 if (ret < 0) {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002624 if (s.compressed) {
Jes Sorensen15654a62010-12-16 14:31:53 +01002625 error_report("could not get block driver info");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002626 goto out;
2627 }
Peter Lieven24f833c2013-11-27 11:07:07 +01002628 } else {
Peter Lieven9fd77f92017-04-21 11:11:55 +02002629 s.compressed = s.compressed || bdi.needs_compressed_writes;
2630 s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
Max Reitz351c8ef2018-05-01 18:57:49 +02002631 s.unallocated_blocks_are_zero = bdi.unallocated_blocks_are_zero;
Peter Lieven24f833c2013-11-27 11:07:07 +01002632 }
2633
Peter Lieven9fd77f92017-04-21 11:11:55 +02002634 ret = convert_do_copy(&s);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002635out:
Peter Lieven13c28af2013-11-27 11:07:01 +01002636 if (!ret) {
2637 qemu_progress_print(100, 0);
2638 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02002639 qemu_progress_end();
Chunyan Liu83d05212014-06-05 17:20:51 +08002640 qemu_opts_del(opts);
2641 qemu_opts_free(create_opts);
Markus Armbrusterfbf28a42014-09-29 16:07:55 +02002642 qemu_opts_del(sn_opts);
Daniel P. Berrangé8d65a3c2018-08-14 13:39:47 +01002643 qobject_unref(open_opts);
Peter Lieven9fd77f92017-04-21 11:11:55 +02002644 blk_unref(s.target);
2645 if (s.src) {
2646 for (bs_i = 0; bs_i < s.src_num; bs_i++) {
2647 blk_unref(s.src[bs_i]);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002648 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002649 g_free(s.src);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002650 }
Peter Lieven9fd77f92017-04-21 11:11:55 +02002651 g_free(s.src_sectors);
Kevin Wolf64bb01a2014-03-03 14:54:07 +01002652fail_getopt:
2653 g_free(options);
2654
Peter Lieven9fd77f92017-04-21 11:11:55 +02002655 return !!ret;
bellardea2384d2004-08-01 21:59:26 +00002656}
2657
bellard57d1a2b2004-08-03 21:15:11 +00002658
bellardfaea38e2006-08-05 21:31:00 +00002659static void dump_snapshots(BlockDriverState *bs)
2660{
2661 QEMUSnapshotInfo *sn_tab, *sn;
2662 int nb_sns, i;
bellardfaea38e2006-08-05 21:31:00 +00002663
2664 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2665 if (nb_sns <= 0)
2666 return;
2667 printf("Snapshot list:\n");
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002668 bdrv_snapshot_dump(NULL);
Wenchao Xia5b917042013-05-25 11:09:45 +08002669 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002670 for(i = 0; i < nb_sns; i++) {
2671 sn = &sn_tab[i];
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002672 bdrv_snapshot_dump(sn);
Wenchao Xia5b917042013-05-25 11:09:45 +08002673 printf("\n");
bellardfaea38e2006-08-05 21:31:00 +00002674 }
Anthony Liguori7267c092011-08-20 22:09:37 -05002675 g_free(sn_tab);
bellardfaea38e2006-08-05 21:31:00 +00002676}
2677
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002678static void dump_json_image_info_list(ImageInfoList *list)
2679{
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002680 QString *str;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002681 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002682 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002683
2684 visit_type_ImageInfoList(v, NULL, &list, &error_abort);
2685 visit_complete(v, &obj);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002686 str = qobject_to_json_pretty(obj);
2687 assert(str != NULL);
2688 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002689 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002690 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002691 qobject_unref(str);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002692}
2693
Benoît Canetc054b3f2012-09-05 13:09:02 +02002694static void dump_json_image_info(ImageInfo *info)
2695{
Benoît Canetc054b3f2012-09-05 13:09:02 +02002696 QString *str;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002697 QObject *obj;
Daniel P. Berrange7d5e1992016-09-30 15:45:28 +01002698 Visitor *v = qobject_output_visitor_new(&obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002699
2700 visit_type_ImageInfo(v, NULL, &info, &error_abort);
2701 visit_complete(v, &obj);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002702 str = qobject_to_json_pretty(obj);
2703 assert(str != NULL);
2704 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002705 qobject_unref(obj);
Eric Blake3b098d52016-06-09 10:48:43 -06002706 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002707 qobject_unref(str);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002708}
2709
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002710static void dump_human_image_info_list(ImageInfoList *list)
2711{
2712 ImageInfoList *elem;
2713 bool delim = false;
2714
2715 for (elem = list; elem; elem = elem->next) {
2716 if (delim) {
2717 printf("\n");
2718 }
2719 delim = true;
2720
Markus Armbrustere1ce7d72019-04-17 21:17:55 +02002721 bdrv_image_info_dump(elem->value);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002722 }
2723}
2724
2725static gboolean str_equal_func(gconstpointer a, gconstpointer b)
2726{
2727 return strcmp(a, b) == 0;
2728}
2729
2730/**
2731 * Open an image file chain and return an ImageInfoList
2732 *
2733 * @filename: topmost image filename
2734 * @fmt: topmost image format (may be NULL to autodetect)
2735 * @chain: true - enumerate entire backing file chain
2736 * false - only topmost image file
2737 *
2738 * Returns a list of ImageInfo objects or NULL if there was an error opening an
2739 * image file. If there was an error a message will have been printed to
2740 * stderr.
2741 */
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002742static ImageInfoList *collect_image_info_list(bool image_opts,
2743 const char *filename,
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002744 const char *fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002745 bool chain, bool force_share)
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002746{
2747 ImageInfoList *head = NULL;
2748 ImageInfoList **last = &head;
2749 GHashTable *filenames;
Wenchao Xia43526ec2013-06-06 12:27:58 +08002750 Error *err = NULL;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002751
2752 filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
2753
2754 while (filename) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02002755 BlockBackend *blk;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002756 BlockDriverState *bs;
2757 ImageInfo *info;
2758 ImageInfoList *elem;
2759
2760 if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
2761 error_report("Backing file '%s' creates an infinite loop.",
2762 filename);
2763 goto err;
2764 }
2765 g_hash_table_insert(filenames, (gpointer)filename, NULL);
2766
Max Reitzefaa7c42016-03-16 19:54:38 +01002767 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08002768 BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
2769 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002770 if (!blk) {
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002771 goto err;
2772 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02002773 bs = blk_bs(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002774
Wenchao Xia43526ec2013-06-06 12:27:58 +08002775 bdrv_query_image_info(bs, &info, &err);
Markus Armbruster84d18f02014-01-30 15:07:28 +01002776 if (err) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01002777 error_report_err(err);
Markus Armbruster26f54e92014-10-07 13:59:04 +02002778 blk_unref(blk);
Wenchao Xia43526ec2013-06-06 12:27:58 +08002779 goto err;
Wenchao Xiafb0ed452013-06-06 12:27:57 +08002780 }
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002781
2782 elem = g_new0(ImageInfoList, 1);
2783 elem->value = info;
2784 *last = elem;
2785 last = &elem->next;
2786
Markus Armbruster26f54e92014-10-07 13:59:04 +02002787 blk_unref(blk);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002788
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002789 /* Clear parameters that only apply to the topmost image */
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002790 filename = fmt = NULL;
Stefan Hajnoczi0da7d132019-12-05 13:46:46 +00002791 image_opts = false;
2792
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002793 if (chain) {
2794 if (info->has_full_backing_filename) {
2795 filename = info->full_backing_filename;
2796 } else if (info->has_backing_filename) {
John Snow92d617a2015-12-14 14:55:15 -05002797 error_report("Could not determine absolute backing filename,"
2798 " but backing filename '%s' present",
2799 info->backing_filename);
2800 goto err;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002801 }
2802 if (info->has_backing_filename_format) {
2803 fmt = info->backing_filename_format;
2804 }
2805 }
2806 }
2807 g_hash_table_destroy(filenames);
2808 return head;
2809
2810err:
2811 qapi_free_ImageInfoList(head);
2812 g_hash_table_destroy(filenames);
2813 return NULL;
2814}
2815
Benoît Canetc054b3f2012-09-05 13:09:02 +02002816static int img_info(int argc, char **argv)
2817{
2818 int c;
2819 OutputFormat output_format = OFORMAT_HUMAN;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002820 bool chain = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002821 const char *filename, *fmt, *output;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002822 ImageInfoList *list;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002823 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08002824 bool force_share = false;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002825
bellardea2384d2004-08-01 21:59:26 +00002826 fmt = NULL;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002827 output = NULL;
bellardea2384d2004-08-01 21:59:26 +00002828 for(;;) {
Benoît Canetc054b3f2012-09-05 13:09:02 +02002829 int option_index = 0;
2830 static const struct option long_options[] = {
2831 {"help", no_argument, 0, 'h'},
2832 {"format", required_argument, 0, 'f'},
2833 {"output", required_argument, 0, OPTION_OUTPUT},
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002834 {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002835 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002836 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08002837 {"force-share", no_argument, 0, 'U'},
Benoît Canetc054b3f2012-09-05 13:09:02 +02002838 {0, 0, 0, 0}
2839 };
Fam Zheng335e9932017-05-03 00:35:39 +08002840 c = getopt_long(argc, argv, ":f:hU",
Benoît Canetc054b3f2012-09-05 13:09:02 +02002841 long_options, &option_index);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002842 if (c == -1) {
bellardea2384d2004-08-01 21:59:26 +00002843 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002844 }
bellardea2384d2004-08-01 21:59:26 +00002845 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002846 case ':':
2847 missing_argument(argv[optind - 1]);
2848 break;
Jes Sorensenef873942010-12-06 15:25:40 +01002849 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08002850 unrecognized_option(argv[optind - 1]);
2851 break;
bellardea2384d2004-08-01 21:59:26 +00002852 case 'h':
2853 help();
2854 break;
2855 case 'f':
2856 fmt = optarg;
2857 break;
Fam Zheng335e9932017-05-03 00:35:39 +08002858 case 'U':
2859 force_share = true;
2860 break;
Benoît Canetc054b3f2012-09-05 13:09:02 +02002861 case OPTION_OUTPUT:
2862 output = optarg;
2863 break;
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002864 case OPTION_BACKING_CHAIN:
2865 chain = true;
2866 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002867 case OPTION_OBJECT: {
2868 QemuOpts *opts;
2869 opts = qemu_opts_parse_noisily(&qemu_object_opts,
2870 optarg, true);
2871 if (!opts) {
2872 return 1;
2873 }
2874 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00002875 case OPTION_IMAGE_OPTS:
2876 image_opts = true;
2877 break;
bellardea2384d2004-08-01 21:59:26 +00002878 }
2879 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02002880 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08002881 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002882 }
bellardea2384d2004-08-01 21:59:26 +00002883 filename = argv[optind++];
2884
Benoît Canetc054b3f2012-09-05 13:09:02 +02002885 if (output && !strcmp(output, "json")) {
2886 output_format = OFORMAT_JSON;
2887 } else if (output && !strcmp(output, "human")) {
2888 output_format = OFORMAT_HUMAN;
2889 } else if (output) {
2890 error_report("--output must be used with human or json as argument.");
2891 return 1;
2892 }
2893
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002894 if (qemu_opts_foreach(&qemu_object_opts,
2895 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02002896 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00002897 return 1;
2898 }
2899
Fam Zheng335e9932017-05-03 00:35:39 +08002900 list = collect_image_info_list(image_opts, filename, fmt, chain,
2901 force_share);
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002902 if (!list) {
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09002903 return 1;
2904 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002905
Benoît Canetc054b3f2012-09-05 13:09:02 +02002906 switch (output_format) {
2907 case OFORMAT_HUMAN:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002908 dump_human_image_info_list(list);
Benoît Canetc054b3f2012-09-05 13:09:02 +02002909 break;
2910 case OFORMAT_JSON:
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002911 if (chain) {
2912 dump_json_image_info_list(list);
2913 } else {
2914 dump_json_image_info(list->value);
2915 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002916 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01002917 }
Benoît Canetc054b3f2012-09-05 13:09:02 +02002918
Stefan Hajnoczi9699bf02012-10-17 14:02:31 +02002919 qapi_free_ImageInfoList(list);
bellardea2384d2004-08-01 21:59:26 +00002920 return 0;
2921}
2922
Eric Blake30065d12019-03-26 13:40:43 -05002923static int dump_map_entry(OutputFormat output_format, MapEntry *e,
2924 MapEntry *next)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002925{
2926 switch (output_format) {
2927 case OFORMAT_HUMAN:
Fam Zheng16b0d552016-01-26 11:59:02 +08002928 if (e->data && !e->has_offset) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002929 error_report("File contains external, encrypted or compressed clusters.");
Eric Blake30065d12019-03-26 13:40:43 -05002930 return -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002931 }
Fam Zheng16b0d552016-01-26 11:59:02 +08002932 if (e->data && !e->zero) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002933 printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
Fam Zheng16b0d552016-01-26 11:59:02 +08002934 e->start, e->length,
2935 e->has_offset ? e->offset : 0,
2936 e->has_filename ? e->filename : "");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002937 }
2938 /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
2939 * Modify the flags here to allow more coalescing.
2940 */
Fam Zheng16b0d552016-01-26 11:59:02 +08002941 if (next && (!next->data || next->zero)) {
2942 next->data = false;
2943 next->zero = true;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002944 }
2945 break;
2946 case OFORMAT_JSON:
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03002947 printf("{ \"start\": %"PRId64", \"length\": %"PRId64","
Fam Zheng16b0d552016-01-26 11:59:02 +08002948 " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002949 e->start, e->length, e->depth,
Fam Zheng16b0d552016-01-26 11:59:02 +08002950 e->zero ? "true" : "false",
2951 e->data ? "true" : "false");
2952 if (e->has_offset) {
Paolo Bonzinic745bfb2013-09-11 18:47:52 +02002953 printf(", \"offset\": %"PRId64"", e->offset);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002954 }
2955 putchar('}');
2956
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03002957 if (next) {
2958 puts(",");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002959 }
2960 break;
2961 }
Eric Blake30065d12019-03-26 13:40:43 -05002962 return 0;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002963}
2964
Eric Blake5e344dd2017-10-11 22:47:02 -05002965static int get_block_status(BlockDriverState *bs, int64_t offset,
2966 int64_t bytes, MapEntry *e)
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002967{
Eric Blake237d78f2017-10-11 22:47:03 -05002968 int ret;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002969 int depth;
Fam Zheng67a0fd22016-01-26 11:58:48 +08002970 BlockDriverState *file;
John Snow28756452016-02-05 13:12:33 -05002971 bool has_offset;
Eric Blake237d78f2017-10-11 22:47:03 -05002972 int64_t map;
Max Reitzf30c66b2019-02-01 20:29:05 +01002973 char *filename = NULL;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002974
2975 /* As an optimization, we could cache the current range of unallocated
2976 * clusters in each file of the chain, and avoid querying the same
2977 * range repeatedly.
2978 */
2979
2980 depth = 0;
2981 for (;;) {
Eric Blake237d78f2017-10-11 22:47:03 -05002982 ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002983 if (ret < 0) {
2984 return ret;
2985 }
Eric Blake237d78f2017-10-11 22:47:03 -05002986 assert(bytes);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002987 if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
2988 break;
2989 }
Kevin Wolf760e0062015-06-17 14:55:21 +02002990 bs = backing_bs(bs);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02002991 if (bs == NULL) {
2992 ret = 0;
2993 break;
2994 }
2995
2996 depth++;
2997 }
2998
John Snow28756452016-02-05 13:12:33 -05002999 has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
3000
Max Reitzf30c66b2019-02-01 20:29:05 +01003001 if (file && has_offset) {
3002 bdrv_refresh_filename(file);
3003 filename = file->filename;
3004 }
3005
John Snow28756452016-02-05 13:12:33 -05003006 *e = (MapEntry) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003007 .start = offset,
Eric Blake237d78f2017-10-11 22:47:03 -05003008 .length = bytes,
John Snow28756452016-02-05 13:12:33 -05003009 .data = !!(ret & BDRV_BLOCK_DATA),
3010 .zero = !!(ret & BDRV_BLOCK_ZERO),
Eric Blake237d78f2017-10-11 22:47:03 -05003011 .offset = map,
John Snow28756452016-02-05 13:12:33 -05003012 .has_offset = has_offset,
3013 .depth = depth,
Max Reitzf30c66b2019-02-01 20:29:05 +01003014 .has_filename = filename,
3015 .filename = filename,
John Snow28756452016-02-05 13:12:33 -05003016 };
3017
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003018 return 0;
3019}
3020
Fam Zheng16b0d552016-01-26 11:59:02 +08003021static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
3022{
3023 if (curr->length == 0) {
3024 return false;
3025 }
3026 if (curr->zero != next->zero ||
3027 curr->data != next->data ||
3028 curr->depth != next->depth ||
3029 curr->has_filename != next->has_filename ||
3030 curr->has_offset != next->has_offset) {
3031 return false;
3032 }
3033 if (curr->has_filename && strcmp(curr->filename, next->filename)) {
3034 return false;
3035 }
3036 if (curr->has_offset && curr->offset + curr->length != next->offset) {
3037 return false;
3038 }
3039 return true;
3040}
3041
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003042static int img_map(int argc, char **argv)
3043{
3044 int c;
3045 OutputFormat output_format = OFORMAT_HUMAN;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003046 BlockBackend *blk;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003047 BlockDriverState *bs;
3048 const char *filename, *fmt, *output;
3049 int64_t length;
3050 MapEntry curr = { .length = 0 }, next;
3051 int ret = 0;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003052 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003053 bool force_share = false;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003054 int64_t start_offset = 0;
3055 int64_t max_length = -1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003056
3057 fmt = NULL;
3058 output = NULL;
3059 for (;;) {
3060 int option_index = 0;
3061 static const struct option long_options[] = {
3062 {"help", no_argument, 0, 'h'},
3063 {"format", required_argument, 0, 'f'},
3064 {"output", required_argument, 0, OPTION_OUTPUT},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003065 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003066 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003067 {"force-share", no_argument, 0, 'U'},
Eyal Moscovicic0469492020-05-13 16:36:29 +03003068 {"start-offset", required_argument, 0, 's'},
3069 {"max-length", required_argument, 0, 'l'},
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003070 {0, 0, 0, 0}
3071 };
Eyal Moscovicic0469492020-05-13 16:36:29 +03003072 c = getopt_long(argc, argv, ":f:s:l:hU",
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003073 long_options, &option_index);
3074 if (c == -1) {
3075 break;
3076 }
3077 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003078 case ':':
3079 missing_argument(argv[optind - 1]);
3080 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003081 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003082 unrecognized_option(argv[optind - 1]);
3083 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003084 case 'h':
3085 help();
3086 break;
3087 case 'f':
3088 fmt = optarg;
3089 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003090 case 'U':
3091 force_share = true;
3092 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003093 case OPTION_OUTPUT:
3094 output = optarg;
3095 break;
Eyal Moscovicic0469492020-05-13 16:36:29 +03003096 case 's':
3097 start_offset = cvtnum("start offset", optarg);
3098 if (start_offset < 0) {
3099 return 1;
3100 }
3101 break;
3102 case 'l':
3103 max_length = cvtnum("max length", optarg);
3104 if (max_length < 0) {
3105 return 1;
3106 }
3107 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003108 case OPTION_OBJECT: {
3109 QemuOpts *opts;
3110 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3111 optarg, true);
3112 if (!opts) {
3113 return 1;
3114 }
3115 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003116 case OPTION_IMAGE_OPTS:
3117 image_opts = true;
3118 break;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003119 }
3120 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003121 if (optind != argc - 1) {
3122 error_exit("Expecting one image file name");
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003123 }
Fam Zhengac1307a2014-04-22 13:36:11 +08003124 filename = argv[optind];
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003125
3126 if (output && !strcmp(output, "json")) {
3127 output_format = OFORMAT_JSON;
3128 } else if (output && !strcmp(output, "human")) {
3129 output_format = OFORMAT_HUMAN;
3130 } else if (output) {
3131 error_report("--output must be used with human or json as argument.");
3132 return 1;
3133 }
3134
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003135 if (qemu_opts_foreach(&qemu_object_opts,
3136 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003137 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003138 return 1;
3139 }
3140
Fam Zheng335e9932017-05-03 00:35:39 +08003141 blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003142 if (!blk) {
3143 return 1;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003144 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003145 bs = blk_bs(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003146
3147 if (output_format == OFORMAT_HUMAN) {
3148 printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003149 } else if (output_format == OFORMAT_JSON) {
3150 putchar('[');
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003151 }
3152
Max Reitzf1d3cd72015-02-05 13:58:18 -05003153 length = blk_getlength(blk);
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003154 if (length < 0) {
3155 error_report("Failed to get size for '%s'", filename);
3156 return 1;
3157 }
Eyal Moscovicic0469492020-05-13 16:36:29 +03003158 if (max_length != -1) {
3159 length = MIN(start_offset + max_length, length);
3160 }
Eyal Moscovici8f282e82020-05-13 16:36:27 +03003161
Eyal Moscovicic0469492020-05-13 16:36:29 +03003162 curr.start = start_offset;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003163 while (curr.start + curr.length < length) {
Eric Blake5e344dd2017-10-11 22:47:02 -05003164 int64_t offset = curr.start + curr.length;
3165 int64_t n;
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003166
3167 /* Probe up to 1 GiB at a time. */
Stefano Garzarella97ede572019-05-08 12:43:24 +02003168 n = MIN(1 * GiB, length - offset);
Eric Blake5e344dd2017-10-11 22:47:02 -05003169 ret = get_block_status(bs, offset, n, &next);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003170
3171 if (ret < 0) {
3172 error_report("Could not read file metadata: %s", strerror(-ret));
3173 goto out;
3174 }
3175
Fam Zheng16b0d552016-01-26 11:59:02 +08003176 if (entry_mergeable(&curr, &next)) {
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003177 curr.length += next.length;
3178 continue;
3179 }
3180
3181 if (curr.length > 0) {
Eric Blake30065d12019-03-26 13:40:43 -05003182 ret = dump_map_entry(output_format, &curr, &next);
3183 if (ret < 0) {
3184 goto out;
3185 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003186 }
3187 curr = next;
3188 }
3189
Eric Blake30065d12019-03-26 13:40:43 -05003190 ret = dump_map_entry(output_format, &curr, NULL);
Eyal Moscovicie46c0b12020-05-13 16:36:28 +03003191 if (output_format == OFORMAT_JSON) {
3192 puts("]");
3193 }
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003194
3195out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003196 blk_unref(blk);
Paolo Bonzini4c93a13b2013-09-04 19:00:33 +02003197 return ret < 0;
3198}
3199
aliguorif7b4a942009-01-07 17:40:15 +00003200#define SNAPSHOT_LIST 1
3201#define SNAPSHOT_CREATE 2
3202#define SNAPSHOT_APPLY 3
3203#define SNAPSHOT_DELETE 4
3204
Stuart Brady153859b2009-06-07 00:42:17 +01003205static int img_snapshot(int argc, char **argv)
aliguorif7b4a942009-01-07 17:40:15 +00003206{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003207 BlockBackend *blk;
aliguorif7b4a942009-01-07 17:40:15 +00003208 BlockDriverState *bs;
3209 QEMUSnapshotInfo sn;
3210 char *filename, *snapshot_name = NULL;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003211 int c, ret = 0, bdrv_oflags;
aliguorif7b4a942009-01-07 17:40:15 +00003212 int action = 0;
3213 qemu_timeval tv;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003214 bool quiet = false;
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003215 Error *err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003216 bool image_opts = false;
Fam Zheng335e9932017-05-03 00:35:39 +08003217 bool force_share = false;
aliguorif7b4a942009-01-07 17:40:15 +00003218
Kevin Wolfce099542016-03-15 13:01:04 +01003219 bdrv_oflags = BDRV_O_RDWR;
aliguorif7b4a942009-01-07 17:40:15 +00003220 /* Parse commandline parameters */
3221 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003222 static const struct option long_options[] = {
3223 {"help", no_argument, 0, 'h'},
3224 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003225 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003226 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003227 {0, 0, 0, 0}
3228 };
Fam Zheng335e9932017-05-03 00:35:39 +08003229 c = getopt_long(argc, argv, ":la:c:d:hqU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003230 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003231 if (c == -1) {
aliguorif7b4a942009-01-07 17:40:15 +00003232 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003233 }
aliguorif7b4a942009-01-07 17:40:15 +00003234 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003235 case ':':
3236 missing_argument(argv[optind - 1]);
3237 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003238 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003239 unrecognized_option(argv[optind - 1]);
3240 break;
aliguorif7b4a942009-01-07 17:40:15 +00003241 case 'h':
3242 help();
Stuart Brady153859b2009-06-07 00:42:17 +01003243 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003244 case 'l':
3245 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003246 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003247 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003248 }
3249 action = SNAPSHOT_LIST;
Naphtali Spreif5edb012010-01-17 16:48:13 +02003250 bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
aliguorif7b4a942009-01-07 17:40:15 +00003251 break;
3252 case 'a':
3253 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003254 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003255 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003256 }
3257 action = SNAPSHOT_APPLY;
3258 snapshot_name = optarg;
3259 break;
3260 case 'c':
3261 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003262 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003263 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003264 }
3265 action = SNAPSHOT_CREATE;
3266 snapshot_name = optarg;
3267 break;
3268 case 'd':
3269 if (action) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003270 error_exit("Cannot mix '-l', '-a', '-c', '-d'");
Stuart Brady153859b2009-06-07 00:42:17 +01003271 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003272 }
3273 action = SNAPSHOT_DELETE;
3274 snapshot_name = optarg;
3275 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003276 case 'q':
3277 quiet = true;
3278 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003279 case 'U':
3280 force_share = true;
3281 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003282 case OPTION_OBJECT: {
3283 QemuOpts *opts;
3284 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3285 optarg, true);
3286 if (!opts) {
3287 return 1;
3288 }
3289 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003290 case OPTION_IMAGE_OPTS:
3291 image_opts = true;
3292 break;
aliguorif7b4a942009-01-07 17:40:15 +00003293 }
3294 }
3295
Kevin Wolffc11eb22013-08-05 10:53:04 +02003296 if (optind != argc - 1) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003297 error_exit("Expecting one image file name");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003298 }
aliguorif7b4a942009-01-07 17:40:15 +00003299 filename = argv[optind++];
3300
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003301 if (qemu_opts_foreach(&qemu_object_opts,
3302 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003303 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003304 return 1;
3305 }
3306
aliguorif7b4a942009-01-07 17:40:15 +00003307 /* Open the image */
Fam Zheng335e9932017-05-03 00:35:39 +08003308 blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
3309 force_share);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003310 if (!blk) {
3311 return 1;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003312 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003313 bs = blk_bs(blk);
aliguorif7b4a942009-01-07 17:40:15 +00003314
3315 /* Perform the requested action */
3316 switch(action) {
3317 case SNAPSHOT_LIST:
3318 dump_snapshots(bs);
3319 break;
3320
3321 case SNAPSHOT_CREATE:
3322 memset(&sn, 0, sizeof(sn));
3323 pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
3324
3325 qemu_gettimeofday(&tv);
3326 sn.date_sec = tv.tv_sec;
3327 sn.date_nsec = tv.tv_usec * 1000;
3328
3329 ret = bdrv_snapshot_create(bs, &sn);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003330 if (ret) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003331 error_report("Could not create snapshot '%s': %d (%s)",
aliguorif7b4a942009-01-07 17:40:15 +00003332 snapshot_name, ret, strerror(-ret));
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003333 }
aliguorif7b4a942009-01-07 17:40:15 +00003334 break;
3335
3336 case SNAPSHOT_APPLY:
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003337 ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003338 if (ret) {
Kevin Wolf0b62bcb2017-11-20 15:28:41 +01003339 error_reportf_err(err, "Could not apply snapshot '%s': ",
3340 snapshot_name);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003341 }
aliguorif7b4a942009-01-07 17:40:15 +00003342 break;
3343
3344 case SNAPSHOT_DELETE:
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003345 ret = bdrv_snapshot_find(bs, &sn, snapshot_name);
3346 if (ret < 0) {
3347 error_report("Could not delete snapshot '%s': snapshot not "
3348 "found", snapshot_name);
Wenchao Xiaa89d89d2013-09-11 14:04:33 +08003349 ret = 1;
Daniel Henrique Barboza8c040932018-11-07 11:09:59 -02003350 } else {
3351 ret = bdrv_snapshot_delete(bs, sn.id_str, sn.name, &err);
3352 if (ret < 0) {
3353 error_reportf_err(err, "Could not delete snapshot '%s': ",
3354 snapshot_name);
3355 ret = 1;
3356 }
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003357 }
aliguorif7b4a942009-01-07 17:40:15 +00003358 break;
3359 }
3360
3361 /* Cleanup */
Markus Armbruster26f54e92014-10-07 13:59:04 +02003362 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003363 if (ret) {
3364 return 1;
3365 }
Stuart Brady153859b2009-06-07 00:42:17 +01003366 return 0;
aliguorif7b4a942009-01-07 17:40:15 +00003367}
3368
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003369static int img_rebase(int argc, char **argv)
3370{
Markus Armbruster26f54e92014-10-07 13:59:04 +02003371 BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
Paolo Bonzini396374c2016-02-25 23:53:54 +01003372 uint8_t *buf_old = NULL;
3373 uint8_t *buf_new = NULL;
Sam Eiderman863cc782019-05-23 19:33:36 +03003374 BlockDriverState *bs = NULL, *prefix_chain_bs = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003375 char *filename;
Max Reitz40055952014-07-22 22:58:42 +02003376 const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
3377 int c, flags, src_flags, ret;
Kevin Wolfce099542016-03-15 13:01:04 +01003378 bool writethrough, src_writethrough;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003379 int unsafe = 0;
Fam Zheng335e9932017-05-03 00:35:39 +08003380 bool force_share = false;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003381 int progress = 0;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003382 bool quiet = false;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003383 Error *local_err = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003384 bool image_opts = false;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003385
3386 /* Parse commandline parameters */
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003387 fmt = NULL;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003388 cache = BDRV_DEFAULT_CACHE;
Max Reitz40055952014-07-22 22:58:42 +02003389 src_cache = BDRV_DEFAULT_CACHE;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003390 out_baseimg = NULL;
3391 out_basefmt = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003392 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003393 static const struct option long_options[] = {
3394 {"help", no_argument, 0, 'h'},
3395 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003396 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08003397 {"force-share", no_argument, 0, 'U'},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003398 {0, 0, 0, 0}
3399 };
Fam Zheng335e9932017-05-03 00:35:39 +08003400 c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003401 long_options, NULL);
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003402 if (c == -1) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003403 break;
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003404 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003405 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003406 case ':':
3407 missing_argument(argv[optind - 1]);
3408 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003409 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003410 unrecognized_option(argv[optind - 1]);
3411 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003412 case 'h':
3413 help();
3414 return 0;
Kevin Wolfe53dbee2010-03-02 12:14:31 +01003415 case 'f':
3416 fmt = optarg;
3417 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003418 case 'F':
3419 out_basefmt = optarg;
3420 break;
3421 case 'b':
3422 out_baseimg = optarg;
3423 break;
3424 case 'u':
3425 unsafe = 1;
3426 break;
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003427 case 'p':
3428 progress = 1;
3429 break;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003430 case 't':
3431 cache = optarg;
3432 break;
Max Reitz40055952014-07-22 22:58:42 +02003433 case 'T':
3434 src_cache = optarg;
3435 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003436 case 'q':
3437 quiet = true;
3438 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003439 case OPTION_OBJECT: {
3440 QemuOpts *opts;
3441 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3442 optarg, true);
3443 if (!opts) {
3444 return 1;
3445 }
3446 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003447 case OPTION_IMAGE_OPTS:
3448 image_opts = true;
3449 break;
Fam Zheng335e9932017-05-03 00:35:39 +08003450 case 'U':
3451 force_share = true;
3452 break;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003453 }
3454 }
3455
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003456 if (quiet) {
3457 progress = 0;
3458 }
3459
Fam Zhengac1307a2014-04-22 13:36:11 +08003460 if (optind != argc - 1) {
3461 error_exit("Expecting one image file name");
3462 }
3463 if (!unsafe && !out_baseimg) {
3464 error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
Jes Sorensenb8fb60d2010-12-06 15:25:39 +01003465 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003466 filename = argv[optind++];
3467
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003468 if (qemu_opts_foreach(&qemu_object_opts,
3469 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003470 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003471 return 1;
3472 }
3473
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003474 qemu_progress_init(progress, 2.0);
3475 qemu_progress_print(0, 100);
3476
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003477 flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
Kevin Wolfce099542016-03-15 13:01:04 +01003478 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003479 if (ret < 0) {
3480 error_report("Invalid cache option: %s", cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003481 goto out;
Federico Simoncelli661a0f72011-06-20 12:48:19 -04003482 }
3483
Kevin Wolfce099542016-03-15 13:01:04 +01003484 src_flags = 0;
3485 ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
Max Reitz40055952014-07-22 22:58:42 +02003486 if (ret < 0) {
3487 error_report("Invalid source cache option: %s", src_cache);
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003488 goto out;
Max Reitz40055952014-07-22 22:58:42 +02003489 }
3490
Kevin Wolfce099542016-03-15 13:01:04 +01003491 /* The source files are opened read-only, don't care about WCE */
3492 assert((src_flags & BDRV_O_RDWR) == 0);
3493 (void) src_writethrough;
3494
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003495 /*
3496 * Open the images.
3497 *
3498 * Ignore the old backing file for unsafe rebase in case we want to correct
3499 * the reference to a renamed or moved backing file.
3500 */
Fam Zheng335e9932017-05-03 00:35:39 +08003501 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
3502 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003503 if (!blk) {
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003504 ret = -1;
3505 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003506 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003507 bs = blk_bs(blk);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003508
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003509 if (out_basefmt != NULL) {
Max Reitz644483d2015-02-05 13:58:17 -05003510 if (bdrv_find_format(out_basefmt) == NULL) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003511 error_report("Invalid format name: '%s'", out_basefmt);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003512 ret = -1;
3513 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003514 }
3515 }
3516
3517 /* For safe rebasing we need to compare old and new backing file */
Stefan Hajnoczi40ed35a2014-08-26 19:17:56 +01003518 if (!unsafe) {
Max Reitz644483d2015-02-05 13:58:17 -05003519 QDict *options = NULL;
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003520 BlockDriverState *base_bs = backing_bs(bs);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003521
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003522 if (base_bs) {
Kevin Wolfd861ab32019-04-25 14:25:10 +02003523 blk_old_backing = blk_new(qemu_get_aio_context(),
3524 BLK_PERM_CONSISTENT_READ,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003525 BLK_PERM_ALL);
3526 ret = blk_insert_bs(blk_old_backing, base_bs,
3527 &local_err);
3528 if (ret < 0) {
Max Reitz35ddd932019-05-09 19:52:35 +02003529 error_reportf_err(local_err,
Sam Eiderman4ebe0612019-05-23 19:33:35 +03003530 "Could not reuse old backing file '%s': ",
3531 base_bs->filename);
Max Reitz35ddd932019-05-09 19:52:35 +02003532 goto out;
3533 }
3534 } else {
3535 blk_old_backing = NULL;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003536 }
Max Reitz644483d2015-02-05 13:58:17 -05003537
Alex Bligha6166732012-10-16 13:46:18 +01003538 if (out_baseimg[0]) {
Max Reitzd16699b2018-05-09 20:20:01 +02003539 const char *overlay_filename;
3540 char *out_real_path;
3541
Fam Zheng335e9932017-05-03 00:35:39 +08003542 options = qdict_new();
Max Reitz644483d2015-02-05 13:58:17 -05003543 if (out_basefmt) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003544 qdict_put_str(options, "driver", out_basefmt);
Fam Zheng335e9932017-05-03 00:35:39 +08003545 }
3546 if (force_share) {
3547 qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
Max Reitz644483d2015-02-05 13:58:17 -05003548 }
3549
Max Reitzf30c66b2019-02-01 20:29:05 +01003550 bdrv_refresh_filename(bs);
Max Reitzd16699b2018-05-09 20:20:01 +02003551 overlay_filename = bs->exact_filename[0] ? bs->exact_filename
3552 : bs->filename;
Max Reitz645ae7d2019-02-01 20:29:14 +01003553 out_real_path =
3554 bdrv_get_full_backing_filename_from_filename(overlay_filename,
3555 out_baseimg,
3556 &local_err);
Max Reitzd16699b2018-05-09 20:20:01 +02003557 if (local_err) {
Max Reitzf22356d2019-05-28 21:53:38 +02003558 qobject_unref(options);
Max Reitzd16699b2018-05-09 20:20:01 +02003559 error_reportf_err(local_err,
3560 "Could not resolve backing filename: ");
3561 ret = -1;
Max Reitzd16699b2018-05-09 20:20:01 +02003562 goto out;
3563 }
3564
Sam Eiderman863cc782019-05-23 19:33:36 +03003565 /*
3566 * Find out whether we rebase an image on top of a previous image
3567 * in its chain.
3568 */
3569 prefix_chain_bs = bdrv_find_backing_image(bs, out_real_path);
Sam Eiderman330c7292019-05-23 19:33:37 +03003570 if (prefix_chain_bs) {
Max Reitzf22356d2019-05-28 21:53:38 +02003571 qobject_unref(options);
Sam Eiderman330c7292019-05-23 19:33:37 +03003572 g_free(out_real_path);
Max Reitzf22356d2019-05-28 21:53:38 +02003573
Kevin Wolfd861ab32019-04-25 14:25:10 +02003574 blk_new_backing = blk_new(qemu_get_aio_context(),
3575 BLK_PERM_CONSISTENT_READ,
Sam Eiderman330c7292019-05-23 19:33:37 +03003576 BLK_PERM_ALL);
3577 ret = blk_insert_bs(blk_new_backing, prefix_chain_bs,
3578 &local_err);
3579 if (ret < 0) {
3580 error_reportf_err(local_err,
3581 "Could not reuse backing file '%s': ",
3582 out_baseimg);
3583 goto out;
3584 }
3585 } else {
3586 blk_new_backing = blk_new_open(out_real_path, NULL,
3587 options, src_flags, &local_err);
3588 g_free(out_real_path);
3589 if (!blk_new_backing) {
3590 error_reportf_err(local_err,
3591 "Could not open new backing file '%s': ",
3592 out_baseimg);
3593 ret = -1;
3594 goto out;
3595 }
Alex Bligha6166732012-10-16 13:46:18 +01003596 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003597 }
3598 }
3599
3600 /*
3601 * Check each unallocated cluster in the COW file. If it is unallocated,
3602 * accesses go to the backing file. We must therefore compare this cluster
3603 * in the old and new backing file, and if they differ we need to copy it
3604 * from the old backing file into the COW file.
3605 *
3606 * If qemu-img crashes during this step, no harm is done. The content of
3607 * the image is the same as the original one at any time.
3608 */
3609 if (!unsafe) {
Eric Blake41536282017-10-11 22:47:15 -05003610 int64_t size;
Max Reitz35ddd932019-05-09 19:52:35 +02003611 int64_t old_backing_size = 0;
Eric Blake41536282017-10-11 22:47:15 -05003612 int64_t new_backing_size = 0;
3613 uint64_t offset;
3614 int64_t n;
Kevin Wolf1f710492012-10-12 14:29:18 +02003615 float local_progress = 0;
TeLeMand6771bf2010-02-08 16:20:00 +08003616
Max Reitzf1d3cd72015-02-05 13:58:18 -05003617 buf_old = blk_blockalign(blk, IO_BUF_SIZE);
3618 buf_new = blk_blockalign(blk, IO_BUF_SIZE);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003619
Eric Blake41536282017-10-11 22:47:15 -05003620 size = blk_getlength(blk);
3621 if (size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003622 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003623 filename, strerror(-size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003624 ret = -1;
3625 goto out;
3626 }
Max Reitz35ddd932019-05-09 19:52:35 +02003627 if (blk_old_backing) {
3628 old_backing_size = blk_getlength(blk_old_backing);
3629 if (old_backing_size < 0) {
3630 char backing_name[PATH_MAX];
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003631
Max Reitz35ddd932019-05-09 19:52:35 +02003632 bdrv_get_backing_filename(bs, backing_name,
3633 sizeof(backing_name));
3634 error_report("Could not get size of '%s': %s",
3635 backing_name, strerror(-old_backing_size));
3636 ret = -1;
3637 goto out;
3638 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003639 }
Max Reitzf1d3cd72015-02-05 13:58:18 -05003640 if (blk_new_backing) {
Eric Blake41536282017-10-11 22:47:15 -05003641 new_backing_size = blk_getlength(blk_new_backing);
3642 if (new_backing_size < 0) {
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003643 error_report("Could not get size of '%s': %s",
Eric Blake41536282017-10-11 22:47:15 -05003644 out_baseimg, strerror(-new_backing_size));
Markus Armbruster52bf1e72014-06-26 13:23:25 +02003645 ret = -1;
3646 goto out;
3647 }
Alex Bligha6166732012-10-16 13:46:18 +01003648 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003649
Eric Blake41536282017-10-11 22:47:15 -05003650 if (size != 0) {
3651 local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
Kevin Wolf1f710492012-10-12 14:29:18 +02003652 }
3653
Eric Blake41536282017-10-11 22:47:15 -05003654 for (offset = 0; offset < size; offset += n) {
Max Reitz1c6e8772019-05-09 19:52:36 +02003655 bool buf_old_is_zero = false;
3656
Eric Blake41536282017-10-11 22:47:15 -05003657 /* How many bytes can we handle with the next read? */
3658 n = MIN(IO_BUF_SIZE, size - offset);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003659
3660 /* If the cluster is allocated, we don't need to take action */
Eric Blake41536282017-10-11 22:47:15 -05003661 ret = bdrv_is_allocated(bs, offset, n, &n);
Paolo Bonzinid6636402013-09-04 19:00:25 +02003662 if (ret < 0) {
3663 error_report("error while reading image metadata: %s",
3664 strerror(-ret));
3665 goto out;
3666 }
Kevin Wolfcc60e322010-04-29 14:47:48 +02003667 if (ret) {
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003668 continue;
3669 }
3670
Sam Eiderman863cc782019-05-23 19:33:36 +03003671 if (prefix_chain_bs) {
3672 /*
3673 * If cluster wasn't changed since prefix_chain, we don't need
3674 * to take action
3675 */
3676 ret = bdrv_is_allocated_above(backing_bs(bs), prefix_chain_bs,
Andrey Shinkevich170d3bd2019-05-29 20:56:14 +03003677 false, offset, n, &n);
Sam Eiderman863cc782019-05-23 19:33:36 +03003678 if (ret < 0) {
3679 error_report("error while reading image metadata: %s",
3680 strerror(-ret));
3681 goto out;
3682 }
3683 if (!ret) {
3684 continue;
3685 }
3686 }
3687
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003688 /*
3689 * Read old and new backing file and take into consideration that
3690 * backing files may be smaller than the COW image.
3691 */
Eric Blake41536282017-10-11 22:47:15 -05003692 if (offset >= old_backing_size) {
3693 memset(buf_old, 0, n);
Max Reitz1c6e8772019-05-09 19:52:36 +02003694 buf_old_is_zero = true;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003695 } else {
Eric Blake41536282017-10-11 22:47:15 -05003696 if (offset + n > old_backing_size) {
3697 n = old_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003698 }
3699
Eric Blake41536282017-10-11 22:47:15 -05003700 ret = blk_pread(blk_old_backing, offset, buf_old, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003701 if (ret < 0) {
3702 error_report("error while reading from old backing file");
3703 goto out;
3704 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003705 }
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003706
Eric Blake41536282017-10-11 22:47:15 -05003707 if (offset >= new_backing_size || !blk_new_backing) {
3708 memset(buf_new, 0, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003709 } else {
Eric Blake41536282017-10-11 22:47:15 -05003710 if (offset + n > new_backing_size) {
3711 n = new_backing_size - offset;
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003712 }
3713
Eric Blake41536282017-10-11 22:47:15 -05003714 ret = blk_pread(blk_new_backing, offset, buf_new, n);
Kevin Wolf87a1b3e2011-12-07 12:42:10 +01003715 if (ret < 0) {
3716 error_report("error while reading from new backing file");
3717 goto out;
3718 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003719 }
3720
3721 /* If they differ, we need to write to the COW file */
3722 uint64_t written = 0;
3723
Eric Blake41536282017-10-11 22:47:15 -05003724 while (written < n) {
Eric Blakedc61cd32017-10-11 22:47:14 -05003725 int64_t pnum;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003726
Eric Blake41536282017-10-11 22:47:15 -05003727 if (compare_buffers(buf_old + written, buf_new + written,
3728 n - written, &pnum))
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003729 {
Max Reitz1c6e8772019-05-09 19:52:36 +02003730 if (buf_old_is_zero) {
3731 ret = blk_pwrite_zeroes(blk, offset + written, pnum, 0);
3732 } else {
3733 ret = blk_pwrite(blk, offset + written,
3734 buf_old + written, pnum, 0);
3735 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003736 if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003737 error_report("Error while writing to COW image: %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003738 strerror(-ret));
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003739 goto out;
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003740 }
3741 }
3742
3743 written += pnum;
3744 }
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003745 qemu_progress_print(local_progress, 100);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003746 }
3747 }
3748
3749 /*
3750 * Change the backing file. All clusters that are different from the old
3751 * backing file are overwritten in the COW file now, so the visible content
3752 * doesn't change when we switch the backing file.
3753 */
Alex Bligha6166732012-10-16 13:46:18 +01003754 if (out_baseimg && *out_baseimg) {
3755 ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
3756 } else {
3757 ret = bdrv_change_backing_file(bs, NULL, NULL);
3758 }
3759
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003760 if (ret == -ENOSPC) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003761 error_report("Could not change the backing file to '%s': No "
3762 "space left in the file header", out_baseimg);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003763 } else if (ret < 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003764 error_report("Could not change the backing file to '%s': %s",
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003765 out_baseimg, strerror(-ret));
3766 }
3767
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003768 qemu_progress_print(100, 0);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003769 /*
3770 * TODO At this point it is possible to check if any clusters that are
3771 * allocated in the COW file are the same in the backing file. If so, they
3772 * could be dropped from the COW file. Don't do this before switching the
3773 * backing file, in case of a crash this would lead to corruption.
3774 */
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003775out:
Jes Sorensen6b837bc2011-03-30 14:16:25 +02003776 qemu_progress_end();
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003777 /* Cleanup */
3778 if (!unsafe) {
Markus Armbruster26f54e92014-10-07 13:59:04 +02003779 blk_unref(blk_old_backing);
Markus Armbruster26f54e92014-10-07 13:59:04 +02003780 blk_unref(blk_new_backing);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003781 }
Paolo Bonzini396374c2016-02-25 23:53:54 +01003782 qemu_vfree(buf_old);
3783 qemu_vfree(buf_new);
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003784
Markus Armbruster26f54e92014-10-07 13:59:04 +02003785 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003786 if (ret) {
3787 return 1;
3788 }
Kevin Wolf3e85c6f2010-01-12 12:55:18 +01003789 return 0;
3790}
3791
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003792static int img_resize(int argc, char **argv)
3793{
Markus Armbruster6750e792015-02-12 17:43:08 +01003794 Error *err = NULL;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003795 int c, ret, relative;
3796 const char *filename, *fmt, *size;
Max Reitz09c5c6d2019-09-18 11:51:44 +02003797 int64_t n, total_size, current_size;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003798 bool quiet = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02003799 BlockBackend *blk = NULL;
Max Reitzdc5f6902017-06-13 22:20:55 +02003800 PreallocMode prealloc = PREALLOC_MODE_OFF;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003801 QemuOpts *param;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003802
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003803 static QemuOptsList resize_options = {
3804 .name = "resize_options",
3805 .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
3806 .desc = {
3807 {
3808 .name = BLOCK_OPT_SIZE,
3809 .type = QEMU_OPT_SIZE,
3810 .help = "Virtual disk size"
3811 }, {
3812 /* end of list */
3813 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003814 },
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003815 };
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003816 bool image_opts = false;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003817 bool shrink = false;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003818
Kevin Wolfe80fec72011-04-29 10:58:12 +02003819 /* Remove size from argv manually so that negative numbers are not treated
3820 * as options by getopt. */
3821 if (argc < 3) {
Fam Zhengac1307a2014-04-22 13:36:11 +08003822 error_exit("Not enough arguments");
Kevin Wolfe80fec72011-04-29 10:58:12 +02003823 return 1;
3824 }
3825
3826 size = argv[--argc];
3827
3828 /* Parse getopt arguments */
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003829 fmt = NULL;
3830 for(;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003831 static const struct option long_options[] = {
3832 {"help", no_argument, 0, 'h'},
3833 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003834 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Max Reitzdc5f6902017-06-13 22:20:55 +02003835 {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003836 {"shrink", no_argument, 0, OPTION_SHRINK},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003837 {0, 0, 0, 0}
3838 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003839 c = getopt_long(argc, argv, ":f:hq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003840 long_options, NULL);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003841 if (c == -1) {
3842 break;
3843 }
3844 switch(c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003845 case ':':
3846 missing_argument(argv[optind - 1]);
3847 break;
Jes Sorensenef873942010-12-06 15:25:40 +01003848 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08003849 unrecognized_option(argv[optind - 1]);
3850 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003851 case 'h':
3852 help();
3853 break;
3854 case 'f':
3855 fmt = optarg;
3856 break;
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01003857 case 'q':
3858 quiet = true;
3859 break;
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003860 case OPTION_OBJECT: {
3861 QemuOpts *opts;
3862 opts = qemu_opts_parse_noisily(&qemu_object_opts,
3863 optarg, true);
3864 if (!opts) {
3865 return 1;
3866 }
3867 } break;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00003868 case OPTION_IMAGE_OPTS:
3869 image_opts = true;
3870 break;
Max Reitzdc5f6902017-06-13 22:20:55 +02003871 case OPTION_PREALLOCATION:
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +02003872 prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
Markus Armbruster06c60b62017-08-24 10:45:57 +02003873 PREALLOC_MODE__MAX, NULL);
Max Reitzdc5f6902017-06-13 22:20:55 +02003874 if (prealloc == PREALLOC_MODE__MAX) {
3875 error_report("Invalid preallocation mode '%s'", optarg);
3876 return 1;
3877 }
3878 break;
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003879 case OPTION_SHRINK:
3880 shrink = true;
3881 break;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003882 }
3883 }
Kevin Wolffc11eb22013-08-05 10:53:04 +02003884 if (optind != argc - 1) {
Max Reitzbe8fbd42018-02-05 17:27:45 +01003885 error_exit("Expecting image file name and size");
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003886 }
3887 filename = argv[optind++];
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003888
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003889 if (qemu_opts_foreach(&qemu_object_opts,
3890 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02003891 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00003892 return 1;
3893 }
3894
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003895 /* Choose grow, shrink, or absolute resize mode */
3896 switch (size[0]) {
3897 case '+':
3898 relative = 1;
3899 size++;
3900 break;
3901 case '-':
3902 relative = -1;
3903 size++;
3904 break;
3905 default:
3906 relative = 0;
3907 break;
3908 }
3909
3910 /* Parse size */
Peter Crosthwaite87ea75d2014-01-01 18:49:17 -08003911 param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01003912 qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
Markus Armbruster6750e792015-02-12 17:43:08 +01003913 if (err) {
3914 error_report_err(err);
Jes Sorensen2a819982010-12-06 17:08:31 +01003915 ret = -1;
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003916 qemu_opts_del(param);
Jes Sorensen2a819982010-12-06 17:08:31 +01003917 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003918 }
Dong Xu Wang20caf0f2012-08-06 10:18:42 +08003919 n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
3920 qemu_opts_del(param);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003921
Max Reitzefaa7c42016-03-16 19:54:38 +01003922 blk = img_open(image_opts, filename, fmt,
Fam Zheng335e9932017-05-03 00:35:39 +08003923 BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
3924 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02003925 if (!blk) {
Jes Sorensen2a819982010-12-06 17:08:31 +01003926 ret = -1;
3927 goto out;
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003928 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003929
Max Reitzdc5f6902017-06-13 22:20:55 +02003930 current_size = blk_getlength(blk);
3931 if (current_size < 0) {
3932 error_report("Failed to inquire current image length: %s",
3933 strerror(-current_size));
3934 ret = -1;
3935 goto out;
3936 }
3937
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003938 if (relative) {
Max Reitzdc5f6902017-06-13 22:20:55 +02003939 total_size = current_size + n * relative;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003940 } else {
3941 total_size = n;
3942 }
3943 if (total_size <= 0) {
Jes Sorensen15654a62010-12-16 14:31:53 +01003944 error_report("New image size must be positive");
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003945 ret = -1;
3946 goto out;
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003947 }
3948
Max Reitzdc5f6902017-06-13 22:20:55 +02003949 if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
3950 error_report("Preallocation can only be used for growing images");
3951 ret = -1;
3952 goto out;
3953 }
3954
Pavel Butsykin4ffca892017-09-18 15:42:27 +03003955 if (total_size < current_size && !shrink) {
3956 warn_report("Shrinking an image will delete all data beyond the "
3957 "shrunken image's end. Before performing such an "
3958 "operation, make sure there is no important data there.");
3959
3960 if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
3961 error_report(
3962 "Use the --shrink option to perform a shrink operation.");
3963 ret = -1;
3964 goto out;
3965 } else {
3966 warn_report("Using the --shrink option will suppress this message. "
3967 "Note that future versions of qemu-img may refuse to "
3968 "shrink images without this option.");
3969 }
3970 }
3971
Max Reitze8d04f92019-09-18 11:51:43 +02003972 /*
3973 * The user expects the image to have the desired size after
3974 * resizing, so pass @exact=true. It is of no use to report
3975 * success when the image has not actually been resized.
3976 */
Kevin Wolf8c6242b2020-04-24 14:54:41 +02003977 ret = blk_truncate(blk, total_size, true, prealloc, 0, &err);
Max Reitz09c5c6d2019-09-18 11:51:44 +02003978 if (!ret) {
3979 qprintf(quiet, "Image resized.\n");
3980 } else {
Max Reitzed3d2ec2017-03-28 22:51:27 +02003981 error_report_err(err);
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003982 }
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003983out:
Markus Armbruster26f54e92014-10-07 13:59:04 +02003984 blk_unref(blk);
MORITA Kazutakac2abcce2010-06-21 04:26:35 +09003985 if (ret) {
3986 return 1;
3987 }
Stefan Hajnocziae6b0ed2010-04-24 09:12:12 +01003988 return 0;
3989}
3990
Max Reitz76a3a342014-10-27 11:12:51 +01003991static void amend_status_cb(BlockDriverState *bs,
Max Reitz8b139762015-07-27 17:51:32 +02003992 int64_t offset, int64_t total_work_size,
3993 void *opaque)
Max Reitz76a3a342014-10-27 11:12:51 +01003994{
3995 qemu_progress_print(100.f * offset / total_work_size, 0);
3996}
3997
Max Reitz51641352018-05-09 23:00:20 +02003998static int print_amend_option_help(const char *format)
3999{
4000 BlockDriver *drv;
4001
4002 /* Find driver and parse its options */
4003 drv = bdrv_find_format(format);
4004 if (!drv) {
4005 error_report("Unknown file format '%s'", format);
4006 return 1;
4007 }
4008
4009 if (!drv->bdrv_amend_options) {
4010 error_report("Format driver '%s' does not support option amendment",
4011 format);
4012 return 1;
4013 }
4014
4015 /* Every driver supporting amendment must have create_opts */
4016 assert(drv->create_opts);
4017
4018 printf("Creation options for '%s':\n", format);
Max Reitz63898712018-10-19 18:49:25 +02004019 qemu_opts_print_help(drv->create_opts, false);
Max Reitz51641352018-05-09 23:00:20 +02004020 printf("\nNote that not all of these options may be amendable.\n");
4021 return 0;
4022}
4023
Max Reitz6f176b42013-09-03 10:09:50 +02004024static int img_amend(int argc, char **argv)
4025{
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004026 Error *err = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004027 int c, ret = 0;
4028 char *options = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004029 QemuOptsList *create_opts = NULL;
4030 QemuOpts *opts = NULL;
Max Reitzbd39e6e2014-07-22 22:58:43 +02004031 const char *fmt = NULL, *filename, *cache;
4032 int flags;
Kevin Wolfce099542016-03-15 13:01:04 +01004033 bool writethrough;
Max Reitz76a3a342014-10-27 11:12:51 +01004034 bool quiet = false, progress = false;
Markus Armbruster26f54e92014-10-07 13:59:04 +02004035 BlockBackend *blk = NULL;
Max Reitz6f176b42013-09-03 10:09:50 +02004036 BlockDriverState *bs = NULL;
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004037 bool image_opts = false;
Max Reitz6f176b42013-09-03 10:09:50 +02004038
Max Reitzbd39e6e2014-07-22 22:58:43 +02004039 cache = BDRV_DEFAULT_CACHE;
Max Reitz6f176b42013-09-03 10:09:50 +02004040 for (;;) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004041 static const struct option long_options[] = {
4042 {"help", no_argument, 0, 'h'},
4043 {"object", required_argument, 0, OPTION_OBJECT},
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00004044 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004045 {0, 0, 0, 0}
4046 };
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004047 c = getopt_long(argc, argv, ":ho:f:t:pq",
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004048 long_options, NULL);
Max Reitz6f176b42013-09-03 10:09:50 +02004049 if (c == -1) {
4050 break;
4051 }
4052
4053 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004054 case ':':
4055 missing_argument(argv[optind - 1]);
4056 break;
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004057 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004058 unrecognized_option(argv[optind - 1]);
4059 break;
4060 case 'h':
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004061 help();
4062 break;
4063 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02004064 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004065 ret = -1;
4066 goto out_no_progress;
4067 }
Stefan Hajnoczif7077622017-03-17 18:45:40 +08004068 break;
4069 case 'f':
4070 fmt = optarg;
4071 break;
4072 case 't':
4073 cache = optarg;
4074 break;
4075 case 'p':
4076 progress = true;
4077 break;
4078 case 'q':
4079 quiet = true;
4080 break;
4081 case OPTION_OBJECT:
4082 opts = qemu_opts_parse_noisily(&qemu_object_opts,
4083 optarg, true);
4084 if (!opts) {
4085 ret = -1;
4086 goto out_no_progress;
4087 }
4088 break;
4089 case OPTION_IMAGE_OPTS:
4090 image_opts = true;
4091 break;
Max Reitz6f176b42013-09-03 10:09:50 +02004092 }
4093 }
4094
Max Reitz6f176b42013-09-03 10:09:50 +02004095 if (!options) {
Fam Zhengac1307a2014-04-22 13:36:11 +08004096 error_exit("Must specify options (-o)");
Max Reitz6f176b42013-09-03 10:09:50 +02004097 }
4098
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004099 if (qemu_opts_foreach(&qemu_object_opts,
4100 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004101 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00004102 ret = -1;
4103 goto out_no_progress;
4104 }
4105
Max Reitz76a3a342014-10-27 11:12:51 +01004106 if (quiet) {
4107 progress = false;
4108 }
4109 qemu_progress_init(progress, 1.0);
4110
Kevin Wolfa283cb62014-02-21 16:24:07 +01004111 filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
4112 if (fmt && has_help_option(options)) {
4113 /* If a format is explicitly specified (and possibly no filename is
4114 * given), print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004115 ret = print_amend_option_help(fmt);
Kevin Wolfa283cb62014-02-21 16:24:07 +01004116 goto out;
4117 }
4118
4119 if (optind != argc - 1) {
Max Reitzb2f27e42014-10-27 11:12:52 +01004120 error_report("Expecting one image file name");
4121 ret = -1;
4122 goto out;
Kevin Wolfa283cb62014-02-21 16:24:07 +01004123 }
Max Reitz6f176b42013-09-03 10:09:50 +02004124
Kevin Wolfce099542016-03-15 13:01:04 +01004125 flags = BDRV_O_RDWR;
4126 ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
Max Reitzbd39e6e2014-07-22 22:58:43 +02004127 if (ret < 0) {
4128 error_report("Invalid cache option: %s", cache);
4129 goto out;
4130 }
4131
Fam Zheng335e9932017-05-03 00:35:39 +08004132 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4133 false);
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004134 if (!blk) {
Max Reitz6f176b42013-09-03 10:09:50 +02004135 ret = -1;
4136 goto out;
4137 }
Markus Armbruster7e7d56d2014-10-07 13:59:05 +02004138 bs = blk_bs(blk);
Max Reitz6f176b42013-09-03 10:09:50 +02004139
4140 fmt = bs->drv->format_name;
4141
Kevin Wolf626f84f2014-02-21 16:24:06 +01004142 if (has_help_option(options)) {
Kevin Wolfa283cb62014-02-21 16:24:07 +01004143 /* If the format was auto-detected, print option help here */
Max Reitz51641352018-05-09 23:00:20 +02004144 ret = print_amend_option_help(fmt);
Max Reitz6f176b42013-09-03 10:09:50 +02004145 goto out;
4146 }
4147
Max Reitz1f996682018-05-09 23:00:17 +02004148 if (!bs->drv->bdrv_amend_options) {
4149 error_report("Format driver '%s' does not support option amendment",
Max Reitzb2439d22014-12-02 18:32:47 +01004150 fmt);
4151 ret = -1;
4152 goto out;
4153 }
4154
Max Reitz1f996682018-05-09 23:00:17 +02004155 /* Every driver supporting amendment must have create_opts */
4156 assert(bs->drv->create_opts);
4157
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004158 create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
Chunyan Liu83d05212014-06-05 17:20:51 +08004159 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Paolo Bonziniece90862017-01-04 15:56:24 +01004160 qemu_opts_do_parse(opts, options, NULL, &err);
4161 if (err) {
4162 error_report_err(err);
4163 ret = -1;
4164 goto out;
Max Reitz6f176b42013-09-03 10:09:50 +02004165 }
4166
Max Reitz76a3a342014-10-27 11:12:51 +01004167 /* In case the driver does not call amend_status_cb() */
4168 qemu_progress_print(0.f, 0);
Max Reitzd1402b52018-05-09 23:00:18 +02004169 ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL, &err);
Max Reitz76a3a342014-10-27 11:12:51 +01004170 qemu_progress_print(100.f, 0);
Max Reitz6f176b42013-09-03 10:09:50 +02004171 if (ret < 0) {
Max Reitzd1402b52018-05-09 23:00:18 +02004172 error_report_err(err);
Max Reitz6f176b42013-09-03 10:09:50 +02004173 goto out;
4174 }
4175
4176out:
Max Reitz76a3a342014-10-27 11:12:51 +01004177 qemu_progress_end();
4178
Max Reitze814dff2015-08-20 16:00:38 -07004179out_no_progress:
Markus Armbruster26f54e92014-10-07 13:59:04 +02004180 blk_unref(blk);
Chunyan Liu83d05212014-06-05 17:20:51 +08004181 qemu_opts_del(opts);
4182 qemu_opts_free(create_opts);
Kevin Wolf626f84f2014-02-21 16:24:06 +01004183 g_free(options);
4184
Max Reitz6f176b42013-09-03 10:09:50 +02004185 if (ret) {
4186 return 1;
4187 }
4188 return 0;
4189}
4190
Kevin Wolfb6133b82014-08-05 14:17:13 +02004191typedef struct BenchData {
4192 BlockBackend *blk;
4193 uint64_t image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004194 bool write;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004195 int bufsize;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004196 int step;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004197 int nrreq;
4198 int n;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004199 int flush_interval;
4200 bool drain_on_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004201 uint8_t *buf;
4202 QEMUIOVector *qiov;
4203
4204 int in_flight;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004205 bool in_flush;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004206 uint64_t offset;
4207} BenchData;
4208
Kevin Wolf55d539c2016-06-03 13:59:41 +02004209static void bench_undrained_flush_cb(void *opaque, int ret)
4210{
4211 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004212 error_report("Failed flush request: %s", strerror(-ret));
Kevin Wolf55d539c2016-06-03 13:59:41 +02004213 exit(EXIT_FAILURE);
4214 }
4215}
4216
Kevin Wolfb6133b82014-08-05 14:17:13 +02004217static void bench_cb(void *opaque, int ret)
4218{
4219 BenchData *b = opaque;
4220 BlockAIOCB *acb;
4221
4222 if (ret < 0) {
Markus Armbrusterdf3c2862016-08-03 13:37:51 +02004223 error_report("Failed request: %s", strerror(-ret));
Kevin Wolfb6133b82014-08-05 14:17:13 +02004224 exit(EXIT_FAILURE);
4225 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004226
4227 if (b->in_flush) {
4228 /* Just finished a flush with drained queue: Start next requests */
4229 assert(b->in_flight == 0);
4230 b->in_flush = false;
4231 } else if (b->in_flight > 0) {
4232 int remaining = b->n - b->in_flight;
4233
Kevin Wolfb6133b82014-08-05 14:17:13 +02004234 b->n--;
4235 b->in_flight--;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004236
4237 /* Time for flush? Drain queue if requested, then flush */
4238 if (b->flush_interval && remaining % b->flush_interval == 0) {
4239 if (!b->in_flight || !b->drain_on_flush) {
4240 BlockCompletionFunc *cb;
4241
4242 if (b->drain_on_flush) {
4243 b->in_flush = true;
4244 cb = bench_cb;
4245 } else {
4246 cb = bench_undrained_flush_cb;
4247 }
4248
4249 acb = blk_aio_flush(b->blk, cb, b);
4250 if (!acb) {
4251 error_report("Failed to issue flush request");
4252 exit(EXIT_FAILURE);
4253 }
4254 }
4255 if (b->drain_on_flush) {
4256 return;
4257 }
4258 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004259 }
4260
4261 while (b->n > b->in_flight && b->in_flight < b->nrreq) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004262 int64_t offset = b->offset;
4263 /* blk_aio_* might look for completed I/Os and kick bench_cb
4264 * again, so make sure this operation is counted by in_flight
4265 * and b->offset is ready for the next submission.
4266 */
4267 b->in_flight++;
4268 b->offset += b->step;
4269 b->offset %= b->image_size;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004270 if (b->write) {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004271 acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004272 } else {
Paolo Bonzini4baaa8c2016-12-07 16:08:27 +01004273 acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004274 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004275 if (!acb) {
4276 error_report("Failed to issue request");
4277 exit(EXIT_FAILURE);
4278 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004279 }
4280}
4281
4282static int img_bench(int argc, char **argv)
4283{
4284 int c, ret = 0;
4285 const char *fmt = NULL, *filename;
4286 bool quiet = false;
4287 bool image_opts = false;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004288 bool is_write = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004289 int count = 75000;
4290 int depth = 64;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004291 int64_t offset = 0;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004292 size_t bufsize = 4096;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004293 int pattern = 0;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004294 size_t step = 0;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004295 int flush_interval = 0;
4296 bool drain_on_flush = true;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004297 int64_t image_size;
4298 BlockBackend *blk = NULL;
4299 BenchData data = {};
4300 int flags = 0;
Kevin Wolf604e8612016-06-14 11:29:32 +02004301 bool writethrough = false;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004302 struct timeval t1, t2;
4303 int i;
Fam Zheng335e9932017-05-03 00:35:39 +08004304 bool force_share = false;
Fam Zheng79d46582018-01-16 14:08:58 +08004305 size_t buf_size;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004306
4307 for (;;) {
4308 static const struct option long_options[] = {
4309 {"help", no_argument, 0, 'h'},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004310 {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004311 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004312 {"pattern", required_argument, 0, OPTION_PATTERN},
Kevin Wolf55d539c2016-06-03 13:59:41 +02004313 {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
Fam Zheng335e9932017-05-03 00:35:39 +08004314 {"force-share", no_argument, 0, 'U'},
Kevin Wolfb6133b82014-08-05 14:17:13 +02004315 {0, 0, 0, 0}
4316 };
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004317 c = getopt_long(argc, argv, ":hc:d:f:ni:o:qs:S:t:wU", long_options,
4318 NULL);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004319 if (c == -1) {
4320 break;
4321 }
4322
4323 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004324 case ':':
4325 missing_argument(argv[optind - 1]);
4326 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004327 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004328 unrecognized_option(argv[optind - 1]);
4329 break;
4330 case 'h':
Kevin Wolfb6133b82014-08-05 14:17:13 +02004331 help();
4332 break;
4333 case 'c':
4334 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004335 unsigned long res;
4336
4337 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004338 error_report("Invalid request count specified");
4339 return 1;
4340 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004341 count = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004342 break;
4343 }
4344 case 'd':
4345 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004346 unsigned long res;
4347
4348 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004349 error_report("Invalid queue depth specified");
4350 return 1;
4351 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004352 depth = res;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004353 break;
4354 }
4355 case 'f':
4356 fmt = optarg;
4357 break;
4358 case 'n':
4359 flags |= BDRV_O_NATIVE_AIO;
4360 break;
Aarushi Mehtacdd26772020-01-20 14:18:55 +00004361 case 'i':
4362 ret = bdrv_parse_aio(optarg, &flags);
4363 if (ret < 0) {
4364 error_report("Invalid aio option: %s", optarg);
4365 ret = -1;
4366 goto out;
4367 }
4368 break;
Kevin Wolfd3199a32015-07-10 18:09:18 +02004369 case 'o':
4370 {
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004371 offset = cvtnum("offset", optarg);
Markus Armbruster606caa02017-02-21 21:14:04 +01004372 if (offset < 0) {
Kevin Wolfd3199a32015-07-10 18:09:18 +02004373 return 1;
4374 }
4375 break;
4376 }
4377 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004378 case 'q':
4379 quiet = true;
4380 break;
4381 case 's':
4382 {
4383 int64_t sval;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004384
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004385 sval = cvtnum_full("buffer size", optarg, 0, INT_MAX);
4386 if (sval < 0) {
Kevin Wolfb6133b82014-08-05 14:17:13 +02004387 return 1;
4388 }
4389
4390 bufsize = sval;
4391 break;
4392 }
Kevin Wolf83de9be2015-07-13 13:13:17 +02004393 case 'S':
4394 {
4395 int64_t sval;
Kevin Wolf83de9be2015-07-13 13:13:17 +02004396
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004397 sval = cvtnum_full("step_size", optarg, 0, INT_MAX);
4398 if (sval < 0) {
Kevin Wolf83de9be2015-07-13 13:13:17 +02004399 return 1;
4400 }
4401
4402 step = sval;
4403 break;
4404 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004405 case 't':
4406 ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
4407 if (ret < 0) {
4408 error_report("Invalid cache mode");
4409 ret = -1;
4410 goto out;
4411 }
4412 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004413 case 'w':
4414 flags |= BDRV_O_RDWR;
4415 is_write = true;
4416 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004417 case 'U':
4418 force_share = true;
4419 break;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004420 case OPTION_PATTERN:
4421 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004422 unsigned long res;
4423
4424 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004425 error_report("Invalid pattern byte specified");
4426 return 1;
4427 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004428 pattern = res;
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004429 break;
4430 }
Kevin Wolf55d539c2016-06-03 13:59:41 +02004431 case OPTION_FLUSH_INTERVAL:
4432 {
Peter Maydell8b3c6792017-02-10 16:28:23 +00004433 unsigned long res;
4434
4435 if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004436 error_report("Invalid flush interval specified");
4437 return 1;
4438 }
Peter Maydell8b3c6792017-02-10 16:28:23 +00004439 flush_interval = res;
Kevin Wolf55d539c2016-06-03 13:59:41 +02004440 break;
4441 }
4442 case OPTION_NO_DRAIN:
4443 drain_on_flush = false;
4444 break;
Kevin Wolfb6133b82014-08-05 14:17:13 +02004445 case OPTION_IMAGE_OPTS:
4446 image_opts = true;
4447 break;
4448 }
4449 }
4450
4451 if (optind != argc - 1) {
4452 error_exit("Expecting one image file name");
4453 }
4454 filename = argv[argc - 1];
4455
Kevin Wolf55d539c2016-06-03 13:59:41 +02004456 if (!is_write && flush_interval) {
4457 error_report("--flush-interval is only available in write tests");
4458 ret = -1;
4459 goto out;
4460 }
4461 if (flush_interval && flush_interval < depth) {
4462 error_report("Flush interval can't be smaller than depth");
4463 ret = -1;
4464 goto out;
4465 }
4466
Fam Zheng335e9932017-05-03 00:35:39 +08004467 blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
4468 force_share);
Kevin Wolfb6133b82014-08-05 14:17:13 +02004469 if (!blk) {
4470 ret = -1;
4471 goto out;
4472 }
4473
4474 image_size = blk_getlength(blk);
4475 if (image_size < 0) {
4476 ret = image_size;
4477 goto out;
4478 }
4479
4480 data = (BenchData) {
Kevin Wolf55d539c2016-06-03 13:59:41 +02004481 .blk = blk,
4482 .image_size = image_size,
4483 .bufsize = bufsize,
4484 .step = step ?: bufsize,
4485 .nrreq = depth,
4486 .n = count,
4487 .offset = offset,
4488 .write = is_write,
4489 .flush_interval = flush_interval,
4490 .drain_on_flush = drain_on_flush,
Kevin Wolfb6133b82014-08-05 14:17:13 +02004491 };
Kevin Wolfd3199a32015-07-10 18:09:18 +02004492 printf("Sending %d %s requests, %d bytes each, %d in parallel "
Kevin Wolf83de9be2015-07-13 13:13:17 +02004493 "(starting at offset %" PRId64 ", step size %d)\n",
Kevin Wolfd3199a32015-07-10 18:09:18 +02004494 data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
Kevin Wolf83de9be2015-07-13 13:13:17 +02004495 data.offset, data.step);
Kevin Wolf55d539c2016-06-03 13:59:41 +02004496 if (flush_interval) {
4497 printf("Sending flush every %d requests\n", flush_interval);
4498 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004499
Fam Zheng79d46582018-01-16 14:08:58 +08004500 buf_size = data.nrreq * data.bufsize;
4501 data.buf = blk_blockalign(blk, buf_size);
Kevin Wolfb6495fa2015-07-10 18:09:18 +02004502 memset(data.buf, pattern, data.nrreq * data.bufsize);
4503
Fam Zheng79d46582018-01-16 14:08:58 +08004504 blk_register_buf(blk, data.buf, buf_size);
4505
Kevin Wolfb6133b82014-08-05 14:17:13 +02004506 data.qiov = g_new(QEMUIOVector, data.nrreq);
4507 for (i = 0; i < data.nrreq; i++) {
4508 qemu_iovec_init(&data.qiov[i], 1);
4509 qemu_iovec_add(&data.qiov[i],
4510 data.buf + i * data.bufsize, data.bufsize);
4511 }
4512
4513 gettimeofday(&t1, NULL);
4514 bench_cb(&data, 0);
4515
4516 while (data.n > 0) {
4517 main_loop_wait(false);
4518 }
4519 gettimeofday(&t2, NULL);
4520
4521 printf("Run completed in %3.3f seconds.\n",
4522 (t2.tv_sec - t1.tv_sec)
4523 + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
4524
4525out:
Fam Zheng79d46582018-01-16 14:08:58 +08004526 if (data.buf) {
4527 blk_unregister_buf(blk, data.buf);
4528 }
Kevin Wolfb6133b82014-08-05 14:17:13 +02004529 qemu_vfree(data.buf);
4530 blk_unref(blk);
4531
4532 if (ret) {
4533 return 1;
4534 }
4535 return 0;
4536}
4537
Eric Blake3b51ab42020-05-12 20:16:45 -05004538enum ImgBitmapAct {
4539 BITMAP_ADD,
4540 BITMAP_REMOVE,
4541 BITMAP_CLEAR,
4542 BITMAP_ENABLE,
4543 BITMAP_DISABLE,
4544 BITMAP_MERGE,
4545};
4546typedef struct ImgBitmapAction {
4547 enum ImgBitmapAct act;
4548 const char *src; /* only used for merge */
4549 QSIMPLEQ_ENTRY(ImgBitmapAction) next;
4550} ImgBitmapAction;
4551
4552static int img_bitmap(int argc, char **argv)
4553{
4554 Error *err = NULL;
4555 int c, ret = 1;
4556 QemuOpts *opts = NULL;
4557 const char *fmt = NULL, *src_fmt = NULL, *src_filename = NULL;
4558 const char *filename, *bitmap;
4559 BlockBackend *blk = NULL, *src = NULL;
4560 BlockDriverState *bs = NULL, *src_bs = NULL;
4561 bool image_opts = false;
4562 int64_t granularity = 0;
4563 bool add = false, merge = false;
4564 QSIMPLEQ_HEAD(, ImgBitmapAction) actions;
4565 ImgBitmapAction *act, *act_next;
4566 const char *op;
4567
4568 QSIMPLEQ_INIT(&actions);
4569
4570 for (;;) {
4571 static const struct option long_options[] = {
4572 {"help", no_argument, 0, 'h'},
4573 {"object", required_argument, 0, OPTION_OBJECT},
4574 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
4575 {"add", no_argument, 0, OPTION_ADD},
4576 {"remove", no_argument, 0, OPTION_REMOVE},
4577 {"clear", no_argument, 0, OPTION_CLEAR},
4578 {"enable", no_argument, 0, OPTION_ENABLE},
4579 {"disable", no_argument, 0, OPTION_DISABLE},
4580 {"merge", required_argument, 0, OPTION_MERGE},
4581 {"granularity", required_argument, 0, 'g'},
4582 {"source-file", required_argument, 0, 'b'},
4583 {"source-format", required_argument, 0, 'F'},
4584 {0, 0, 0, 0}
4585 };
4586 c = getopt_long(argc, argv, ":b:f:F:g:h", long_options, NULL);
4587 if (c == -1) {
4588 break;
4589 }
4590
4591 switch (c) {
4592 case ':':
4593 missing_argument(argv[optind - 1]);
4594 break;
4595 case '?':
4596 unrecognized_option(argv[optind - 1]);
4597 break;
4598 case 'h':
4599 help();
4600 break;
4601 case 'b':
4602 src_filename = optarg;
4603 break;
4604 case 'f':
4605 fmt = optarg;
4606 break;
4607 case 'F':
4608 src_fmt = optarg;
4609 break;
4610 case 'g':
4611 granularity = cvtnum("granularity", optarg);
4612 if (granularity < 0) {
4613 return 1;
4614 }
4615 break;
4616 case OPTION_ADD:
4617 act = g_new0(ImgBitmapAction, 1);
4618 act->act = BITMAP_ADD;
4619 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4620 add = true;
4621 break;
4622 case OPTION_REMOVE:
4623 act = g_new0(ImgBitmapAction, 1);
4624 act->act = BITMAP_REMOVE;
4625 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4626 break;
4627 case OPTION_CLEAR:
4628 act = g_new0(ImgBitmapAction, 1);
4629 act->act = BITMAP_CLEAR;
4630 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4631 break;
4632 case OPTION_ENABLE:
4633 act = g_new0(ImgBitmapAction, 1);
4634 act->act = BITMAP_ENABLE;
4635 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4636 break;
4637 case OPTION_DISABLE:
4638 act = g_new0(ImgBitmapAction, 1);
4639 act->act = BITMAP_DISABLE;
4640 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4641 break;
4642 case OPTION_MERGE:
4643 act = g_new0(ImgBitmapAction, 1);
4644 act->act = BITMAP_MERGE;
4645 act->src = optarg;
4646 QSIMPLEQ_INSERT_TAIL(&actions, act, next);
4647 merge = true;
4648 break;
4649 case OPTION_OBJECT:
4650 opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true);
4651 if (!opts) {
4652 goto out;
4653 }
4654 break;
4655 case OPTION_IMAGE_OPTS:
4656 image_opts = true;
4657 break;
4658 }
4659 }
4660
4661 if (qemu_opts_foreach(&qemu_object_opts,
4662 user_creatable_add_opts_foreach,
4663 qemu_img_object_print_help, &error_fatal)) {
4664 goto out;
4665 }
4666
4667 if (QSIMPLEQ_EMPTY(&actions)) {
4668 error_report("Need at least one of --add, --remove, --clear, "
4669 "--enable, --disable, or --merge");
4670 goto out;
4671 }
4672
4673 if (granularity && !add) {
4674 error_report("granularity only supported with --add");
4675 goto out;
4676 }
4677 if (src_fmt && !src_filename) {
4678 error_report("-F only supported with -b");
4679 goto out;
4680 }
4681 if (src_filename && !merge) {
4682 error_report("Merge bitmap source file only supported with "
4683 "--merge");
4684 goto out;
4685 }
4686
4687 if (optind != argc - 2) {
4688 error_report("Expecting filename and bitmap name");
4689 goto out;
4690 }
4691
4692 filename = argv[optind];
4693 bitmap = argv[optind + 1];
4694
4695 blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR, false, false,
4696 false);
4697 if (!blk) {
4698 goto out;
4699 }
4700 bs = blk_bs(blk);
4701 if (src_filename) {
4702 src = img_open(false, src_filename, src_fmt, 0, false, false, false);
4703 if (!src) {
4704 goto out;
4705 }
4706 src_bs = blk_bs(src);
4707 } else {
4708 src_bs = bs;
4709 }
4710
4711 QSIMPLEQ_FOREACH_SAFE(act, &actions, next, act_next) {
4712 switch (act->act) {
4713 case BITMAP_ADD:
4714 qmp_block_dirty_bitmap_add(bs->node_name, bitmap,
4715 !!granularity, granularity, true, true,
4716 false, false, &err);
4717 op = "add";
4718 break;
4719 case BITMAP_REMOVE:
4720 qmp_block_dirty_bitmap_remove(bs->node_name, bitmap, &err);
4721 op = "remove";
4722 break;
4723 case BITMAP_CLEAR:
4724 qmp_block_dirty_bitmap_clear(bs->node_name, bitmap, &err);
4725 op = "clear";
4726 break;
4727 case BITMAP_ENABLE:
4728 qmp_block_dirty_bitmap_enable(bs->node_name, bitmap, &err);
4729 op = "enable";
4730 break;
4731 case BITMAP_DISABLE:
4732 qmp_block_dirty_bitmap_disable(bs->node_name, bitmap, &err);
4733 op = "disable";
4734 break;
Eric Blake6c729dd2020-05-21 14:21:35 -05004735 case BITMAP_MERGE:
4736 do_dirty_bitmap_merge(bs->node_name, bitmap, src_bs->node_name,
4737 act->src, &err);
Eric Blake3b51ab42020-05-12 20:16:45 -05004738 op = "merge";
4739 break;
Eric Blake3b51ab42020-05-12 20:16:45 -05004740 default:
4741 g_assert_not_reached();
4742 }
4743
4744 if (err) {
4745 error_reportf_err(err, "Operation %s on bitmap %s failed: ",
4746 op, bitmap);
4747 goto out;
4748 }
4749 g_free(act);
4750 }
4751
4752 ret = 0;
4753
4754 out:
4755 blk_unref(src);
4756 blk_unref(blk);
4757 qemu_opts_del(opts);
4758 return ret;
4759}
4760
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004761#define C_BS 01
4762#define C_COUNT 02
4763#define C_IF 04
4764#define C_OF 010
Reda Sallahif7c15532016-08-10 16:16:09 +02004765#define C_SKIP 020
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004766
4767struct DdInfo {
4768 unsigned int flags;
4769 int64_t count;
4770};
4771
4772struct DdIo {
4773 int bsz; /* Block size */
4774 char *filename;
4775 uint8_t *buf;
Reda Sallahif7c15532016-08-10 16:16:09 +02004776 int64_t offset;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004777};
4778
4779struct DdOpts {
4780 const char *name;
4781 int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
4782 unsigned int flag;
4783};
4784
4785static int img_dd_bs(const char *arg,
4786 struct DdIo *in, struct DdIo *out,
4787 struct DdInfo *dd)
4788{
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004789 int64_t res;
4790
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004791 res = cvtnum_full("bs", arg, 1, INT_MAX);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004792
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004793 if (res < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004794 return 1;
4795 }
4796 in->bsz = out->bsz = res;
4797
4798 return 0;
4799}
4800
4801static int img_dd_count(const char *arg,
4802 struct DdIo *in, struct DdIo *out,
4803 struct DdInfo *dd)
4804{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004805 dd->count = cvtnum("count", arg);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004806
Markus Armbruster606caa02017-02-21 21:14:04 +01004807 if (dd->count < 0) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004808 return 1;
4809 }
4810
4811 return 0;
4812}
4813
4814static int img_dd_if(const char *arg,
4815 struct DdIo *in, struct DdIo *out,
4816 struct DdInfo *dd)
4817{
4818 in->filename = g_strdup(arg);
4819
4820 return 0;
4821}
4822
4823static int img_dd_of(const char *arg,
4824 struct DdIo *in, struct DdIo *out,
4825 struct DdInfo *dd)
4826{
4827 out->filename = g_strdup(arg);
4828
4829 return 0;
4830}
4831
Reda Sallahif7c15532016-08-10 16:16:09 +02004832static int img_dd_skip(const char *arg,
4833 struct DdIo *in, struct DdIo *out,
4834 struct DdInfo *dd)
4835{
Eyal Moscovici43d589b2020-05-13 16:36:26 +03004836 in->offset = cvtnum("skip", arg);
Reda Sallahif7c15532016-08-10 16:16:09 +02004837
Markus Armbruster606caa02017-02-21 21:14:04 +01004838 if (in->offset < 0) {
Reda Sallahif7c15532016-08-10 16:16:09 +02004839 return 1;
4840 }
4841
4842 return 0;
4843}
4844
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004845static int img_dd(int argc, char **argv)
4846{
4847 int ret = 0;
4848 char *arg = NULL;
4849 char *tmp;
4850 BlockDriver *drv = NULL, *proto_drv = NULL;
4851 BlockBackend *blk1 = NULL, *blk2 = NULL;
4852 QemuOpts *opts = NULL;
4853 QemuOptsList *create_opts = NULL;
4854 Error *local_err = NULL;
4855 bool image_opts = false;
4856 int c, i;
4857 const char *out_fmt = "raw";
4858 const char *fmt = NULL;
4859 int64_t size = 0;
4860 int64_t block_count = 0, out_pos, in_pos;
Fam Zheng335e9932017-05-03 00:35:39 +08004861 bool force_share = false;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004862 struct DdInfo dd = {
4863 .flags = 0,
4864 .count = 0,
4865 };
4866 struct DdIo in = {
4867 .bsz = 512, /* Block size is by default 512 bytes */
4868 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004869 .buf = NULL,
4870 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004871 };
4872 struct DdIo out = {
4873 .bsz = 512,
4874 .filename = NULL,
Reda Sallahif7c15532016-08-10 16:16:09 +02004875 .buf = NULL,
4876 .offset = 0
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004877 };
4878
4879 const struct DdOpts options[] = {
4880 { "bs", img_dd_bs, C_BS },
4881 { "count", img_dd_count, C_COUNT },
4882 { "if", img_dd_if, C_IF },
4883 { "of", img_dd_of, C_OF },
Reda Sallahif7c15532016-08-10 16:16:09 +02004884 { "skip", img_dd_skip, C_SKIP },
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004885 { NULL, NULL, 0 }
4886 };
4887 const struct option long_options[] = {
4888 { "help", no_argument, 0, 'h'},
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004889 { "object", required_argument, 0, OPTION_OBJECT},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004890 { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
Fam Zheng335e9932017-05-03 00:35:39 +08004891 { "force-share", no_argument, 0, 'U'},
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004892 { 0, 0, 0, 0 }
4893 };
4894
Fam Zheng335e9932017-05-03 00:35:39 +08004895 while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004896 if (c == EOF) {
4897 break;
4898 }
4899 switch (c) {
4900 case 'O':
4901 out_fmt = optarg;
4902 break;
4903 case 'f':
4904 fmt = optarg;
4905 break;
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004906 case ':':
4907 missing_argument(argv[optind - 1]);
4908 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004909 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08004910 unrecognized_option(argv[optind - 1]);
4911 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004912 case 'h':
4913 help();
4914 break;
Fam Zheng335e9932017-05-03 00:35:39 +08004915 case 'U':
4916 force_share = true;
4917 break;
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004918 case OPTION_OBJECT:
4919 if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004920 ret = -1;
4921 goto out;
4922 }
Stefan Hajnoczi2a245702017-06-19 16:00:02 +01004923 break;
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004924 case OPTION_IMAGE_OPTS:
4925 image_opts = true;
4926 break;
4927 }
4928 }
4929
4930 for (i = optind; i < argc; i++) {
4931 int j;
4932 arg = g_strdup(argv[i]);
4933
4934 tmp = strchr(arg, '=');
4935 if (tmp == NULL) {
4936 error_report("unrecognized operand %s", arg);
4937 ret = -1;
4938 goto out;
4939 }
4940
4941 *tmp++ = '\0';
4942
4943 for (j = 0; options[j].name != NULL; j++) {
4944 if (!strcmp(arg, options[j].name)) {
4945 break;
4946 }
4947 }
4948 if (options[j].name == NULL) {
4949 error_report("unrecognized operand %s", arg);
4950 ret = -1;
4951 goto out;
4952 }
4953
4954 if (options[j].f(tmp, &in, &out, &dd) != 0) {
4955 ret = -1;
4956 goto out;
4957 }
4958 dd.flags |= options[j].flag;
4959 g_free(arg);
4960 arg = NULL;
4961 }
4962
4963 if (!(dd.flags & C_IF && dd.flags & C_OF)) {
4964 error_report("Must specify both input and output files");
4965 ret = -1;
4966 goto out;
4967 }
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004968
4969 if (qemu_opts_foreach(&qemu_object_opts,
4970 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02004971 qemu_img_object_print_help, &error_fatal)) {
Daniel P. Berrange83d4bf92017-05-15 17:47:09 +01004972 ret = -1;
4973 goto out;
4974 }
4975
Fam Zheng335e9932017-05-03 00:35:39 +08004976 blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
4977 force_share);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02004978
4979 if (!blk1) {
4980 ret = -1;
4981 goto out;
4982 }
4983
4984 drv = bdrv_find_format(out_fmt);
4985 if (!drv) {
4986 error_report("Unknown file format");
4987 ret = -1;
4988 goto out;
4989 }
4990 proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
4991
4992 if (!proto_drv) {
4993 error_report_err(local_err);
4994 ret = -1;
4995 goto out;
4996 }
4997 if (!drv->create_opts) {
4998 error_report("Format driver '%s' does not support image creation",
4999 drv->format_name);
5000 ret = -1;
5001 goto out;
5002 }
5003 if (!proto_drv->create_opts) {
5004 error_report("Protocol driver '%s' does not support image creation",
5005 proto_drv->format_name);
5006 ret = -1;
5007 goto out;
5008 }
5009 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5010 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5011
5012 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5013
5014 size = blk_getlength(blk1);
5015 if (size < 0) {
5016 error_report("Failed to get size for '%s'", in.filename);
5017 ret = -1;
5018 goto out;
5019 }
5020
5021 if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
5022 dd.count * in.bsz < size) {
5023 size = dd.count * in.bsz;
5024 }
5025
Reda Sallahif7c15532016-08-10 16:16:09 +02005026 /* Overflow means the specified offset is beyond input image's size */
5027 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5028 size < in.bsz * in.offset)) {
5029 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
5030 } else {
5031 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
5032 size - in.bsz * in.offset, &error_abort);
5033 }
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005034
5035 ret = bdrv_create(drv, out.filename, opts, &local_err);
5036 if (ret < 0) {
5037 error_reportf_err(local_err,
5038 "%s: error while creating output image: ",
5039 out.filename);
5040 ret = -1;
5041 goto out;
5042 }
5043
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005044 /* TODO, we can't honour --image-opts for the target,
5045 * since it needs to be given in a format compatible
5046 * with the bdrv_create() call above which does not
5047 * support image-opts style.
5048 */
Daniel P. Berrange29cf9332017-05-15 17:47:12 +01005049 blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
Daniel P. Berrangeea204dd2017-05-15 17:47:10 +01005050 false, false, false);
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005051
5052 if (!blk2) {
5053 ret = -1;
5054 goto out;
5055 }
5056
Reda Sallahif7c15532016-08-10 16:16:09 +02005057 if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
5058 size < in.offset * in.bsz)) {
5059 /* We give a warning if the skip option is bigger than the input
5060 * size and create an empty output disk image (i.e. like dd(1)).
5061 */
5062 error_report("%s: cannot skip to specified offset", in.filename);
5063 in_pos = size;
5064 } else {
5065 in_pos = in.offset * in.bsz;
5066 }
5067
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005068 in.buf = g_new(uint8_t, in.bsz);
5069
Reda Sallahif7c15532016-08-10 16:16:09 +02005070 for (out_pos = 0; in_pos < size; block_count++) {
Reda Sallahi86ce1f62016-08-10 04:43:12 +02005071 int in_ret, out_ret;
5072
5073 if (in_pos + in.bsz > size) {
5074 in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
5075 } else {
5076 in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
5077 }
5078 if (in_ret < 0) {
5079 error_report("error while reading from input image file: %s",
5080 strerror(-in_ret));
5081 ret = -1;
5082 goto out;
5083 }
5084 in_pos += in_ret;
5085
5086 out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
5087
5088 if (out_ret < 0) {
5089 error_report("error while writing to output image file: %s",
5090 strerror(-out_ret));
5091 ret = -1;
5092 goto out;
5093 }
5094 out_pos += out_ret;
5095 }
5096
5097out:
5098 g_free(arg);
5099 qemu_opts_del(opts);
5100 qemu_opts_free(create_opts);
5101 blk_unref(blk1);
5102 blk_unref(blk2);
5103 g_free(in.filename);
5104 g_free(out.filename);
5105 g_free(in.buf);
5106 g_free(out.buf);
5107
5108 if (ret) {
5109 return 1;
5110 }
5111 return 0;
5112}
5113
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005114static void dump_json_block_measure_info(BlockMeasureInfo *info)
5115{
5116 QString *str;
5117 QObject *obj;
5118 Visitor *v = qobject_output_visitor_new(&obj);
5119
5120 visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
5121 visit_complete(v, &obj);
5122 str = qobject_to_json_pretty(obj);
5123 assert(str != NULL);
5124 printf("%s\n", qstring_get_str(str));
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005125 qobject_unref(obj);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005126 visit_free(v);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005127 qobject_unref(str);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005128}
5129
5130static int img_measure(int argc, char **argv)
5131{
5132 static const struct option long_options[] = {
5133 {"help", no_argument, 0, 'h'},
5134 {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
5135 {"object", required_argument, 0, OPTION_OBJECT},
5136 {"output", required_argument, 0, OPTION_OUTPUT},
5137 {"size", required_argument, 0, OPTION_SIZE},
5138 {"force-share", no_argument, 0, 'U'},
5139 {0, 0, 0, 0}
5140 };
5141 OutputFormat output_format = OFORMAT_HUMAN;
5142 BlockBackend *in_blk = NULL;
5143 BlockDriver *drv;
5144 const char *filename = NULL;
5145 const char *fmt = NULL;
5146 const char *out_fmt = "raw";
5147 char *options = NULL;
5148 char *snapshot_name = NULL;
5149 bool force_share = false;
5150 QemuOpts *opts = NULL;
5151 QemuOpts *object_opts = NULL;
5152 QemuOpts *sn_opts = NULL;
5153 QemuOptsList *create_opts = NULL;
5154 bool image_opts = false;
5155 uint64_t img_size = UINT64_MAX;
5156 BlockMeasureInfo *info = NULL;
5157 Error *local_err = NULL;
5158 int ret = 1;
5159 int c;
5160
5161 while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
5162 long_options, NULL)) != -1) {
5163 switch (c) {
5164 case '?':
5165 case 'h':
5166 help();
5167 break;
5168 case 'f':
5169 fmt = optarg;
5170 break;
5171 case 'O':
5172 out_fmt = optarg;
5173 break;
5174 case 'o':
Markus Armbruster6d2b5cb2020-04-15 09:49:25 +02005175 if (accumulate_options(&options, optarg) < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005176 goto out;
5177 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005178 break;
5179 case 'l':
5180 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
5181 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
5182 optarg, false);
5183 if (!sn_opts) {
5184 error_report("Failed in parsing snapshot param '%s'",
5185 optarg);
5186 goto out;
5187 }
5188 } else {
5189 snapshot_name = optarg;
5190 }
5191 break;
5192 case 'U':
5193 force_share = true;
5194 break;
5195 case OPTION_OBJECT:
5196 object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
5197 optarg, true);
5198 if (!object_opts) {
5199 goto out;
5200 }
5201 break;
5202 case OPTION_IMAGE_OPTS:
5203 image_opts = true;
5204 break;
5205 case OPTION_OUTPUT:
5206 if (!strcmp(optarg, "json")) {
5207 output_format = OFORMAT_JSON;
5208 } else if (!strcmp(optarg, "human")) {
5209 output_format = OFORMAT_HUMAN;
5210 } else {
5211 error_report("--output must be used with human or json "
5212 "as argument.");
5213 goto out;
5214 }
5215 break;
5216 case OPTION_SIZE:
5217 {
5218 int64_t sval;
5219
Eyal Moscovici43d589b2020-05-13 16:36:26 +03005220 sval = cvtnum("image size", optarg);
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005221 if (sval < 0) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005222 goto out;
5223 }
5224 img_size = (uint64_t)sval;
5225 }
5226 break;
5227 }
5228 }
5229
5230 if (qemu_opts_foreach(&qemu_object_opts,
5231 user_creatable_add_opts_foreach,
Kevin Wolfc6e5cdf2019-10-11 21:49:17 +02005232 qemu_img_object_print_help, &error_fatal)) {
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005233 goto out;
5234 }
5235
5236 if (argc - optind > 1) {
5237 error_report("At most one filename argument is allowed.");
5238 goto out;
5239 } else if (argc - optind == 1) {
5240 filename = argv[optind];
5241 }
5242
Stefan Hajnoczic3673dc2020-02-21 11:25:21 +00005243 if (!filename && (image_opts || fmt || snapshot_name || sn_opts)) {
5244 error_report("--image-opts, -f, and -l require a filename argument.");
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005245 goto out;
5246 }
5247 if (filename && img_size != UINT64_MAX) {
5248 error_report("--size N cannot be used together with a filename.");
5249 goto out;
5250 }
5251 if (!filename && img_size == UINT64_MAX) {
5252 error_report("Either --size N or one filename must be specified.");
5253 goto out;
5254 }
5255
5256 if (filename) {
5257 in_blk = img_open(image_opts, filename, fmt, 0,
5258 false, false, force_share);
5259 if (!in_blk) {
5260 goto out;
5261 }
5262
5263 if (sn_opts) {
5264 bdrv_snapshot_load_tmp(blk_bs(in_blk),
5265 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
5266 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
5267 &local_err);
5268 } else if (snapshot_name != NULL) {
5269 bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
5270 snapshot_name, &local_err);
5271 }
5272 if (local_err) {
5273 error_reportf_err(local_err, "Failed to load snapshot: ");
5274 goto out;
5275 }
5276 }
5277
5278 drv = bdrv_find_format(out_fmt);
5279 if (!drv) {
5280 error_report("Unknown file format '%s'", out_fmt);
5281 goto out;
5282 }
5283 if (!drv->create_opts) {
5284 error_report("Format driver '%s' does not support image creation",
5285 drv->format_name);
5286 goto out;
5287 }
5288
5289 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5290 create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
5291 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5292 if (options) {
5293 qemu_opts_do_parse(opts, options, NULL, &local_err);
5294 if (local_err) {
5295 error_report_err(local_err);
5296 error_report("Invalid options for file format '%s'", out_fmt);
5297 goto out;
5298 }
5299 }
5300 if (img_size != UINT64_MAX) {
5301 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5302 }
5303
5304 info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
5305 if (local_err) {
5306 error_report_err(local_err);
5307 goto out;
5308 }
5309
5310 if (output_format == OFORMAT_HUMAN) {
5311 printf("required size: %" PRIu64 "\n", info->required);
5312 printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
Eric Blake5d72c682020-05-21 14:21:34 -05005313 if (info->has_bitmaps) {
5314 printf("bitmaps size: %" PRIu64 "\n", info->bitmaps);
5315 }
Stefan Hajnoczifd03c2b2017-07-05 13:57:36 +01005316 } else {
5317 dump_json_block_measure_info(info);
5318 }
5319
5320 ret = 0;
5321
5322out:
5323 qapi_free_BlockMeasureInfo(info);
5324 qemu_opts_del(object_opts);
5325 qemu_opts_del(opts);
5326 qemu_opts_del(sn_opts);
5327 qemu_opts_free(create_opts);
5328 g_free(options);
5329 blk_unref(in_blk);
5330 return ret;
5331}
Kevin Wolfb6133b82014-08-05 14:17:13 +02005332
Anthony Liguoric227f092009-10-01 16:12:16 -05005333static const img_cmd_t img_cmds[] = {
Stuart Brady153859b2009-06-07 00:42:17 +01005334#define DEF(option, callback, arg_string) \
5335 { option, callback },
5336#include "qemu-img-cmds.h"
5337#undef DEF
Stuart Brady153859b2009-06-07 00:42:17 +01005338 { NULL, NULL, },
5339};
5340
bellardea2384d2004-08-01 21:59:26 +00005341int main(int argc, char **argv)
5342{
Anthony Liguoric227f092009-10-01 16:12:16 -05005343 const img_cmd_t *cmd;
Stuart Brady153859b2009-06-07 00:42:17 +01005344 const char *cmdname;
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005345 Error *local_error = NULL;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005346 char *trace_file = NULL;
Jeff Cody7db16892014-04-25 17:02:32 -04005347 int c;
Jeff Cody7db16892014-04-25 17:02:32 -04005348 static const struct option long_options[] = {
5349 {"help", no_argument, 0, 'h'},
Denis V. Lunev10985132016-06-17 17:44:13 +03005350 {"version", no_argument, 0, 'V'},
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005351 {"trace", required_argument, NULL, 'T'},
Jeff Cody7db16892014-04-25 17:02:32 -04005352 {0, 0, 0, 0}
5353 };
bellardea2384d2004-08-01 21:59:26 +00005354
MORITA Kazutaka526eda12013-07-23 17:30:11 +09005355#ifdef CONFIG_POSIX
5356 signal(SIGPIPE, SIG_IGN);
5357#endif
5358
Christophe Fergeauf5852ef2019-01-31 17:46:14 +01005359 error_init(argv[0]);
Daniel P. Berrangefe4db842016-10-04 14:35:52 +01005360 module_call_init(MODULE_INIT_TRACE);
Fam Zheng10f5bff2014-02-10 14:48:51 +08005361 qemu_init_exec_dir(argv[0]);
Kevin Wolf53f76e52010-12-16 15:10:32 +01005362
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005363 if (qemu_init_main_loop(&local_error)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +01005364 error_report_err(local_error);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +03005365 exit(EXIT_FAILURE);
5366 }
5367
Eduardo Habkoste8f2d272016-05-12 11:10:04 -03005368 qcrypto_init(&error_fatal);
Daniel P. Berrangec2297082016-04-06 12:12:06 +01005369
Daniel P. Berrange064097d2016-02-10 18:41:01 +00005370 module_call_init(MODULE_INIT_QOM);
bellardea2384d2004-08-01 21:59:26 +00005371 bdrv_init();
Fam Zhengac1307a2014-04-22 13:36:11 +08005372 if (argc < 2) {
5373 error_exit("Not enough arguments");
5374 }
Stuart Brady153859b2009-06-07 00:42:17 +01005375
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005376 qemu_add_opts(&qemu_object_opts);
Daniel P. Berrangeeb769f72016-02-17 10:10:20 +00005377 qemu_add_opts(&qemu_source_opts);
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005378 qemu_add_opts(&qemu_trace_opts);
Daniel P. Berrange3babeb12016-02-17 10:10:17 +00005379
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005380 while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
Denis V. Lunev10985132016-06-17 17:44:13 +03005381 switch (c) {
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005382 case ':':
5383 missing_argument(argv[optind - 1]);
5384 return 0;
Stefan Hajnoczi4581c162017-03-17 18:45:39 +08005385 case '?':
Stefan Hajnoczic9192972017-03-17 18:45:41 +08005386 unrecognized_option(argv[optind - 1]);
5387 return 0;
5388 case 'h':
Denis V. Lunev10985132016-06-17 17:44:13 +03005389 help();
5390 return 0;
5391 case 'V':
5392 printf(QEMU_IMG_VERSION);
5393 return 0;
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005394 case 'T':
5395 g_free(trace_file);
5396 trace_file = trace_opt_parse(optarg);
5397 break;
Stuart Brady153859b2009-06-07 00:42:17 +01005398 }
bellardea2384d2004-08-01 21:59:26 +00005399 }
Stuart Brady153859b2009-06-07 00:42:17 +01005400
Denis V. Lunev10985132016-06-17 17:44:13 +03005401 cmdname = argv[optind];
Jeff Cody7db16892014-04-25 17:02:32 -04005402
Denis V. Lunev10985132016-06-17 17:44:13 +03005403 /* reset getopt_long scanning */
5404 argc -= optind;
5405 if (argc < 1) {
Jeff Cody5f6979c2014-04-28 14:37:18 -04005406 return 0;
5407 }
Denis V. Lunev10985132016-06-17 17:44:13 +03005408 argv += optind;
Richard W.M. Jonesd339d762019-01-18 10:11:14 +00005409 qemu_reset_optind();
Denis V. Lunev10985132016-06-17 17:44:13 +03005410
Denis V. Lunev06a1e0c2016-06-17 17:44:14 +03005411 if (!trace_init_backends()) {
5412 exit(1);
5413 }
5414 trace_init_file(trace_file);
5415 qemu_set_log(LOG_TRACE);
5416
Denis V. Lunev10985132016-06-17 17:44:13 +03005417 /* find the command */
5418 for (cmd = img_cmds; cmd->name != NULL; cmd++) {
5419 if (!strcmp(cmdname, cmd->name)) {
5420 return cmd->handler(argc, argv);
5421 }
5422 }
Jeff Cody7db16892014-04-25 17:02:32 -04005423
Stuart Brady153859b2009-06-07 00:42:17 +01005424 /* not found */
Fam Zhengac1307a2014-04-22 13:36:11 +08005425 error_exit("Command not found: %s", cmdname);
bellardea2384d2004-08-01 21:59:26 +00005426}